diff --git a/.gitignore b/.gitignore index e63d33ae031..66ce7837b26 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,8 @@ auths/* # Documentation docs/* !docs/management-api-v8.md +!docs/websocket-tunnel.md +!docs/websocket-tunnel_CN.md AGENTS.md CLAUDE.md GEMINI.md diff --git a/README.md b/README.md index 4bcfb4a1769..73d37a3825f 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ You can access the following providers locally and with multiple CLI accounts th Devin - Devin models (SWE-2, GPT-6 Astra, Claude Fable 5.1, etc.). Connect a Devin account with --devin-login to route the models available to that account. + Devin models (SWE-2, SWE-2 Flash, GPT-6 Astra, Claude Fable 5.1, etc.). Connect a Devin account with --devin-login to route the models available to that account. @@ -97,10 +97,6 @@ PackyCode provides special discounts for our software users: register using PatewayAI is an API relay service provider for experienced AI developers, with full support for the Claude and Codex model families. All models come from high-quality official channels, with no dilution or counterfeiting, and transparent, verifiable billing details. Economy mode starts at just 5% of the official price. Register through this link to receive trial credits and participate in occasional promotions for free credits. The platform also supports enterprise-grade concurrency, a dedicated management dashboard, formal contracts and invoices, and two-way referral rewards of up to $150. -Modelflare -Thanks to Modelflare for sponsoring this project! Modelflare: Full strength, stable, nothing watered down. Global SOTA models at a lower cost. Operated by US-based Havenbyte LLC, Modelflare supports GPT, Claude, Gemini, Grok, and other leading models through common compatible protocols, plus 40+ image and video models. Cache compensation is a highlight: selected OpenAI groups (price-first, stable, and premium) guarantee daily cache hit rates of 65%, 75%, or 85%, and if eligible requests fall short, Modelflare refunds the difference, visible on the usage dashboard after settlement. Special offers: a single top-up of US$20 unlocks the GPT discount group at a 0.015x price multiplier, and a single top-up of US$50 unlocks the Claude discount group at a 0.03x multiplier. Register via this exclusive link to get started. - - kedaya.ai kedaya.ai is a stable and efficient AI model API relay service provider, covering leading models including Claude, GPT, Gemini, Grok, Antigravity, and DeepSeek. It supports native OpenAI (including Responses), Anthropic, and Gemini protocols, enabling seamless integration with clients such as CLIProxyAPI, Claude Code, Codex, Gemini CLI, and Grok CLI. OpenAI and Grok model prices can be as low as 0.1% of official rates! Exclusive registration link. @@ -119,6 +115,18 @@ PackyCode provides special discounts for our software users: register using Chenju Thanks to 陈局 (Chenju) for sponsoring this project! Probably the only slot here that won't ask you to sign up — no signup link, no promo code. Just raising a glass to the maintainers, because good open source deserves to be paid for. Come shoot the breeze on X: @chenju_ai + +DeepSider API +Access leading AI models like GPT, Claude, Gemini, and DeepSeek—all in one place. We connect through official channels from major providers, with no shared account pools or reverse engineering. Save up to 71% compared with official rates. Track your usage in real time with transparent billing, and access AI at a lower cost. Try DeepSider API. + + +OriginCoder +OriginCoder is an enterprise-grade AI gateway designed for low latency, reliability, and high concurrency. We build and operate our Claude Max and GPT Pro account pools entirely in-house. Pools that maintain full model performance are priced at 30–40% of official rates, and we publish each pool’s performance status in real time. Access GPT, Claude, Grok, Gemini-4-Carbon, DeepSeek, and other leading AI models through coding tools such as Claude Code and Codex. Use it for AI chat, coding assistance, image generation, and video generation. We operate overseas in compliance with local regulations and have served more than 15,000 customers since launching in August 2025. Our pricing is transparent, with no overage fees and top-ups starting at CNY 10. We keep the service running smoothly during peak hours through 24/7 monitoring, redundant account pools, and automatic failover between nodes. Check our service status. We protect your privacy by not storing conversation content. We support business payments and invoicing. Our support team responds within 3 minutes, and our technical team is available 24/7. Users in mainland China can connect through our China-optimized gateway. + + +VisionCoder +VisionCoder | China’s OpenRouter — one API for leading Chinese and global AI models. Access DeepSeek, Qwen, Kimi, GLM, GPT, Claude, Gemini, and Grok, with intelligent routing across suppliers and automatic failover. Failed requests are free, pricing is public, and every charge can be verified. Works with coding tools such as Claude Code and Codex, with one-click import into CC Switch and WorkBuddy. Teams can purchase centrally, assign subscription packages by seat, and reclaim them for reassignment, with business bank transfers and invoicing supported. Supplier applications are open: list your model endpoints and earn traffic based on quality. Monthly settlement to business bank accounts, itemized usage records, and customer billing and invoicing handled by VisionCoder. Join the VibeCoding Challenge for CNY 2,350 in top-up credits per round, including CNY 1,000 in top-up credits for first place. + @@ -310,7 +318,7 @@ A Cloudflare-based LLM gateway and proxy server: CLIProxyAPI deployed to Cloudfl ### [Hermes CLIProxyAPI Provider](https://github.com/duu261/hermes-cliproxyapi-provider) -Model-provider plugin for [Hermes Agent](https://github.com/NousResearch/hermes-agent) that registers one Hermes provider per CLIProxyAPI provider, each on the wire its executor accepts (Anthropic Messages, Responses or Chat Completions), with context windows and reasoning levels read from CLIProxyAPI. Optional read-only Management API pass for exact provider grouping. Listed in the [Hermes plugin catalog](https://hermes-agent.nousresearch.com/docs/plugins/cliproxyapi-provider): `hermes plugins install cliproxyapi-provider`. +Model-provider plugin for [Hermes Agent](https://github.com/NousResearch/hermes-agent) that registers one Hermes provider per CLIProxyAPI provider, each on the wire its executor accepts (Anthropic Messages, Responses or Chat Completions), with context windows and reasoning levels read from CLIProxyAPI. Optional read-only Management API pass for exact provider grouping. A companion plugin adds a `/cpa` chat command for each pool's account health and, on request, each account's live quota. Listed in the [Hermes plugin catalog](https://hermes-agent.nousresearch.com/docs/plugins): `hermes plugins install cliproxyapi-provider` and `hermes plugins install cpa-status`. ### [Ebb](https://github.com/lucasnsaraujo/ebb) diff --git a/README_CN.md b/README_CN.md index 2132c49d765..19f62484235 100644 --- a/README_CN.md +++ b/README_CN.md @@ -40,7 +40,7 @@ CLIProxyAPI 是一个为 CLI 提供 OpenAI/Gemini/Claude/Codex/Grok 兼容 API Devin - Devin 提供的模型(SWE-2、GPT-6 Astra、Claude Fable 5.1 等)。使用 --devin-login 连接 Devin 账户,即可路由该账户可用的模型。 + Devin 提供的模型(SWE-2、SWE-2 Flash、GPT-6 Astra、Claude Fable 5.1 等)。使用 --devin-login 连接 Devin 账户,即可路由该账户可用的模型。 @@ -92,10 +92,6 @@ PackyCode 为本软件用户提供了特别优惠:使用此链接注册即可获得试用额度,还可参与不定时营销活动领取免费额度。平台同时支持企业级并发、专属管理后台、正式合同与发票,并提供最高 150 美元的双向推荐奖励。 -Modelflare -感谢 Modelflare 赞助本项目!Modelflare:满血稳定不掺水,低成本享受全球 SOTA 模型。站点由美国 LLC 主体 Havenbyte LLC 运营,支持 GPT、Claude、Gemini、Grok 等主流模型和常用兼容协议,还支持 40 多种图片和视频模型。缓存补偿是一大亮点:部分 OpenAI 价格优先、稳定和高级分组提供每日 65%、75%、85% 的缓存命中率保障,符合条件的请求没达到目标的,平台补偿差额,结算后可在用量看板查看。特惠活动:单笔充值 US$20 即可解锁 0.015 倍价格倍率的 GPT 特惠分组,单笔充值 US$50 即可解锁 0.03 倍价格倍率的 Claude 特惠分组。通过专属链接注册即可参与。 - - kedaya.ai kedaya.ai 是一家稳定高效的 AI 模型 API 中转服务商,覆盖 Claude、GPT、Gemini、Grok、Antigravity、DeepSeek 等主流模型,兼容 OpenAI(含 Responses)、Anthropic、Gemini 原生协议,可无缝接入 CLIProxyAPI、Claude Code、Codex、Gemini CLI、Grok CLI 等客户端。OpenAI及Grok模型价格最低可达官方0.01折!专属入口:https://kedaya.ai/register?aff=824X8RAHCYXM @@ -114,6 +110,18 @@ PackyCode 为本软件用户提供了特别优惠:使用陈局 感谢 陈局 赞助了本项目!这大概是本栏唯一一个不打站点广告的。好的开源项目值得被付费,陈局来随个份子,敬作者一杯。X 上找 陈局 吹吹水。 + +DeepSider API +一站式接入 GPT、Claude、Gemini、DeepSeek 等领先 AI 模型。我们通过主流供应商的官方渠道接入,不使用共享账号池或逆向工程。相比官方价格,最高可节省 71%。实时追踪用量,计费透明,以更低成本使用 AI。体验 DeepSider API。 + + +DeepSider API +OriginCoder|低延迟、高稳定、高并发的企业级 AI 网关,Claude Max 与 GPT Pro 号池全部自建自营,不降智池价格为官方的 3–4 折,池内降智状态实时公开可查,支持 GPT、Claude、Grok、Gemini-4-Carbon、DeepSeek 等国内外主流模型,可直接用于 Claude Code、Codex 等编程工具,支持 AI 对话、编程辅助、图像生成和视频生成,海外正规运营,自 2025 年 8 月运营至今,已服务 1.5 万+ 客户,费率公开、无超额费、10 元起充,后台 7×24 小时监测、号池冗余、多节点自动切换,保障高峰期访问稳定,服务状态公开可查,不保存用户会话内容,保护隐私安全,支持对公支付与企业开票,客服 3 分钟内响应、技术团队 24 小时值守,国内用户可通过国内加速入口访问。 + + +VisionCoder +VisionCoder|国内版 OpenRouter,一个 API 接入国内外主流大模型。 覆盖 DeepSeek、Qwen、Kimi、GLM、GPT、Claude、Gemini、Grok,多供应商智能选路、故障自动切换,失败请求不收费,价格公开、账单可复算。适配 Claude Code、Codex 等编程工具,支持 CC Switch 和 WorkBuddy 一键导入。企业统一采购,按席位下发订阅套餐、收回再分配,支持对公转账与开票。供应商入驻开放:上架线路,按质量拿流量;月结对公、用量可查,用户侧计费开票交给平台。 更有 VibeCoding 挑战赛,每期奖励合计 2,350 元加油包,一等奖 1,000 元加油包。 + @@ -301,7 +309,7 @@ Claude Code 状态栏,按当前 CPA 实例展示 Codex / Grok / Antigravity / ### [Hermes CLIProxyAPI Provider](https://github.com/duu261/hermes-cliproxyapi-provider) -[Hermes Agent](https://github.com/NousResearch/hermes-agent) 的模型提供方插件:为每个 CLIProxyAPI 提供方注册一个 Hermes 提供方,各自使用其执行器接受的协议(Anthropic Messages、Responses 或 Chat Completions),上下文窗口与推理等级读取自 CLIProxyAPI。可选只读 Management API 查询,用于精确的提供方分组。已收录于 [Hermes 插件目录](https://hermes-agent.nousresearch.com/docs/plugins/cliproxyapi-provider):`hermes plugins install cliproxyapi-provider`。 +[Hermes Agent](https://github.com/NousResearch/hermes-agent) 的模型提供方插件:为每个 CLIProxyAPI 提供方注册一个 Hermes 提供方,各自使用其执行器接受的协议(Anthropic Messages、Responses 或 Chat Completions),上下文窗口与推理等级读取自 CLIProxyAPI。可选只读 Management API 查询,用于精确的提供方分组。配套插件提供 `/cpa` 聊天命令,可查看每个号池的账号状态,并可按需查看每个账号的实时额度。已收录于 [Hermes 插件目录](https://hermes-agent.nousresearch.com/docs/plugins):`hermes plugins install cliproxyapi-provider` 与 `hermes plugins install cpa-status`。 ### [Ebb](https://github.com/lucasnsaraujo/ebb) diff --git a/README_JA.md b/README_JA.md index 8eca9f71b95..a5064334448 100644 --- a/README_JA.md +++ b/README_JA.md @@ -40,7 +40,7 @@ CLIProxyAPI は、CLI向けのOpenAI/Gemini/Claude/Codex/Grok互換APIインタ Devin - Devinのモデル(SWE-2、GPT-6 Astra、Claude Fable 5.1など)。--devin-loginでDevinアカウントに接続し、そのアカウントで利用可能なモデルにリクエストを送れます。 + Devinのモデル(SWE-2、SWE-2 Flash、GPT-6 Astra、Claude Fable 5.1など)。--devin-loginでDevinアカウントに接続し、そのアカウントで利用可能なモデルにリクエストを送れます。 @@ -92,10 +92,6 @@ PackyCodeは当ソフトウェアのユーザーに特別割引を提供して PatewayAI は、経験豊富な AI 開発者向けの API リレーサービスプロバイダーで、Claude および Codex シリーズのモデルを完全にサポートしています。すべてのモデルは高品質な公式チャネルから提供され、希釈や偽装は一切なく、課金明細も透明で確認可能です。エコノミーモードは公式価格のわずか5%から利用できます。こちらのリンクから登録するとトライアルクレジットを受け取れるほか、不定期のキャンペーンで無料クレジットを獲得できます。また、エンタープライズ級の同時接続、専用管理ダッシュボード、正式な契約書と請求書に対応し、双方に最大150米ドルが付与される紹介特典も提供しています。 -Modelflare -Modelflare による本プロジェクトへのご支援に感謝します!Modelflare:フルスペックで安定、水増しなし。世界の SOTA モデルを低コストで利用できます。米国法人 Havenbyte LLC が運営し、GPT、Claude、Gemini、Grok などの主要モデルと一般的な互換プロトコルに対応しているほか、40 種類以上の画像・動画モデルもサポートしています。キャッシュ補償が大きな特長です:一部の OpenAI 価格優先・安定・プレミアムグループでは、1 日あたり 65%、75%、85% のキャッシュヒット率を保証し、対象リクエストが目標に達しなかった場合は差額を補償します。精算後に使用量ダッシュボードで確認できます。特別キャンペーン:1 回 US$20 のチャージで価格倍率 0.015 倍の GPT 特別グループが、1 回 US$50 のチャージで価格倍率 0.03 倍の Claude 特別グループが解放されます。専用リンクから登録してご参加ください。 - - kedaya.ai kedaya.ai は、安定性と効率性に優れた AI モデル API 中継サービスプロバイダーです。Claude、GPT、Gemini、Grok、Antigravity、DeepSeek などの主要モデルをカバーし、OpenAI(Responses を含む)、Anthropic、Gemini のネイティブプロトコルに対応しているため、CLIProxyAPI、Claude Code、Codex、Gemini CLI、Grok CLI などのクライアントにシームレスに接続できます。OpenAI および Grok モデルの価格は、最安で公式価格の 0.1% から!専用リンク:https://kedaya.ai/register?aff=824X8RAHCYXM @@ -114,6 +110,14 @@ PackyCodeは当ソフトウェアのユーザーに特別割引を提供して Chenju 陈局 (Chenju) による本プロジェクトへのご支援に感謝します!おそらくこの欄で唯一、登録リンクもプロモーションコードもない枠です。優れたオープンソースプロジェクトには対価が支払われるべきという想いから、メンテナーに敬意を表して一杯おごります。X の @chenju_ai で気軽に雑談しましょう。 + +OriginCoder +OriginCoderは、低遅延で安定した接続を提供し、大量の同時リクエストにも対応する企業向けAIゲートウェイです。Claude MaxとGPT Proのアカウントプールは、構築から運用まですべて自社で管理。モデル本来の性能で利用できるプールを公式料金の30〜40%で提供し、各プールの性能低下の有無もリアルタイムで公開しています。GPT、Claude、Grok、Gemini-4-Carbon、DeepSeekなど、世界各国の主要AIモデルに対応し、Claude CodeやCodexなどの開発ツールからも利用できます。AIチャット、コーディング支援、画像生成、動画生成にも対応しています。海外を拠点に現地の法令に従ってサービスを運営しており、2025年8月のサービス開始以来、15,000を超えるお客様にご利用いただいています。料金はすべて公開しており、超過料金はかかりません。10人民元からチャージできます。24時間365日の監視、アカウントプールの冗長化、複数ノード間の自動切り替えにより、アクセスが集中する時間帯も安定した接続を維持します。サービスの稼働状況はステータスページで公開しています。会話の内容は保存せず、お客様のプライバシーを守ります。法人名義でのお支払いと請求書の発行にも対応しています。カスタマーサポートへのお問い合わせには3分以内に返信し、技術チームは24時間体制で対応します。中国本土からご利用の方には、アクセスを高速化した専用サイトをご用意しています。 + + +VisionCoder +VisionCoder|中国発の OpenRouter 型サービス。中国・海外の主要 AI モデルを、1つの API で。 DeepSeek、Qwen、Kimi、GLM、GPT、Claude、Gemini、Grok に対応。複数サプライヤーから接続先を自動選択し、障害時は別の接続先へ切り替えます。失敗したリクエストは課金なし。料金を公開し、請求額の計算も確認できます。 Claude Code、Codex などの開発ツールに対応し、CC Switch と WorkBuddy へワンクリックでインポート。企業は一括購入したサブスクリプションをメンバーごとに割り当て、回収・再割り当ても可能。法人名義の銀行振込と請求書発行にも対応します。サプライヤー募集中:モデルの接続先を登録し、品質に応じてトラフィックを獲得。法人向け月次精算・利用明細の確認に対応し、ユーザーへの課金・請求書発行は VisionCoder が担当します。 VibeCoding チャレンジも開催。各回の賞品は 合計2,350元相当の追加利用クレジット、最優秀賞は 1,000元相当の追加利用クレジット。 + @@ -300,7 +304,7 @@ Cloudflare ベースの LLM ゲートウェイ兼プロキシサーバー。CLIP ### [Hermes CLIProxyAPI Provider](https://github.com/duu261/hermes-cliproxyapi-provider) -[Hermes Agent](https://github.com/NousResearch/hermes-agent) 向けのモデルプロバイダープラグイン。CLIProxyAPI のプロバイダーごとに Hermes プロバイダーを 1 つ登録し、それぞれの executor が受け付けるプロトコル(Anthropic Messages、Responses、Chat Completions)を使います。コンテキストウィンドウと推論レベルは CLIProxyAPI から取得します。正確なプロバイダーグループ分けのための読み取り専用 Management API 照会はオプションです。[Hermes プラグインカタログ](https://hermes-agent.nousresearch.com/docs/plugins/cliproxyapi-provider)に掲載されています:`hermes plugins install cliproxyapi-provider`。 +[Hermes Agent](https://github.com/NousResearch/hermes-agent) 向けのモデルプロバイダープラグイン。CLIProxyAPI のプロバイダーごとに Hermes プロバイダーを 1 つ登録し、それぞれの executor が受け付けるプロトコル(Anthropic Messages、Responses、Chat Completions)を使います。コンテキストウィンドウと推論レベルは CLIProxyAPI から取得します。正確なプロバイダーグループ分けのための読み取り専用 Management API 照会はオプションです。コンパニオンプラグインの `/cpa` チャットコマンドで、各プールのアカウント状態と、必要に応じて各アカウントのリアルタイムのクォータを確認できます。[Hermes プラグインカタログ](https://hermes-agent.nousresearch.com/docs/plugins)に掲載されています:`hermes plugins install cliproxyapi-provider` および `hermes plugins install cpa-status`。 ### [Ebb](https://github.com/lucasnsaraujo/ebb) diff --git a/assets/deepsiderapi.png b/assets/deepsiderapi.png new file mode 100644 index 00000000000..10b1684269d Binary files /dev/null and b/assets/deepsiderapi.png differ diff --git a/assets/modelflare.png b/assets/modelflare.png deleted file mode 100644 index 91bd54198db..00000000000 Binary files a/assets/modelflare.png and /dev/null differ diff --git a/assets/origincoder.png b/assets/origincoder.png new file mode 100644 index 00000000000..248c82c2e67 Binary files /dev/null and b/assets/origincoder.png differ diff --git a/assets/visioncoder.svg b/assets/visioncoder.svg new file mode 100644 index 00000000000..7812022a597 --- /dev/null +++ b/assets/visioncoder.svg @@ -0,0 +1,20 @@ + + VisionCoder + + + + + + + + + + + + + + + + + + diff --git a/cmd/server/main.go b/cmd/server/main.go index 254dce6337d..86f3f8374bf 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -72,9 +72,22 @@ func shouldEnableExampleAPIKeySafeMode(cfg *config.Config, commandMode, tuiMode, // It parses command-line flags, loads configuration, and starts the appropriate // service based on the provided flags (login, codex-login, or server mode). func main() { + os.Exit(run()) +} + +func logStartupErrorf(format string, args ...any) { + if log.StandardLogger().Out != os.Stderr { + _, _ = fmt.Fprintf(os.Stderr, format+"\n", args...) + } + log.Errorf(format, args...) +} + +// run finishes deferred cleanup before main applies the process exit status. +func run() (exitStatus int) { if printHostVersion(os.Args[1:], os.Stdout) { - return + return 0 } + log.SetOutput(os.Stderr) if len(os.Args) > 1 && os.Args[1] == "discover" { discoverFlags := flag.NewFlagSet("discover", flag.ExitOnError) @@ -98,7 +111,7 @@ func main() { Include: include, Exclude: exclude, }) - os.Exit(code) + return code } // For legacy --discover-json flag or JSON requests, keep stdout clean @@ -114,6 +127,7 @@ func main() { var claudeLogin bool var noBrowser bool var oauthCallbackPort int + var loginProxyURL string var antigravityLogin bool var kimiLogin bool var kimiAILogin bool @@ -145,6 +159,7 @@ func main() { flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth") flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth") flag.IntVar(&oauthCallbackPort, "oauth-callback-port", 0, "Override OAuth callback port (defaults to provider-specific port)") + flag.StringVar(&loginProxyURL, "login-proxy", "", "Proxy URL used for the OAuth login flow and saved as the new credential's proxy_url (http, https, socks5, socks5h)") flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth") flag.BoolVar(&kimiLogin, "kimi-login", false, "Login to Kimi (.com) using OAuth") flag.BoolVar(&kimiAILogin, "kimi-ai-login", false, "Login to Kimi.ai using OAuth") @@ -209,8 +224,8 @@ func main() { // Parse the command-line flags. flag.Parse() if parentPID < 0 { - log.Errorf("parent pid must be positive") - return + logStartupErrorf("parent pid must be positive") + return 1 } if discoverGateways || discoverJSON { @@ -223,7 +238,7 @@ func main() { Include: include, Exclude: exclude, }) - os.Exit(code) + return code } // Core application variables. @@ -260,7 +275,7 @@ func main() { wd, err := os.Getwd() if err != nil { log.Errorf("failed to get working directory: %v", err) - return + return 1 } // Load environment variables from .env if present. @@ -358,7 +373,7 @@ func main() { cancelHome() if errHomeCfg != nil { log.Errorf("invalid -home-jwt: %v", errHomeCfg) - return + return 1 } if homeDisableClusterDiscovery { homeCfg.DisableClusterDiscovery = true @@ -375,13 +390,13 @@ func main() { cancelHomeConfig() if errGetConfig != nil { log.Errorf("failed to fetch config from home: %v", errGetConfig) - return + return 1 } parsed, errParseConfig := config.ParseConfigBytes(raw) if errParseConfig != nil { log.Errorf("failed to parse config payload from home: %v", errParseConfig) - return + return 1 } if parsed == nil { parsed = &config.Config{} @@ -438,7 +453,7 @@ func main() { } } if errHomePlugins != nil { - return + return 1 } cfg = parsed @@ -468,14 +483,14 @@ func main() { cancel() if err != nil { log.Errorf("failed to initialize postgres token store: %v", err) - return + return 1 } examplePath := filepath.Join(wd, "config.example.yaml") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { cancel() log.Errorf("failed to bootstrap postgres-backed config: %v", errBootstrap) - return + return 1 } cancel() configFilePath = pgStoreInst.ConfigPath() @@ -499,7 +514,7 @@ func main() { parsed, errParse := url.Parse(resolvedEndpoint) if errParse != nil { log.Errorf("failed to parse object store endpoint %q: %v", objectStoreEndpoint, errParse) - return + return 1 } switch strings.ToLower(parsed.Scheme) { case "http": @@ -508,11 +523,11 @@ func main() { useSSL = true default: log.Errorf("unsupported object store scheme %q (only http and https are allowed)", parsed.Scheme) - return + return 1 } if parsed.Host == "" { log.Errorf("object store endpoint %q is missing host information", objectStoreEndpoint) - return + return 1 } resolvedEndpoint = parsed.Host if parsed.Path != "" && parsed.Path != "/" { @@ -532,14 +547,14 @@ func main() { objectStoreInst, err = store.NewObjectTokenStore(objCfg) if err != nil { log.Errorf("failed to initialize object token store: %v", err) - return + return 1 } examplePath := filepath.Join(wd, "config.example.yaml") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) if errBootstrap := objectStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { cancel() log.Errorf("failed to bootstrap object-backed config: %v", errBootstrap) - return + return 1 } cancel() configFilePath = objectStoreInst.ConfigPath() @@ -565,7 +580,7 @@ func main() { gitStoreInst.SetBaseDir(authDir) if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil { log.Errorf("failed to prepare git token store: %v", errRepo) - return + return 1 } configFilePath = gitStoreInst.ConfigPath() if configFilePath == "" { @@ -575,20 +590,20 @@ func main() { examplePath := filepath.Join(wd, "config.example.yaml") if _, errExample := os.Stat(examplePath); errExample != nil { log.Errorf("failed to find template config file: %v", errExample) - return + return 1 } if errCopy := misc.CopyConfigTemplate(examplePath, configFilePath); errCopy != nil { log.Errorf("failed to bootstrap git-backed config: %v", errCopy) - return + return 1 } if errCommit := persistSeededConfig(context.Background(), configFilePath, gitStoreInst.PersistConfig); errCommit != nil { log.Errorf("failed to commit initial git-backed config: %v", errCommit) - return + return 1 } log.Infof("git-backed config initialized from template: %s", configFilePath) } else if statErr != nil { log.Errorf("failed to inspect git-backed config: %v", statErr) - return + return 1 } cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) if err == nil { @@ -602,14 +617,14 @@ func main() { wd, err = os.Getwd() if err != nil { log.Errorf("failed to get working directory: %v", err) - return + return 1 } configFilePath = filepath.Join(wd, "config.yaml") cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) } if err != nil { log.Errorf("failed to load config: %v", err) - return + return 1 } if cfg == nil { cfg = &config.Config{} @@ -646,7 +661,7 @@ func main() { if err = logging.ConfigureLogOutput(cfg); err != nil { log.Errorf("failed to configure log output: %v", err) - return + return 1 } log.Infof("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate) @@ -655,8 +670,8 @@ func main() { util.SetLogLevel(cfg) if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir); errResolveAuthDir != nil { - log.Errorf("failed to resolve auth directory: %v", errResolveAuthDir) - return + logStartupErrorf("failed to resolve auth directory: %v", errResolveAuthDir) + return 1 } else { cfg.AuthDir = resolvedAuthDir } @@ -667,6 +682,7 @@ func main() { options := &cmd.LoginOptions{ NoBrowser: noBrowser, CallbackPort: oauthCallbackPort, + ProxyURL: loginProxyURL, } commandMode := vertexImport != "" || siwcBind != "" || antigravityLogin || codexLogin || codexDeviceLogin || claudeLogin || kimiLogin || kimiAILogin || xaiLogin || devinLogin || metaLogin @@ -700,13 +716,13 @@ func main() { errHomePluginLoad := homeplugins.MarkLoadResults(&homePluginSyncReport, pluginHost) errReportPlugins := home.ReportPluginStatus(context.Background(), homeClient, cfg.Home.NodeID, homePluginSyncReport) if errHomePluginLoad != nil { - log.Errorf("failed to load home plugins: %v", errHomePluginLoad) + logStartupErrorf("failed to load home plugins: %v", errHomePluginLoad) } if errReportPlugins != nil { log.Warnf("failed to report home plugin load status: %v", errReportPlugins) } if errHomePluginLoad != nil { - return + return 1 } } if homeClient != nil { @@ -717,10 +733,7 @@ func main() { } if pluginHost.HasTriggeredCommandLineFlags() { if exitCode, handled := pluginHost.ExecuteCommandLine(context.Background(), os.Args[0], os.Args[1:], configFilePath, flag.CommandLine); handled { - if exitCode != 0 { - os.Exit(exitCode) - } - return + return exitCode } } @@ -759,7 +772,7 @@ func main() { if isCloudDeploy && !configFileExists { // No config file available, just wait for shutdown cmd.WaitForCloudDeploy() - return + return 0 } if localModel && (!tuiMode || standalone) { log.Info("Local model mode: using embedded catalogs unless an explicit catalog source is configured") @@ -805,11 +818,23 @@ func main() { ready := false backoff := 100 * time.Millisecond for i := 0; i < 30; i++ { + select { + case <-done: + i = 30 + default: + } + if i >= 30 { + break + } if _, errGetConfig := client.GetConfig(); errGetConfig == nil { ready = true break } - time.Sleep(backoff) + select { + case <-done: + i = 30 + case <-time.After(backoff): + } if backoff < time.Second { backoff = time.Duration(float64(backoff) * 1.5) } @@ -820,24 +845,30 @@ func main() { cancel() <-done fmt.Fprintf(os.Stderr, "TUI error: embedded server is not ready\n") - return + return 1 } + var errTUI error if errRun := tui.Run(cfg.Port, password, hook, origStdout); errRun != nil { restoreIO() fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun) + errTUI = errRun } else { restoreIO() } cancel() <-done + if errTUI != nil { + return 1 + } } else { // Default TUI mode: pure management client. // The proxy server must already be running (locally or remotely). baseURL := resolveManagementBaseURL(managementBaseURL, cfg) if errRun := tui.RunWithBaseURL(baseURL, password, nil, os.Stdout); errRun != nil { fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun) + return 1 } } } else { @@ -845,9 +876,15 @@ func main() { managementasset.StartAutoUpdater(context.Background(), configFilePath) misc.StartAntigravityVersionUpdater(context.Background()) registry.SetLocalModelCatalogs(localModel) - cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, hostOptions, serverOptions...) + if errStart := cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, hostOptions, serverOptions...); errStart != nil { + if log.StandardLogger().Out != os.Stderr { + _, _ = fmt.Fprintf(os.Stderr, "proxy service error: %v\n", errStart) + } + return 1 + } } } + return 0 } // resolveManagementBaseURL determines the management API base URL for TUI client mode. diff --git a/cmd/server/main_exit_test.go b/cmd/server/main_exit_test.go new file mode 100644 index 00000000000..f82cb4f46b4 --- /dev/null +++ b/cmd/server/main_exit_test.go @@ -0,0 +1,256 @@ +package main + +import ( + "bytes" + "context" + "flag" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" +) + +const serverExitHelperEnv = "CLIPROXY_TEST_SERVER_EXIT_HELPER" + +func TestServerExitHelper(t *testing.T) { + if os.Getenv(serverExitHelperEnv) != "1" { + return + } + for index, arg := range os.Args { + if arg == "--" { + os.Args = append([]string{os.Args[0]}, os.Args[index+1:]...) + flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) + main() + return + } + } + t.Fatal("missing server arguments") +} + +func newServerExitCommand(t *testing.T, dir string, args ...string) (*exec.Cmd, *bytes.Buffer, *bytes.Buffer) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + t.Cleanup(cancel) + cmdArgs := append([]string{"-test.run=^TestServerExitHelper$", "--"}, args...) + command := exec.CommandContext(ctx, os.Args[0], cmdArgs...) + command.Dir = dir + // Isolate from host store environment variables and prevent external network calls. + command.Env = append(os.Environ(), + serverExitHelperEnv+"=1", + "HOME_JWT=", "home_jwt=", + "PGSTORE_DSN=", "pgstore_dsn=", + "GITSTORE_GIT_URL=", "gitstore_git_url=", + "OBJECTSTORE_ENDPOINT=", "objectstore_endpoint=", + "DEPLOY=", "WRITABLE_PATH=", "writable_path=", + "HTTP_PROXY=http://127.0.0.1:1", "HTTPS_PROXY=http://127.0.0.1:1", + "NO_PROXY=127.0.0.1,localhost", + ) + stdout := &bytes.Buffer{} + stderr := &bytes.Buffer{} + command.Stdout = stdout + command.Stderr = stderr + return command, stdout, stderr +} + +func writeTestServerConfig(t *testing.T, dir string, port int) string { + t.Helper() + configPath := filepath.Join(dir, "config.yaml") + content := fmt.Sprintf( + "config-version: 8\nserver:\n host: 127.0.0.1\n port: %d\nmanagement:\n secret-key: \"$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy\"\n disable-control-panel: true\noauth:\n auth-dir: %q\naccess:\n api-keys: [test-server-exit-key]\n", + port, + filepath.Join(dir, "auths"), + ) + if errWrite := os.WriteFile(configPath, []byte(content), 0o600); errWrite != nil { + t.Fatal(errWrite) + } + return configPath +} + +func TestMissingConfigExitsWithFailure(t *testing.T) { + dir := t.TempDir() + missingPath := filepath.Join(dir, "missing.yaml") + command, stdout, stderr := newServerExitCommand(t, dir, "--config", missingPath) + errRun := command.Run() + if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 { + t.Fatalf("expected exit code 1 for missing config, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s", + errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "failed to load config") { + t.Fatalf("expected config load error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String()) + } + if strings.Contains(stdout.String(), "failed to load config") { + t.Fatalf("did not expect config load error on stdout, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String()) + } +} + +func TestMalformedConfigExitsWithFailure(t *testing.T) { + dir := t.TempDir() + invalidPath := filepath.Join(dir, "invalid.yaml") + if errWrite := os.WriteFile(invalidPath, []byte("routing: [\n"), 0o600); errWrite != nil { + t.Fatal(errWrite) + } + command, stdout, stderr := newServerExitCommand(t, dir, "--config", invalidPath) + errRun := command.Run() + if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 { + t.Fatalf("expected exit code 1 for malformed config, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s", + errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "failed to load config") { + t.Fatalf("expected config load error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String()) + } + if strings.Contains(stdout.String(), "failed to load config") || strings.Contains(stdout.String(), "failed to parse plugin bootstrap config") { + t.Fatalf("did not expect config error/warn diagnostics on stdout, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String()) + } +} + +func TestTUIClientFailureExitsWithFailure(t *testing.T) { + dir := t.TempDir() + configPath := writeTestServerConfig(t, dir, 18317) + command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--tui") + errRun := command.Run() + if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 { + t.Fatalf("expected exit code 1 for TUI failure, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s", + errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "TUI error:") { + t.Fatalf("expected TUI error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String()) + } +} + +func TestTUIStandaloneEmbeddedServerNotReadyExitsWithFailure(t *testing.T) { + listener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + t.Cleanup(func() { + _ = listener.Close() + }) + go func() { + for { + conn, errAccept := listener.Accept() + if errAccept != nil { + return + } + _ = conn.Close() + } + }() + + dir := t.TempDir() + configPath := writeTestServerConfig(t, dir, listener.Addr().(*net.TCPAddr).Port) + command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--tui", "--standalone", "--local-model") + errRun := command.Run() + if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 { + t.Fatalf("expected exit code 1 when standalone embedded server is not ready, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s", + errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "TUI error: embedded server is not ready") { + t.Fatalf("expected embedded server not ready error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String()) + } +} + +func TestTUIStandaloneFailureExitsWithFailure(t *testing.T) { + listener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + port := listener.Addr().(*net.TCPAddr).Port + if errClose := listener.Close(); errClose != nil { + t.Fatal(errClose) + } + + dir := t.TempDir() + configPath := writeTestServerConfig(t, dir, port) + command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--tui", "--standalone", "--local-model") + errRun := command.Run() + if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 { + t.Fatalf("expected exit code 1 for standalone TUI failure, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s", + errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "TUI error:") { + t.Fatalf("expected TUI error on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String()) + } +} + +func TestServerOccupiedPortExitsWithFailure(t *testing.T) { + listener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + t.Cleanup(func() { + _ = listener.Close() + }) + + dir := t.TempDir() + configPath := writeTestServerConfig(t, dir, listener.Addr().(*net.TCPAddr).Port) + command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--local-model") + errRun := command.Run() + if command.ProcessState == nil || command.ProcessState.ExitCode() != 1 { + t.Fatalf("expected exit code 1 for occupied port, got err=%v exit=%d\nstdout:\n%s\nstderr:\n%s", + errRun, command.ProcessState.ExitCode(), stdout.String(), stderr.String()) + } + if !strings.Contains(stderr.String(), "failed to start HTTP server") { + t.Fatalf("expected HTTP bind failure on stderr, got:\nstdout:\n%s\nstderr:\n%s", stdout.String(), stderr.String()) + } +} + +func TestServerInterruptExitsSuccessfully(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("os.Interrupt cannot be sent to a process on Windows") + } + listener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + port := listener.Addr().(*net.TCPAddr).Port + if errClose := listener.Close(); errClose != nil { + t.Fatal(errClose) + } + + dir := t.TempDir() + configPath := writeTestServerConfig(t, dir, port) + command, stdout, stderr := newServerExitCommand(t, dir, "--config", configPath, "--local-model") + if errStart := command.Start(); errStart != nil { + t.Fatal(errStart) + } + t.Cleanup(func() { + _ = command.Process.Kill() + }) + + done := make(chan error, 1) + go func() { + done <- command.Wait() + }() + + deadline := time.NewTimer(10 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + + for { + connection, errDial := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), 100*time.Millisecond) + if errDial == nil { + _ = connection.Close() + break + } + select { + case errWait := <-done: + t.Fatalf("server exited before listening: %v\nstdout:\n%s\nstderr:\n%s", errWait, stdout.String(), stderr.String()) + case <-deadline.C: + t.Fatal("server did not start listening") + case <-ticker.C: + } + } + + if errSignal := command.Process.Signal(os.Interrupt); errSignal != nil { + t.Fatal(errSignal) + } + if errWait := <-done; errWait != nil { + t.Fatalf("expected a successful interrupt shutdown, got %v\nstdout:\n%s\nstderr:\n%s", errWait, stdout.String(), stderr.String()) + } +} diff --git a/config.example.yaml b/config.example.yaml index 90311aeb898..d90538ba829 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -57,6 +57,14 @@ server: # - 127.0.0.1 # - 192.0.2.0/24 + # Graceful shutdown drain budget, in seconds. When the process receives SIGINT/SIGTERM, + # in-flight HTTP requests are allowed to finish for up to this many seconds before + # remaining connections are forcibly closed. Shutdown never hangs longer than this budget. + # Default 0 keeps the legacy behavior: close immediately without draining. + # Note: hijacked connections (WebSocket sessions) are not drained; they are + # released by their own connection managers after the drain window. + shutdown-timeout: 0 + # TLS settings for HTTPS. When enabled, the server listens with the provided certificate and key. tls: enable: false @@ -170,11 +178,28 @@ routing: strategy: "round-robin" # round-robin (default), weighted-round-robin, fill-first # weighted-round-robin uses each credential's integer weight (default 1, maximum 1,000,000). # Non-positive weights exclude the credential while this strategy is active. + # Sticky requests (including inherited and LCP bindings) also consume weighted credits + # without moving existing bindings. Compensation is scoped to each eligible credential set; + # priority tiers, transport preferences, and retry/cooldown subsets do not share credits. + # Pinned requests use the eligible pool before pinning, within the pinned credential + # priority tier and transport class, even when session-affinity is disabled. + # Returning to a pool resumes its retained credits. + # Settled credits are capped at +/-32 times the eligible pool total; ratios are approximate. + # In-flight offsets are preserved until the pool settles, regardless of commit order. + # Sticky requests keep their bindings but stop adding compensation when the full + # credit delta cannot fit the cap; new sessions keep earning credit to avoid starvation. + # Credits are process-local and reset on restart or selector replacement. + # In Home mode, compatible Home versions charge retained WS turns from usage after completion; + # CPA preserves the retained credential and concurrency slot instead of redispatching each turn. # For OAuth/file credentials, add a top-level numeric "weight" field to the auth JSON. # Enable universal session-sticky routing for all clients. - # Explicit Claude Code, Codex, OpenCode, and pi session headers are preferred, - # followed by prompt_cache_key, Responses conversation IDs, legacy body IDs, - # execution or derived session identity, and the existing first-message hash fallback. + # Explicit Claude Code, Codex, OpenCode, pi, and generic (X-Session-ID) session headers + # are preferred, followed by prompt_cache_key, Responses conversation IDs, legacy body IDs, + # execution session identity, Merkle LCP prefix/compaction matching, derived session + # identity, and the existing first-message hash fallback. + # LCP compaction matching requires at least 2 shared trailing turns; clients whose + # compaction replaces all earlier turns with a summary should send X-Session-ID (or + # another explicit session ID), or affinity starts a new binding at every compaction. # Automatic failover is always enabled when bound auth becomes unavailable. # An established binding outranks credential priority: once a session is bound, that # credential is kept even if a higher-priority credential recovers. Credential priority @@ -198,6 +223,8 @@ routing: # - "quota": transient errors (408, 5xx, empty stream, buffer limit) fail over for that # request only while keeping the session bound to its original credential; quota and auth # errors (429, 401/402/403, 404/model support, invalid_grant) rebind as normal. + # - "never": never move or fail over an established session to another credential; + # keep the binding and return the error (or retry the same credential) instead. # Ignored when routing.session-affinity is false. session-affinity-rebind-on: "any" @@ -280,7 +307,7 @@ requests: # default: # Default rules only set parameters when they are missing in the payload. # - models: # - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*") - # protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity + # protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity, meta # from-protocol: "responses" # restricts the rule to the source protocol, options: openai, responses, gemini, claude # headers: # all configured request headers must match; values support "*" wildcards # X-Client-Tier: "tenant-*-region-*" @@ -294,10 +321,15 @@ requests: # - "metadata.disable_payload" # params: # JSON path (gjson/sjson syntax) -> value # "generationConfig.thinkingConfig.thinkingBudget": 32768 + # - models: + # - name: "muse-*" + # protocol: "meta" + # params: + # prompt_cache_retention: "24h" # opt into Meta's 24h prompt cache when the client omits prompt_cache_retention # default-raw: # Default raw rules set parameters using raw JSON when missing (must be valid JSON). # - models: # - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*") - # protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity + # protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity, meta # params: # JSON path (gjson/sjson syntax) -> raw JSON value (strings are used as-is, must be valid JSON) # "generationConfig.responseJsonSchema": "{\"type\":\"object\",\"properties\":{\"answer\":{\"type\":\"string\"}}}" # override: # Override rules always set parameters, overwriting any existing values. @@ -310,7 +342,7 @@ requests: # service_tier: priority # - models: # - name: "gpt-*" # Supports wildcards (e.g., "gpt-*") - # protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity + # protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity, meta # params: # JSON path (gjson/sjson syntax) -> value # "reasoning.effort": "high" # - models: @@ -321,13 +353,13 @@ requests: # override-raw: # Override raw rules always set parameters using raw JSON (must be valid JSON). # - models: # - name: "gpt-*" # Supports wildcards (e.g., "gpt-*") - # protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity + # protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity, meta # params: # JSON path (gjson/sjson syntax) -> raw JSON value (strings are used as-is, must be valid JSON) # "response_format": "{\"type\":\"json_schema\",\"json_schema\":{\"name\":\"answer\",\"schema\":{\"type\":\"object\"}}}" # filter: # Filter rules remove specified parameters from the payload. # - models: # - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*") - # protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity + # protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity, meta # params: # JSON paths (gjson/sjson syntax) to remove from the payload # - "generationConfig.thinkingConfig.thinkingBudget" # - "generationConfig.responseJsonSchema" @@ -473,6 +505,16 @@ upstream: # Default false keeps the translation and catalog behavior that predate tool_search support. tool-search: false + # When true, inject Anthropic server-side refusal fallbacks on cloaked Claude requests + # when the request body does not already specify fallbacks (claude-opus-5-5 -> claude-opus-4-8, + # claude-fable-5-1 -> claude-opus-5). Default false never opts requests into cross-model + # fallback unless the caller or requests.payload rules explicitly provide fallbacks. + # When fallback occurs, translated OpenAI Chat Completions and Responses payloads report + # the actual serving model and attach structured fallback metadata (choices[0].delta.fallback / + # choices[0].message.fallback and fallbacks for Chat; response.fallback and response.fallbacks + # for Responses). + server-side-fallback: false + # Days to retain the cloaked currentDate pin per session in in-memory mode # (server.kv-store.disabled: true without Home), so an idle gap or a credential # switch cannot re-anchor the date and invalidate earlier thinking signatures and the @@ -512,9 +554,9 @@ upstream: # the same exact software baseline rather than learning newer client versions (unless the # credential resolves to cloak_mode: never, which preserves the confirmed caller's headers). # header-defaults: - # user-agent: "claude-cli/2.1.280 (external, cli)" - # package-version: "0.112.1" - # runtime-version: "v26.3.0" + # user-agent: "claude-cli/2.1.321 (external, cli)" + # package-version: "0.128.0" + # runtime-version: "v26.12.1" # os: "MacOS" # arch: "arm64" # timeout: "600" @@ -729,6 +771,7 @@ upstream: # max-context-length: 1048576 # optional: override Codex client context window metadata # force-mapping: true # optional: rewrite response model fields back to the alias # # Preserve thinking blocks with empty signatures for compatible upstreams. +# # Also handle compaction_trigger requests with local summary compaction instead of forwarding them upstream. # # client.codex.optimize-multi-agent-v2 applies to both OAuth and API-key credentials. # is-compat: false # # Optional: enable configuration_update for this API-key model; omitted defaults to false. @@ -792,7 +835,7 @@ upstream: # rebuild-mid-system-message: false # optional: default is false; when true, move messages with role "system" into the top-level Claude system field # native-tool-search: false # optional: default is false; when true, trust this key's custom base-url with Anthropic native tool search (defer_loading + tool_reference) for Codex tool_search; requires upstream.claude.tool-search: true # cloak: # optional: explicitly enable request cloaking for non-Claude-Code clients -# mode: "auto" # "auto" (default inside this block): cloak only when client is not Claude Code +# mode: "auto" # omitted inherits shared default; explicit "auto": cloak only when client is not Claude Code # # "always": cloak every unconfirmed client; confirmed native Claude Code still passes through # # "never" / "uncloak": never apply cloaking; on non-CLI API keys, also strip incoming Claude Code identity/billing attribution # # This "cloak" block applies to this api-keys.claude key entry only. For Claude OAuth @@ -805,6 +848,11 @@ upstream: # sensitive-words: # optional: words to obfuscate with zero-width characters # - "API" # - "proxy" +# sensitive-words-replace: # optional: literal sensitive-word replacements ("target": "replacement") +# "Claude Code": "Claude" +# sensitive-patterns-replace: # optional: ordered Go RE2 regex replacements ("replacement": "" deletes matches) +# - pattern: '(?m)^You are omp[^\n]*\n?' +# replacement: "" # cache-user-id: true # optional: default is false; set true to reuse cached user_id per API key instead of generating a random one each request # # Every custom tool on a cloaked OAuth request automatically uses a caller-stable opaque mcp____ alias. # @@ -1177,13 +1225,22 @@ oauth: # Antigravity provider behavior. antigravity: - # sensitive-words: # optional: words to obfuscate with zero-width characters in system instructions + # sensitive-words: # optional: words to obfuscate with combining grapheme joiners (U+034F) in system instructions # - "API" # - "proxy" + # sensitive-words-replace: # optional: literal sensitive-word replacements ("target": "replacement") in system instructions + # "You are Codex, an agent based on GPT-5.": "You are a helpful coding assistant." + # sensitive-patterns-replace: # optional: ordered Go RE2 regex replacements in system instructions (deleting flagged text with "" is recommended over obfuscation for Antigravity) + # - pattern: '(?m)^RFC 2119[^\n]*\n?' + # replacement: "" + # - pattern: '(?s).*?\n?' + # replacement: "" # connection-pool: # optional: upstream HTTP connection pool settings # enabled: false # whether to enable connection pooling (default: false) # idle-conn-timeout: "30s" # idle keep-alive timeout (default: 30s, capped at 210s) # max-idle-conns-per-host: 2 # max idle connections per host per credential (default: 2) + # tos-pause-window: "6h" # optional: pool-wide protective pause after the first 403 TOS_VIOLATION + # (default "6h"; set "0"/"off"/"false"/"none"/"disabled" to disable the pause) # Use credits as a last resort after free-tier Claude quota is exhausted. antigravity-credits: true @@ -1199,9 +1256,14 @@ oauth: # Devin provider behavior. # devin: - # sensitive-words: # optional: words to obfuscate with zero-width characters in system instructions and prompts + # sensitive-words: # optional: words to remove matching lines in system prompts # - "API" # - "proxy" + # sensitive-words-replace: # optional: literal sensitive-word replacements ("target": "replacement") in system prompts + # "Claude Code": "Claude" + # sensitive-patterns-replace: # optional: ordered Go RE2 regex replacements in system prompts ("replacement": "" deletes matches) + # - pattern: '(?m)^You are omp[^\n]*\n?' + # replacement: "" # Image and video behavior. multimedia: diff --git a/docs/codex-refresh-recovery.md b/docs/codex-refresh-recovery.md index bd84b35196e..4cd284ebbb1 100644 --- a/docs/codex-refresh-recovery.md +++ b/docs/codex-refresh-recovery.md @@ -1,6 +1,6 @@ # Codex refresh recovery -A lost refresh response does not establish whether the provider consumed the refresh token. CLIProxyAPI records a claim **before** sending a Codex or local SIWC refresh request. Transport failures, unreadable or invalid successful responses, and HTTP responses without a qualified no-effect contract stop replay. A 429 or 5xx status alone is not such a contract. Redirects cannot replay refresh POSTs. +A lost refresh response does not establish whether the provider consumed the refresh token. CLIProxyAPI records a claim **before** sending a Codex or local SIWC refresh request. Failures proven to occur before any request bytes can be written (request creation, DNS resolution, TCP/proxy dial, HTTP proxy `CONNECT`, and origin TLS handshake prior to connection handoff) release the pending claim so the grant can be retried later; on macOS, maintenance wakes lacking interactive power capabilities also defer renewal before claiming. Ambiguous post-connection transport failures, unreadable or invalid successful responses, and HTTP responses without a qualified no-effect contract keep the claim and stop replay. A 429 or 5xx status alone is not such a contract. Redirects cannot replay refresh POSTs. ## Recovery diff --git a/docs/management-api-v8.md b/docs/management-api-v8.md index f91304442d9..3dbc15daf73 100644 --- a/docs/management-api-v8.md +++ b/docs/management-api-v8.md @@ -64,6 +64,48 @@ The Home-owned revision fields `credentials.concurrency.observation-barrier-revision`, and `plugins.auth-revision` cannot be changed through these endpoints. +### Weighted routing with session affinity + +Set `routing.strategy` to `weighted-round-robin` to use per-credential integer +`weight` values (default `1`, maximum `1000000`; non-positive values are excluded). +With `routing.session-affinity` enabled, sticky requests, parent inheritance, +Guardian selections, and LCP matches also consume weighted credits without moving +existing bindings. New or reselected sessions favor under-served credentials +within the same eligible credential set. For example, with weights `3:1`, four +sticky requests to the second credential can be compensated by twelve new +requests to the first when both remain eligible. + +Different priority tiers, transport preferences, and retry/cooldown candidate +sets keep separate credits; returning to a set resumes its retained credits. +Pinned requests account against the eligible pool before pinning, within the +pinned credential's priority tier and transport class, even when session affinity +is disabled. Pinned and ordinary requests share the same weighted credits. A +lower-priority binding never shifts the request ratio among higher-priority credentials. + +Settled credits are capped at ±32 times the eligible pool total, so request +ratios are approximate rather than guaranteed. While reservations are in flight, +committed balances can temporarily exceed the cap; their pending offsets remain +intact until the pool settles, including when the last reservation rolls back. Sticky requests still use their binding at +the cap, but stop adding compensation when their full credit delta cannot fit. +New sessions continue repaying debt and earning credit, so excessive sticky +traffic does not starve smaller-weight peers. + +Credits are local to the CPA process and reset on restart, selector replacement, +or bounded pool-cache eviction. Concurrent selections see pending credit; local +selection/binding success confirms it, while failure releases it. In Home mode, +scheduling and credit accounting remain owned by Home. With matching CPA and Home +versions, retained WebSocket responses (including Codex duplex successors) report +`home_selection.reused` through usage so Home can charge later turns without +redispatching or acquiring another concurrency slot. The scheduling model is +carried separately from the upstream model. First-turn primary usage does not +charge again. Split additional-model billing records (such as image usage) carry +`home_selection.additional` and never add scheduling charges, even when they have +independent execution IDs. Each reused execution is charged once through primary +usage; redelivery of that execution ID is deduplicated. +Compensation arrives after completion and uses Home's current eligible +pool and API-key permissions, so it remains approximate. Old peers ignore the +optional metadata; missing usage cannot compensate a reused turn. + ### Codex multi-agent configuration migration `client.codex.optimize-multi-agent-v2` is the sole runtime setting. Loading older @@ -114,7 +156,7 @@ retain the corresponding business operation's fields. | `/oauth/callback` | GET, POST | Submit an OAuth callback. | | `/plugins` | GET | List installed plugins. | | `/plugins/` | DELETE | Delete a plugin. | -| `/plugins/store` | GET | List the plugin store. | +| `/plugins/store` | GET | List the plugin store (supports optional `?refresh=true` to bypass cached release checks). | | `/plugins/store//install` | POST | Install or update a plugin. | | `/plugins//quota` | GET, POST, DELETE | Read, fetch, or reset plugin quota. | diff --git a/docs/pinable/upstream-sync.md b/docs/pinable/upstream-sync.md index dc871c663c9..634018b3ad9 100644 --- a/docs/pinable/upstream-sync.md +++ b/docs/pinable/upstream-sync.md @@ -1,3 +1,35 @@ +# 2026-11-14 synchronization target + +This synchronization integrates upstream stable `v8.0.70` +(`905e70c48b47b7a1cb4a27dd3abc901e2cdd1e4a`) into fork main +`f4d741cb55474c7ac47646e9139c24bb1be457b3`: 108 upstream commits while +preserving all 53 fork-only commits and both merge parents. The Go module +remains `/v8`; the Desktop host contract remains `1`. + +Conflict resolution combines upstream's explicit startup exit statuses and +plugin interceptor host with Pinable's version-only entrypoint, ephemeral keys, +parent supervision and runtime control. Atomic config replacement watches remain +alongside upstream's synchronized auth-directory switching. Where upstream now +provides equivalent websocket/interrupt test synchronization, use its guarded +implementations without duplicating test helpers. + +The packaged runtime smoke now also checks authenticated +`GET /v8/management/config` returns a JSON object and rejects unauthenticated or +public-API credentials. Existing v8 config migration, v0 host control, native +discovery, ephemeral key isolation and shutdown checks remain enabled. This +verifies the management center's backend endpoint, not the user's installed +Desktop process or cached management HTML. + +The provider session-registration test now uses cancellation-aware in-process +fakes for every built-in provider. This prevents asynchronous device polling +from escaping a restored global HTTP transport and contacting live OAuth +endpoints; production authentication is unchanged. + +The immutable runtime version remains source timestamp plus commit SHA, generated +by the existing main workflow. Merge with a merge commit, never squash/rebase. +Stable runtime publication still requires all six native platform packages and +quality checks. No Desktop installation or deployment is changed by this sync. + # 2026-11-08 synchronization target This synchronization integrates upstream `router-for-me/CLIProxyAPI` at diff --git a/docs/websocket-tunnel.md b/docs/websocket-tunnel.md new file mode 100644 index 00000000000..cc06e66129b --- /dev/null +++ b/docs/websocket-tunnel.md @@ -0,0 +1,531 @@ +# WebSocket Tunnel Integration Guide + +CLIProxyAPI provides a built-in, multi-tenant, many-to-many **WebSocket Tunnel** (`GET /v1/tunnel`) that relays opaque packets between authenticated **Client** and **Server** devices. CLIProxyAPI acts strictly as a zero-inspection packet switch: it enforces `access.api-keys` tenant isolation, tracks online device topology, verifies sender identity headers, and forwards payloads without inspecting or mutating business content. + +--- + +## 1. Architecture & Core Guarantees + +```text + +-----------------------------------------+ + | CLIProxyAPI (GET /v1/tunnel) | + | | + [Client C1] <===> Tenant Realm (access.api-keys[0]) <===> [Server S1] + [Client C2] <===> - Single WS connection per peer <===> [Server S2] + | - Full-duplex N x M multiplexing | + +-----------------------------------------+ + | Tenant Realm (access.api-keys[1]) | + [Client C3] <===> (Completely invisible to [0]) <===> [Server S3] + +-----------------------------------------+ +``` + +1. **Mandatory `access.api-keys` Authentication & Tenant Isolation**: + - Every connection must authenticate against an entry configured under `access.api-keys` in `config.yaml`. + - Unlike AI proxy endpoints that may allow unauthenticated access when `access.api-keys` is empty, `/v1/tunnel` **always rejects** connections (`401 Unauthorized`) if `access.api-keys` is empty or unmatched. + - Peers authenticated under different `access.api-keys` are **completely invisible** to one another. They do not share server lists, cannot route packets across keys, and do not share UUID uniqueness namespaces. +2. **Device Identity (`uuid` + `name` + Server `type`) & Uniqueness**: + - Every connecting peer (both `client` and `server`) must declare its `role`, `uuid`, and `name`. Connecting `server` peers must additionally declare a non-empty `type` (arbitrary free-form input, at least 1 non-whitespace character). + - Within the same `access.api-key` realm, **`uuid` is strictly unique across all connected clients and servers**. Duplicate online UUIDs are rejected during the HTTP handshake with `409 Conflict` (existing connections are never kicked). Once the previous connection closes, the same `uuid` may reconnect immediately. + - **`name` and server `type` may be duplicated** across multiple devices. +3. **Single Multiplexed WebSocket Connection per Device**: + - Each device maintains exactly one WebSocket connection and multiplexes all control events and multi-peer data streams over it: + - **Text frames (`Opcode 0x1`)** carry UTF-8 JSON control messages (discovery & non-fatal routing errors). + - **Binary frames (`Opcode 0x2`)** carry secondary-encapsulated business packets (4-byte fixed header + source UUID + destination UUID + opaque raw payload). +4. **Payload Agnosticism**: + - Raw payloads can be arbitrary binary streams, encrypted frames, Protobuf messages, UTF-8/JSON text, or empty (`0`-byte) signals up to **64 MiB** per frame. + +--- + +## 2. Connecting & Handshake Authentication + +### 2.1 Endpoint + +```http +GET /v1/tunnel HTTP/1.1 +Host: : +Upgrade: websocket +Connection: Upgrade +Sec-WebSocket-Key: +Sec-WebSocket-Version: 13 +``` + +Use `ws://` when TLS is disabled on CLIProxyAPI and `wss://` when `server.tls.enable: true` (or behind a TLS reverse proxy). + +### 2.2 Supplying the `access.api-keys` Credential + +CLIProxyAPI inspects candidate credentials in the following priority order and binds the connection to the **first non-empty candidate that matches a configured `access.api-keys` entry**: + +| Priority | Source | Example | +| --- | --- | --- | +| 1 | `Authorization` header | `Authorization: Bearer sk-your-access-key` (or raw `Authorization: sk-your-access-key`) | +| 2 | `X-Goog-Api-Key` header | `X-Goog-Api-Key: sk-your-access-key` | +| 3 | `X-Api-Key` header | `X-Api-Key: sk-your-access-key` | +| 4 | URL Query `key` | `/v1/tunnel?key=sk-your-access-key&...` (recommended for browser `WebSocket` clients) | +| 5 | URL Query `auth_token` | `/v1/tunnel?auth_token=sk-your-access-key&...` | + +> **Security Note**: Query parameters `key` and `auth_token` are automatically masked in CLIProxyAPI access logs, but HTTP headers (`Authorization: Bearer ...` or `X-Api-Key`) remain preferred whenever the client WebSocket SDK supports custom handshake headers. + +### 2.3 Declaring Role, UUID, Device Name, and Server Type + +Each parameter is read from the **URL Query** first; if omitted or blank in the query string, CLIProxyAPI falls back to the corresponding **`X-Tunnel-*` HTTP header**: + +| Parameter | Query Key | Fallback Header | Constraints | +| --- | --- | --- | --- | +| Role | `role` | `X-Tunnel-Role` | Required. Case-insensitive `"client"` or `"server"` (surrounding whitespace trimmed). | +| Device UUID | `uuid` | `X-Tunnel-UUID` | Required. `1..128` printable non-whitespace ASCII bytes (`0x21..0x7E`) after trimming surrounding whitespace. Must be unique among active connections under the same `api-key`. | +| Device Name | `name` | `X-Tunnel-Name` | Required. `1..256` UTF-8 bytes after trimming surrounding whitespace. Must be valid UTF-8 and must not contain ASCII control characters (`0x00..0x1F` or `0x7F`). Duplicate names are allowed. | +| Server Type | `type` | `X-Tunnel-Type` | Required when `role=server` (at least 1 non-whitespace character); ignored when `role=client`. Arbitrary free-form input, `1..256` UTF-8 bytes after trimming surrounding whitespace. Must be valid UTF-8 and must not contain ASCII control characters (`0x00..0x1F` or `0x7F`). Duplicate types are allowed. | + +**Example Handshake URL (Client)**: + +```text +wss://proxy.example.com/v1/tunnel?role=client&uuid=550e8400-e29b-41d4-a716-446655440000&name=MacBook-Pro +``` + +**Example Handshake URL (Server)**: + +```text +wss://proxy.example.com/v1/tunnel?role=server&uuid=6ba7b810-9dad-11d1-80b4-00c04fd430c8&name=Build-Node-01&type=build-agent +``` + +### 2.4 HTTP Handshake Error Responses + +All authentication, validation, and conflict checks run **before** upgrading the connection. The tunnel handler returns HTTP JSON errors in the form `{"error":""}` for these checks and for a closed hub. Global middleware can reject the request earlier with a different response body (including an empty body), as distinguished below: + +| HTTP Status | Condition | Response Body | +| --- | --- | --- | +| `400 Bad Request` | Invalid/missing `role`, `uuid`, `name`, or (when `role=server`) `type` | `{"error":"invalid or missing role: must be client or server"}` / `{"error":"invalid or missing uuid"}` / `{"error":"invalid or missing name"}` / `{"error":"invalid or missing type"}` | +| `401 Unauthorized` | `access.api-keys` is empty, credential missing, or no candidate matches | `{"error":"invalid or missing api key"}` | +| `403 Forbidden` | Safe-mode active because `access.api-keys` still contains template placeholder keys | `{"error":"unsafe_example_api_key","message":"..."}` | +| `405 Method Not Allowed` | `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `TRACE`, or `CONNECT` (includes `Allow: GET` header) | `{"error":"method not allowed"}` | +| `409 Conflict` | Another client or server with the same `uuid` is already online (or upgrading) under the same `api-key` | `{"error":"device uuid already connected"}` | +| `503 Service Unavailable` | Tunnel hub is closed during server shutdown | `{"error":"tunnel hub is closed"}` | +| `503 Service Unavailable` | Global Home heartbeat gate is unhealthy in Home mode; request is rejected before reaching the tunnel handler | Empty body | + +`HEAD` returns no response body. `OPTIONS /v1/tunnel` is the CORS exception: global CORS middleware returns `204 No Content` for preflight requests without upgrading or authenticating a tunnel connection. + +--- + +## 3. Control Channel Protocol (WebSocket Text Frames) + +All control frames use **WebSocket Text Messages (`Opcode 0x1`)** encoded as UTF-8 JSON objects. The entire message, including unknown fields, nested values, and field names, must be valid UTF-8; invalid bytes return non-fatal `invalid_control_frame` without executing the command. Inbound control messages are limited to **4,096 bytes** (`MaxControlFrameBytes`), across all fragments, before JSON parsing. Larger controls terminate the connection with **`1009 Message Too Big`**, not an `error` frame. The inbound `type` is limited to **64 bytes** and `request_id` to **128 UTF-8 bytes**; field violations within the message-size limit return non-fatal `invalid_control_frame`. Unknown types are not echoed into error messages. Outbound server snapshots may exceed 4 KiB and are governed by the outbound budgets in §5. + +### 3.1 `server_list` (CLIProxyAPI → Client) + +Delivered **as the very first application message** when a `client` connects (if the initial snapshot cannot fit the outbound budgets, the connection instead closes with `1008` before other application messages), and also sent in response to a client's `list_servers` request. The `servers` array is always non-null (`[]` when empty) and sorted lexicographically by `uuid`. + +```json +{ + "type": "server_list", + "request_id": "sync-01", + "servers": [ + { + "uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "name": "Build-Node-01", + "type": "build-agent" + }, + { + "uuid": "7c9e6679-7425-40de-944b-e07fc1f90ae7", + "name": "Build-Node-02", + "type": "build-agent" + } + ] +} +``` + +- `servers[].uuid`, `servers[].name`, `servers[].type` (`string`): Each online server's unique identifier, display name, and declared server type. +- `request_id` (`string`, optional): Omitted on the automatic initial push; echoed verbatim when replying to `list_servers` if the request included a non-empty `request_id`. +- **Causal Ordering Guarantee**: The initial `server_list` snapshot is enqueued atomically under the tenant lock before the client becomes visible to subsequent broadcasts. Any `server_online` or `server_offline` event received after the initial `server_list` strictly reflects state transitions occurring after that snapshot. + +### 3.2 `list_servers` (Client → CLIProxyAPI) + +Clients may query the latest server list at any time over the existing connection: + +```json +{ + "type": "list_servers", + "request_id": "sync-01" +} +``` + +- `request_id` (`string`, optional): `0..128` UTF-8 bytes without ASCII control characters. +- Only `client` peers may send `list_servers`. If a `server` peer sends `list_servers`, CLIProxyAPI replies with an `error` frame (`code: "unsupported_role_action"`). + +### 3.3 `server_online` & `server_offline` (CLIProxyAPI → All Online Clients in Same Tenant) + +Broadcast in real time whenever a `server` connects to or disconnects from the same `access.api-key` realm: + +```json +{ + "type": "server_online", + "server": { + "uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "name": "Build-Node-01", + "type": "build-agent" + } +} +``` + +```json +{ + "type": "server_offline", + "server": { + "uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "name": "Build-Node-01", + "type": "build-agent" + } +} +``` + +- Both `server_online` and `server_offline` carry `server.uuid`, `server.name`, and `server.type`. + +### 3.4 `error` (CLIProxyAPI → Sender Peer) + +Reports a non-fatal protocol or routing error for an individual message **within transport size limits**, without closing the multiplexed WebSocket connection. Oversized messages instead close with `1009` (see §4.3). Errors are best-effort: they may be dropped if the sender's own outbound queue or byte budget is exhausted: + +```json +{ + "type": "error", + "code": "target_not_found", + "target_uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "message": "target peer is not connected" +} +``` + +| Error `code` | Trigger Condition | +| --- | --- | +| `invalid_control_frame` | Text frame contains invalid UTF-8 anywhere, is not valid JSON, is not an object, has an unknown/oversized `type`, or has an invalid `request_id`. | +| `unsupported_role_action` | A `server` peer sent a client-only control command (`list_servers`). | +| `invalid_data_frame` | Binary frame is shorter than 4 bytes, `SrcUUIDLen`/`DstUUIDLen` is `0` or `> 128`, UUID bytes are truncated or contain invalid ASCII, or `RawPayload` exceeds `64 MiB` while total message bytes remain at or below `64 MiB + 512`. Larger messages close with `1009`. | +| `unsupported_version` | Binary frame byte `0` (`Version`) is not `0x01`. | +| `source_uuid_mismatch` | Binary frame `SrcUUID` does not match the sender connection's authenticated `uuid`. | +| `target_not_found` | `DstUUID` is not currently connected under the same `access.api-key` realm. | +| `invalid_target_role` | Attempted same-role routing (`client → client` or `server → server`). | +| `target_buffer_full` | Target peer's outbound frame slots or per-peer/per-tenant byte budget is exhausted. | + +--- + +## 4. Data Channel Secondary Encapsulation Protocol (WebSocket Binary Frames) + +All Client ↔ Server business packets are exchanged as **WebSocket Binary Messages (`Opcode 0x2`)** using a compact, zero-Base64 binary header: + +### 4.1 Wire Frame Layout + +```text + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Version (0x01)| PayloadType | SrcUUIDLen | DstUUIDLen | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| SrcUUID (SrcUUIDLen bytes) | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| DstUUID (DstUUIDLen bytes) | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| RawPayload (0 .. 67,108,864 bytes) | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +``` + +| Byte Offset | Field | Type | Description | +| --- | --- | --- | --- | +| `0` | `Version` | `uint8` | Must be `0x01`. | +| `1` | `PayloadType` | `uint8` | Application-level payload hint (`0x00` = binary, `0x01` = UTF-8 text, `0x02..0xFF` = custom application sub-types). Forwarded verbatim without inspection. | +| `2` | `SrcUUIDLen` | `uint8` | Byte length of `SrcUUID` (`1..128`). | +| `3` | `DstUUIDLen` | `uint8` | Byte length of `DstUUID` (`1..128`). | +| `4 .. 4+SrcUUIDLen-1` | `SrcUUID` | ASCII | **Client → Server**: sender's `client_uuid`.
**Server → Client**: sender's `server_uuid`. | +| `4+SrcUUIDLen .. 4+SrcUUIDLen+DstUUIDLen-1` | `DstUUID` | ASCII | **Client → Server**: target `server_uuid`.
**Server → Client**: target `client_uuid`. | +| `4+SrcUUIDLen+DstUUIDLen .. end` | `RawPayload` | `[]byte` | Opaque business packet (`0` bytes up to `64 MiB` / `67,108,864` bytes). | + +### 4.2 Routing & Anti-Spoofing Rules + +1. **Client → Server Encapsulation**: + - The client encapsulates its raw payload with `SrcUUID = ` and `DstUUID = `. + - CLIProxyAPI verifies `SrcUUID == authenticated_client.uuid` and confirms `DstUUID` is an online `server` in the same `api-key` realm, then forwards the binary frame to that server. + - The server decapsulates the frame, obtaining the verified `client_uuid` (`SrcUUID`) and `RawPayload`. +2. **Server → Client Encapsulation**: + - To reply or push unsolicited data to any connected client, the server encapsulates its raw payload with `SrcUUID = ` and `DstUUID = `. + - CLIProxyAPI verifies `SrcUUID == authenticated_server.uuid` and confirms `DstUUID` is an online `client` in the same `api-key` realm, then forwards the binary frame to that client. + - The client decapsulates the frame, obtaining the verified `server_uuid` (`SrcUUID`) and `RawPayload`. +3. **Many-to-Many Multiplexing**: + - A single client can interleave frames to `S1`, `S2`, ..., `Sm` on its single WebSocket connection. + - A single server can interleave frames to `C1`, `C2`, ..., `Cn` on its single WebSocket connection. + +### 4.3 Message Size Boundaries + +Sizes refer to the reassembled WebSocket message body (the tunnel header and payload), excluding RFC 6455 framing/masking bytes. Fragmentation does not bypass limits. + +| Boundary | Behavior | +| --- | --- | +| Binary raw payload `0..64 MiB` (`67,108,864` bytes), valid header | Accepted, subject to routing and outbound budgets. | +| Binary raw payload `>64 MiB`, total message `<=MaxInboundFrameBytes` (`67,109,376` bytes) | Non-fatal `invalid_data_frame`; connection stays open. For 1-byte source/destination UUIDs, a `64 MiB + 1` payload has a 6-byte header and falls here. | +| Any binary message `>MaxInboundFrameBytes = 64 MiB + 512` | Bounded reading detects the excess and requests **`1009 Message Too Big`** through the tunnel’s single-writer close flow; no JSON error is promised. At exactly the limit the message reaches protocol validation (and an oversized payload is rejected non-fatally). | +| Inbound text control message `>4,096` bytes | Terminates with **`1009 Message Too Big`** before JSON parsing; no `invalid_control_frame` response. Exactly 4,096 bytes is allowed if valid. | + +### 4.4 Fatal Transport Close Codes + +| Close Code | Trigger Condition | +| --- | --- | +| `1002 Protocol Error` | Invalid, unknown, or reserved WebSocket opcodes, invalid close codes, and invalid UTF-8 close reasons are rejected by the RFC 6455 transport layer before tunnel message dispatch. The connection terminates; no non-fatal `invalid_control_frame` JSON response is sent. | +| `1009 Message Too Big` | A reassembled message exceeds a transport size limit described in §4.3. The connection terminates instead of returning a JSON error. | + +--- + +## 5. Connection Lifecycle, Keepalive & Hot-Reload Behavior + +- **Heartbeat (Ping / Pong)**: + - CLIProxyAPI sends a WebSocket `Ping` control frame every **30 seconds** and imposes no artificial read/write timeouts on idle connections. Standard WebSocket libraries (browser `WebSocket`, `gorilla/websocket`, `ws`, URLSession, Tungstite) automatically reply with `Pong`. For incoming Pings, CLIProxyAPI keeps only the latest pending Pong payload (at most 125 bytes) in a bounded, non-blocking slot; its single writer sends Pongs with no write deadline. Peer-initiated Close frames use the same close state machine and single writer, replying with the received code and an empty reason without a write deadline. +- **Transport Deadline Protection**: + - After a successful upgrade, a connection wrapper suppresses all finite `SetDeadline`, `SetReadDeadline`, and `SetWriteDeadline` calls before they reach the underlying connection. Zero deadlines still pass through. A streaming inspector checks incoming RFC 6455 headers and masked Close payloads before Gorilla receives them, retaining only a fixed-size header and at most 125 Close payload bytes, without copying data payloads. Fatal framing errors immediately unregister the peer, free its UUID, broadcast `server_offline` for a server, and start bounded local reclamation, without waiting for Gorilla’s write token or its 1-second protocol-error write timer. An already active socket write is interrupted by immediately closing the raw transport; otherwise, the single writer sends `1002`, with a 1-second local grace period if that close stalls. Interrupted peers may observe `1006`; no socket deadline is installed. Gorilla v1.5.3 rejects any pipelined bytes buffered by HTTP Hijack before sending `101`, so accepted post-upgrade input cannot bypass the inspector. Binary and text size limits use bounded reassembled-message reads rather than Gorilla’s `SetReadLimit`, so oversized messages close with `1009` through the tunnel’s single writer. +- **Configuration Hot-Reload (`access.api-keys` Revocation)**: + - When `config.yaml` is reloaded or updated via Management API v8, if an `access.api-key` is removed, CLIProxyAPI immediately unregisters all client and server connections under that key and requests WebSocket Close **`1008` (`ClosePolicyViolation`, `"api key revoked"`)** asynchronously. The single writer finishes any active healthy write, prioritizes the close frame, discards remaining queued frames, and closes the socket. Connections under unchanged keys continue uninterrupted. + - Revocation also immediately invalidates and clears all pending UUID reservations. Re-adding the same key allows a fresh connection with the same UUID immediately. Any pre-revocation handshake that later finishes upgrading still receives `1008` (`"api key revoked"`); its commit or failed-upgrade cleanup cannot remove a newer reservation or replace the new connection. +- **Server Shutdown**: + - When CLIProxyAPI stops, it immediately unregisters active tunnel connections and asynchronously requests WebSocket Close **`1001` (`CloseGoingAway`, `"server shutting down"`)** using the same close state machine. + - Revocation and shutdown never wait for socket writes. A **1-second local close grace period** forces socket reclamation if the close/active write stalls; this installs no read/write deadlines and does not limit active connections. Healthy readers receive the requested close code even with queued/active writes; genuinely stalled peers may observe abnormal closure (`1006`) instead. This fallback cannot delay revocation or shutdown of other peers. +- **Slow-Consumer Protection**: + - Each connection has an isolated 256-frame outbound queue. **All outbound JSON control and binary data bytes, including in-flight writes**, count toward a **per-peer budget of `64 MiB + 512` bytes** and a **per-API-key tenant budget of `256 MiB`**. The API server constructs its internal Hub with these built-in defaults. `internal/wstunnel.Options` (`SendQueueSize`, `MaxPeerQueuedBytes`, `MaxTenantQueuedBytes`) is only for internal Hub construction within CLIProxyAPI; it is not importable or configurable by external SDK consumers, nor exposed as YAML settings. For internal construction only, an unspecified tenant limit defaults to the larger of 256 MiB and the per-peer limit. There is no shared cross-tenant budget. Reservations are released after writing or discarding frames. In-flight write bytes remain charged to the API key's `256 MiB` tenant budget across disconnects and reconnects until the underlying socket write drains or is reclaimed. + - Per-peer exhaustion rejects only that target, so healthy peers in the same tenant continue exchanging while tenant budget remains available. Tenant-wide exhaustion rejects further enqueues only within that tenant; other tenants remain unaffected. Rejected data sends produce `{"type":"error","code":"target_buffer_full","target_uuid":"..."}` when the sender has room for the error. If an initial/queried `server_list` or a topology broadcast cannot fit its recipient's frame/byte budgets, CLIProxyAPI requests `1008` (`"control queue overflow"`), forcing resynchronization after reconnect rather than silently losing topology state. + +### Recommended Client State Machine + +1. Connect to `GET /v1/tunnel` with `role=client`, `uuid`, `name`, and `api-key`. +2. On open, wait for the first text frame (`type == "server_list"`) to initialize the local `Map` of online servers. +3. On `server_online`, insert `msg.server.uuid -> { name: msg.server.name, type: msg.server.type }`. +4. On `server_offline`, remove `msg.server.uuid` and fail/retry any pending application requests targeting that server. +5. On disconnect: + - If close code is `1008` (`api key revoked`), stop retrying until credentials are updated; + - If HTTP handshake returned `409 Conflict`, ensure no duplicate instance shares the same `uuid`, then retry with exponential backoff; + - Otherwise, reconnect with exponential backoff and rebuild local server state from the new initial `server_list`. + +--- + +## 6. Reference Implementation Examples + +### 6.1 TypeScript / JavaScript (Browser & Node.js) + +```typescript +const PROTOCOL_VERSION = 0x01; +export const PAYLOAD_BINARY = 0x00; +export const PAYLOAD_TEXT = 0x01; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +export interface DecodedTunnelPacket { + version: number; + payloadType: number; + srcUUID: string; + dstUUID: string; + payload: Uint8Array; +} + +export function encodeTunnelPacket( + payloadType: number, + srcUUID: string, + dstUUID: string, + payload: Uint8Array, +): Uint8Array { + const srcBytes = textEncoder.encode(srcUUID); + const dstBytes = textEncoder.encode(dstUUID); + if (srcBytes.length < 1 || srcBytes.length > 128) { + throw new Error("invalid srcUUID length"); + } + if (dstBytes.length < 1 || dstBytes.length > 128) { + throw new Error("invalid dstUUID length"); + } + const frame = new Uint8Array(4 + srcBytes.length + dstBytes.length + payload.length); + frame[0] = PROTOCOL_VERSION; + frame[1] = payloadType & 0xff; + frame[2] = srcBytes.length; + frame[3] = dstBytes.length; + frame.set(srcBytes, 4); + frame.set(dstBytes, 4 + srcBytes.length); + frame.set(payload, 4 + srcBytes.length + dstBytes.length); + return frame; +} + +export function decodeTunnelPacket(raw: ArrayBuffer | Uint8Array): DecodedTunnelPacket { + const bytes = raw instanceof Uint8Array ? raw : new Uint8Array(raw); + if (bytes.length < 4) { + throw new Error("binary frame shorter than 4-byte header"); + } + const version = bytes[0]; + if (version !== PROTOCOL_VERSION) { + throw new Error(`unsupported protocol version: ${version}`); + } + const payloadType = bytes[1]; + const srcLen = bytes[2]; + const dstLen = bytes[3]; + const headerLen = 4 + srcLen + dstLen; + if (srcLen < 1 || dstLen < 1 || bytes.length < headerLen) { + throw new Error("malformed tunnel packet header"); + } + return { + version, + payloadType, + srcUUID: textDecoder.decode(bytes.subarray(4, 4 + srcLen)), + dstUUID: textDecoder.decode(bytes.subarray(4 + srcLen, headerLen)), + payload: bytes.subarray(headerLen), + }; +} + +// Browser / Node 22+ Client Usage Example: +export function connectTunnelClient(baseWsUrl: string, apiKey: string, clientUUID: string, clientName: string) { + const params = new URLSearchParams({ + key: apiKey, + role: "client", + uuid: clientUUID, + name: clientName, + }); + const ws = new WebSocket(`${baseWsUrl}/v1/tunnel?${params.toString()}`); + ws.binaryType = "arraybuffer"; + + const servers = new Map(); + + ws.onmessage = (event) => { + if (typeof event.data === "string") { + const ctrl = JSON.parse(event.data); + switch (ctrl.type) { + case "server_list": + servers.clear(); + for (const srv of ctrl.servers) { + servers.set(srv.uuid, { name: srv.name, type: srv.type }); + } + break; + case "server_online": + servers.set(ctrl.server.uuid, { name: ctrl.server.name, type: ctrl.server.type }); + break; + case "server_offline": + servers.delete(ctrl.server.uuid); + break; + case "error": + console.warn("Tunnel error:", ctrl.code, ctrl.message, ctrl.target_uuid); + break; + } + return; + } + + const pkt = decodeTunnelPacket(event.data as ArrayBuffer); + // pkt.srcUUID is the verified server UUID; pkt.payload is the raw response bytes. + if (pkt.payloadType === PAYLOAD_TEXT) { + console.log(`Message from server ${pkt.srcUUID}:`, textDecoder.decode(pkt.payload)); + } + }; + + return { + ws, + servers, + sendText(serverUUID: string, text: string) { + ws.send(encodeTunnelPacket(PAYLOAD_TEXT, clientUUID, serverUUID, textEncoder.encode(text))); + }, + sendBinary(serverUUID: string, data: Uint8Array) { + ws.send(encodeTunnelPacket(PAYLOAD_BINARY, clientUUID, serverUUID, data)); + }, + refreshServers(requestId = "manual-refresh") { + ws.send(JSON.stringify({ type: "list_servers", request_id: requestId })); + }, + }; +} +``` + +### 6.2 Go Server Peer Example + +```go +package main + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "sync" + + "github.com/gorilla/websocket" +) + +const ( + ProtocolVersion1 byte = 0x01 + PayloadTypeBinary byte = 0x00 + PayloadTypeText byte = 0x01 +) + +func EncodeFrame(payloadType byte, srcUUID, dstUUID string, payload []byte) ([]byte, error) { + if len(srcUUID) == 0 || len(srcUUID) > 128 || len(dstUUID) == 0 || len(dstUUID) > 128 { + return nil, errors.New("uuid length must be between 1 and 128 bytes") + } + buf := make([]byte, 0, 4+len(srcUUID)+len(dstUUID)+len(payload)) + buf = append(buf, ProtocolVersion1, payloadType, byte(len(srcUUID)), byte(len(dstUUID))) + buf = append(buf, srcUUID...) + buf = append(buf, dstUUID...) + buf = append(buf, payload...) + return buf, nil +} + +func DecodeFrame(raw []byte) (payloadType byte, srcUUID, dstUUID string, payload []byte, err error) { + if len(raw) < 4 { + return 0, "", "", nil, errors.New("short header") + } + if raw[0] != ProtocolVersion1 { + return 0, "", "", nil, fmt.Errorf("unsupported version: %d", raw[0]) + } + srcLen, dstLen := int(raw[2]), int(raw[3]) + headerLen := 4 + srcLen + dstLen + if srcLen < 1 || dstLen < 1 || len(raw) < headerLen { + return 0, "", "", nil, errors.New("malformed header lengths") + } + return raw[1], string(raw[4 : 4+srcLen]), string(raw[4+srcLen : headerLen]), raw[headerLen:], nil +} + +func RunEchoTunnelServer(proxyWSBaseURL, apiKey, serverUUID, serverName, serverType string) error { + q := url.Values{ + "role": {"server"}, + "uuid": {serverUUID}, + "name": {serverName}, + "type": {serverType}, + } + headers := http.Header{ + "Authorization": {"Bearer " + apiKey}, + } + conn, _, errDial := websocket.DefaultDialer.Dial(proxyWSBaseURL+"/v1/tunnel?"+q.Encode(), headers) + if errDial != nil { + return errDial + } + defer func() { + if errClose := conn.Close(); errClose != nil { + fmt.Printf("websocket close error: %v\n", errClose) + } + }() + + var writeMu sync.Mutex + for { + msgType, raw, errRead := conn.ReadMessage() + if errRead != nil { + return errRead + } + if msgType == websocket.TextMessage { + // Non-fatal control/error notifications from CLIProxyAPI + fmt.Printf("control frame: %s\n", string(raw)) + continue + } + if msgType != websocket.BinaryMessage { + continue + } + + pType, clientUUID, dstUUID, body, errDec := DecodeFrame(raw) + if errDec != nil || dstUUID != serverUUID { + continue + } + + // Reply to the originating client over the same multiplexed connection. + reply, errEnc := EncodeFrame(pType, serverUUID, clientUUID, body) + if errEnc != nil { + continue + } + writeMu.Lock() + errWrite := conn.WriteMessage(websocket.BinaryMessage, reply) + writeMu.Unlock() + if errWrite != nil { + return errWrite + } + } +} +``` diff --git a/docs/websocket-tunnel_CN.md b/docs/websocket-tunnel_CN.md new file mode 100644 index 00000000000..1ebdf8cdc0e --- /dev/null +++ b/docs/websocket-tunnel_CN.md @@ -0,0 +1,530 @@ +# WebSocket Tunnel 客户端与服务端对接技术文档 + +CLIProxyAPI 内置支持多租户隔离、多对多全双工复用的 **WebSocket Tunnel**(`GET /v1/tunnel`),用于在已认证的**客户端(Client)**与**服务端(Server)**设备之间透明交换任意数据包。CLIProxyAPI 自身不解析、不修改任何业务载荷内容,仅负责基于 `access.api-keys` 的租户隔离、在线设备发现、源身份防伪造校验以及高速数据包路由转发。 + +--- + +## 1. 架构模型与核心约束 + +```text + +-----------------------------------------+ + | CLIProxyAPI (GET /v1/tunnel) | + | | + [Client C1] <===> 租户隔离域 (access.api-keys[0]) <===> [Server S1] + [Client C2] <===> - 单设备仅维持 1 条 WS 连接 <===> [Server S2] + | - N x M 全双工多路复用交换 | + +-----------------------------------------+ + | 租户隔离域 (access.api-keys[1]) | + [Client C3] <===> (与 [0] 完全隔离、互不可见) <===> [Server S3] + +-----------------------------------------+ +``` + +1. **强制 `access.api-keys` 认证与严格租户隔离**: + - 所有连接必须使用 `config.yaml` 中 `access.api-keys` 配置的密钥完成握手认证。 + - 与普通 AI 代理路由不同,当 `access.api-keys` 未配置(为空)时,`/v1/tunnel` **一律拒绝所有连接**(返回 HTTP `401 Unauthorized`),绝不匿名放行。 + - 不同 `access.api-keys` 下的客户端与服务端**完全互不可见**:不共享在线服务端列表、禁止跨密钥发包、也不共享设备 `uuid` 唯一性命名空间。 +2. **设备身份声明(`uuid` + `name` + 服务端 `type`)与唯一性**: + - 客户端与服务端在连接时均必须声明 `role`、设备唯一标识 `uuid` 与设备名称 `name`;当 `role=server` 时,还必须声明非空的服务端类型 `type`(支持任意自定义输入,至少包含 1 个非空白字符)。 + - 在**同一个 `access.api-key`** 租户域内,同时在线的所有设备(跨 `client` 与 `server`)**不允许 `uuid` 重复**。若某 `uuid` 当前已在线,重复发起的新连接会在 HTTP 握手阶段直接收到 `409 Conflict` 拒绝响应(不会踢掉原有连接);原连接断开后,相同 `uuid` 可立即重连。 + - 不同设备允许使用相同的设备名称(`name` 可重复)与相同的服务端类型(`type` 可重复)。 +3. **单设备单 WebSocket 连接多路复用**: + - 每个设备仅建立并复用一条 WebSocket 长连接,通过原生帧类型隔离控制面与数据面: + - **文本帧(`TextMessage`,Opcode `0x1`)**:承载 UTF-8 JSON 控制信令(服务端列表同步、上下线通知及非致命错误反馈)。 + - **二进制帧(`BinaryMessage`,Opcode `0x2`)**:承载二次封装后的业务数据包(4 字节定长包头 + 发送方 `uuid` + 接收方 `uuid` + 原始业务载荷)。 +4. **业务载荷完全透明**: + - 原始数据包可以是任意二进制字节流、加密流、Protobuf、文件分片、UTF-8/JSON 文本或 `0` 字节空信号包,单帧原始载荷上限为 **64 MiB**。 + +--- + +## 2. 连接建立与握手鉴权规范 + +### 2.1 接入端点 + +```http +GET /v1/tunnel HTTP/1.1 +Host: : +Upgrade: websocket +Connection: Upgrade +Sec-WebSocket-Key: +Sec-WebSocket-Version: 13 +``` + +未启用 TLS 时使用 `ws://`,启用 `server.tls.enable: true`(或部署在 HTTPS 反向代理后)时使用 `wss://`。 + +### 2.2 `access.api-keys` 凭证传递方式 + +CLIProxyAPI 按以下优先级顺序提取候选凭证,并将连接绑定到**第一个非空且命中 `access.api-keys` 配置项的密钥**: + +| 优先级 | 凭证来源 | 示例 | +| --- | --- | --- | +| 1 | `Authorization` 请求头 | `Authorization: Bearer sk-your-access-key`(或直接传 `Authorization: sk-your-access-key`) | +| 2 | `X-Goog-Api-Key` 请求头 | `X-Goog-Api-Key: sk-your-access-key` | +| 3 | `X-Api-Key` 请求头 | `X-Api-Key: sk-your-access-key` | +| 4 | URL Query 参数 `key` | `/v1/tunnel?key=sk-your-access-key&...`(适合浏览器原生 `WebSocket` API) | +| 5 | URL Query 参数 `auth_token` | `/v1/tunnel?auth_token=sk-your-access-key&...` | + +> **安全说明**:CLIProxyAPI 访问日志已自动对 Query 中的 `key` 与 `auth_token` 脱敏,但在支持自定义握手请求头的 SDK 中仍优先推荐使用 `Authorization: Bearer ...` 或 `X-Api-Key` 请求头。 + +### 2.3 角色与设备身份声明参数 + +各字段均优先读取 **URL Query 参数**;若对应 Query 参数缺失或为空白,则自动回退读取同名 **`X-Tunnel-*` 请求头**: + +| 参数含义 | Query 参数名 | 回退请求头名 | 校验规则 | +| --- | --- | --- | --- | +| 连接角色 | `role` | `X-Tunnel-Role` | 必填。去除首尾空白后不区分大小写,仅允许 `"client"` 或 `"server"`。 | +| 设备唯一标识 | `uuid` | `X-Tunnel-UUID` | 必填。去除首尾空白后字节长度为 `1..128`,且所有字节必须为可打印无空白 ASCII 字符(`0x21..0x7E`)。同一 `api-key` 下在线唯一。 | +| 设备名称 | `name` | `X-Tunnel-Name` | 必填。去除首尾空白后 UTF-8 字节长度为 `1..256`,必须为合法 UTF-8 且不含 ASCII 控制字符(`0x00..0x1F` 或 `0x7F`)。允许重名。 | +| 服务端类型 | `type` | `X-Tunnel-Type` | 当 `role=server` 时必填(去除首尾空白后至少 1 个字符);当 `role=client` 时忽略。支持任意自定义输入,去除首尾空白后 UTF-8 字节长度为 `1..256`,必须为合法 UTF-8 且不含 ASCII 控制字符(`0x00..0x1F` 或 `0x7F`)。允许重复。 | + +**客户端连接 URL 示例**: + +```text +wss://proxy.example.com/v1/tunnel?role=client&uuid=550e8400-e29b-41d4-a716-446655440000&name=MacBook-Pro +``` + +**服务端连接 URL 示例**: + +```text +wss://proxy.example.com/v1/tunnel?role=server&uuid=6ba7b810-9dad-11d1-80b4-00c04fd430c8&name=Build-Node-01&type=build-agent +``` + +### 2.4 HTTP 握手阶段错误响应码 + +所有鉴权、参数合法性与 `uuid` 冲突检查均在 WebSocket Upgrade **之前**完成。这些检查失败或 Hub 已关闭时,隧道处理器返回 `{"error":""}` 形式的 HTTP JSON 错误。全局中间件可能在请求到达隧道处理器之前拒绝请求,并返回不同格式的响应体(包括空响应体),具体区别如下: + +| HTTP 状态码 | 触发场景 | 响应体示例 | +| --- | --- | --- | +| `400 Bad Request` | `role`、`uuid`、`name` 缺失或不符合格式限制,或 `role=server` 时 `type` 缺失/不符合格式限制 | `{"error":"invalid or missing role: must be client or server"}` / `{"error":"invalid or missing uuid"}` / `{"error":"invalid or missing name"}` / `{"error":"invalid or missing type"}` | +| `401 Unauthorized` | 系统未配置 `access.api-keys`、未传凭证或所有候选凭证均不匹配 | `{"error":"invalid or missing api key"}` | +| `403 Forbidden` | `access.api-keys` 仍包含示例模板密钥触发系统 Safe-Mode 保护 | `{"error":"unsafe_example_api_key","message":"..."}` | +| `405 Method Not Allowed` | `POST`、`PUT`、`PATCH`、`DELETE`、`HEAD`、`TRACE` 或 `CONNECT`(响应头附带 `Allow: GET`) | `{"error":"method not allowed"}` | +| `409 Conflict` | 同一 `api-key` 下已存在相同 `uuid` 的在线客户端或服务端(或正在握手中) | `{"error":"device uuid already connected"}` | +| `503 Service Unavailable` | 服务停机时 Tunnel Hub 已关闭 | `{"error":"tunnel hub is closed"}` | +| `503 Service Unavailable` | Home 模式下全局 Home 心跳门禁未就绪,请求在到达隧道处理器之前被拒绝 | 空响应体 | + +`HEAD` 不返回响应体。`OPTIONS /v1/tunnel` 是 CORS 例外:全局 CORS 中间件对预检请求返回 `204 No Content`,不升级连接,也不执行隧道连接鉴权。 + +--- + +## 3. 控制通道协议规范(WebSocket Text JSON 帧) + +控制通道统一使用 **WebSocket 文本帧(`Opcode 0x1`)**,内容为 UTF-8 编码的 JSON 对象。整条消息(包括未知字段、嵌套值和字段名)都必须是合法 UTF-8;存在非法字节时返回非致命 `invalid_control_frame`,不执行命令。入站控制消息在解析 JSON 前按所有分片合计限制为 **4,096 字节**(`MaxControlFrameBytes`);超过时以 **`1009 Message Too Big`** 终止连接,不返回 `error` 帧。入站 `type` 最多 **64 字节**,`request_id` 最多 **128 字节 UTF-8**;在消息总长度限制内违反字段限制时返回非致命 `invalid_control_frame`。未知类型不会被回显到错误消息。出站服务端列表可以超过 4 KiB,但受 §5 的发送字节预算约束。 + +### 3.1 `server_list`:全量在线服务端列表(CLIProxyAPI → Client) + +客户端首次握手注册成功后**收到的第 1 条应用消息为 `server_list`**(若首连列表无法计入发送预算,则改为以 `1008` 关闭,不先发送其他应用消息);此外客户端主动发送 `list_servers` 查询时也会返回该消息。`servers` 始终为数组(无在线服务端时为 `[]`),按 `uuid` 字典序升序排列。 + +```json +{ + "type": "server_list", + "request_id": "sync-01", + "servers": [ + { + "uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "name": "Build-Node-01", + "type": "build-agent" + }, + { + "uuid": "7c9e6679-7425-40de-944b-e07fc1f90ae7", + "name": "Build-Node-02", + "type": "build-agent" + } + ] +} +``` + +- `servers[].uuid`、`servers[].name`、`servers[].type`(字符串):在线服务端的唯一标识、设备名称与握手声明的服务端类型。 +- `request_id`(可选字符串):首连自动推送时不包含此字段;响应 `list_servers` 查询且请求带有非空 `request_id` 时原样回显。 +- **因果顺序保证**:首连 `server_list` 快照在租户写锁内生成并率先写入客户端发送队列槽位 `0` 后,该客户端才对后续广播可见,因此后续收到的任何 `server_online` / `server_offline` 均严格发生在首连快照之后,不会乱序。 + +### 3.2 `list_servers`:主动查询在线服务端列表(Client → CLIProxyAPI) + +客户端可在连接存续期间随时发送该消息主动刷新列表: + +```json +{ + "type": "list_servers", + "request_id": "sync-01" +} +``` + +- `request_id`(可选字符串):`0..128` 字节 UTF-8 字符串,不含 ASCII 控制字符。 +- 仅限 `client` 角色调用;若 `server` 角色发送该消息,将收到 `error` 控制帧(`code: "unsupported_role_action"`)。 + +### 3.3 `server_online` 与 `server_offline`:服务端上下线实时推送(CLIProxyAPI → 同租户所有在线 Client) + +当同一 `access.api-key` 下有服务端新接入或断开时,CLIProxyAPI 实时向该密钥下所有在线客户端推送增量通知: + +```json +{ + "type": "server_online", + "server": { + "uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "name": "Build-Node-01", + "type": "build-agent" + } +} +``` + +```json +{ + "type": "server_offline", + "server": { + "uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "name": "Build-Node-01", + "type": "build-agent" + } +} +``` + +- `server_online` 与 `server_offline` 均携带完整的 `server.uuid`、`server.name` 与 `server.type` 字段。 + +### 3.4 `error`:非致命控制与路由错误通知(CLIProxyAPI → 发送方 Peer) + +消息**未超过传输层大小限制**但格式有误或目标不可达时,CLIProxyAPI 向发送方返回 `error` 文本帧,不会断开当前复用的 WebSocket 长连接。超大消息改为以 `1009` 关闭(见 §4.3)。错误通知为尽力投递;发送方自己的队列或字节预算耗尽时可能丢弃: + +```json +{ + "type": "error", + "code": "target_not_found", + "target_uuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + "message": "target peer is not connected" +} +``` + +| 错误码 `code` | 触发原因 | +| --- | --- | +| `invalid_control_frame` | 文本帧任意位置包含非法 UTF-8、不是合法 JSON 对象、`type` 未知/超长、`request_id` 超长/含控制字符。 | +| `unsupported_role_action` | `server` 角色发送了仅限客户端使用的控制指令(如 `list_servers`)。 | +| `invalid_data_frame` | 二进制帧长度小于 4 字节、`SrcUUIDLen`/`DstUUIDLen` 为 `0` 或 `> 128`、UUID 字节截断/含非法字符,或 `RawPayload` 超过 `64 MiB` 但消息总长仍不超过 `64 MiB + 512`;超过后者则以 `1009` 关闭。 | +| `unsupported_version` | 二进制帧第 `0` 字节 `Version` 不等于 `0x01`。 | +| `source_uuid_mismatch` | 二进制帧声明的 `SrcUUID` 与当前连接握手认证绑定的真实 `uuid` 不一致(防伪造拦截)。 | +| `target_not_found` | 目标 `DstUUID` 在当前 `access.api-key` 租户下不存在或已离线。 | +| `invalid_target_role` | 尝试在相同角色设备间发包(禁止 `client → client` 或 `server → server`)。 | +| `target_buffer_full` | 目标设备发送队列帧槽位或单连接/单租户字节预算耗尽。 | + +--- + +## 4. 数据通道二次封装协议规范(WebSocket Binary 帧) + +所有客户端与服务端之间的业务数据包均使用 **WebSocket 二进制帧(`Opcode 0x2`)** 传输,采用零 Base64 膨胀的紧凑二进制二次封装头。 + +### 4.1 二进制帧字节布局 + +```text + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Version (0x01)| PayloadType | SrcUUIDLen | DstUUIDLen | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| SrcUUID (SrcUUIDLen bytes) | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| DstUUID (DstUUIDLen bytes) | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| RawPayload (0 .. 67,108,864 bytes) | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +``` + +| 字节偏移 | 字段名 | 类型 | 说明 | +| --- | --- | --- | --- | +| `0` | `Version` | `uint8` | 协议版本号,固定为 `0x01`。 | +| `1` | `PayloadType` | `uint8` | 应用层载荷类型提示(`0x00` = 二进制,`0x01` = UTF-8 文本,`0x02..0xFF` = 业务自定义扩展子类型)。CLIProxyAPI 原样透传该字节,不校验载荷内容。 | +| `2` | `SrcUUIDLen` | `uint8` | 发送方 `SrcUUID` 的字节长度(合法范围 `1..128`)。 | +| `3` | `DstUUIDLen` | `uint8` | 接收方 `DstUUID` 的字节长度(合法范围 `1..128`)。 | +| `4 .. 4+SrcUUIDLen-1` | `SrcUUID` | ASCII | **客户端 → 服务端**:填入客户端自身 `client_uuid`。
**服务端 → 客户端**:填入服务端自身 `server_uuid`。 | +| `4+SrcUUIDLen .. 4+SrcUUIDLen+DstUUIDLen-1` | `DstUUID` | ASCII | **客户端 → 服务端**:填入目标服务端 `server_uuid`。
**服务端 → 客户端**:填入目标客户端 `client_uuid`。 | +| `4+SrcUUIDLen+DstUUIDLen .. 帧尾` | `RawPayload` | `[]byte` | 原始业务数据包字节(`0` 字节至最大 `64 MiB` / `67,108,864` 字节)。 | + +### 4.2 双向封装与多对多路由规则 + +1. **客户端 → 服务端方向**: + - 客户端在发送原始业务数据包时,封装 `SrcUUID = `、`DstUUID = `; + - CLIProxyAPI 校验 `SrcUUID` 必须等于当前客户端连接认证的 `uuid`,并在同一 `api-key` 租户域内确认 `DstUUID` 为在线 `server`,随后直接将该二进制帧原样转发至目标服务端连接; + - 服务端解封装后即可拿到可信的来源客户端 `client_uuid`(`SrcUUID`)与原始数据包 `RawPayload`。 +2. **服务端 → 客户端方向**: + - 服务端无论是响应请求还是主动向客户端推送流式数据,均封装 `SrcUUID = `、`DstUUID = `; + - CLIProxyAPI 校验 `SrcUUID` 等于当前服务端连接认证的 `uuid`,并在同一 `api-key` 租户域内确认 `DstUUID` 为在线 `client`,随后直接将该二进制帧转发至目标客户端连接; + - 客户端解封装后即可拿到可信的来源服务端 `server_uuid`(`SrcUUID`)与原始数据包 `RawPayload`。 +3. **多对多单连接复用**: + - 任意客户端可在同一条 WebSocket 连接上并发向多个服务端(`S1`, `S2`, ..., `Sm`)交错收发数据包; + - 任意服务端可在同一条 WebSocket 连接上并发与多个客户端(`C1`, `C2`, ..., `Cn`)交错收发数据包。 + +### 4.3 消息大小精确边界 + +以下长度均为重组后的 WebSocket 消息体(隧道包头与载荷),不含 RFC 6455 帧头/掩码字节;分片不能绕过限制。 + +| 边界 | 行为 | +| --- | --- | +| 二进制原始载荷 `0..64 MiB`(`67,108,864` 字节)且包头合法 | 通过大小校验,仍受路由与发送预算限制。 | +| 二进制原始载荷 `>64 MiB`,但消息总长 `<=MaxInboundFrameBytes`(`67,109,376` 字节) | 返回非致命 `invalid_data_frame`,连接保持;例如源/目标 UUID 各 1 字节时,`64 MiB + 1` 字节载荷加 6 字节包头属于此情形。 | +| 二进制消息总长 `>MaxInboundFrameBytes = 64 MiB + 512` | 有界读取检测超限后,通过隧道单写协程的统一关闭流程以 **`1009 Message Too Big`** 终止连接,不保证返回 JSON 错误;恰好等于上限时仍进入协议校验(超大载荷被非致命拒绝)。 | +| 入站文本控制消息 `>4,096` 字节 | JSON 解析前以 **`1009 Message Too Big`** 终止连接,不返回 `invalid_control_frame`;恰好 4,096 字节且 JSON/字段合法时允许。 | + +### 4.4 传输层致命关闭码 + +| 关闭码 | 触发条件 | +| --- | --- | +| `1002 Protocol Error` | 非法、未知或保留的 WebSocket opcode、非法关闭码及包含非法 UTF-8 的关闭原因,在隧道消息分发前即被 RFC 6455 传输层拒绝。连接直接终止,不返回非致命 `invalid_control_frame` JSON 错误。 | +| `1009 Message Too Big` | 重组后的消息超过 §4.3 所述传输大小限制。连接直接终止,不返回 JSON 错误。 | + +--- + +## 5. 连接生命周期、保活与热重载行为 + +- **Ping / Pong 心跳保活**: + - CLIProxyAPI 默认每 **30 秒** 向在线连接发送一次标准 WebSocket `Ping` 控制帧,且不对空闲长连接施加人为读写超时中断。主流 WebSocket 客户端库均会自动回复 `Pong`。对于收到的 Ping,CLIProxyAPI 使用有界、非阻塞的单槽位,仅保留最新待发送的 Pong 载荷(最多 125 字节),交由单写协程在无写 deadline 的情况下应答。对端主动发送的 Close 帧也通过相同关闭状态机与单写协程处理,以收到的关闭码和空原因应答,不设置写 deadline。 +- **传输层 deadline 防护**: + - 升级成功后,连接包装器会拦截所有有限 `SetDeadline`、`SetReadDeadline` 与 `SetWriteDeadline`,确保它们不会传递到底层连接;空 deadline 仍正常透传。流式检查器在 Gorilla 收到字节前校验入站 RFC 6455 帧头与掩码 Close 载荷,仅保留定长帧头和最多 125 字节的 Close 载荷,不复制数据载荷。致命帧错误立即注销设备、释放 UUID、为服务端广播 `server_offline` 并启动有界本地回收,不等待 Gorilla 写令牌或其 1 秒协议错误写入计时器。若套接字写入已经活跃,则立即关闭原始传输以中断写入;否则交由单写协程发送 `1002`,仅在该关闭写入停滞时使用 1 秒本地回收宽限期。被中断的对端可能看到 `1006`,整个流程不设置套接字 deadline。Gorilla v1.5.3 在发送 `101` 前拒绝 HTTP Hijack 缓冲区中的所有提前数据,因此已接受的升级后入站字节不会绕过检查器。二进制与文本大小限制采用重组消息的有界读取,而非 Gorilla 的 `SetReadLimit`,因此超限消息统一交由隧道单写协程以 `1009` 关闭。 +- **配置热重载与密钥吊销(`1008 Policy Violation`)**: + - 当管理员修改 `config.yaml` 或通过 Management API v8 更新 `access.api-keys` 时,若某个正在使用的 `api-key` 被删除,CLIProxyAPI 会立即注销该密钥下的所有客户端与服务端,并异步请求 WebSocket Close **`1008`(`"api key revoked"`)**;单写协程完成正在进行的健康写入后优先发送关闭帧,丢弃其余排队帧并回收套接字;其他未变更密钥下的活跃连接完全不受影响。 + - 吊销还会立即清除并使该密钥下所有待完成握手的 UUID 预约失效。重新添加相同密钥后,可立即使用相同 UUID 建立新连接;吊销前的旧握手即使随后升级成功,仍收到 `1008`(`"api key revoked"`),其提交或升级失败清理不会删除新的预约或覆盖新连接。 +- **服务停机通知(`1001 Going Away`)**: + - 当 CLIProxyAPI 停机时,立即注销所有在线连接,并通过相同关闭状态机异步请求 WebSocket Close **`1001`(`"server shutting down"`)**。 + - 吊销与停机调用均不等待网络写入。关闭/当前写入阻塞时,**1 秒本地关闭宽限期**结束后强制回收套接字;该机制不设置读写 deadline,也不限制正常活跃连接。健康接收方即使有排队/正在写入的帧仍会收到指定关闭码;真正停滞的对端可能只能看到异常关闭(`1006`),但不能拖延其他连接的吊销或停机。 +- **慢消费者背压隔离**: + - 每个连接拥有独立的 256 帧发送队列。**所有出站 JSON 控制与二进制数据字节(包括正在写入的帧)**共同计入 **单连接 `64 MiB + 512` 字节**与**每个 API Key 租户 `256 MiB`**预算。API 服务使用这些内置默认值构建内部 Hub。`internal/wstunnel.Options`(`SendQueueSize`、`MaxPeerQueuedBytes`、`MaxTenantQueuedBytes`)仅供 CLIProxyAPI 内部构建 Hub 使用,外部 SDK 消费者无法导入或配置,也不暴露为 YAML 配置项。仅在内部构建时,未指定租户预算才取 256 MiB 与单连接预算的较大值。不存在跨租户共享预算,写入完成或帧被丢弃时归还预算。断连与重连期间,正在写入的字节仍计入同一 API Key 的 `256 MiB` 租户预算,直到底层套接字写入完成或套接字被回收。 + - 单连接预算耗尽仅拒绝该目标;同租户仍有总预算时,其他健康节点继续交换。租户预算耗尽仅影响该租户的后续入队,其他租户不受影响。数据入队失败时,仅在发送方自身还有空间时投递 `target_buffer_full`。首连/主动查询 `server_list` 或拓扑广播无法计入接收方帧/字节预算时,请求 `1008`(`"control queue overflow"`)关闭,促使重连重建列表,避免静默失步。 + +### 客户端推荐对接状态机 + +1. 使用 `role=client`、`uuid`、`name` 与 `api-key` 连接 `GET /v1/tunnel`。 +2. 连接打开后读取首条文本帧 `server_list`,用其初始化本地在线服务端路由表 `Map`。 +3. 收到 `server_online` 时写入或更新 `server.uuid -> { name: server.name, type: server.type }`;收到 `server_offline` 时移除 `server.uuid` 并快速失败或切换正在等待该服务端的业务请求。 +4. 连接断开时: + - 若收到 WebSocket Close `1008` 且原因为 `"api key revoked"`,停止盲目重连并提示更换有效密钥; + - 若握手返回 HTTP `409 Conflict`,检查是否存在相同 `uuid` 的重复进程实例,退避后重试; + - 其他网络闪断或 `1001` 停机重启场景下,按指数退避重连并在连接恢复后以新的首条 `server_list` 重建本地服务端列表。 + +--- + +## 6. 客户端与服务端对接参考代码 + +### 6.1 TypeScript / JavaScript 对接示例(浏览器与 Node.js 通用) + +```typescript +const PROTOCOL_VERSION = 0x01; +export const PAYLOAD_BINARY = 0x00; +export const PAYLOAD_TEXT = 0x01; + +const textEncoder = new TextEncoder(); +const textDecoder = new TextDecoder(); + +export interface DecodedTunnelPacket { + version: number; + payloadType: number; + srcUUID: string; + dstUUID: string; + payload: Uint8Array; +} + +export function encodeTunnelPacket( + payloadType: number, + srcUUID: string, + dstUUID: string, + payload: Uint8Array, +): Uint8Array { + const srcBytes = textEncoder.encode(srcUUID); + const dstBytes = textEncoder.encode(dstUUID); + if (srcBytes.length < 1 || srcBytes.length > 128) { + throw new Error("invalid srcUUID length"); + } + if (dstBytes.length < 1 || dstBytes.length > 128) { + throw new Error("invalid dstUUID length"); + } + const frame = new Uint8Array(4 + srcBytes.length + dstBytes.length + payload.length); + frame[0] = PROTOCOL_VERSION; + frame[1] = payloadType & 0xff; + frame[2] = srcBytes.length; + frame[3] = dstBytes.length; + frame.set(srcBytes, 4); + frame.set(dstBytes, 4 + srcBytes.length); + frame.set(payload, 4 + srcBytes.length + dstBytes.length); + return frame; +} + +export function decodeTunnelPacket(raw: ArrayBuffer | Uint8Array): DecodedTunnelPacket { + const bytes = raw instanceof Uint8Array ? raw : new Uint8Array(raw); + if (bytes.length < 4) { + throw new Error("binary frame shorter than 4-byte header"); + } + const version = bytes[0]; + if (version !== PROTOCOL_VERSION) { + throw new Error(`unsupported protocol version: ${version}`); + } + const payloadType = bytes[1]; + const srcLen = bytes[2]; + const dstLen = bytes[3]; + const headerLen = 4 + srcLen + dstLen; + if (srcLen < 1 || dstLen < 1 || bytes.length < headerLen) { + throw new Error("malformed tunnel packet header"); + } + return { + version, + payloadType, + srcUUID: textDecoder.decode(bytes.subarray(4, 4 + srcLen)), + dstUUID: textDecoder.decode(bytes.subarray(4 + srcLen, headerLen)), + payload: bytes.subarray(headerLen), + }; +} + +// Client connection and multi-server multiplexing example: +export function connectTunnelClient(baseWsUrl: string, apiKey: string, clientUUID: string, clientName: string) { + const params = new URLSearchParams({ + key: apiKey, + role: "client", + uuid: clientUUID, + name: clientName, + }); + const ws = new WebSocket(`${baseWsUrl}/v1/tunnel?${params.toString()}`); + ws.binaryType = "arraybuffer"; + + const servers = new Map(); + + ws.onmessage = (event) => { + if (typeof event.data === "string") { + const ctrl = JSON.parse(event.data); + switch (ctrl.type) { + case "server_list": + servers.clear(); + for (const srv of ctrl.servers) { + servers.set(srv.uuid, { name: srv.name, type: srv.type }); + } + break; + case "server_online": + servers.set(ctrl.server.uuid, { name: ctrl.server.name, type: ctrl.server.type }); + break; + case "server_offline": + servers.delete(ctrl.server.uuid); + break; + case "error": + console.warn("Tunnel error:", ctrl.code, ctrl.message, ctrl.target_uuid); + break; + } + return; + } + + const pkt = decodeTunnelPacket(event.data as ArrayBuffer); + // pkt.srcUUID is the verified server UUID; pkt.payload is the raw response payload. + if (pkt.payloadType === PAYLOAD_TEXT) { + console.log(`收到服务端 ${pkt.srcUUID} 消息:`, textDecoder.decode(pkt.payload)); + } + }; + + return { + ws, + servers, + sendText(serverUUID: string, text: string) { + ws.send(encodeTunnelPacket(PAYLOAD_TEXT, clientUUID, serverUUID, textEncoder.encode(text))); + }, + sendBinary(serverUUID: string, data: Uint8Array) { + ws.send(encodeTunnelPacket(PAYLOAD_BINARY, clientUUID, serverUUID, data)); + }, + refreshServers(requestId = "manual-refresh") { + ws.send(JSON.stringify({ type: "list_servers", request_id: requestId })); + }, + }; +} +``` + +### 6.2 Go 服务端节点对接示例 + +```go +package main + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "sync" + + "github.com/gorilla/websocket" +) + +const ( + ProtocolVersion1 byte = 0x01 + PayloadTypeBinary byte = 0x00 + PayloadTypeText byte = 0x01 +) + +func EncodeFrame(payloadType byte, srcUUID, dstUUID string, payload []byte) ([]byte, error) { + if len(srcUUID) == 0 || len(srcUUID) > 128 || len(dstUUID) == 0 || len(dstUUID) > 128 { + return nil, errors.New("uuid length must be between 1 and 128 bytes") + } + buf := make([]byte, 0, 4+len(srcUUID)+len(dstUUID)+len(payload)) + buf = append(buf, ProtocolVersion1, payloadType, byte(len(srcUUID)), byte(len(dstUUID))) + buf = append(buf, srcUUID...) + buf = append(buf, dstUUID...) + buf = append(buf, payload...) + return buf, nil +} + +func DecodeFrame(raw []byte) (payloadType byte, srcUUID, dstUUID string, payload []byte, err error) { + if len(raw) < 4 { + return 0, "", "", nil, errors.New("short header") + } + if raw[0] != ProtocolVersion1 { + return 0, "", "", nil, fmt.Errorf("unsupported version: %d", raw[0]) + } + srcLen, dstLen := int(raw[2]), int(raw[3]) + headerLen := 4 + srcLen + dstLen + if srcLen < 1 || dstLen < 1 || len(raw) < headerLen { + return 0, "", "", nil, errors.New("malformed header lengths") + } + return raw[1], string(raw[4 : 4+srcLen]), string(raw[4+srcLen : headerLen]), raw[headerLen:], nil +} + +func RunEchoTunnelServer(proxyWSBaseURL, apiKey, serverUUID, serverName, serverType string) error { + q := url.Values{ + "role": {"server"}, + "uuid": {serverUUID}, + "name": {serverName}, + "type": {serverType}, + } + headers := http.Header{ + "Authorization": {"Bearer " + apiKey}, + } + conn, _, errDial := websocket.DefaultDialer.Dial(proxyWSBaseURL+"/v1/tunnel?"+q.Encode(), headers) + if errDial != nil { + return errDial + } + defer func() { + if errClose := conn.Close(); errClose != nil { + fmt.Printf("websocket close error: %v\n", errClose) + } + }() + + var writeMu sync.Mutex + for { + msgType, raw, errRead := conn.ReadMessage() + if errRead != nil { + return errRead + } + if msgType == websocket.TextMessage { + // Non-fatal control or error notification from CLIProxyAPI + fmt.Printf("control frame: %s\n", string(raw)) + continue + } + if msgType != websocket.BinaryMessage { + continue + } + + pType, clientUUID, dstUUID, body, errDec := DecodeFrame(raw) + if errDec != nil || dstUUID != serverUUID { + continue + } + + // Encapsulate serverUUID and reply to the originating client over the same multiplexed connection + reply, errEnc := EncodeFrame(pType, serverUUID, clientUUID, body) + if errEnc != nil { + continue + } + writeMu.Lock() + errWrite := conn.WriteMessage(websocket.BinaryMessage, reply) + writeMu.Unlock() + if errWrite != nil { + return errWrite + } + } +} +``` diff --git a/internal/api/buffered_conn.go b/internal/api/buffered_conn.go index 1d126455291..fde124172f3 100644 --- a/internal/api/buffered_conn.go +++ b/internal/api/buffered_conn.go @@ -11,6 +11,10 @@ type bufferedConn struct { reader *bufio.Reader } +func (c *bufferedConn) NetConn() net.Conn { + return c.Conn +} + func (c *bufferedConn) Read(p []byte) (int, error) { if c == nil { return 0, net.ErrClosed diff --git a/internal/api/handlers/management/auth_cache.go b/internal/api/handlers/management/auth_cache.go new file mode 100644 index 00000000000..664ab8568ac --- /dev/null +++ b/internal/api/handlers/management/auth_cache.go @@ -0,0 +1,175 @@ +package management + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "sync" + "time" + + "golang.org/x/crypto/bcrypt" +) + +const ( + managementAuthCacheTTL = time.Hour + managementAuthCacheMaxEntries = 64 +) + +type managementAuthCacheEntry struct { + expiresAt time.Time +} + +type managementAuthLookup struct { + done chan struct{} + ok bool +} + +// managementAuthCache caches verified management secret digests for a bounded TTL +// so repeated polling requests do not re-run bcrypt on every call. +type managementAuthCache struct { + mu sync.Mutex + hmacKey []byte + generation uint64 + entries map[[sha256.Size]byte]managementAuthCacheEntry + inflight map[[sha256.Size]byte]*managementAuthLookup + nowFunc func() time.Time + bcryptCompare func(hashedPassword, password []byte) error +} + +func (c *managementAuthCache) now() time.Time { + if c != nil && c.nowFunc != nil { + return c.nowFunc() + } + return time.Now() +} + +func (c *managementAuthCache) compare(hashedPassword, password []byte) error { + if c != nil && c.bcryptCompare != nil { + return c.bcryptCompare(hashedPassword, password) + } + return bcrypt.CompareHashAndPassword(hashedPassword, password) +} + +func (c *managementAuthCache) invalidate() { + if c == nil { + return + } + c.mu.Lock() + c.generation++ + clear(c.entries) + c.mu.Unlock() +} + +func (c *managementAuthCache) ensureHMACKeyLocked() bool { + if len(c.hmacKey) > 0 { + return true + } + key := make([]byte, 32) + if _, errRead := rand.Read(key); errRead != nil { + return false + } + c.hmacKey = key + return true +} + +func (c *managementAuthCache) digestLocked(secretHash, provided string) [sha256.Size]byte { + mac := hmac.New(sha256.New, c.hmacKey) + var lenBuf [8]byte + binary.BigEndian.PutUint64(lenBuf[:], uint64(len(secretHash))) + _, _ = mac.Write(lenBuf[:]) + _, _ = mac.Write([]byte(secretHash)) + binary.BigEndian.PutUint64(lenBuf[:], uint64(len(provided))) + _, _ = mac.Write(lenBuf[:]) + _, _ = mac.Write([]byte(provided)) + var out [sha256.Size]byte + mac.Sum(out[:0]) + return out +} + +func (c *managementAuthCache) evictLocked(now time.Time) { + for k, entry := range c.entries { + if !now.Before(entry.expiresAt) { + delete(c.entries, k) + } + } + for len(c.entries) >= managementAuthCacheMaxEntries { + var oldestKey [sha256.Size]byte + var oldestAt time.Time + first := true + for k, entry := range c.entries { + if first || entry.expiresAt.Before(oldestAt) { + oldestKey = k + oldestAt = entry.expiresAt + first = false + } + } + if first { + break + } + delete(c.entries, oldestKey) + } +} + +func (c *managementAuthCache) verify(secretHash, provided string) bool { + if c == nil || secretHash == "" { + return false + } + + c.mu.Lock() + if !c.ensureHMACKeyLocked() { + c.mu.Unlock() + return c.compare([]byte(secretHash), []byte(provided)) == nil + } + digest := c.digestLocked(secretHash, provided) + now := c.now() + if entry, ok := c.entries[digest]; ok { + if now.Before(entry.expiresAt) { + c.mu.Unlock() + return true + } + delete(c.entries, digest) + } + if pending := c.inflight[digest]; pending != nil { + c.mu.Unlock() + <-pending.done + return pending.ok + } + if c.inflight == nil { + c.inflight = make(map[[sha256.Size]byte]*managementAuthLookup) + } + lookup := &managementAuthLookup{done: make(chan struct{})} + c.inflight[digest] = lookup + gen := c.generation + c.mu.Unlock() + + return c.finishLookup(secretHash, provided, digest, gen, lookup) +} + +func (c *managementAuthCache) finishLookup(secretHash, provided string, digest [sha256.Size]byte, gen uint64, lookup *managementAuthLookup) bool { + ok := false + defer func() { + c.mu.Lock() + if ok && c.generation == gen { + // Start the TTL after verification completes so cold-path CPU time + // does not shorten the effective cache window. + verifiedAt := c.now() + if c.entries == nil { + c.entries = make(map[[sha256.Size]byte]managementAuthCacheEntry) + } + if len(c.entries) >= managementAuthCacheMaxEntries { + c.evictLocked(verifiedAt) + } + c.entries[digest] = managementAuthCacheEntry{ + expiresAt: verifiedAt.Add(managementAuthCacheTTL), + } + } + lookup.ok = ok + delete(c.inflight, digest) + close(lookup.done) + c.mu.Unlock() + }() + + ok = c.compare([]byte(secretHash), []byte(provided)) == nil + return ok +} diff --git a/internal/api/handlers/management/auth_files.go b/internal/api/handlers/management/auth_files.go index b8d8d75d498..93af86bada3 100644 --- a/internal/api/handlers/management/auth_files.go +++ b/internal/api/handlers/management/auth_files.go @@ -698,6 +698,17 @@ func (h *Handler) buildAuthFileEntryLocked(auth *coreauth.Auth, quota authFileQu entry["quota_plugin_id"] = pluginID } } + // Surface a TOS appeal link for operator action when the credential was + // deactivated by an Antigravity TOS_VIOLATION (issue #7515). Only exposed on + // the maintained v8 surface; the deprecated v0 shape stays frozen. + if quota.v8 && auth.Metadata != nil { + if appeal, ok := auth.Metadata["tos_appeal_url"].(string); ok && strings.TrimSpace(appeal) != "" { + entry["tos_appeal_url"] = strings.TrimSpace(appeal) + } + if appealText, ok := auth.Metadata["tos_appeal_url_text"].(string); ok && strings.TrimSpace(appealText) != "" { + entry["tos_appeal_url_text"] = strings.TrimSpace(appealText) + } + } // Declarative quota_probe is only executed by the v0 quota/fetch route. if !quota.v8 && auth.Metadata != nil { if probe, okProbe := auth.Metadata["quota_probe"]; okProbe && probe != nil { diff --git a/internal/api/handlers/management/auth_files_targeted_oauth_test.go b/internal/api/handlers/management/auth_files_targeted_oauth_test.go index 9f36501156b..6a465298092 100644 --- a/internal/api/handlers/management/auth_files_targeted_oauth_test.go +++ b/internal/api/handlers/management/auth_files_targeted_oauth_test.go @@ -60,6 +60,7 @@ func (s *targetedTestAntigravityOAuthService) FetchProjectID(_ context.Context, } type targetedTestKimiOAuthService struct { + pollDone chan struct{} domain string accessToken string refreshToken string @@ -77,7 +78,12 @@ func (s *targetedTestKimiOAuthService) StartDeviceFlow(_ context.Context) (*kimi }, nil } -func (s *targetedTestKimiOAuthService) WaitForAuthorization(_ context.Context, _ *kimi.DeviceCodeResponse) (*kimi.KimiAuthBundle, error) { +func (s *targetedTestKimiOAuthService) WaitForAuthorization(ctx context.Context, _ *kimi.DeviceCodeResponse) (*kimi.KimiAuthBundle, error) { + if s.pollDone != nil { + defer close(s.pollDone) + <-ctx.Done() + return nil, ctx.Err() + } return &kimi.KimiAuthBundle{ TokenData: &kimi.KimiTokenData{ AccessToken: s.accessToken, @@ -143,6 +149,8 @@ func (s *targetedTestClaudeOAuthService) CreateTokenStorage(bundle *claude.Claud } type targetedTestXAIOAuthService struct { + // pollDone keeps registration-only tests pending until session cancellation. + pollDone chan struct{} email string subject string accessToken string @@ -159,7 +167,12 @@ func (s *targetedTestXAIOAuthService) StartDeviceFlow(_ context.Context) (*xaiau }, nil } -func (s *targetedTestXAIOAuthService) WaitForAuthorization(_ context.Context, _ *xaiauth.DeviceCodeResponse) (*xaiauth.AuthBundle, error) { +func (s *targetedTestXAIOAuthService) WaitForAuthorization(ctx context.Context, _ *xaiauth.DeviceCodeResponse) (*xaiauth.AuthBundle, error) { + if s.pollDone != nil { + defer close(s.pollDone) + <-ctx.Done() + return nil, ctx.Err() + } return &xaiauth.AuthBundle{ TokenData: xaiauth.TokenData{ AccessToken: s.accessToken, @@ -192,6 +205,7 @@ func (s *targetedTestXAIOAuthService) CreateTokenStorage(bundle *xaiauth.AuthBun } type targetedTestMetaOAuthService struct { + pollDone chan struct{} email string accessToken string } @@ -207,7 +221,12 @@ func (s *targetedTestMetaOAuthService) StartDeviceFlow(_ context.Context) (*meta }, nil } -func (s *targetedTestMetaOAuthService) WaitForAuthorization(_ context.Context, _ *metaauth.DeviceCodeResponse) (*metaauth.MetaAuthBundle, error) { +func (s *targetedTestMetaOAuthService) WaitForAuthorization(ctx context.Context, _ *metaauth.DeviceCodeResponse) (*metaauth.MetaAuthBundle, error) { + if s.pollDone != nil { + defer close(s.pollDone) + <-ctx.Done() + return nil, ctx.Err() + } return &metaauth.MetaAuthBundle{ TokenData: &metaauth.TokenData{ AccessToken: s.accessToken, @@ -241,22 +260,6 @@ func (s *targetedTestMetaOAuthService) CreateTokenStorage(bundle *metaauth.MetaA func TestStartOAuthV8TargetedSessionRegistrationAcrossBuiltinProviders(t *testing.T) { gin.SetMode(gin.TestMode) - origTransport := http.DefaultTransport - http.DefaultTransport = roundTripFunc(func(req *http.Request) (*http.Response, error) { - rec := httptest.NewRecorder() - rec.Header().Set("Content-Type", "application/json") - switch { - case strings.Contains(req.URL.Path, "openid-configuration"): - _, _ = rec.WriteString(`{"device_authorization_endpoint":"https://auth.x.ai/device","token_endpoint":"https://auth.x.ai/token"}`) - case strings.Contains(req.URL.Path, "device"): - _, _ = rec.WriteString(`{"device_code":"dev-code","user_code":"ABCD-1234","verification_uri":"https://example.test/verify","verification_uri_complete":"https://example.test/verify?code=ABCD-1234","expires_in":600,"interval":5}`) - default: - _, _ = rec.WriteString(`{"error":"authorization_pending"}`) - } - return rec.Result(), nil - }) - t.Cleanup(func() { http.DefaultTransport = origTransport }) - origCodexFactory := newCodexOAuthService newCodexOAuthService = func(*config.Config) codexOAuthService { return &targetedRecoveryTestCodexOAuthService{authDir: t.TempDir(), email: "a@x.test", accountID: "acc-1"} @@ -269,6 +272,44 @@ func TestStartOAuthV8TargetedSessionRegistrationAcrossBuiltinProviders(t *testin } t.Cleanup(func() { newAntigravityOAuthService = origAgFactory }) + // Device-flow handlers poll asynchronously. Do not temporarily replace the + // global transport: delayed polls could outlive it and reach real providers. + // These fakes stay pending until subtest session cleanup cancels them. + newPollDone := func(provider string) chan struct{} { + done := make(chan struct{}) + t.Cleanup(func() { + select { + case <-done: + case <-time.After(5 * time.Second): + t.Errorf("%s registration poll did not stop after session cancellation", provider) + } + }) + return done + } + origXAIFactory := newXAIOAuthService + newXAIOAuthService = func(*config.Config, string) xaiOAuthService { + return &targetedTestXAIOAuthService{pollDone: newPollDone("xai")} + } + t.Cleanup(func() { newXAIOAuthService = origXAIFactory }) + + origKimiFactory := newKimiOAuthService + newKimiOAuthService = func(_ *config.Config, domain string) kimiOAuthService { + return &targetedTestKimiOAuthService{domain: domain, pollDone: newPollDone(domain)} + } + t.Cleanup(func() { newKimiOAuthService = origKimiFactory }) + + origMetaFactory := newMetaOAuthService + newMetaOAuthService = func(*config.Config, string) metaOAuthService { + return &targetedTestMetaOAuthService{pollDone: newPollDone("meta")} + } + t.Cleanup(func() { newMetaOAuthService = origMetaFactory }) + + origClaudeFactory := newClaudeOAuthService + newClaudeOAuthService = func(*config.Config, string) claudeOAuthService { + return &targetedTestClaudeOAuthService{} + } + t.Cleanup(func() { newClaudeOAuthService = origClaudeFactory }) + origDevinFactory := newDevinOAuthService newDevinOAuthService = func(*config.Config) devinOAuthService { return &fakeDevinOAuthService{} diff --git a/internal/api/handlers/management/config_v8.go b/internal/api/handlers/management/config_v8.go index 5f944095803..926e88ddfcb 100644 --- a/internal/api/handlers/management/config_v8.go +++ b/internal/api/handlers/management/config_v8.go @@ -207,7 +207,18 @@ func (h *Handler) ConfigV8(c *gin.Context) { if saved, errSaved := os.ReadFile(h.configFilePath); errSaved == nil { c.Header("ETag", configV8ETag(config.ComputeSourceHash(saved))) } + prevSecretHash := "" + if h.cfg != nil { + prevSecretHash = h.cfg.RemoteManagement.SecretKey + } h.cfg = next + nextSecretHash := "" + if next != nil { + nextSecretHash = next.RemoteManagement.SecretKey + } + if prevSecretHash != nextSecretHash { + h.authCache.invalidate() + } snapshot := h.reloadSnapshotConfigLocked() h.reloadConfigAfterManagementSaveAsync(c.Request.Context(), snapshot) c.JSON(http.StatusOK, gin.H{"status": "ok", "config-version": 8}) diff --git a/internal/api/handlers/management/config_v8_test.go b/internal/api/handlers/management/config_v8_test.go index 95741ac20b0..3fb01ce33e3 100644 --- a/internal/api/handlers/management/config_v8_test.go +++ b/internal/api/handlers/management/config_v8_test.go @@ -975,3 +975,101 @@ api-keys: } } } + +func TestConfigV8_SensitiveWordsReplace(t *testing.T) { + gin.SetMode(gin.TestMode) + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte("server: {port: 8317}\n"), 0600); err != nil { + t.Fatal(err) + } + cfg, err := config.LoadConfig(path) + if err != nil { + t.Fatal(err) + } + h := &Handler{cfg: cfg, configFilePath: path} + router := gin.New() + router.GET("/v8/management/config/*path", h.ConfigV8) + router.PUT("/v8/management/config/*path", h.ConfigV8) + router.PATCH("/v8/management/config/*path", h.ConfigV8) + router.DELETE("/v8/management/config/*path", h.ConfigV8) + + for _, endpoint := range []string{ + "/v8/management/config/oauth/providers/antigravity/sensitive-words-replace", + "/v8/management/config/oauth/providers/devin/sensitive-words-replace", + } { + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodPut, endpoint, strings.NewReader(`{"You are Codex, an agent based on GPT-5.":"You are a helpful coding assistant."}`))) + if w.Code != http.StatusOK { + t.Fatalf("PUT %s: status=%d body=%s", endpoint, w.Code, w.Body.String()) + } + getRec := httptest.NewRecorder() + router.ServeHTTP(getRec, httptest.NewRequest(http.MethodGet, endpoint, nil)) + if getRec.Code != http.StatusOK || !strings.Contains(getRec.Body.String(), "You are a helpful coding assistant.") { + t.Fatalf("GET %s: status=%d body=%s", endpoint, getRec.Code, getRec.Body.String()) + } + delRec := httptest.NewRecorder() + router.ServeHTTP(delRec, httptest.NewRequest(http.MethodDelete, endpoint, nil)) + if delRec.Code != http.StatusOK { + t.Fatalf("DELETE %s: status=%d body=%s", endpoint, delRec.Code, delRec.Body.String()) + } + } + + claudePut := httptest.NewRecorder() + router.ServeHTTP(claudePut, httptest.NewRequest( + http.MethodPut, + "/v8/management/config/api-keys/claude", + strings.NewReader(`[{"name":"claude-1","keys":[{"api-key":"sk-ant-1","cloak":{"sensitive-words-replace":{"Claude Code":"Claude"}}}] }]`), + )) + if claudePut.Code != http.StatusOK { + t.Fatalf("PUT api-keys/claude: status=%d body=%s", claudePut.Code, claudePut.Body.String()) + } +} + +func TestConfigV8_SensitivePatternsReplace(t *testing.T) { + gin.SetMode(gin.TestMode) + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte("server: {port: 8317}\n"), 0600); err != nil { + t.Fatal(err) + } + cfg, err := config.LoadConfig(path) + if err != nil { + t.Fatal(err) + } + h := &Handler{cfg: cfg, configFilePath: path} + router := gin.New() + router.GET("/v8/management/config/*path", h.ConfigV8) + router.PUT("/v8/management/config/*path", h.ConfigV8) + router.PATCH("/v8/management/config/*path", h.ConfigV8) + router.DELETE("/v8/management/config/*path", h.ConfigV8) + + for _, endpoint := range []string{ + "/v8/management/config/oauth/providers/antigravity/sensitive-patterns-replace", + "/v8/management/config/oauth/providers/devin/sensitive-patterns-replace", + } { + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodPut, endpoint, strings.NewReader(`[{"pattern":"(?m)^RFC 2119[^\\n]*\\n?","replacement":""}]`))) + if w.Code != http.StatusOK { + t.Fatalf("PUT %s: status=%d body=%s", endpoint, w.Code, w.Body.String()) + } + getRec := httptest.NewRecorder() + router.ServeHTTP(getRec, httptest.NewRequest(http.MethodGet, endpoint, nil)) + if getRec.Code != http.StatusOK || !strings.Contains(getRec.Body.String(), "RFC 2119") { + t.Fatalf("GET %s: status=%d body=%s", endpoint, getRec.Code, getRec.Body.String()) + } + delRec := httptest.NewRecorder() + router.ServeHTTP(delRec, httptest.NewRequest(http.MethodDelete, endpoint, nil)) + if delRec.Code != http.StatusOK { + t.Fatalf("DELETE %s: status=%d body=%s", endpoint, delRec.Code, delRec.Body.String()) + } + } + + claudePut := httptest.NewRecorder() + router.ServeHTTP(claudePut, httptest.NewRequest( + http.MethodPut, + "/v8/management/config/api-keys/claude", + strings.NewReader(`[{"name":"claude-1","keys":[{"api-key":"sk-ant-1","cloak":{"sensitive-patterns-replace":[{"pattern":"Claude\\s+Code","replacement":"Claude"}]}}] }]`), + )) + if claudePut.Code != http.StatusOK { + t.Fatalf("PUT api-keys/claude: status=%d body=%s", claudePut.Code, claudePut.Body.String()) + } +} diff --git a/internal/api/handlers/management/handler.go b/internal/api/handlers/management/handler.go index 3a61b902b4f..c1c696210e0 100644 --- a/internal/api/handlers/management/handler.go +++ b/internal/api/handlers/management/handler.go @@ -21,7 +21,6 @@ import ( sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" log "github.com/sirupsen/logrus" - "golang.org/x/crypto/bcrypt" ) type attemptInfo struct { @@ -61,7 +60,8 @@ type Handler struct { pluginStoreHTTPClient pluginstore.HTTPDoer pluginStoreRateLimiter *pluginstore.GitHubRateLimiter pluginReleases pluginReleaseCache - siwcOAuthFactory func(*config.Config) siwcOAuthService + authCache managementAuthCache + siwcOAuthFactory func(*config.Config, string) siwcOAuthService siwcCommitMu sync.Mutex pluginLoginSaveMu sync.Mutex @@ -141,7 +141,18 @@ func (h *Handler) SetConfig(cfg *config.Config) { log.Debug("management: ignoring config reload parsed from an older config file version") return } + prevSecretHash := "" + if h.cfg != nil { + prevSecretHash = h.cfg.RemoteManagement.SecretKey + } h.cfg = cloned + nextSecretHash := "" + if cloned != nil { + nextSecretHash = cloned.RemoteManagement.SecretKey + } + if prevSecretHash != nextSecretHash { + h.authCache.invalidate() + } } // configSnapshot reads h.cfg under h.mu, for code that runs outside the request holding it. @@ -450,7 +461,7 @@ func (h *Handler) AuthenticateManagementKey(clientIP string, localClient bool, p return true, 0, "" } - if secretHash == "" || bcrypt.CompareHashAndPassword([]byte(secretHash), []byte(provided)) != nil { + if secretHash == "" || !h.authCache.verify(secretHash, provided) { fail() return false, http.StatusUnauthorized, "invalid management key" } diff --git a/internal/api/handlers/management/handler_test.go b/internal/api/handlers/management/handler_test.go index b75663d8b7e..031fdb1d6bb 100644 --- a/internal/api/handlers/management/handler_test.go +++ b/internal/api/handlers/management/handler_test.go @@ -1,14 +1,21 @@ package management import ( + "fmt" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" + "sync" + "sync/atomic" "testing" + "time" "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" + "golang.org/x/crypto/bcrypt" ) func TestAuthenticateManagementKey_LocalhostIPBan_BlocksCorrectKeyDuringBan(t *testing.T) { @@ -86,3 +93,397 @@ func TestMiddlewareSetsSupportPluginHeader(t *testing.T) { } }) } + +func TestAuthenticateManagementKey_ReusesVerifiedSecretWithinOneHourTTL(t *testing.T) { + hash, errHash := bcrypt.GenerateFromPassword([]byte("test-secret"), bcrypt.DefaultCost) + if errHash != nil { + t.Fatalf("bcrypt.GenerateFromPassword() error = %v", errHash) + } + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + var nowMu sync.Mutex + var compareCalls atomic.Int64 + h := &Handler{ + cfg: &config.Config{ + RemoteManagement: config.RemoteManagement{ + SecretKey: string(hash), + }, + }, + failedAttempts: make(map[string]*attemptInfo), + authCache: managementAuthCache{ + nowFunc: func() time.Time { + nowMu.Lock() + defer nowMu.Unlock() + return now + }, + bcryptCompare: func(hashedPassword, password []byte) error { + compareCalls.Add(1) + return bcrypt.CompareHashAndPassword(hashedPassword, password) + }, + }, + } + + if allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + t.Fatalf("initial auth failed: status=%d msg=%q", statusCode, errMsg) + } + if got := compareCalls.Load(); got != 1 { + t.Fatalf("initial bcrypt calls = %d, want 1", got) + } + + for i := 0; i < 10; i++ { + if allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + t.Fatalf("cached auth %d failed: status=%d msg=%q", i+1, statusCode, errMsg) + } + } + if got := compareCalls.Load(); got != 1 { + t.Fatalf("bcrypt calls after repeated polling = %d, want 1", got) + } + + nowMu.Lock() + now = now.Add(time.Hour - time.Second) + nowMu.Unlock() + if allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + t.Fatalf("auth just before 1h expiry failed: status=%d msg=%q", statusCode, errMsg) + } + if got := compareCalls.Load(); got != 1 { + t.Fatalf("bcrypt calls before 1h expiry = %d, want 1", got) + } + + nowMu.Lock() + now = now.Add(time.Second) + nowMu.Unlock() + if allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + t.Fatalf("auth at 1h expiry failed: status=%d msg=%q", statusCode, errMsg) + } + if got := compareCalls.Load(); got != 2 { + t.Fatalf("bcrypt calls at 1h expiry = %d, want 2", got) + } + + if allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + t.Fatalf("auth after re-verification failed: status=%d msg=%q", statusCode, errMsg) + } + if got := compareCalls.Load(); got != 2 { + t.Fatalf("bcrypt calls after refresh = %d, want 2", got) + } +} + +func TestAuthenticateManagementKey_NeverCachesFailuresAndPreservesIPBan(t *testing.T) { + hash, errHash := bcrypt.GenerateFromPassword([]byte("test-secret"), bcrypt.MinCost) + if errHash != nil { + t.Fatalf("bcrypt.GenerateFromPassword() error = %v", errHash) + } + var compareCalls atomic.Int64 + h := &Handler{ + cfg: &config.Config{ + RemoteManagement: config.RemoteManagement{ + SecretKey: string(hash), + }, + }, + failedAttempts: make(map[string]*attemptInfo), + authCache: managementAuthCache{ + bcryptCompare: func(hashedPassword, password []byte) error { + compareCalls.Add(1) + return bcrypt.CompareHashAndPassword(hashedPassword, password) + }, + }, + } + + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + t.Fatal("expected valid secret to succeed") + } + if got := compareCalls.Load(); got != 1 { + t.Fatalf("bcrypt calls = %d, want 1", got) + } + + // Four wrong attempts must each invoke bcrypt (never negative-cached) and not ban yet. + for i := 0; i < 4; i++ { + allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "wrong-secret") + if allowed || statusCode != http.StatusUnauthorized || errMsg != "invalid management key" { + t.Fatalf("wrong attempt %d = (%v, %d, %q), want (false, 401, invalid management key)", i+1, allowed, statusCode, errMsg) + } + } + if got := compareCalls.Load(); got != 5 { + t.Fatalf("bcrypt calls after 4 failures = %d, want 5", got) + } + + // A cached hit must reset the failed-attempt counter. + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + t.Fatal("expected cached valid secret to succeed and reset attempts") + } + if got := compareCalls.Load(); got != 5 { + t.Fatalf("bcrypt calls on cached hit = %d, want 5", got) + } + + // Five consecutive failures after reset trigger the 30-minute IP ban. + for i := 0; i < 5; i++ { + allowed, statusCode, _ := h.AuthenticateManagementKey("127.0.0.1", true, "wrong-secret") + if allowed || statusCode != http.StatusUnauthorized { + t.Fatalf("post-reset failure %d = (%v, %d), want (false, 401)", i+1, allowed, statusCode) + } + } + if got := compareCalls.Load(); got != 10 { + t.Fatalf("bcrypt calls after 5 failures = %d, want 10", got) + } + + // Even with the valid secret already cached, the banned IP must still receive 403. + allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret") + if allowed || statusCode != http.StatusForbidden || !strings.HasPrefix(errMsg, "IP banned due to too many failed attempts. Try again in") { + t.Fatalf("banned auth with cached key = (%v, %d, %q), want (false, 403, IP banned...)", allowed, statusCode, errMsg) + } + if got := compareCalls.Load(); got != 10 { + t.Fatalf("banned request should short-circuit before bcrypt; calls = %d, want 10", got) + } +} + +func TestAuthenticateManagementKey_InvalidatesCacheOnSecretChangeAndRemoval(t *testing.T) { + hash1, errHash1 := bcrypt.GenerateFromPassword([]byte("secret-one"), bcrypt.MinCost) + if errHash1 != nil { + t.Fatalf("bcrypt.GenerateFromPassword(1) error = %v", errHash1) + } + hash2, errHash2 := bcrypt.GenerateFromPassword([]byte("secret-two"), bcrypt.MinCost) + if errHash2 != nil { + t.Fatalf("bcrypt.GenerateFromPassword(2) error = %v", errHash2) + } + var compareCalls atomic.Int64 + h := &Handler{ + cfg: &config.Config{ + RemoteManagement: config.RemoteManagement{ + SecretKey: string(hash1), + }, + }, + failedAttempts: make(map[string]*attemptInfo), + authCache: managementAuthCache{ + bcryptCompare: func(hashedPassword, password []byte) error { + compareCalls.Add(1) + return bcrypt.CompareHashAndPassword(hashedPassword, password) + }, + }, + } + + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "secret-one"); !allowed { + t.Fatal("expected secret-one to succeed") + } + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "secret-one"); !allowed { + t.Fatal("expected cached secret-one to succeed") + } + if got := compareCalls.Load(); got != 1 { + t.Fatalf("bcrypt calls before rotation = %d, want 1", got) + } + + // Rotate via SetConfig. + h.SetConfig(&config.Config{ + RemoteManagement: config.RemoteManagement{ + SecretKey: string(hash2), + }, + }) + if allowed, statusCode, _ := h.AuthenticateManagementKey("127.0.0.1", true, "secret-one"); allowed || statusCode != http.StatusUnauthorized { + t.Fatalf("stale secret-one after SetConfig = (%v, %d), want (false, 401)", allowed, statusCode) + } + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "secret-two"); !allowed { + t.Fatal("expected secret-two to succeed after rotation") + } + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "secret-two"); !allowed { + t.Fatal("expected cached secret-two to succeed") + } + if got := compareCalls.Load(); got != 3 { + t.Fatalf("bcrypt calls after rotation = %d, want 3", got) + } + + // Rotating back to hash1 must not reuse pre-rotation cached entry. + h.SetConfig(&config.Config{ + RemoteManagement: config.RemoteManagement{ + SecretKey: string(hash1), + }, + }) + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "secret-one"); !allowed { + t.Fatal("expected secret-one to succeed after rotating back") + } + if got := compareCalls.Load(); got != 4 { + t.Fatalf("bcrypt calls after rotating back = %d, want 4", got) + } + + // Direct h.cfg swap (e.g. PutConfigYAML) still misses because digest includes secretHash. + h.mu.Lock() + h.cfg = &config.Config{ + RemoteManagement: config.RemoteManagement{ + SecretKey: string(hash2), + }, + } + h.mu.Unlock() + if allowed, statusCode, _ := h.AuthenticateManagementKey("127.0.0.1", true, "secret-one"); allowed || statusCode != http.StatusUnauthorized { + t.Fatalf("stale secret-one after direct cfg swap = (%v, %d), want (false, 401)", allowed, statusCode) + } + + // Clearing secret-key denies further requests immediately. + h.SetConfig(&config.Config{}) + allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "secret-two") + if allowed || statusCode != http.StatusForbidden || errMsg != "remote management key not set" { + t.Fatalf("auth after secret removal = (%v, %d, %q), want (false, 403, remote management key not set)", allowed, statusCode, errMsg) + } +} + +func TestAuthenticateManagementKey_CoalescesConcurrentColdCacheLookups(t *testing.T) { + hash, errHash := bcrypt.GenerateFromPassword([]byte("test-secret"), bcrypt.MinCost) + if errHash != nil { + t.Fatalf("bcrypt.GenerateFromPassword() error = %v", errHash) + } + var compareCalls atomic.Int64 + started := make(chan struct{}, 1) + release := make(chan struct{}) + h := &Handler{ + cfg: &config.Config{ + RemoteManagement: config.RemoteManagement{ + SecretKey: string(hash), + }, + }, + failedAttempts: make(map[string]*attemptInfo), + authCache: managementAuthCache{ + bcryptCompare: func(hashedPassword, password []byte) error { + compareCalls.Add(1) + if string(password) == "test-secret" { + select { + case started <- struct{}{}: + default: + } + <-release + } + return bcrypt.CompareHashAndPassword(hashedPassword, password) + }, + }, + } + + const workers = 8 + var wg sync.WaitGroup + results := make([]bool, workers) + for i := 0; i < workers; i++ { + wg.Add(1) + go func(idx int) { + defer wg.Done() + allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret") + results[idx] = allowed + }(i) + } + + <-started + // A different/wrong secret runs independently without blocking on or succeeding from the valid lookup. + wrongAllowed, wrongStatus, _ := h.AuthenticateManagementKey("127.0.0.2", true, "wrong-secret") + if wrongAllowed || wrongStatus != http.StatusUnauthorized { + t.Fatalf("concurrent wrong secret = (%v, %d), want (false, 401)", wrongAllowed, wrongStatus) + } + + close(release) + wg.Wait() + + for i, allowed := range results { + if !allowed { + t.Fatalf("worker %d failed", i) + } + } + // 1 coalesced lookup for "test-secret" + 1 lookup for "wrong-secret". + if got := compareCalls.Load(); got != 2 { + t.Fatalf("bcrypt calls = %d, want 2", got) + } +} + +func TestManagementAuthCache_BoundsEntries(t *testing.T) { + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + cache := managementAuthCache{ + nowFunc: func() time.Time { return now }, + bcryptCompare: func(_, _ []byte) error { + return nil + }, + } + for i := 0; i < managementAuthCacheMaxEntries+16; i++ { + now = now.Add(time.Second) + if !cache.verify(fmt.Sprintf("hash-%d", i), "secret") { + t.Fatalf("verify(%d) = false, want true", i) + } + } + cache.mu.Lock() + entryCount := len(cache.entries) + cache.mu.Unlock() + if entryCount > managementAuthCacheMaxEntries { + t.Fatalf("cache entries = %d, want <= %d", entryCount, managementAuthCacheMaxEntries) + } +} + +func TestMiddleware_AuthenticatesRealBcryptHashAndInvalidatesOnConfigV8Update(t *testing.T) { + gin.SetMode(gin.TestMode) + hash1, errHash1 := bcrypt.GenerateFromPassword([]byte("key-one"), bcrypt.DefaultCost) + if errHash1 != nil { + t.Fatalf("bcrypt.GenerateFromPassword(1) error = %v", errHash1) + } + hash2, errHash2 := bcrypt.GenerateFromPassword([]byte("key-two"), bcrypt.MinCost) + if errHash2 != nil { + t.Fatalf("bcrypt.GenerateFromPassword(2) error = %v", errHash2) + } + + path := filepath.Join(t.TempDir(), "config.yaml") + initialYAML := fmt.Sprintf("config-version: 8\nmanagement:\n secret-key: %q\n", string(hash1)) + if errWrite := os.WriteFile(path, []byte(initialYAML), 0o600); errWrite != nil { + t.Fatal(errWrite) + } + cfg, errLoad := config.LoadConfig(path) + if errLoad != nil { + t.Fatal(errLoad) + } + + h := &Handler{cfg: cfg, configFilePath: path, failedAttempts: make(map[string]*attemptInfo)} + router := gin.New() + v8 := router.Group("/v8/management", h.Middleware()) + v8.GET("/config/*path", h.ConfigV8) + v8.PUT("/config/*path", h.ConfigV8) + + doReq := func(method, url, key, body string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest(method, url, strings.NewReader(body)) + req.RemoteAddr = "127.0.0.1:12345" + if key != "" { + req.Header.Set("Authorization", "Bearer "+key) + } + router.ServeHTTP(rec, req) + return rec + } + + for i := 0; i < 3; i++ { + if rec := doReq(http.MethodGet, "/v8/management/config/management", "key-one", ""); rec.Code != http.StatusOK { + t.Fatalf("GET #%d status = %d, want 200; body=%s", i+1, rec.Code, rec.Body.String()) + } + } + + updateBody := fmt.Sprintf("%q", string(hash2)) + if rec := doReq(http.MethodPut, "/v8/management/config/management/secret-key", "key-one", updateBody); rec.Code != http.StatusOK { + t.Fatalf("PUT secret-key status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } + + if rec := doReq(http.MethodGet, "/v8/management/config/management", "key-one", ""); rec.Code != http.StatusUnauthorized { + t.Fatalf("GET with old key after ConfigV8 update status = %d, want 401; body=%s", rec.Code, rec.Body.String()) + } + if rec := doReq(http.MethodGet, "/v8/management/config/management", "key-two", ""); rec.Code != http.StatusOK { + t.Fatalf("GET with new key after ConfigV8 update status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } +} + +func BenchmarkAuthenticateManagementKey_Cached(b *testing.B) { + hash, errHash := bcrypt.GenerateFromPassword([]byte("test-secret"), bcrypt.DefaultCost) + if errHash != nil { + b.Fatalf("bcrypt.GenerateFromPassword() error = %v", errHash) + } + h := &Handler{ + cfg: &config.Config{ + RemoteManagement: config.RemoteManagement{ + SecretKey: string(hash), + }, + }, + failedAttempts: make(map[string]*attemptInfo), + } + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + b.Fatal("warmup auth failed") + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + if allowed, _, _ := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret"); !allowed { + b.Fatal("cached auth failed") + } + } +} diff --git a/internal/api/handlers/management/in_flight.go b/internal/api/handlers/management/in_flight.go new file mode 100644 index 00000000000..b4ba9bc50f2 --- /dev/null +++ b/internal/api/handlers/management/in_flight.go @@ -0,0 +1,40 @@ +package management + +import ( + "net/http" + "time" + + "github.com/gin-gonic/gin" +) + +// inFlightResponse is the read-only payload for the standalone in-flight +// request count endpoint. It intentionally exposes counts only: no request +// bodies, prompts, client addresses, or credential identifiers. +type inFlightResponse struct { + InFlight int64 `json:"in_flight"` + OldestStartedAt *time.Time `json:"oldest_started_at,omitempty"` + ByProvider map[string]int64 `json:"by_provider"` +} + +// GetInFlightRequests reports the current in-flight request count on a +// standalone instance. In Home mode the snapshot stays empty because the +// execution registry is the authoritative in-flight source there. +func (h *Handler) GetInFlightRequests(c *gin.Context) { + if h == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"}) + return + } + resp := inFlightResponse{ByProvider: map[string]int64{}} + if h.authManager != nil { + snapshot := h.authManager.InFlightSnapshot() + resp.InFlight = snapshot.InFlight + if !snapshot.OldestStartedAt.IsZero() { + oldest := snapshot.OldestStartedAt.UTC() + resp.OldestStartedAt = &oldest + } + if len(snapshot.ByProvider) > 0 { + resp.ByProvider = snapshot.ByProvider + } + } + c.JSON(http.StatusOK, resp) +} diff --git a/internal/api/handlers/management/in_flight_test.go b/internal/api/handlers/management/in_flight_test.go new file mode 100644 index 00000000000..755c490fc14 --- /dev/null +++ b/internal/api/handlers/management/in_flight_test.go @@ -0,0 +1,63 @@ +package management + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func TestGetInFlightRequestsReturnsSnapshot(t *testing.T) { + gin.SetMode(gin.TestMode) + manager := coreauth.NewManager(nil, nil, nil) + h := &Handler{authManager: manager} + + rec := httptest.NewRecorder() + ginCtx, _ := gin.CreateTestContext(rec) + ginCtx.Request = httptest.NewRequest(http.MethodGet, "/v8/management/observability/requests/in-flight", nil) + + h.GetInFlightRequests(ginCtx) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + + var payload struct { + InFlight int64 `json:"in_flight"` + OldestStartedAt string `json:"oldest_started_at"` + ByProvider map[string]int64 `json:"by_provider"` + } + if errUnmarshal := json.Unmarshal(rec.Body.Bytes(), &payload); errUnmarshal != nil { + t.Fatalf("unmarshal response: %v", errUnmarshal) + } + if payload.InFlight != 0 { + t.Fatalf("in_flight = %d, want 0", payload.InFlight) + } +} + +func TestGetInFlightRequestsNilManager(t *testing.T) { + gin.SetMode(gin.TestMode) + h := &Handler{} + + rec := httptest.NewRecorder() + ginCtx, _ := gin.CreateTestContext(rec) + ginCtx.Request = httptest.NewRequest(http.MethodGet, "/v8/management/observability/requests/in-flight", nil) + + h.GetInFlightRequests(ginCtx) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + var payload struct { + InFlight int64 `json:"in_flight"` + } + if errUnmarshal := json.Unmarshal(rec.Body.Bytes(), &payload); errUnmarshal != nil { + t.Fatalf("unmarshal response: %v", errUnmarshal) + } + if payload.InFlight != 0 { + t.Fatalf("in_flight = %d, want 0", payload.InFlight) + } +} diff --git a/internal/api/handlers/management/model_definitions_test.go b/internal/api/handlers/management/model_definitions_test.go index 78646e8ca07..53f8b4f0a1f 100644 --- a/internal/api/handlers/management/model_definitions_test.go +++ b/internal/api/handlers/management/model_definitions_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "slices" + "strings" "sync/atomic" "testing" @@ -274,3 +275,105 @@ func TestRefreshModelDefinitions_UpdatesCatalogAndReportsChangedProviders(t *tes t.Fatalf("status = %d, want %d; body = %s", recFail.Code, http.StatusBadGateway, recFail.Body.String()) } } + +type oauthCatalogPlugin struct { + provider string + models []pluginapi.ModelInfo +} + +func (p oauthCatalogPlugin) Identifier() string { return p.provider } + +func (p oauthCatalogPlugin) ParseAuth(context.Context, pluginapi.AuthParseRequest) (pluginapi.AuthParseResponse, error) { + return pluginapi.AuthParseResponse{}, nil +} + +func (p oauthCatalogPlugin) StartLogin(context.Context, pluginapi.AuthLoginStartRequest) (pluginapi.AuthLoginStartResponse, error) { + return pluginapi.AuthLoginStartResponse{}, nil +} + +func (p oauthCatalogPlugin) PollLogin(context.Context, pluginapi.AuthLoginPollRequest) (pluginapi.AuthLoginPollResponse, error) { + return pluginapi.AuthLoginPollResponse{}, nil +} + +func (p oauthCatalogPlugin) RefreshAuth(context.Context, pluginapi.AuthRefreshRequest) (pluginapi.AuthRefreshResponse, error) { + return pluginapi.AuthRefreshResponse{}, nil +} + +func (p oauthCatalogPlugin) StaticModels(context.Context, pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{Provider: p.provider, Models: p.models}, nil +} + +func (p oauthCatalogPlugin) ModelsForAuth(context.Context, pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{Provider: p.provider, Models: p.models}, nil +} + +func (p oauthCatalogPlugin) Execute(context.Context, pluginapi.ExecutorRequest) (pluginapi.ExecutorResponse, error) { + return pluginapi.ExecutorResponse{}, nil +} + +func (p oauthCatalogPlugin) ExecuteStream(context.Context, pluginapi.ExecutorRequest) (pluginapi.ExecutorStreamResponse, error) { + return pluginapi.ExecutorStreamResponse{}, nil +} + +func (p oauthCatalogPlugin) CountTokens(context.Context, pluginapi.ExecutorRequest) (pluginapi.ExecutorResponse, error) { + return pluginapi.ExecutorResponse{}, nil +} + +func (p oauthCatalogPlugin) HttpRequest(context.Context, pluginapi.ExecutorHTTPRequest) (pluginapi.ExecutorHTTPResponse, error) { + return pluginapi.ExecutorHTTPResponse{}, nil +} + +func TestGetStaticModelDefinitions_OAuthPluginCatalogDecoupledFromRegistry(t *testing.T) { + for _, tc := range []struct { + name string + scope pluginapi.ExecutorModelScope + }{ + {name: "unset scope with auth provider", scope: ""}, + {name: "explicit oauth scope", scope: pluginapi.ExecutorModelScopeOAuth}, + {name: "explicit both scope with auth provider", scope: pluginapi.ExecutorModelScopeBoth}, + } { + t.Run(tc.name, func(t *testing.T) { + provider := "demo-oauth-7512-" + strings.ReplaceAll(tc.name, " ", "-") + reg := registry.GetGlobalRegistry() + pluginID := provider + "-plugin" + staticClientID := "plugin:" + pluginID + ":" + provider + ":executor" + t.Cleanup(func() { + reg.UnregisterClient(staticClientID) + }) + + plugin := oauthCatalogPlugin{ + provider: provider, + models: []pluginapi.ModelInfo{ + {ID: "demo-a", DisplayName: "Demo A"}, + {ID: "demo-blocked", DisplayName: "Demo Blocked"}, + }, + } + host := pluginhost.New() + host.RegisterPluginForTest(pluginID, pluginapi.Plugin{ + Capabilities: pluginapi.Capabilities{ + AuthProvider: plugin, + ModelProvider: plugin, + Executor: plugin, + ExecutorModelScope: tc.scope, + }, + }) + host.RegisterModels(t.Context(), reg) + host.RegisterExecutors(coreauth.NewManager(nil, nil, nil), reg) + + if available := reg.GetAvailableModelsByProvider(provider); len(available) != 0 { + t.Fatalf("GetAvailableModelsByProvider(%q) = %#v, want empty without active credentials", provider, available) + } + + h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, nil) + h.SetPluginHost(host) + + rec, body := invokeGetStaticModelDefinitions(t, h, provider) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d; body = %s", rec.Code, http.StatusOK, rec.Body.String()) + } + if len(body.Models) != 2 || body.Models[0].ID != "demo-a" || body.Models[1].ID != "demo-blocked" { + t.Fatalf("models = %#v, want [demo-a demo-blocked]", body.Models) + } + }) + } +} diff --git a/internal/api/handlers/management/oauth_siwc.go b/internal/api/handlers/management/oauth_siwc.go index 4f271821bc3..8aba13d99c1 100644 --- a/internal/api/handlers/management/oauth_siwc.go +++ b/internal/api/handlers/management/oauth_siwc.go @@ -19,6 +19,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/proxyutil" log "github.com/sirupsen/logrus" ) @@ -135,6 +136,32 @@ func resolveSIWCBindFile(authDir, path string) (string, map[string]any, error) { return realPath, metadata, nil } +func resolveSIWCBindProxyURL(target *coreauth.Auth, diskMetadata map[string]any) (string, error) { + if raw, exists := diskMetadata["proxy_url"]; exists && raw != nil { + str, ok := raw.(string) + if !ok { + return "", errors.New("invalid proxy_url") + } + trimmed := strings.TrimSpace(str) + if trimmed != "" { + if _, _, errBuild := proxyutil.BuildHTTPTransport(trimmed); errBuild != nil { + return "", errBuild + } + } + return trimmed, nil + } + if target != nil { + trimmed := strings.TrimSpace(target.ProxyURL) + if trimmed != "" { + if _, _, errBuild := proxyutil.BuildHTTPTransport(trimmed); errBuild != nil { + return "", errBuild + } + } + return trimmed, nil + } + return "", nil +} + // GetSIWCStatus returns the read-only local SIWC status ("off", "valid", or "invalid") // for a Codex credential without triggering any upstream refresh or verification request. func (h *Handler) GetSIWCStatus(c *gin.Context) { @@ -254,9 +281,14 @@ func (h *Handler) StartSIWCBind(c *gin.Context) { c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to initialize SIWC authorization"}) return } - var service siwcOAuthService = codex.NewCodexAuth(cfg) + accountProxyURL, errProxy := resolveSIWCBindProxyURL(target, metadata) + if errProxy != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "SIWC binding target has invalid proxy_url"}) + return + } + var service siwcOAuthService = codex.NewCodexAuthWithProxyURL(cfg, accountProxyURL) if factory != nil { - service = factory(cfg) + service = factory(cfg, accountProxyURL) } authURL, errURL := service.GenerateSIWCAuthURL(state, nonce, deviceID, codex.SIWCRedirectURI, pkce) if errURL != nil { diff --git a/internal/api/handlers/management/oauth_siwc_test.go b/internal/api/handlers/management/oauth_siwc_test.go index 4cf5a201d66..228a512dfe2 100644 --- a/internal/api/handlers/management/oauth_siwc_test.go +++ b/internal/api/handlers/management/oauth_siwc_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "net" "net/http" "net/http/httptest" "net/url" @@ -16,6 +17,7 @@ import ( "testing" "time" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" @@ -92,7 +94,7 @@ func setupSIWCFlow(t *testing.T, blocked bool) *siwcFixture { } }) } - h := &Handler{cfg: cfg, authManager: manager, siwcOAuthFactory: func(*config.Config) siwcOAuthService { return service }} + h := &Handler{cfg: cfg, authManager: manager, siwcOAuthFactory: func(*config.Config, string) siwcOAuthService { return service }} router := gin.New() router.POST("/bind", h.StartSIWCBind) router.GET("/siwc-status", h.GetSIWCStatus) @@ -813,3 +815,445 @@ func TestWriteAuthFileWaitsForCodexFileLock(t *testing.T) { }) } } + +func startSIWCConnectCountingProxy(t *testing.T, hits *atomic.Int32) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + http.Error(w, "proxy sentinel intercepted request", http.StatusBadGateway) + })) + t.Cleanup(srv.Close) + return srv +} + +func TestSIWCBindUsesAccountProxyPrecedence(t *testing.T) { + t.Run("account_proxy_overrides_global_proxy", func(t *testing.T) { + store := newOAuthSessionStore(time.Minute) + replaceOAuthSessionStoreForTest(t, store) + + var globalHits atomic.Int32 + var accountHits atomic.Int32 + globalProxy := startSIWCConnectCountingProxy(t, &globalHits) + accountProxy := startSIWCConnectCountingProxy(t, &accountHits) + + dir := t.TempDir() + path := filepath.Join(dir, "codex.json") + metadata := map[string]any{ + "type": "codex", + "access_token": "outer", + "refresh_token": "outer-refresh", + "account_id": "account", + "proxy_url": accountProxy.URL, + } + if errWrite := codex.WriteJSONFileAtomic(path, metadata); errWrite != nil { + t.Fatal(errWrite) + } + + cfg := &config.Config{AuthDir: dir} + cfg.ProxyURL = globalProxy.URL + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + auth, errRegister := manager.Register(context.Background(), &coreauth.Auth{ + ID: "codex.json", + FileName: "codex.json", + Provider: "codex", + ProxyURL: accountProxy.URL, + Metadata: metadata, + Attributes: map[string]string{"path": path}, + Status: coreauth.StatusActive, + }) + if errRegister != nil { + t.Fatal(errRegister) + } + + h := &Handler{cfg: cfg, authManager: manager} + router := gin.New() + router.POST("/bind", h.StartSIWCBind) + router.POST("/callback", h.PostOAuthCallbackV8) + router.GET("/status", h.GetAuthStatus) + + wStart := siwcRequest(t, router, http.MethodPost, "/bind", map[string]any{"name": auth.FileName}) + if wStart.Code != http.StatusOK { + t.Fatalf("start: %d %s", wStart.Code, wStart.Body.String()) + } + state := ojson.GetBytes(wStart.Body.Bytes(), "state").String() + session, ok := store.Get(state) + if !ok || session.SIWC == nil { + t.Fatal("missing SIWC session") + } + t.Cleanup(func() { CancelOAuthSession(state) }) + + wCB := siwcRequest(t, router, http.MethodPost, "/callback", map[string]any{ + "provider": "codex", + "redirect_url": siwcCallbackURL(state), + }) + if wCB.Code != http.StatusOK { + t.Fatalf("callback: %d %s", wCB.Code, wCB.Body.String()) + } + waitSIWCExchange(t, session.SIWC) + + if accountHits.Load() == 0 { + t.Fatalf("expected SIWC token exchange to use account proxy %s, got accountHits=%d globalHits=%d", accountProxy.URL, accountHits.Load(), globalHits.Load()) + } + if globalHits.Load() != 0 { + t.Fatalf("expected global proxy not to be used when account proxy is set, got globalHits=%d", globalHits.Load()) + } + }) + + t.Run("unreachable_account_proxy_fails_without_global_fallback", func(t *testing.T) { + for _, scheme := range []string{"http", "socks5h"} { + t.Run(scheme, func(t *testing.T) { + store := newOAuthSessionStore(time.Minute) + replaceOAuthSessionStoreForTest(t, store) + + var globalHits atomic.Int32 + globalProxy := startSIWCConnectCountingProxy(t, &globalHits) + + ln, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + deadProxyURL := scheme + "://" + ln.Addr().String() + _ = ln.Close() + + dir := t.TempDir() + path := filepath.Join(dir, "codex.json") + metadata := map[string]any{ + "type": "codex", + "access_token": "outer", + "refresh_token": "outer-refresh", + "account_id": "account", + "proxy_url": deadProxyURL, + } + if errWrite := codex.WriteJSONFileAtomic(path, metadata); errWrite != nil { + t.Fatal(errWrite) + } + + cfg := &config.Config{AuthDir: dir} + cfg.ProxyURL = globalProxy.URL + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + auth, errRegister := manager.Register(context.Background(), &coreauth.Auth{ + ID: "codex.json", + FileName: "codex.json", + Provider: "codex", + ProxyURL: deadProxyURL, + Metadata: metadata, + Attributes: map[string]string{"path": path}, + Status: coreauth.StatusActive, + }) + if errRegister != nil { + t.Fatal(errRegister) + } + + h := &Handler{cfg: cfg, authManager: manager} + router := gin.New() + router.POST("/bind", h.StartSIWCBind) + router.POST("/callback", h.PostOAuthCallbackV8) + router.GET("/status", h.GetAuthStatus) + + wStart := siwcRequest(t, router, http.MethodPost, "/bind", map[string]any{"name": auth.FileName}) + if wStart.Code != http.StatusOK { + t.Fatalf("start: %d %s", wStart.Code, wStart.Body.String()) + } + state := ojson.GetBytes(wStart.Body.Bytes(), "state").String() + session, ok := store.Get(state) + if !ok || session.SIWC == nil { + t.Fatal("missing SIWC session") + } + t.Cleanup(func() { CancelOAuthSession(state) }) + + wCB := siwcRequest(t, router, http.MethodPost, "/callback", map[string]any{ + "provider": "codex", + "redirect_url": siwcCallbackURL(state), + }) + if wCB.Code != http.StatusOK { + t.Fatalf("callback: %d %s", wCB.Code, wCB.Body.String()) + } + waitSIWCExchange(t, session.SIWC) + + status := performOAuthStatusRequest(t, router, state) + if status.Status != "error" { + t.Fatalf("expected error status on unreachable %s account proxy, got %#v", scheme, status) + } + if globalHits.Load() != 0 { + t.Fatalf("expected no fallback to global proxy when %s account proxy fails, got globalHits=%d", scheme, globalHits.Load()) + } + }) + } + }) +} + +func TestSIWCBindProxyEndToEndAndValidation(t *testing.T) { + cases := []struct { + name string + globalProxyMode string + accountProxyMode string + wantAccountHits int32 + wantGlobalHits int32 + wantDirectHits int32 + wantPreserveProxy bool + wantNoDiskProxyKey bool + }{ + { + name: "account_proxy_without_global_proxy", + globalProxyMode: "empty", + accountProxyMode: "proxy", + wantAccountHits: 1, + wantGlobalHits: 0, + wantDirectHits: 0, + wantPreserveProxy: true, + }, + { + name: "account_proxy_overrides_different_global_proxy", + globalProxyMode: "proxy", + accountProxyMode: "proxy", + wantAccountHits: 1, + wantGlobalHits: 0, + wantDirectHits: 0, + wantPreserveProxy: true, + }, + { + name: "no_account_proxy_inherits_global_proxy", + globalProxyMode: "proxy", + accountProxyMode: "empty", + wantAccountHits: 0, + wantGlobalHits: 1, + wantDirectHits: 0, + wantNoDiskProxyKey: true, + }, + { + name: "disk_proxy_url_used_when_memory_proxy_empty", + globalProxyMode: "proxy", + accountProxyMode: "disk-only", + wantAccountHits: 1, + wantGlobalHits: 0, + wantDirectHits: 0, + wantPreserveProxy: true, + }, + { + name: "memory_proxy_fallback_when_disk_missing_proxy_url", + globalProxyMode: "proxy", + accountProxyMode: "memory-only", + wantAccountHits: 1, + wantGlobalHits: 0, + wantDirectHits: 0, + wantNoDiskProxyKey: true, + }, + { + name: "direct_account_proxy_bypasses_global_proxy", + globalProxyMode: "proxy", + accountProxyMode: "direct", + wantAccountHits: 0, + wantGlobalHits: 0, + wantDirectHits: 1, + wantPreserveProxy: true, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + store := newOAuthSessionStore(time.Minute) + replaceOAuthSessionStoreForTest(t, store) + + var directHits atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-Via-Session-Proxy") != "1" { + directHits.Add(1) + } + doc := ojson.NewDocString("{}") + _ = doc.Set("access_token", "bound-siwc-access") + _ = doc.Set("refresh_token", "bound-siwc-refresh") + _ = doc.Set("id_token", "bound-siwc-id") + _ = doc.Set("expires_in", 3600) + _ = doc.Set("scope", codex.SIWCScope) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(doc.Bytes()) + })) + t.Cleanup(upstream.Close) + t.Cleanup(codex.OverrideSIWCTokenEndpointURLForTest(upstream.URL)) + + var globalHits atomic.Int32 + var globalProxyURL string + if tc.globalProxyMode == "proxy" { + gp := startForwardHTTPProxy(t, &globalHits, "", false) + t.Cleanup(gp.Close) + globalProxyURL = gp.URL + } + + var accountHits atomic.Int32 + var diskProxyURL string + var authProxyURL string + switch tc.accountProxyMode { + case "proxy": + ap := startForwardHTTPProxy(t, &accountHits, "", false) + t.Cleanup(ap.Close) + diskProxyURL = ap.URL + authProxyURL = ap.URL + case "disk-only": + ap := startForwardHTTPProxy(t, &accountHits, "", false) + t.Cleanup(ap.Close) + diskProxyURL = ap.URL + case "memory-only": + ap := startForwardHTTPProxy(t, &accountHits, "", false) + t.Cleanup(ap.Close) + authProxyURL = ap.URL + case "direct": + diskProxyURL = "direct" + authProxyURL = "direct" + } + + dir := t.TempDir() + path := filepath.Join(dir, "codex.json") + metadata := map[string]any{ + "type": "codex", + "access_token": "outer", + "refresh_token": "outer-refresh", + "account_id": "account", + "note": "keep-me", + } + if diskProxyURL != "" { + metadata["proxy_url"] = diskProxyURL + } + if errWrite := codex.WriteJSONFileAtomic(path, metadata); errWrite != nil { + t.Fatal(errWrite) + } + + cfg := &config.Config{AuthDir: dir} + cfg.ProxyURL = globalProxyURL + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + auth, errRegister := manager.Register(context.Background(), &coreauth.Auth{ + ID: "codex.json", + FileName: "codex.json", + Provider: "codex", + ProxyURL: authProxyURL, + Metadata: metadata, + Attributes: map[string]string{"path": path}, + Status: coreauth.StatusActive, + }) + if errRegister != nil { + t.Fatal(errRegister) + } + + h := &Handler{cfg: cfg, authManager: manager} + router := gin.New() + router.POST("/bind", h.StartSIWCBind) + router.POST("/callback", h.PostOAuthCallbackV8) + router.GET("/status", h.GetAuthStatus) + + wStart := siwcRequest(t, router, http.MethodPost, "/bind", map[string]any{"name": auth.FileName}) + if wStart.Code != http.StatusOK { + t.Fatalf("start: %d %s", wStart.Code, wStart.Body.String()) + } + state := ojson.GetBytes(wStart.Body.Bytes(), "state").String() + session, ok := store.Get(state) + if !ok || session.SIWC == nil { + t.Fatal("missing SIWC session") + } + t.Cleanup(func() { CancelOAuthSession(state) }) + + wCB := siwcRequest(t, router, http.MethodPost, "/callback", map[string]any{ + "provider": "codex", + "redirect_url": siwcCallbackURL(state), + }) + if wCB.Code != http.StatusOK { + t.Fatalf("callback: %d %s", wCB.Code, wCB.Body.String()) + } + waitSIWCExchange(t, session.SIWC) + + status := performOAuthStatusRequest(t, router, state) + if status.Status != "ok" { + t.Fatalf("status = %#v, want ok", status) + } + if accountHits.Load() != tc.wantAccountHits { + t.Fatalf("accountHits = %d, want %d", accountHits.Load(), tc.wantAccountHits) + } + if globalHits.Load() != tc.wantGlobalHits { + t.Fatalf("globalHits = %d, want %d", globalHits.Load(), tc.wantGlobalHits) + } + if directHits.Load() != tc.wantDirectHits { + t.Fatalf("directHits = %d, want %d", directHits.Load(), tc.wantDirectHits) + } + + got, okGot := manager.GetByID(auth.ID) + if !okGot || got == nil { + t.Fatal("missing auth after bind") + } + if got.Metadata["note"] != "keep-me" || got.Metadata["use_siwc"] != true { + t.Fatalf("unexpected memory metadata after bind: %#v", got.Metadata) + } + diskBytes, errRead := os.ReadFile(path) + if errRead != nil { + t.Fatal(errRead) + } + if !ojson.ValidBytes(diskBytes) { + t.Fatalf("invalid disk JSON: %s", string(diskBytes)) + } + disk := ojson.ParseBytes(diskBytes) + if disk.Get("note").String() != "keep-me" || !disk.Get("use_siwc").Bool() { + t.Fatalf("unexpected disk metadata after bind: %s", string(diskBytes)) + } + if tc.wantPreserveProxy { + if got.Metadata["proxy_url"] != diskProxyURL || disk.Get("proxy_url").String() != diskProxyURL { + t.Fatalf("proxy_url not preserved: meta=%v disk=%q want=%q", got.Metadata["proxy_url"], disk.Get("proxy_url").String(), diskProxyURL) + } + if authProxyURL != "" && got.ProxyURL != authProxyURL { + t.Fatalf("auth.ProxyURL not preserved: got=%q want=%q", got.ProxyURL, authProxyURL) + } + } + if tc.wantNoDiskProxyKey { + if disk.Get("proxy_url").Exists() { + t.Fatalf("unexpected proxy_url key written to disk: %s", disk.Get("proxy_url").Raw) + } + if authProxyURL != "" && got.ProxyURL != authProxyURL { + t.Fatalf("auth.ProxyURL not preserved: got=%q want=%q", got.ProxyURL, authProxyURL) + } + } + }) + } + + t.Run("rejects_invalid_account_proxy_url", func(t *testing.T) { + for _, badProxy := range []any{"://bad-proxy", "ftp://127.0.0.1:21", 12345} { + store := newOAuthSessionStore(time.Minute) + replaceOAuthSessionStoreForTest(t, store) + + dir := t.TempDir() + path := filepath.Join(dir, "codex.json") + metadata := map[string]any{ + "type": "codex", + "access_token": "outer", + "refresh_token": "outer-refresh", + "account_id": "account", + "proxy_url": badProxy, + } + if errWrite := codex.WriteJSONFileAtomic(path, metadata); errWrite != nil { + t.Fatal(errWrite) + } + + cfg := &config.Config{AuthDir: dir} + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + auth, errRegister := manager.Register(context.Background(), &coreauth.Auth{ + ID: "codex.json", + FileName: "codex.json", + Provider: "codex", + Metadata: metadata, + Attributes: map[string]string{"path": path}, + Status: coreauth.StatusActive, + }) + if errRegister != nil { + t.Fatal(errRegister) + } + + h := &Handler{cfg: cfg, authManager: manager} + router := gin.New() + router.POST("/bind", h.StartSIWCBind) + + wStart := siwcRequest(t, router, http.MethodPost, "/bind", map[string]any{"name": auth.FileName}) + if wStart.Code != http.StatusBadRequest { + t.Fatalf("bad proxy %v: status = %d, want 400; body = %s", badProxy, wStart.Code, wStart.Body.String()) + } + } + }) +} diff --git a/internal/api/handlers/management/plugin_store.go b/internal/api/handlers/management/plugin_store.go index ec2470f80f9..c9295f0c51f 100644 --- a/internal/api/handlers/management/plugin_store.go +++ b/internal/api/handlers/management/plugin_store.go @@ -158,7 +158,7 @@ func (h *Handler) ListPluginStore(c *gin.Context) { } } client := h.newPluginStoreClient(proxyURL, "", storeAuth) - latestVersions := h.latestPluginVersions(c.Request.Context(), client, latestInput) + latestVersions := h.latestPluginVersions(c.Request.Context(), client, latestInput, pluginStoreForceRefresh(c)) entries := make([]pluginStoreListEntry, 0, len(plugins)) for index, item := range plugins { @@ -220,6 +220,14 @@ func (h *Handler) ListPluginStore(c *gin.Context) { }) } +func pluginStoreForceRefresh(c *gin.Context) bool { + if c == nil { + return false + } + refresh := strings.TrimSpace(c.Query("refresh")) + return strings.EqualFold(refresh, "true") || refresh == "1" +} + func (h *Handler) InstallPluginFromStore(c *gin.Context) { h.installPluginFromStore(c, runtime.GOOS, runtime.GOARCH) } diff --git a/internal/api/handlers/management/plugin_store_release.go b/internal/api/handlers/management/plugin_store_release.go index 1e64dcf05ae..62e05465231 100644 --- a/internal/api/handlers/management/plugin_store_release.go +++ b/internal/api/handlers/management/plugin_store_release.go @@ -13,11 +13,13 @@ import ( const ( pluginReleaseCacheTTL = time.Hour pluginReleaseFailureCacheTTL = 30 * time.Second + pluginReleaseRefreshFloor = 10 * time.Second pluginReleaseConcurrency = 2 ) type pluginReleaseCacheEntry struct { version string + checkedAt time.Time nextCheckAt time.Time } @@ -64,7 +66,7 @@ func (cache *pluginReleaseCache) cached(client pluginstore.Client, plugin plugin } // latestPluginVersions preserves catalog order, including skipped placeholders. -func (h *Handler) latestPluginVersions(ctx context.Context, client pluginstore.Client, plugins []pluginstore.Plugin) []string { +func (h *Handler) latestPluginVersions(ctx context.Context, client pluginstore.Client, plugins []pluginstore.Plugin, force bool) []string { versions := make([]string, len(plugins)) var wg sync.WaitGroup for index, plugin := range plugins { @@ -74,14 +76,14 @@ func (h *Handler) latestPluginVersions(ctx context.Context, client pluginstore.C wg.Add(1) go func(index int) { defer wg.Done() - versions[index] = h.latestPluginVersion(ctx, client, plugins[index]) + versions[index] = h.latestPluginVersion(ctx, client, plugins[index], force) }(index) } wg.Wait() return versions } -func (h *Handler) latestPluginVersion(ctx context.Context, client pluginstore.Client, plugin pluginstore.Plugin) string { +func (h *Handler) latestPluginVersion(ctx context.Context, client pluginstore.Client, plugin pluginstore.Plugin, force bool) string { if pluginstore.PluginInstallType(plugin) != pluginstore.InstallTypeGitHubRelease { return "" } @@ -95,7 +97,12 @@ func (h *Handler) latestPluginVersion(ctx context.Context, client pluginstore.Cl for { cache.mu.Lock() entry = cache.entries[key] - if cache.now().Before(entry.nextCheckAt) || ctx.Err() != nil { + now := cache.now() + fresh := now.Before(entry.nextCheckAt) + if force { + fresh = !entry.checkedAt.IsZero() && now.Before(entry.checkedAt.Add(pluginReleaseRefreshFloor)) + } + if fresh || ctx.Err() != nil { cache.mu.Unlock() return entry.version } @@ -137,18 +144,21 @@ func (h *Handler) latestPluginVersion(ctx context.Context, client pluginstore.Cl version, errRelease = pluginstore.ReleaseVersion(release) } if ctx.Err() == nil { - ttl := pluginReleaseFailureCacheTTL - if errRelease != nil { - log.WithError(errRelease).WithField("plugin_id", plugin.ID).Warn("pluginstore: failed to fetch latest release") - } else { - entry.version = version - ttl = pluginReleaseCacheTTL - } // Start the TTL when the lookup finishes, not when it was queued. - entry.nextCheckAt = cache.now().Add(ttl) + now := cache.now() + entry.checkedAt = now var rateLimit *pluginstore.RateLimitError - if errors.As(errRelease, &rateLimit) { + if errRelease == nil { + entry.version = version + entry.nextCheckAt = now.Add(pluginReleaseCacheTTL) + } else if errors.As(errRelease, &rateLimit) { + log.WithError(errRelease).WithField("plugin_id", plugin.ID).Warn("pluginstore: failed to fetch latest release") entry.nextCheckAt = rateLimit.RetryAt + } else { + log.WithError(errRelease).WithField("plugin_id", plugin.ID).Warn("pluginstore: failed to fetch latest release") + if next := now.Add(pluginReleaseFailureCacheTTL); next.After(entry.nextCheckAt) { + entry.nextCheckAt = next + } } } } diff --git a/internal/api/handlers/management/plugin_store_release_test.go b/internal/api/handlers/management/plugin_store_release_test.go index 82bf26250e8..d0ea54ea840 100644 --- a/internal/api/handlers/management/plugin_store_release_test.go +++ b/internal/api/handlers/management/plugin_store_release_test.go @@ -134,7 +134,7 @@ func TestPluginReleaseCacheRetainsSuccessAndUsesCompletionTime(t *testing.T) { })} check := func(want string, wantCalls int) { t.Helper() - if got := h.latestPluginVersion(context.Background(), client, plugin); got != want || calls != wantCalls { + if got := h.latestPluginVersion(context.Background(), client, plugin, false); got != want || calls != wantCalls { t.Fatalf("version=%q calls=%d, want %q/%d", got, calls, want, wantCalls) } } @@ -176,11 +176,11 @@ func TestPluginReleaseCacheCoalescesConcurrentLookups(t *testing.T) { h := &Handler{} plugin := pluginstore.Plugin{Repository: "https://github.com/test/plugin"} results := make(chan string, 21) - go func() { results <- h.latestPluginVersion(context.Background(), client, plugin) }() + go func() { results <- h.latestPluginVersion(context.Background(), client, plugin, false) }() <-started for range 20 { ctx := &pluginReleaseWaitContext{Context: context.Background(), waiting: make(chan struct{})} - go func() { results <- h.latestPluginVersion(ctx, client, plugin) }() + go func() { results <- h.latestPluginVersion(ctx, client, plugin, false) }() <-ctx.waiting } close(release) @@ -211,11 +211,11 @@ func TestPluginReleaseCacheCanceledLeaderHandsOffToFollower(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() leaderResult := make(chan string, 1) - go func() { leaderResult <- h.latestPluginVersion(ctx, client, plugin) }() + go func() { leaderResult <- h.latestPluginVersion(ctx, client, plugin, false) }() <-started waitCtx := &pluginReleaseWaitContext{Context: context.Background(), waiting: make(chan struct{})} followerResult := make(chan string, 1) - go func() { followerResult <- h.latestPluginVersion(waitCtx, client, plugin) }() + go func() { followerResult <- h.latestPluginVersion(waitCtx, client, plugin, false) }() <-waitCtx.waiting cancel() if got := <-leaderResult; got != "" { @@ -237,13 +237,13 @@ func TestPluginReleaseCacheCanceledFollowerDoesNotCancelLeader(t *testing.T) { h := &Handler{} plugin := pluginstore.Plugin{Repository: "https://github.com/test/plugin"} leaderResult := make(chan string, 1) - go func() { leaderResult <- h.latestPluginVersion(context.Background(), client, plugin) }() + go func() { leaderResult <- h.latestPluginVersion(context.Background(), client, plugin, false) }() <-started ctx, cancel := context.WithCancel(context.Background()) defer cancel() waitCtx := &pluginReleaseWaitContext{Context: ctx, waiting: make(chan struct{})} followerResult := make(chan string, 1) - go func() { followerResult <- h.latestPluginVersion(waitCtx, client, plugin) }() + go func() { followerResult <- h.latestPluginVersion(waitCtx, client, plugin, false) }() <-waitCtx.waiting cancel() if got := <-followerResult; got != "" { @@ -269,7 +269,7 @@ func TestPluginReleaseCacheSharesConcurrencyAndCancelsQueuedLookup(t *testing.T) results := make(chan string, pluginReleaseConcurrency) for index := range pluginReleaseConcurrency { go func() { - results <- h.latestPluginVersion(context.Background(), client, pluginstore.Plugin{Repository: fmt.Sprintf("https://github.com/test/plugin-%d", index)}) + results <- h.latestPluginVersion(context.Background(), client, pluginstore.Plugin{Repository: fmt.Sprintf("https://github.com/test/plugin-%d", index)}, false) }() } for range pluginReleaseConcurrency { @@ -280,7 +280,7 @@ func TestPluginReleaseCacheSharesConcurrencyAndCancelsQueuedLookup(t *testing.T) waitCtx := &pluginReleaseWaitContext{Context: ctx, waiting: make(chan struct{})} queuedResult := make(chan string, 1) plugin := pluginstore.Plugin{Repository: "https://github.com/test/queued"} - go func() { queuedResult <- h.latestPluginVersion(waitCtx, client, plugin) }() + go func() { queuedResult <- h.latestPluginVersion(waitCtx, client, plugin, false) }() <-waitCtx.waiting cancel() if got := <-queuedResult; got != "" || calls.Load() != pluginReleaseConcurrency { @@ -290,7 +290,7 @@ func TestPluginReleaseCacheSharesConcurrencyAndCancelsQueuedLookup(t *testing.T) for range pluginReleaseConcurrency { <-results } - if got := h.latestPluginVersion(context.Background(), client, plugin); got != "1.0.0" || calls.Load() != pluginReleaseConcurrency+1 { + if got := h.latestPluginVersion(context.Background(), client, plugin, false); got != "1.0.0" || calls.Load() != pluginReleaseConcurrency+1 { t.Fatalf("canceled lookup was negatively cached: version=%q calls=%d", got, calls.Load()) } } @@ -310,7 +310,7 @@ func TestPluginReleaseCacheSeparatesCredentialsAndEgress(t *testing.T) { client.ResolvedAuth = []pluginstore.ResolvedAuthConfig{{Match: "https://api.github.com/", Type: pluginstore.AuthTypeGitHubToken, Token: pluginstore.Secret(token)}} client.ResolvedAuthExpiresAt = time.Now().Add(time.Hour) } - if got := h.latestPluginVersion(context.Background(), client, plugin); got != "1.0.0" { + if got := h.latestPluginVersion(context.Background(), client, plugin, false); got != "1.0.0" { t.Fatalf("version = %q", got) } } @@ -318,7 +318,7 @@ func TestPluginReleaseCacheSeparatesCredentialsAndEgress(t *testing.T) { t.Fatalf("calls = %d, want 3", calls.Load()) } client.NetworkScope = "other-proxy" - h.latestPluginVersion(context.Background(), client, plugin) + h.latestPluginVersion(context.Background(), client, plugin, false) if calls.Load() != 4 { t.Fatalf("calls after proxy change = %d, want 4", calls.Load()) } @@ -352,7 +352,7 @@ func TestPluginReleaseChecksStopQueuedRequestsDuringCooldown(t *testing.T) { h.pluginReleases.entries[pluginReleaseKey(client, plugins[index])] = pluginReleaseCacheEntry{version: "1.0.0"} } result := make(chan []string, 1) - go func() { result <- h.latestPluginVersions(context.Background(), client, plugins) }() + go func() { result <- h.latestPluginVersions(context.Background(), client, plugins, false) }() for range pluginReleaseConcurrency { <-started } @@ -463,3 +463,132 @@ func TestListPluginStoreUsesCachedUninstalledVersionWithoutRefresh(t *testing.T) t.Fatalf("plugins=%#v requests=%v", body.Plugins, httpClient.counts) } } + +func listPluginStoreWithQueryForTest(t *testing.T, h *Handler, query string) pluginStoreListResponse { + t.Helper() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v8/management/plugins/store"+query, nil) + h.ListPluginStore(c) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d; body=%s", rec.Code, rec.Body.String()) + } + var body pluginStoreListResponse + if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil { + t.Fatal(errDecode) + } + return body +} + +func TestListPluginStoreRefreshBypassesCacheWithFloor(t *testing.T) { + t.Parallel() + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + releaseTag := "v0.1.0" + var releaseCalls int + h := &Handler{ + cfg: &config.Config{Plugins: config.PluginsConfig{ + Dir: writeManagementPluginFile(t, "sample-provider-v0.1.0"), + }}, + pluginReleases: pluginReleaseCache{nowFunc: func() time.Time { return now }}, + pluginStoreHTTPClient: pluginReleaseDoerFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host != "api.github.com" { + return fakePluginStoreHTTPClient{pluginstore.DefaultRegistryURL: registryJSON(t)}.Do(req) + } + releaseCalls++ + return pluginReleaseResponse(releaseTag), nil + }), + } + + body := listPluginStoreWithQueryForTest(t, h, "") + if body.Plugins[0].Version != "0.1.0" || body.Plugins[0].UpdateAvailable || releaseCalls != 1 { + t.Fatalf("initial entry=%#v releaseCalls=%d", body.Plugins[0], releaseCalls) + } + + releaseTag = "v0.2.0" + now = now.Add(time.Minute) + body = listPluginStoreWithQueryForTest(t, h, "") + if body.Plugins[0].Version != "0.1.0" || body.Plugins[0].UpdateAvailable || releaseCalls != 1 { + t.Fatalf("cached entry=%#v releaseCalls=%d, want cached 0.1.0 without network call", body.Plugins[0], releaseCalls) + } + + body = listPluginStoreWithQueryForTest(t, h, "?refresh=true") + if body.Plugins[0].Version != "0.2.0" || !body.Plugins[0].UpdateAvailable || releaseCalls != 2 { + t.Fatalf("refreshed entry=%#v releaseCalls=%d, want 0.2.0 with update_available=true and 2 calls", body.Plugins[0], releaseCalls) + } + + releaseTag = "v0.3.0" + now = now.Add(5 * time.Second) + body = listPluginStoreWithQueryForTest(t, h, "?refresh=true") + if body.Plugins[0].Version != "0.2.0" || releaseCalls != 2 { + t.Fatalf("floor-throttled entry=%#v releaseCalls=%d, want 0.2.0 and 2 calls within 10s floor", body.Plugins[0], releaseCalls) + } + + now = now.Add(5 * time.Second) + body = listPluginStoreWithQueryForTest(t, h, "?refresh=1") + if body.Plugins[0].Version != "0.3.0" || !body.Plugins[0].UpdateAvailable || releaseCalls != 3 { + t.Fatalf("refresh=1 entry=%#v releaseCalls=%d, want 0.3.0 and 3 calls after 10s floor", body.Plugins[0], releaseCalls) + } +} + +func TestListPluginStoreRefreshPreservesRateLimiterAndSkipsUninstalled(t *testing.T) { + t.Parallel() + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + reset := time.Now().Add(time.Hour).Truncate(time.Second) + registry := pluginstore.Registry{ + SchemaVersion: pluginstore.SchemaVersion, + Plugins: []pluginstore.Plugin{ + { + ID: "installed-plugin", Name: "Installed", Description: "Installed plugin", Author: "owner", + Version: "0.1.0", Repository: "https://github.com/owner/installed-plugin", + }, + { + ID: "uninstalled-plugin", Name: "Uninstalled", Description: "Uninstalled plugin", Author: "owner", + Version: "0.1.0", Repository: "https://github.com/owner/uninstalled-plugin", + }, + }, + } + registryBytes, errMarshal := json.Marshal(registry) + if errMarshal != nil { + t.Fatal(errMarshal) + } + var releaseCalls int + rateLimited := false + h := &Handler{ + cfg: &config.Config{Plugins: config.PluginsConfig{ + Dir: writeManagementPluginFile(t, "installed-plugin-v0.1.0"), + }}, + pluginReleases: pluginReleaseCache{nowFunc: func() time.Time { return now }}, + pluginStoreRateLimiter: &pluginstore.GitHubRateLimiter{}, + pluginStoreHTTPClient: pluginReleaseDoerFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host != "api.github.com" { + return fakePluginStoreHTTPClient{pluginstore.DefaultRegistryURL: registryBytes}.Do(req) + } + releaseCalls++ + if !rateLimited { + return pluginReleaseResponse("v0.2.0"), nil + } + headers := make(http.Header) + headers.Set("X-RateLimit-Remaining", "0") + headers.Set("X-RateLimit-Reset", strconv.FormatInt(reset.Unix(), 10)) + return &http.Response{StatusCode: http.StatusForbidden, Header: headers, Body: io.NopCloser(strings.NewReader("limited"))}, nil + }), + } + + body := listPluginStoreWithQueryForTest(t, h, "?refresh=true") + if body.Plugins[0].Version != "0.2.0" || body.Plugins[1].Version != "0.1.0" || releaseCalls != 1 { + t.Fatalf("first refresh plugins=%#v releaseCalls=%d, want installed=0.2.0 uninstalled=0.1.0 calls=1", body.Plugins, releaseCalls) + } + + rateLimited = true + now = now.Add(time.Minute) + body = listPluginStoreWithQueryForTest(t, h, "?refresh=true") + if body.Plugins[0].Version != "0.2.0" || releaseCalls != 2 { + t.Fatalf("rate-limited refresh plugins=%#v releaseCalls=%d, want cached 0.2.0 and 2 calls", body.Plugins, releaseCalls) + } + + now = now.Add(time.Minute) + body = listPluginStoreWithQueryForTest(t, h, "?refresh=true") + if body.Plugins[0].Version != "0.2.0" || releaseCalls != 2 { + t.Fatalf("cooldown refresh plugins=%#v releaseCalls=%d, want rate limiter to block network call during cooldown", body.Plugins, releaseCalls) + } +} diff --git a/internal/api/handlers/management/plugin_store_test.go b/internal/api/handlers/management/plugin_store_test.go index 4669b73935e..18b7a613ca0 100644 --- a/internal/api/handlers/management/plugin_store_test.go +++ b/internal/api/handlers/management/plugin_store_test.go @@ -16,6 +16,7 @@ import ( "strings" "sync" "testing" + "time" "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" @@ -402,6 +403,74 @@ func TestListPluginStoreShowsLatestReleaseVersionAndCaches(t *testing.T) { } } +func TestListPluginStoreRefreshQueryBypassesCache(t *testing.T) { + t.Parallel() + + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + httpClient := &countingPluginStoreHTTPClient{responses: fakePluginStoreHTTPClient{ + "https://registry.example/registry.json": registryJSON(t), + "https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/latest": []byte(`{ + "tag_name": "v0.1.0", + "assets": [] + }`), + }} + h := &Handler{ + cfg: &config.Config{ + Plugins: config.PluginsConfig{ + Enabled: true, + Dir: writeManagementPluginFile(t, "sample-provider-v0.1.0"), + }, + }, + configFilePath: writeTestConfigFile(t), + pluginStoreRegistryURL: "https://registry.example/registry.json", + pluginStoreHTTPClient: httpClient, + pluginReleases: pluginReleaseCache{nowFunc: func() time.Time { return now }}, + } + + listWithQuery := func(query string) pluginStoreListResponse { + t.Helper() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v8/management/plugins/store"+query, nil) + h.ListPluginStore(c) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String()) + } + var body pluginStoreListResponse + if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil { + t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String()) + } + return body + } + + body := listWithQuery("") + if body.Plugins[0].Version != "0.1.0" || body.Plugins[0].UpdateAvailable { + t.Fatalf("initial plugin = %#v, want 0.1.0 without update", body.Plugins[0]) + } + + httpClient.mu.Lock() + httpClient.responses["https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/latest"] = []byte(`{ + "tag_name": "v0.2.0", + "assets": [] + }`) + httpClient.mu.Unlock() + + now = now.Add(pluginReleaseRefreshFloor) + body = listWithQuery("?refresh=false") + if body.Plugins[0].Version != "0.1.0" || body.Plugins[0].UpdateAvailable { + t.Fatalf("refresh=false plugin = %#v, want cached 0.1.0", body.Plugins[0]) + } + + body = listWithQuery("?refresh=true") + if body.Plugins[0].Version != "0.2.0" || !body.Plugins[0].UpdateAvailable { + t.Fatalf("refresh=true plugin = %#v, want refreshed 0.2.0 with update_available=true", body.Plugins[0]) + } + releaseCalls := httpClient.count("https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/latest") + if releaseCalls != 2 { + t.Fatalf("latest release fetched %d times, want 2", releaseCalls) + } +} + func TestListPluginStoreFallsBackToRegistryVersion(t *testing.T) { t.Parallel() diff --git a/internal/api/handlers/management/plugins.go b/internal/api/handlers/management/plugins.go index f09ef236566..5fa91a22f06 100644 --- a/internal/api/handlers/management/plugins.go +++ b/internal/api/handlers/management/plugins.go @@ -29,6 +29,7 @@ type pluginListEntry struct { Path string `json:"path"` Configured bool `json:"configured"` Registered bool `json:"registered"` + Priority *int `json:"priority,omitempty"` Enabled bool `json:"enabled"` EffectiveEnabled bool `json:"effective_enabled"` SupportsOAuth bool `json:"supports_oauth"` @@ -126,11 +127,17 @@ func (h *Handler) ListPlugins(c *gin.Context) { } entries[id] = entry } + v8Request := isManagementV8PluginsRequest(c) if host != nil { for _, info := range host.RegisteredPlugins() { entry := entries[info.ID] entry.ID = htmlsanitize.String(info.ID) entry.Registered = true + if v8Request { + // Expose runtime snapshot priority on v8; the deprecated v0 route keeps its frozen response shape. + priority := info.Priority + entry.Priority = &priority + } entry.SupportsOAuth = info.SupportsOAuth entry.OAuthProvider = htmlsanitize.String(info.OAuthProvider) entry.OAuthProviders = pluginOAuthProviders(info.OAuthProviders) @@ -170,6 +177,17 @@ func (h *Handler) ListPlugins(c *gin.Context) { }) } +func isManagementV8PluginsRequest(c *gin.Context) bool { + if c == nil { + return false + } + if c.GetBool(ConfigV8ContextKey) { + return true + } + return c.Request != nil && c.Request.URL != nil && + (c.Request.URL.Path == "/v8/management/plugins" || c.Request.URL.Path == "/v8/management/plugins/") +} + // GetPluginConfig returns the preserved plugins.configs. object as JSON. func (h *Handler) GetPluginConfig(c *gin.Context) { id, okID := pluginIDFromRequest(c) diff --git a/internal/api/handlers/management/plugins_test.go b/internal/api/handlers/management/plugins_test.go index 008fb675cd0..d9e1fa09e17 100644 --- a/internal/api/handlers/management/plugins_test.go +++ b/internal/api/handlers/management/plugins_test.go @@ -14,6 +14,7 @@ import ( "testing" "time" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" @@ -172,6 +173,118 @@ func TestListPluginsIncludesScannedAndConfiguredPlugins(t *testing.T) { } } +func TestListPluginsRuntimePriority(t *testing.T) { + t.Parallel() + + pluginsDir := writeManagementPluginFile(t, "scanned") + archDir := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH) + discoveredConfiguredPath := filepath.Join(archDir, "discovered-configured"+managementPluginExtension(runtime.GOOS)) + if errWrite := os.WriteFile(discoveredConfiguredPath, []byte("x"), 0o644); errWrite != nil { + t.Fatalf("WriteFile(%s) error = %v", discoveredConfiguredPath, errWrite) + } + + host := pluginhost.New() + host.RegisterPluginForTest("registered", pluginapi.Plugin{}) + host.RegisterPluginWithPriorityForTest("zero-priority", 0, pluginapi.Plugin{}) + host.RegisterPluginWithPriorityForTest("negative-priority", -5, pluginapi.Plugin{}) + + enabled := true + disabled := false + h := &Handler{ + cfg: &config.Config{ + Plugins: config.PluginsConfig{ + Enabled: true, + Dir: pluginsDir, + Configs: map[string]config.PluginInstanceConfig{ + "registered": {Enabled: &enabled, Priority: 99}, + "zero-priority": {Enabled: &enabled, Priority: 50}, + "negative-priority": {Enabled: &disabled, Priority: 10}, + "configured-only": {Enabled: &enabled, Priority: 42}, + "discovered-configured": {Enabled: &disabled, Priority: 24}, + }, + }, + }, + pluginHost: host, + } + + router := gin.New() + v8 := router.Group("/v8/management", func(c *gin.Context) { + c.Set(ConfigV8ContextKey, true) + c.Next() + }) + v8.GET("/plugins", h.ListPlugins) + router.GET("/v0/management/plugins", h.ListPlugins) + + directV8Router := gin.New() + directV8Router.GET("/v8/management/plugins", h.ListPlugins) + + fetchEntries := func(t *testing.T, srv http.Handler, path string) map[string]ojson.Result { + t.Helper() + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + if rec.Code != http.StatusOK || !ojson.ValidBytes(rec.Body.Bytes()) { + t.Fatalf("GET %s status=%d body=%s", path, rec.Code, rec.Body.String()) + } + plugins := ojson.Parse(rec.Body.String()).Get("plugins") + if !plugins.IsArray() { + t.Fatalf("GET %s missing plugins array: %s", path, rec.Body.String()) + } + out := make(map[string]ojson.Result, len(plugins.Array())) + for _, item := range plugins.Array() { + out[item.Get("id").String()] = item + } + return out + } + + for _, tc := range []struct { + name string + srv http.Handler + }{ + {name: "v8-context", srv: router}, + {name: "v8-direct-path", srv: directV8Router}, + } { + t.Run(tc.name, func(t *testing.T) { + entries := fetchEntries(t, tc.srv, "/v8/management/plugins") + for id, want := range map[string]int64{ + "registered": 1, + "zero-priority": 0, + "negative-priority": -5, + } { + reg, okReg := entries[id] + if !okReg { + t.Fatalf("missing %s plugin entry", id) + } + priority := reg.Get("priority") + if !priority.Exists() || priority.Type != ojson.Number || priority.Int() != want { + t.Fatalf("%s priority = %s (exists=%v, type=%v), want numeric runtime priority %d; entry=%s", id, priority.Raw, priority.Exists(), priority.Type, want, reg.Raw) + } + } + for _, unregisteredID := range []string{"configured-only", "scanned", "discovered-configured"} { + entry, okEntry := entries[unregisteredID] + if !okEntry { + t.Fatalf("missing %s plugin entry", unregisteredID) + } + if p := entry.Get("priority"); p.Exists() { + t.Fatalf("%s unregistered plugin exposed priority = %s; entry=%s", unregisteredID, p.Raw, entry.Raw) + } + } + }) + } + + t.Run("v0-deprecated-frozen", func(t *testing.T) { + entries := fetchEntries(t, router, "/v0/management/plugins") + for _, id := range []string{"registered", "zero-priority", "negative-priority", "configured-only", "scanned", "discovered-configured"} { + entry, okEntry := entries[id] + if !okEntry { + t.Fatalf("missing %s plugin entry on v0", id) + } + if p := entry.Get("priority"); p.Exists() { + t.Fatalf("deprecated v0 route exposed priority on %s: %s", id, entry.Raw) + } + } + }) +} + func TestListPluginsUsesConfiguredStoreVersionWhenFilesCoexist(t *testing.T) { t.Parallel() diff --git a/internal/api/interceptor_host.go b/internal/api/interceptor_host.go new file mode 100644 index 00000000000..36802104998 --- /dev/null +++ b/internal/api/interceptor_host.go @@ -0,0 +1,271 @@ +package api + +import ( + "context" + "fmt" + "reflect" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +// delegatedInterceptorHost forwards PluginInterceptorHost calls to an +// embedder-provided primary host while delegating model routing, plugin +// executor dispatch, request lifecycle, and websocket observer callbacks back +// to the internal plugin host. Installing this host keeps plugin model +// routing, plugin executor routes, lifecycle callbacks, and websocket +// observers functional when a custom interceptor host replaces the plugin +// host on request handlers. + +type delegatedInterceptorHost struct { + primary handlers.PluginInterceptorHost + pluginHost *pluginhost.Host +} + +var ( + _ handlers.PluginInterceptorHost = (*delegatedInterceptorHost)(nil) + _ handlers.PluginExecutorHost = (*delegatedInterceptorHost)(nil) +) + +// InterceptRequestBeforeAuth delegates to the embedder's host. +func (h *delegatedInterceptorHost) InterceptRequestBeforeAuth(ctx context.Context, req pluginapi.RequestInterceptRequest) pluginapi.RequestInterceptResponse { + return h.primary.InterceptRequestBeforeAuth(ctx, req) +} + +// InterceptRequestBeforeAuthExcept forwards the plugin-skip identifier to the embedder's host when it +// implements the skip-aware interface, preventing plugin-initiated nested executions +// from re-entering their own interceptor; otherwise it falls back to the base method. +func (h *delegatedInterceptorHost) InterceptRequestBeforeAuthExcept(ctx context.Context, req pluginapi.RequestInterceptRequest, skipPluginID string) pluginapi.RequestInterceptResponse { + if skipper, ok := h.primary.(interface { + InterceptRequestBeforeAuthExcept(context.Context, pluginapi.RequestInterceptRequest, string) pluginapi.RequestInterceptResponse + }); ok { + return skipper.InterceptRequestBeforeAuthExcept(ctx, req, skipPluginID) + } + return h.primary.InterceptRequestBeforeAuth(ctx, req) +} + +// InterceptRequestAfterAuth delegates to the embedder's host. +func (h *delegatedInterceptorHost) InterceptRequestAfterAuth(ctx context.Context, req pluginapi.RequestInterceptRequest) pluginapi.RequestInterceptResponse { + return h.primary.InterceptRequestAfterAuth(ctx, req) +} + +// InterceptRequestAfterAuthExcept forwards the plugin-skip identifier to the embedder's host when it +// implements the skip-aware interface, preventing plugin-initiated nested executions +// from re-entering their own interceptor; otherwise it falls back to the base method. +func (h *delegatedInterceptorHost) InterceptRequestAfterAuthExcept(ctx context.Context, req pluginapi.RequestInterceptRequest, skipPluginID string) pluginapi.RequestInterceptResponse { + if skipper, ok := h.primary.(interface { + InterceptRequestAfterAuthExcept(context.Context, pluginapi.RequestInterceptRequest, string) pluginapi.RequestInterceptResponse + }); ok { + return skipper.InterceptRequestAfterAuthExcept(ctx, req, skipPluginID) + } + return h.primary.InterceptRequestAfterAuth(ctx, req) +} + +// InterceptResponse delegates to the embedder's host. +func (h *delegatedInterceptorHost) InterceptResponse(ctx context.Context, req pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + return h.primary.InterceptResponse(ctx, req) +} + +// InterceptResponseExcept forwards the plugin-skip identifier to the embedder's host when it +// implements the skip-aware interface, preventing plugin-initiated nested executions +// from re-entering their own interceptor; otherwise it falls back to the base method. +func (h *delegatedInterceptorHost) InterceptResponseExcept(ctx context.Context, req pluginapi.ResponseInterceptRequest, skipPluginID string) pluginapi.ResponseInterceptResponse { + if skipper, ok := h.primary.(interface { + InterceptResponseExcept(context.Context, pluginapi.ResponseInterceptRequest, string) pluginapi.ResponseInterceptResponse + }); ok { + return skipper.InterceptResponseExcept(ctx, req, skipPluginID) + } + return h.primary.InterceptResponse(ctx, req) +} + +// InterceptStreamChunk delegates to the embedder's host. +func (h *delegatedInterceptorHost) InterceptStreamChunk(ctx context.Context, req pluginapi.StreamChunkInterceptRequest) pluginapi.StreamChunkInterceptResponse { + return h.primary.InterceptStreamChunk(ctx, req) +} + +// InterceptStreamChunkExcept forwards the plugin-skip identifier to the embedder's host when it +// implements the skip-aware interface, preventing plugin-initiated nested executions +// from re-entering their own interceptor; otherwise it falls back to the base method. +func (h *delegatedInterceptorHost) InterceptStreamChunkExcept(ctx context.Context, req pluginapi.StreamChunkInterceptRequest, skipPluginID string) pluginapi.StreamChunkInterceptResponse { + if skipper, ok := h.primary.(interface { + InterceptStreamChunkExcept(context.Context, pluginapi.StreamChunkInterceptRequest, string) pluginapi.StreamChunkInterceptResponse + }); ok { + return skipper.InterceptStreamChunkExcept(ctx, req, skipPluginID) + } + return h.primary.InterceptStreamChunk(ctx, req) +} + +// RouteModel delegates to the internal plugin host so model routing stays +// functional when the interceptor host is replaced. This mirrors the +// PluginHost-as-router fallback in handlers.modelRouterHost. +func (h *delegatedInterceptorHost) RouteModel(ctx context.Context, req pluginapi.ModelRouteRequest) (pluginapi.ModelRouteResponse, bool) { + if h.pluginHost == nil { + return pluginapi.ModelRouteResponse{}, false + } + return h.pluginHost.RouteModel(ctx, req) +} + +// RouteModelExcept delegates skip-aware routing to the internal plugin host. +func (h *delegatedInterceptorHost) RouteModelExcept(ctx context.Context, req pluginapi.ModelRouteRequest, skipPluginID string) (pluginapi.ModelRouteResponse, bool) { + if h.pluginHost == nil { + return pluginapi.ModelRouteResponse{}, false + } + return h.pluginHost.RouteModelExcept(ctx, req, skipPluginID) +} + +// HasModelRouters delegates to the internal plugin host. +func (h *delegatedInterceptorHost) HasModelRouters() bool { + return h.pluginHost != nil && h.pluginHost.HasModelRouters() +} + +// HasModelRoutersExcept delegates skip-aware detection to the internal plugin host. +func (h *delegatedInterceptorHost) HasModelRoutersExcept(skipPluginID string) bool { + return h.pluginHost != nil && h.pluginHost.HasModelRoutersExcept(skipPluginID) +} + +// HasRequestInterceptors reports whether the embedder's host actually has +// request interceptors. The primary host is queried first through the optional +// detector interface; when it does not implement detection, the handler's +// default true semantics apply so the interceptor is invoked. +func (h *delegatedInterceptorHost) HasRequestInterceptors() bool { + if h.primary == nil { + return false + } + if detector, ok := h.primary.(interface{ HasRequestInterceptors() bool }); ok { + return detector.HasRequestInterceptors() + } + return true +} + +// HasStreamInterceptors reports whether the embedder's host has stream +// interceptors, with the same optional-detector default-true semantics. +func (h *delegatedInterceptorHost) HasStreamInterceptors() bool { + if h.primary == nil { + return false + } + if detector, ok := h.primary.(interface{ HasStreamInterceptors() bool }); ok { + return detector.HasStreamInterceptors() + } + return true +} + +// StreamChunkPayloadIncludesRequestBody delegates payload policy to the +// embedder's host, preserving the handler's default-true semantics when the +// primary host does not implement the policy interface. +func (h *delegatedInterceptorHost) StreamChunkPayloadIncludesRequestBody() bool { + if h.primary == nil { + return false + } + if policy, ok := h.primary.(interface{ StreamChunkPayloadIncludesRequestBody() bool }); ok { + return policy.StreamChunkPayloadIncludesRequestBody() + } + return true +} + +// StreamChunkPayloadIncludesHistory delegates payload policy to the embedder's +// host with the same default-true semantics. +func (h *delegatedInterceptorHost) StreamChunkPayloadIncludesHistory() bool { + if h.primary == nil { + return false + } + if policy, ok := h.primary.(interface{ StreamChunkPayloadIncludesHistory() bool }); ok { + return policy.StreamChunkPayloadIncludesHistory() + } + return true +} + +// CompleteRequest delegates request lifecycle completion to the internal +// plugin host, which owns plugin usage accounting and completion callbacks. +func (h *delegatedInterceptorHost) CompleteRequest(ctx context.Context, completion pluginapi.RequestCompletion) { + if h.pluginHost == nil { + return + } + h.pluginHost.CompleteRequest(ctx, completion) +} + +// CompleteRequestExcept forwards the plugin-skip identifier so a plugin that +// initiated nested execution does not receive its own completion callback, +// preventing recursive dispatch. +func (h *delegatedInterceptorHost) CompleteRequestExcept(ctx context.Context, completion pluginapi.RequestCompletion, skipPluginID string) { + if h.pluginHost == nil { + return + } + h.pluginHost.CompleteRequestExcept(ctx, completion, skipPluginID) +} + +// HasWebSocketResponseObservers delegates detection to the plugin host. +func (h *delegatedInterceptorHost) HasWebSocketResponseObservers() bool { + return h.pluginHost != nil && h.pluginHost.HasWebSocketResponseObservers() +} + +// ObserveWebSocketResponseEvent delegates observer dispatch to the plugin host. +func (h *delegatedInterceptorHost) ObserveWebSocketResponseEvent(ctx context.Context, event pluginapi.WebSocketResponseEvent) { + if h.pluginHost == nil { + return + } + h.pluginHost.ObserveWebSocketResponseEvent(ctx, event) +} + +// ObserveWebSocketResponseEventExcept forwards the plugin-skip identifier so a +// plugin that initiated nested execution does not observe its own events. +func (h *delegatedInterceptorHost) ObserveWebSocketResponseEventExcept(ctx context.Context, event pluginapi.WebSocketResponseEvent, skipPluginID string) { + if h.pluginHost == nil { + return + } + h.pluginHost.ObserveWebSocketResponseEventExcept(ctx, event, skipPluginID) +} + +// ExecutePluginExecutor delegates direct plugin-executor dispatch to the +// internal plugin host so a model route targeting a plugin executor still +// works when the interceptor host is replaced. Without this, pluginExecutorHost +// returns nil and the handler responds 502 plugin executor host is unavailable. +func (h *delegatedInterceptorHost) ExecutePluginExecutor(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) { + if h.pluginHost == nil { + return coreexecutor.Response{}, fmt.Errorf("plugin executor host is unavailable") + } + return h.pluginHost.ExecutePluginExecutor(ctx, pluginID, req, opts) +} + +// ExecutePluginExecutorStream delegates streaming plugin-executor dispatch. +func (h *delegatedInterceptorHost) ExecutePluginExecutorStream(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) { + if h.pluginHost == nil { + return nil, fmt.Errorf("plugin executor host is unavailable") + } + return h.pluginHost.ExecutePluginExecutorStream(ctx, pluginID, req, opts) +} + +// CountPluginExecutor delegates token counting to the internal plugin host. +func (h *delegatedInterceptorHost) CountPluginExecutor(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) { + if h.pluginHost == nil { + return coreexecutor.Response{}, fmt.Errorf("plugin executor host is unavailable") + } + return h.pluginHost.CountPluginExecutor(ctx, pluginID, req, opts) +} + +// PluginExecutorRequestToFormat delegates executor input-format resolution to +// the internal plugin host. +func (h *delegatedInterceptorHost) PluginExecutorRequestToFormat(pluginID string, req coreexecutor.Request, opts coreexecutor.Options) sdktranslator.Format { + if h.pluginHost == nil { + return "" + } + return h.pluginHost.PluginExecutorRequestToFormat(pluginID, req, opts) +} + +// normalizeInterceptorHost unwraps typed-nil PluginInterceptorHost values so +// the server can treat them as unset and avoid wrapping a nil primary. +func normalizeInterceptorHost(host handlers.PluginInterceptorHost) handlers.PluginInterceptorHost { + if host == nil { + return nil + } + v := reflect.ValueOf(host) + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + if v.IsNil() { + return nil + } + } + return host +} diff --git a/internal/api/middleware/request_logging.go b/internal/api/middleware/request_logging.go index 36d5860cc64..72c13855c61 100644 --- a/internal/api/middleware/request_logging.go +++ b/internal/api/middleware/request_logging.go @@ -51,7 +51,8 @@ func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc { } loggerEnabled := logger.IsEnabled() - captureBody := shouldCaptureRequestBody(loggerEnabled, c.Request) + hasMatchedRoute := c.FullPath() != "" + captureBody := hasMatchedRoute && shouldCaptureRequestBody(loggerEnabled, c.Request) // Capture request metadata before authentication without reading the request body. requestInfo, err := captureRequestInfo(c, false) @@ -65,9 +66,13 @@ func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc { wrapper.ginContext = c if !loggerEnabled { wrapper.logOnErrorOnly = true + deferredAPICapture := logging.NewDeferredAPICapture() + wrapper.deferredAPICapture = deferredAPICapture + c.Request = c.Request.WithContext(logging.WithDeferredAPICapture(c.Request.Context(), deferredAPICapture)) + c.Set(logging.DeferredAPIResponseContextKey, deferredAPICapture) } c.Writer = wrapper - attachRequestLogSources(c, logger, loggerEnabled) + attachRequestLogSources(c, logger, loggerEnabled && hasMatchedRoute) deferredCapture := attachDeferredRequestBodyCapture(c.Request, logger, requestInfo, false, false) if captureBody { c.Set(authenticatedRequestBodyCapturerContextKey, func() { diff --git a/internal/api/middleware/request_logging_test.go b/internal/api/middleware/request_logging_test.go index b1bf861ad39..f328c3c1a81 100644 --- a/internal/api/middleware/request_logging_test.go +++ b/internal/api/middleware/request_logging_test.go @@ -13,6 +13,7 @@ import ( "path/filepath" "runtime" "strings" + "sync" "testing" "time" @@ -24,6 +25,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" ) func TestShouldSkipMethodForRequestLogging(t *testing.T) { @@ -995,3 +997,626 @@ func TestResponseWriterLogOnErrorOnlyZeroBufferUntilActionableError(t *testing.T t.Fatalf("wrapper.body.String() = %q, want %q", got, errFrame) } } + +func TestRequestLoggingMiddleware_Unrouted404DoesNotEvictErrorDumpRing(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("unrouted 404 does not create error log or evict existing error dumps when request-log is false", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(false, logsDir, "", 5) + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/messages", func(c *gin.Context) { + c.JSON(http.StatusBadGateway, gin.H{"error": "upstream failure"}) + }) + router.NoRoute(func(c *gin.Context) { + c.AbortWithStatus(http.StatusNotFound) + }) + + realFailReq := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"claude-sonnet-4-5"}`)) + realFailReq.Header.Set("Content-Type", "application/json") + realFailResp := httptest.NewRecorder() + router.ServeHTTP(realFailResp, realFailReq) + if realFailResp.Code != http.StatusBadGateway { + t.Fatalf("status = %d, want %d", realFailResp.Code, http.StatusBadGateway) + } + + for i := 0; i < 10; i++ { + probeReq := httptest.NewRequest(http.MethodPost, "/v1/files", strings.NewReader(`{"purpose":"user_data"}`)) + probeReq.Header.Set("Content-Type", "application/json") + probeResp := httptest.NewRecorder() + router.ServeHTTP(probeResp, probeReq) + if probeResp.Code != http.StatusNotFound { + t.Fatalf("probe %d status = %d, want %d", i, probeResp.Code, http.StatusNotFound) + } + } + + entries, errRead := os.ReadDir(logsDir) + if errRead != nil { + t.Fatalf("read logs dir: %v", errRead) + } + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + if len(names) != 1 || !strings.HasPrefix(names[0], "error-v1-messages-") { + t.Fatalf("expected only the original error-v1-messages-*.log dump to survive, got: %v", names) + } + }) + + t.Run("unrouted 404 does not create error log when request-log is true", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(true, logsDir, "", 5) + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/messages", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"ok": true}) + }) + router.NoRoute(func(c *gin.Context) { + c.AbortWithStatus(http.StatusNotFound) + }) + + probeReq := httptest.NewRequest(http.MethodPost, "/v1/files", strings.NewReader(`{"purpose":"user_data"}`)) + probeReq.Header.Set("Content-Type", "application/json") + probeResp := httptest.NewRecorder() + router.ServeHTTP(probeResp, probeReq) + if probeResp.Code != http.StatusNotFound { + t.Fatalf("status = %d, want %d", probeResp.Code, http.StatusNotFound) + } + + entries, errRead := os.ReadDir(logsDir) + if errRead != nil && !os.IsNotExist(errRead) { + t.Fatalf("read logs dir: %v", errRead) + } + if len(entries) != 0 { + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + t.Fatalf("expected 0 files for unrouted 404 when request-log=true, got: %v", names) + } + }) + + t.Run("routed 404 still creates error log when request-log is false", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(false, logsDir, "", 5) + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/messages", func(c *gin.Context) { + c.JSON(http.StatusNotFound, gin.H{"error": "model not found"}) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"missing-model"}`)) + req.Header.Set("Content-Type", "application/json") + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + if resp.Code != http.StatusNotFound { + t.Fatalf("status = %d, want %d", resp.Code, http.StatusNotFound) + } + + entries, errRead := os.ReadDir(logsDir) + if errRead != nil { + t.Fatalf("read logs dir: %v", errRead) + } + if len(entries) != 1 || !strings.HasPrefix(entries[0].Name(), "error-v1-messages-") { + t.Fatalf("expected 1 error-v1-messages-*.log for routed 404, got: %+v", entries) + } + }) + + t.Run("unrouted streaming 404 does not initialize stream writer or leak temp files when request-log is true", func(t *testing.T) { + logsDir := t.TempDir() + fileLogger := logging.NewFileRequestLogger(true, logsDir, "", 5) + spy := &spyRequestLogger{underlying: fileLogger} + + router := gin.New() + router.Use(RequestLoggingMiddleware(spy)) + router.NoRoute(func(c *gin.Context) { + c.Header("Content-Type", "text/event-stream") + c.Writer.WriteHeader(http.StatusNotFound) + _, _ = c.Writer.Write([]byte("event: error\ndata: not found\n\n")) + }) + + probeReq := httptest.NewRequest(http.MethodPost, "/v1/files", strings.NewReader(`{"stream":true}`)) + probeReq.Header.Set("Content-Type", "application/json") + probeResp := httptest.NewRecorder() + router.ServeHTTP(probeResp, probeReq) + if probeResp.Code != http.StatusNotFound { + t.Fatalf("status = %d, want %d", probeResp.Code, http.StatusNotFound) + } + if spy.lastStreamingRequestID != "" || spy.lastStreamWriter != nil { + t.Fatalf("expected LogStreamingRequest not to be called for unrouted 404, got requestID=%q writer=%v", spy.lastStreamingRequestID, spy.lastStreamWriter) + } + + entries, errRead := os.ReadDir(logsDir) + if errRead != nil && !os.IsNotExist(errRead) { + t.Fatalf("read logs dir: %v", errRead) + } + if len(entries) != 0 { + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + t.Fatalf("expected 0 files/temp dirs for unrouted streaming 404, got: %v", names) + } + }) + + t.Run("unrouted streaming 200 to uncommitted 404 transition discards stream writer without creating error log", func(t *testing.T) { + logsDir := t.TempDir() + fileLogger := logging.NewFileRequestLogger(true, logsDir, "", 5) + + router := gin.New() + router.Use(RequestLoggingMiddleware(fileLogger)) + router.NoRoute(func(c *gin.Context) { + c.Header("Content-Type", "text/event-stream") + c.Writer.WriteHeader(http.StatusOK) + c.Writer.WriteHeader(http.StatusNotFound) + _, _ = c.Writer.Write([]byte("data: not found\n\n")) + }) + + probeReq := httptest.NewRequest(http.MethodPost, "/v1/files", strings.NewReader(`{"stream":true}`)) + probeReq.Header.Set("Content-Type", "application/json") + probeResp := httptest.NewRecorder() + router.ServeHTTP(probeResp, probeReq) + if probeResp.Code != http.StatusNotFound { + t.Fatalf("status = %d, want %d", probeResp.Code, http.StatusNotFound) + } + + entries, errRead := os.ReadDir(logsDir) + if errRead != nil && !os.IsNotExist(errRead) { + t.Fatalf("read logs dir: %v", errRead) + } + if len(entries) != 0 { + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + t.Fatalf("expected 0 files/temp dirs after discarded streaming 404, got: %v", names) + } + }) +} + +func TestRequestLoggingMiddlewareErrorLogKeepsUpstreamResponseWhenRequestLogDisabled(t *testing.T) { + gin.SetMode(gin.TestMode) + + readSingleErrorLog := func(t *testing.T, logsDir string) string { + t.Helper() + entries, errReadDir := os.ReadDir(logsDir) + if errReadDir != nil { + t.Fatalf("read logs dir: %v", errReadDir) + } + var errorLogPaths []string + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), "error-") && strings.HasSuffix(entry.Name(), ".log") { + errorLogPaths = append(errorLogPaths, filepath.Join(logsDir, entry.Name())) + } + } + if len(errorLogPaths) != 1 { + t.Fatalf("error log count = %d, want 1 (entries=%v)", len(errorLogPaths), entries) + } + content, errReadFile := os.ReadFile(errorLogPaths[0]) + if errReadFile != nil { + t.Fatalf("read error log: %v", errReadFile) + } + return string(content) + } + + t.Run("non-stream WriteErrorResponse keeps per-attempt upstream status masked headers body and error", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(false, logsDir, "", 10) + cfg := &config.Config{} + baseHandler := handlers.NewBaseAPIHandlers(&cfg.SDKConfig, nil) + largeAttemptTwoBody := "data: {\"type\":\"response.created\",\"id\":\"resp_2\"}\n\n" + strings.Repeat("x", 70*1024) + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/chat/completions", func(c *gin.Context) { + executorCtx := context.WithValue(context.Background(), "gin", c) + + helps.RecordAPIRequest(executorCtx, cfg, helps.UpstreamRequestLog{ + URL: "https://cli-chat-proxy.grok.com/v1/responses", + Method: http.MethodPost, + Headers: http.Header{"Authorization": []string{"Bearer super-secret-request-token"}}, + Body: []byte(`{"model":"grok-4.7","stream":true}`), + }) + helps.RecordAPIResponseMetadata(executorCtx, cfg, http.StatusBadGateway, http.Header{ + "Content-Type": []string{"text/event-stream"}, + "Authorization": []string{"Bearer super-secret-response-token"}, + "X-Request-Id": []string{"xai-req-1"}, + }) + helps.AppendAPIResponseChunk(executorCtx, cfg, []byte("event: response.created")) + helps.AppendAPIResponseChunk(executorCtx, cfg, []byte(`data: {"type":"response.created","id":"resp_1"}`)) + helps.RecordAPIResponseError(executorCtx, cfg, errors.New("unexpected EOF")) + + helps.RecordAPIRequest(executorCtx, cfg, helps.UpstreamRequestLog{ + URL: "https://cli-chat-proxy.grok.com/v1/responses", + Method: http.MethodPost, + Body: []byte(`{"model":"grok-4.7","stream":true,"attempt":2}`), + }) + helps.RecordAPIResponseMetadata(executorCtx, cfg, http.StatusOK, http.Header{ + "Content-Type": []string{"text/event-stream"}, + "Set-Cookie": []string{"session=super-secret-cookie-value"}, + }) + helps.AppendAPIResponseChunk(executorCtx, cfg, []byte(largeAttemptTwoBody)) + + baseHandler.WriteErrorResponse(c, &interfaces.ErrorMessage{ + StatusCode: http.StatusRequestTimeout, + Error: errors.New("xai stream error: stream disconnected before response.completed or response.incomplete"), + }) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"grok-4.7","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + + if resp.Code != http.StatusRequestTimeout { + t.Fatalf("response status = %d, want %d", resp.Code, http.StatusRequestTimeout) + } + + logText := readSingleErrorLog(t, logsDir) + apiRequestIdx := strings.Index(logText, "=== API REQUEST 1 ===") + apiResponseIdx := strings.Index(logText, "=== API RESPONSE 1 ===") + downstreamResponseIdx := strings.Index(logText, "=== RESPONSE ===") + if apiRequestIdx == -1 || apiResponseIdx == -1 || downstreamResponseIdx == -1 { + t.Fatalf("missing expected log sections (req=%d, apiResp=%d, resp=%d):\n%s", apiRequestIdx, apiResponseIdx, downstreamResponseIdx, logText) + } + if apiRequestIdx >= apiResponseIdx || apiResponseIdx >= downstreamResponseIdx { + t.Fatalf("unexpected section order (req=%d, apiResp=%d, resp=%d):\n%s", apiRequestIdx, apiResponseIdx, downstreamResponseIdx, logText) + } + + apiResponseSection := logText[apiResponseIdx:downstreamResponseIdx] + downstreamSection := logText[downstreamResponseIdx:] + for _, want := range []string{ + "=== API RESPONSE 1 ===", + "Status: 502", + "Authorization: Bearer supe...oken", + "X-Request-Id: xai-req-1", + "event: response.created\ndata: {\"type\":\"response.created\",\"id\":\"resp_1\"}", + "Error: unexpected EOF", + "=== API RESPONSE 2 ===", + "Status: 200", + "data: {\"type\":\"response.created\",\"id\":\"resp_2\"}", + "[API RESPONSE BODY TRUNCATED: captured first ", + } { + if !strings.Contains(apiResponseSection, want) { + t.Fatalf("API RESPONSE section missing %q:\n%s", want, apiResponseSection) + } + } + for _, secret := range []string{"super-secret-response-token", "super-secret-cookie-value"} { + if strings.Contains(logText, secret) { + t.Fatalf("error log leaked sensitive header value %q:\n%s", secret, logText) + } + } + if strings.Contains(apiResponseSection, `"code":"request_timeout"`) { + t.Fatalf("API RESPONSE section should contain upstream attempts rather than proxy synthesized error JSON:\n%s", apiResponseSection) + } + if !strings.Contains(downstreamSection, "Status: 408") || !strings.Contains(downstreamSection, "xai stream error: stream disconnected before response.completed or response.incomplete") { + t.Fatalf("downstream RESPONSE section missing final proxy error:\n%s", downstreamSection) + } + }) + + t.Run("mid-stream SSE error keeps upstream response in error log", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(false, logsDir, "", 10) + cfg := &config.Config{} + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/chat/completions", func(c *gin.Context) { + c.Header("Content-Type", "text/event-stream") + executorCtx := context.WithValue(context.Background(), "gin", c) + helps.RecordAPIRequest(executorCtx, cfg, helps.UpstreamRequestLog{ + URL: "https://cli-chat-proxy.grok.com/v1/responses", + Method: http.MethodPost, + Body: []byte(`{"model":"grok-4.7","stream":true}`), + }) + helps.RecordAPIResponseMetadata(executorCtx, cfg, http.StatusOK, http.Header{ + "Content-Type": []string{"text/event-stream"}, + "X-Request-Id": []string{"xai-stream-1"}, + }) + helps.AppendAPIResponseChunk(executorCtx, cfg, []byte(`data: {"type":"response.failed","response":{"error":{"message":"upstream quota exceeded"}}}`)) + helps.RecordAPIResponseError(executorCtx, cfg, errors.New("upstream quota exceeded")) + + c.Writer.WriteHeader(http.StatusOK) + _, _ = c.Writer.Write([]byte("data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n")) + c.Set("API_RESPONSE_ERROR", []*interfaces.ErrorMessage{ + { + StatusCode: http.StatusTooManyRequests, + Error: errors.New("upstream quota exceeded"), + }, + }) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"grok-4.7","stream":true}`)) + req.Header.Set("Content-Type", "application/json") + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + + logText := readSingleErrorLog(t, logsDir) + for _, want := range []string{ + "=== API REQUEST 1 ===", + "=== API RESPONSE 1 ===", + "Status: 200", + "X-Request-Id: xai-stream-1", + `data: {"type":"response.failed","response":{"error":{"message":"upstream quota exceeded"}}}`, + "Error: upstream quota exceeded", + } { + if !strings.Contains(logText, want) { + t.Fatalf("mid-stream error log missing %q:\n%s", want, logText) + } + } + }) + + t.Run("rejected upstream websocket upgrade keeps handshake request and response in error log", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(false, logsDir, "", 10) + cfg := &config.Config{} + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/responses", func(c *gin.Context) { + executorCtx := context.WithValue(context.Background(), "gin", c) + helps.RecordAPIWebsocketUpgradeRejection( + executorCtx, + cfg, + helps.UpstreamRequestLog{ + URL: "https://chatgpt.com/backend-api/codex/responses", + Method: http.MethodGet, + Headers: http.Header{"Authorization": []string{"Bearer super-secret-ws-token"}}, + }, + http.StatusForbidden, + http.Header{ + "Content-Type": []string{"application/json"}, + "Set-Cookie": []string{"cf_clearance=super-secret-cf-cookie"}, + }, + []byte(`{"error":{"message":"websocket handshake rejected"}}`), + ) + c.JSON(http.StatusForbidden, gin.H{"error": "websocket handshake rejected"}) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5-codex","input":"hi"}`)) + req.Header.Set("Content-Type", "application/json") + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + + logText := readSingleErrorLog(t, logsDir) + for _, want := range []string{ + "=== API REQUEST 1 ===", + "Upstream URL: https://chatgpt.com/backend-api/codex/responses", + "=== API RESPONSE 1 ===", + "Status: 403", + `{"error":{"message":"websocket handshake rejected"}}`, + } { + if !strings.Contains(logText, want) { + t.Fatalf("websocket rejection error log missing %q:\n%s", want, logText) + } + } + for _, secret := range []string{"super-secret-ws-token", "super-secret-cf-cookie"} { + if strings.Contains(logText, secret) { + t.Fatalf("websocket rejection error log leaked secret %q:\n%s", secret, logText) + } + } + }) + + t.Run("successful request with request-log off writes no log file", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(false, logsDir, "", 10) + cfg := &config.Config{} + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/chat/completions", func(c *gin.Context) { + executorCtx := context.WithValue(context.Background(), "gin", c) + helps.RecordAPIRequest(executorCtx, cfg, helps.UpstreamRequestLog{ + URL: "https://cli-chat-proxy.grok.com/v1/responses", + Method: http.MethodPost, + Body: []byte(`{"model":"grok-4.7"}`), + }) + helps.RecordAPIResponseMetadata(executorCtx, cfg, http.StatusOK, http.Header{ + "Content-Type": []string{"text/event-stream"}, + }) + helps.AppendAPIResponseChunk(executorCtx, cfg, []byte(`data: {"type":"response.completed"}`)) + c.JSON(http.StatusOK, gin.H{"id": "chatcmpl_1"}) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"grok-4.7"}`)) + req.Header.Set("Content-Type", "application/json") + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + + if resp.Code != http.StatusOK { + t.Fatalf("response status = %d, want %d", resp.Code, http.StatusOK) + } + entries, errReadDir := os.ReadDir(logsDir) + if errReadDir != nil && !os.IsNotExist(errReadDir) { + t.Fatalf("read logs dir: %v", errReadDir) + } + if len(entries) != 0 { + t.Fatalf("expected 0 log files for successful request with request-log=false, got: %v", entries) + } + }) +} + +func TestRequestLoggingMiddlewareIsolatesDeferredResponseAcrossStreamCancelAndGinContextReuse(t *testing.T) { + gin.SetMode(gin.TestMode) + + readSingleErrorLog := func(t *testing.T, logsDir string) string { + t.Helper() + entries, errReadDir := os.ReadDir(logsDir) + if errReadDir != nil { + t.Fatalf("read logs dir: %v", errReadDir) + } + var errorLogPaths []string + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), "error-") && strings.HasSuffix(entry.Name(), ".log") { + errorLogPaths = append(errorLogPaths, filepath.Join(logsDir, entry.Name())) + } + } + if len(errorLogPaths) != 1 { + t.Fatalf("error log count = %d, want 1 (entries=%v)", len(errorLogPaths), entries) + } + content, errReadFile := os.ReadFile(errorLogPaths[0]) + if errReadFile != nil { + t.Fatalf("read error log: %v", errReadFile) + } + return string(content) + } + + t.Run("late stream producer after cancel does not pollute reused Gin context", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(false, logsDir, "", 10) + cfg := &config.Config{} + baseHandler := handlers.NewBaseAPIHandlers(&cfg.SDKConfig, nil) + + const cancelledTurns = 8 + turn2Active := make(chan struct{}) + var producers sync.WaitGroup + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/chat/completions", func(c *gin.Context) { + if c.GetHeader("X-Turn") == "2" { + cliCtx, cliCancel := baseHandler.GetContextWithCancel(nil, c, context.Background()) + defer cliCancel() + helps.RecordAPIRequest(cliCtx, cfg, helps.UpstreamRequestLog{ + URL: "https://api.example.com/turn2", + Method: http.MethodPost, + Body: []byte(`{"turn":2}`), + }) + helps.RecordAPIResponseMetadata(cliCtx, cfg, http.StatusBadGateway, http.Header{ + "Content-Type": []string{"application/json"}, + }) + helps.AppendAPIResponseChunk(cliCtx, cfg, []byte(`{"error":"turn2-upstream-failure"}`)) + close(turn2Active) + producers.Wait() + baseHandler.WriteErrorResponse(c, &interfaces.ErrorMessage{ + StatusCode: http.StatusBadGateway, + Error: errors.New("turn2 failed"), + }) + return + } + + cliCtx, cliCancel := baseHandler.GetContextWithCancel(nil, c, context.Background()) + helps.RecordAPIRequest(cliCtx, cfg, helps.UpstreamRequestLog{ + URL: "https://api.example.com/turn1", + Method: http.MethodPost, + Body: []byte(`{"turn":1}`), + }) + helps.RecordAPIResponseMetadata(cliCtx, cfg, http.StatusOK, http.Header{ + "Content-Type": []string{"text/event-stream"}, + }) + helps.AppendAPIResponseChunk(cliCtx, cfg, []byte(`data: {"turn":1,"early":true}`)) + producerStarted := make(chan struct{}) + producers.Add(1) + go func(streamCtx context.Context) { + defer producers.Done() + close(producerStarted) + <-turn2Active + helps.RecordAPIRequest(streamCtx, cfg, helps.UpstreamRequestLog{ + URL: "https://api.example.com/turn1-late-req", + Method: http.MethodPost, + Body: []byte(`{"turn":1,"late":true}`), + }) + helps.RecordAPIResponseMetadata(streamCtx, cfg, http.StatusInternalServerError, http.Header{ + "X-Turn1-Late": []string{"leaked"}, + }) + helps.AppendAPIResponseChunk(streamCtx, cfg, []byte("turn1-late-stream-chunk")) + helps.RecordAPIResponseError(streamCtx, cfg, errors.New("turn1-late-stream-error")) + }(cliCtx) + <-producerStarted + cliCancel() + c.Status(clienterror.StatusClientClosedRequest) + }) + + for range cancelledTurns { + req1 := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"stream":true}`)) + req1.Header.Set("Content-Type", "application/json") + req1.Header.Set("X-Turn", "1") + router.ServeHTTP(httptest.NewRecorder(), req1) + } + + req2 := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"stream":false}`)) + req2.Header.Set("Content-Type", "application/json") + req2.Header.Set("X-Turn", "2") + resp2 := httptest.NewRecorder() + router.ServeHTTP(resp2, req2) + if resp2.Code != http.StatusBadGateway { + t.Fatalf("turn 2 status = %d, want %d", resp2.Code, http.StatusBadGateway) + } + + logText := readSingleErrorLog(t, logsDir) + for _, want := range []string{ + "https://api.example.com/turn2", + `{"error":"turn2-upstream-failure"}`, + } { + if !strings.Contains(logText, want) { + t.Fatalf("turn 2 error log missing %q:\n%s", want, logText) + } + } + for _, leaked := range []string{ + "turn1-late-req", + "X-Turn1-Late", + "turn1-late-stream-chunk", + "turn1-late-stream-error", + } { + if strings.Contains(logText, leaked) { + t.Fatalf("turn 2 error log leaked stale turn 1 data %q:\n%s", leaked, logText) + } + } + }) + + t.Run("concurrent stream producer during Finalize is race-free", func(t *testing.T) { + logsDir := t.TempDir() + logger := logging.NewFileRequestLogger(false, logsDir, "", 10) + cfg := &config.Config{} + baseHandler := handlers.NewBaseAPIHandlers(&cfg.SDKConfig, nil) + + producerStarted := make(chan struct{}) + producerDone := make(chan struct{}) + + router := gin.New() + router.Use(RequestLoggingMiddleware(logger)) + router.POST("/v1/chat/completions", func(c *gin.Context) { + cliCtx, cliCancel := baseHandler.GetContextWithCancel(nil, c, context.Background()) + defer cliCancel() + helps.RecordAPIRequest(cliCtx, cfg, helps.UpstreamRequestLog{ + URL: "https://api.example.com/v1/responses", + Method: http.MethodPost, + Body: []byte(`{"stream":true}`), + }) + helps.RecordAPIResponseMetadata(cliCtx, cfg, http.StatusOK, http.Header{ + "Content-Type": []string{"text/event-stream"}, + }) + go func(streamCtx context.Context) { + defer close(producerDone) + close(producerStarted) + for range 32 { + helps.AppendAPIResponseChunk(streamCtx, cfg, []byte(`data: {"delta":"chunk"}`)) + } + helps.RecordAPIResponseError(streamCtx, cfg, errors.New("stream aborted")) + }(cliCtx) + <-producerStarted + c.Header("Content-Type", "text/event-stream") + c.Writer.WriteHeader(http.StatusOK) + c.Set("API_RESPONSE_ERROR", []*interfaces.ErrorMessage{ + { + StatusCode: http.StatusBadGateway, + Error: errors.New("mid-stream abort"), + }, + }) + }) + + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"stream":true}`)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(httptest.NewRecorder(), req) + <-producerDone + + logText := readSingleErrorLog(t, logsDir) + if !strings.Contains(logText, "=== API RESPONSE 1 ===") { + t.Fatalf("concurrent error log missing API RESPONSE 1:\n%s", logText) + } + }) +} diff --git a/internal/api/middleware/response_writer.go b/internal/api/middleware/response_writer.go index 72c977df121..c540cd9e011 100644 --- a/internal/api/middleware/response_writer.go +++ b/internal/api/middleware/response_writer.go @@ -40,21 +40,22 @@ type RequestInfo struct { // It is designed to handle both standard and streaming responses, ensuring that logging operations do not block the client response. type ResponseWriterWrapper struct { gin.ResponseWriter - body *bytes.Buffer // body is a buffer to store the response body for non-streaming responses. - isStreaming bool // isStreaming indicates whether the response is a streaming type (e.g., text/event-stream). - streamWriter logging.StreamingLogWriter // streamWriter is a writer for handling streaming log entries. - chunkChannel chan []byte // chunkChannel is a channel for asynchronously passing response chunks to the logger. - streamDone chan struct{} // streamDone signals when the streaming goroutine completes. - logger logging.RequestLogger // logger is the instance of the request logger service. - requestInfo *RequestInfo // requestInfo holds the details of the original request. - ginContext *gin.Context // ginContext holds the Gin request context for mid-stream error inspection. - statusCode int // statusCode stores the HTTP status code of the response. - headers map[string][]string // headers stores the response headers. - logOnErrorOnly bool // logOnErrorOnly enables logging only when an error response is detected. - hijacked bool // hijacked reports whether the underlying connection was hijacked. - panicked bool // panicked records whether a handler panicked (even after committing a 2xx response). - finalized bool // finalized prevents post-Finalize writes (e.g. outer recovery) from reopening stream writers. - firstChunkTimestamp time.Time // firstChunkTimestamp captures TTFB for streaming responses. + body *bytes.Buffer // body is a buffer to store the response body for non-streaming responses. + isStreaming bool // isStreaming indicates whether the response is a streaming type (e.g., text/event-stream). + streamWriter logging.StreamingLogWriter // streamWriter is a writer for handling streaming log entries. + chunkChannel chan []byte // chunkChannel is a channel for asynchronously passing response chunks to the logger. + streamDone chan struct{} // streamDone signals when the streaming goroutine completes. + logger logging.RequestLogger // logger is the instance of the request logger service. + requestInfo *RequestInfo // requestInfo holds the details of the original request. + ginContext *gin.Context // ginContext holds the Gin request context for mid-stream error inspection. + statusCode int // statusCode stores the HTTP status code of the response. + headers map[string][]string // headers stores the response headers. + logOnErrorOnly bool // logOnErrorOnly enables logging only when an error response is detected. + deferredAPICapture *logging.DeferredAPICapture // deferredAPICapture retains bounded upstream request/response attempts for error logs. + hijacked bool // hijacked reports whether the underlying connection was hijacked. + panicked bool // panicked records whether a handler panicked (even after committing a 2xx response). + finalized bool // finalized prevents post-Finalize writes (e.g. outer recovery) from reopening stream writers. + firstChunkTimestamp time.Time // firstChunkTimestamp captures TTFB for streaming responses. } // NewResponseWriterWrapper creates and initializes a new ResponseWriterWrapper. @@ -165,18 +166,22 @@ func (w *ResponseWriterWrapper) closeConnectionIfRequestBodyUnconsumed(statusCod } func (w *ResponseWriterWrapper) shouldBufferResponseBody() bool { + status := w.effectiveStatusCode() + apiErrors := extractAPIResponseErrors(w.ginContext) + if status < http.StatusBadRequest { + if apiErrStatus := actionableAPIResponseErrorStatus(apiErrors); apiErrStatus >= http.StatusBadRequest { + status = apiErrStatus + } + } + if !w.panicked && isUnroutedNotFound(w.ginContext, status, apiErrors) { + return false + } if w.logger != nil && w.logger.IsEnabled() { return true } if !w.logOnErrorOnly { return false } - status := w.effectiveStatusCode() - if status < http.StatusBadRequest { - if apiErrStatus := actionableAPIResponseErrorStatus(extractAPIResponseErrors(w.ginContext)); apiErrStatus >= http.StatusBadRequest { - status = apiErrStatus - } - } return status >= http.StatusBadRequest && status != clienterror.StatusClientClosedRequest } @@ -232,25 +237,29 @@ func (w *ResponseWriterWrapper) WriteHeader(statusCode int) { // If streaming, initialize streaming log writer once and refresh uncommitted status updates. if !w.finalized && w.isStreaming && w.logger != nil && w.logger.IsEnabled() { if w.streamWriter == nil { - streamWriter, err := w.logger.LogStreamingRequest( - w.requestInfo.URL, - w.requestInfo.Method, - w.requestInfo.Headers, - w.currentCapturedRequestBody(), - w.requestInfo.RequestID, - ) - if err == nil { - chunkChan := make(chan []byte, 100) // Buffered channel for async writes - doneChan := make(chan struct{}) - w.streamWriter = streamWriter - w.chunkChannel = chunkChan - w.streamDone = doneChan - - // Start async chunk processor with captured locals so Finalize clearing fields cannot race. - go w.processStreamingChunks(doneChan, chunkChan, streamWriter) - - // Write status immediately - _ = streamWriter.WriteStatus(statusCode, w.headers) + if !w.panicked && isUnroutedNotFound(w.ginContext, statusCode, extractAPIResponseErrors(w.ginContext)) { + w.isStreaming = false + } else { + streamWriter, err := w.logger.LogStreamingRequest( + w.requestInfo.URL, + w.requestInfo.Method, + w.requestInfo.Headers, + w.currentCapturedRequestBody(), + w.requestInfo.RequestID, + ) + if err == nil { + chunkChan := make(chan []byte, 100) // Buffered channel for async writes + doneChan := make(chan struct{}) + w.streamWriter = streamWriter + w.chunkChannel = chunkChan + w.streamDone = doneChan + + // Start async chunk processor with captured locals so Finalize clearing fields cannot race. + go w.processStreamingChunks(doneChan, chunkChan, streamWriter) + + // Write status immediately + _ = streamWriter.WriteStatus(statusCode, w.headers) + } } } else { _ = w.streamWriter.WriteStatus(statusCode, w.headers) @@ -365,6 +374,7 @@ func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error { if w.requestInfo != nil && w.requestInfo.deferredBodyCapture != nil { defer w.requestInfo.deferredBodyCapture.Cleanup() } + defer w.closeDeferredAPICapture(c) if w.logger == nil { return nil } @@ -397,9 +407,10 @@ func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error { apiRequestSource := w.extractAPIRequestSource(c) apiResponseSource := w.extractAPIResponseSource(c) apiWebsocketTimelineSource := w.extractAPIWebsocketTimelineSource(c) - if !w.logger.IsEnabled() && !forceLog { + if (!w.logger.IsEnabled() && !forceLog) || (!w.panicked && isUnroutedNotFound(c, finalStatusCode, slicesAPIResponseError)) { + errDiscard := w.discardStreamingLogWriter() cleanupFileBodySources(websocketTimelineSource, apiRequestSource, apiResponseSource, apiWebsocketTimelineSource) - return nil + return errDiscard } if w.isStreaming && w.streamWriter != nil { @@ -483,7 +494,13 @@ func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error { if forceLog && len(apiRequest) == 0 { apiRequest = w.extractDeferredAPIRequest(c) } - return w.logRequest(w.extractRequestBody(c), finalStatusCode, w.cloneHeaders(), w.extractResponseBody(c), w.extractWebsocketTimeline(c), websocketTimelineSource, apiRequest, apiRequestSource, w.extractAPIResponse(c), apiResponseSource, w.extractAPIWebsocketTimeline(c), apiWebsocketTimelineSource, w.extractAPIResponseTimestamp(c), slicesAPIResponseError, forceLog) + apiResponse := w.extractAPIResponse(c) + if forceLog { + if deferredResponse := w.extractDeferredAPIResponse(c); len(deferredResponse) > 0 { + apiResponse = deferredResponse + } + } + return w.logRequest(w.extractRequestBody(c), finalStatusCode, w.cloneHeaders(), w.extractResponseBody(c), w.extractWebsocketTimeline(c), websocketTimelineSource, apiRequest, apiRequestSource, apiResponse, apiResponseSource, w.extractAPIWebsocketTimeline(c), apiWebsocketTimelineSource, w.extractAPIResponseTimestamp(c), slicesAPIResponseError, forceLog) } func (w *ResponseWriterWrapper) cloneHeaders() map[string][]string { @@ -512,9 +529,17 @@ func (w *ResponseWriterWrapper) extractAPIRequest(c *gin.Context) []byte { } func (w *ResponseWriterWrapper) extractDeferredAPIRequest(c *gin.Context) []byte { + if w != nil && w.deferredAPICapture != nil && w.deferredAPICapture.HasRequests() { + return w.deferredAPICapture.RenderAPIRequests() + } if c == nil { return nil } + if value, exists := c.Get(logging.DeferredAPIResponseContextKey); exists { + if capture, ok := value.(*logging.DeferredAPICapture); ok && capture != nil && capture.HasRequests() { + return capture.RenderAPIRequests() + } + } value, exists := c.Get(logging.DeferredAPIRequestContextKey) if !exists { return nil @@ -533,6 +558,41 @@ func (w *ResponseWriterWrapper) extractDeferredAPIRequest(c *gin.Context) []byte return body.Bytes() } +func (w *ResponseWriterWrapper) extractDeferredAPIResponse(c *gin.Context) []byte { + if w != nil && w.deferredAPICapture != nil { + if !w.deferredAPICapture.HasPayload() { + return nil + } + return w.deferredAPICapture.RenderAPIResponse() + } + if c == nil { + return nil + } + value, exists := c.Get(logging.DeferredAPIResponseContextKey) + if !exists { + return nil + } + deferred, ok := value.(logging.DeferredAPIResponse) + if !ok || deferred == nil || !deferred.HasPayload() { + return nil + } + return deferred.RenderAPIResponse() +} + +func (w *ResponseWriterWrapper) closeDeferredAPICapture(c *gin.Context) { + if w != nil && w.deferredAPICapture != nil { + w.deferredAPICapture.Close() + } + if c == nil { + return + } + if value, exists := c.Get(logging.DeferredAPIResponseContextKey); exists { + if closer, ok := value.(interface{ Close() }); ok && closer != nil { + closer.Close() + } + } +} + func (w *ResponseWriterWrapper) extractAPIResponse(c *gin.Context) []byte { apiResponse, isExist := c.Get("API_RESPONSE") if !isExist { @@ -823,6 +883,26 @@ func mergeFileBodySource(payload []byte, source *logging.FileBodySource) ([]byte return buf.Bytes(), nil } +func (w *ResponseWriterWrapper) discardStreamingLogWriter() error { + if w == nil || w.streamWriter == nil { + return nil + } + if w.chunkChannel != nil { + close(w.chunkChannel) + w.chunkChannel = nil + } + if w.streamDone != nil { + <-w.streamDone + w.streamDone = nil + } + streamWriter := w.streamWriter + w.streamWriter = nil + if discarder, ok := streamWriter.(interface{ Discard() error }); ok { + return discarder.Discard() + } + return streamWriter.Close() +} + func cleanupFileBodySources(sources ...*logging.FileBodySource) { for _, source := range sources { if source == nil { @@ -886,6 +966,58 @@ func isContextCanceled(c *gin.Context) bool { return ctx != nil && errors.Is(ctx.Err(), context.Canceled) } +func isUnroutedNotFound(c *gin.Context, statusCode int, apiErrors []*interfaces.ErrorMessage) bool { + if statusCode != http.StatusNotFound { + return false + } + if hasActionableAPIResponseErrors(apiErrors) { + return false + } + if c == nil || c.FullPath() != "" { + return false + } + if hasRecordedUpstreamActivity(c) { + return false + } + return true +} + +func hasRecordedUpstreamActivity(c *gin.Context) bool { + if c == nil { + return false + } + for _, key := range []string{"API_REQUEST", "API_RESPONSE", "API_WEBSOCKET_TIMELINE"} { + if value, exists := c.Get(key); exists { + if data, ok := value.([]byte); ok && len(data) > 0 { + return true + } + } + } + if value, exists := c.Get(logging.DeferredAPIRequestContextKey); exists { + if requests, ok := value.([]logging.DeferredAPIRequest); ok && len(requests) > 0 { + return true + } + } + if value, exists := c.Get(logging.DeferredAPIResponseContextKey); exists { + if capture, ok := value.(*logging.DeferredAPICapture); ok && capture != nil && capture.HasRequests() { + return true + } + if response, ok := value.(logging.DeferredAPIResponse); ok && response != nil && response.HasPayload() { + return true + } + } + for _, key := range []string{ + logging.APIRequestSourceContextKey, + logging.APIResponseSourceContextKey, + logging.APIWebsocketTimelineSourceContextKey, + } { + if source := extractFileBodySource(c, key); source != nil && source.HasPayload() { + return true + } + } + return false +} + func hasActionableError(c *gin.Context, statusCode int, apiErrors []*interfaces.ErrorMessage) bool { if hasActionableAPIResponseErrors(apiErrors) { return true @@ -893,6 +1025,9 @@ func hasActionableError(c *gin.Context, statusCode int, apiErrors []*interfaces. if statusCode == clienterror.StatusClientClosedRequest { return false } + if isUnroutedNotFound(c, statusCode, apiErrors) { + return false + } if isContextCanceled(c) && statusCode < http.StatusBadRequest { return false } diff --git a/internal/api/middleware/response_writer_test.go b/internal/api/middleware/response_writer_test.go index 70814fc2536..0e987696bc5 100644 --- a/internal/api/middleware/response_writer_test.go +++ b/internal/api/middleware/response_writer_test.go @@ -7,6 +7,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -284,6 +285,17 @@ func TestHasActionableError(t *testing.T) { apiErrors: []*interfaces.ErrorMessage{{StatusCode: 0, Error: fmt.Errorf("read: %w", context.Canceled)}}, want: false, }, + { + name: "404 unrouted without api errors", + statusCode: http.StatusNotFound, + want: false, + }, + { + name: "404 with actionable upstream api error", + statusCode: http.StatusNotFound, + apiErrors: []*interfaces.ErrorMessage{{StatusCode: http.StatusNotFound, Error: errors.New("upstream 404")}}, + want: true, + }, } for _, tc := range tests { @@ -305,12 +317,14 @@ func TestHasActionableError(t *testing.T) { } type recordingRequestLogger struct { - loggedCalls []int - enabled bool + loggedCalls []int + apiResponses [][]byte + enabled bool } func (l *recordingRequestLogger) LogRequest(url, method string, requestHeaders map[string][]string, body []byte, statusCode int, responseHeaders map[string][]string, response, websocketTimeline, apiRequest, apiResponse, apiWebsocketTimeline []byte, apiResponseErrors []*interfaces.ErrorMessage, requestID string, requestTimestamp, apiResponseTimestamp time.Time) error { l.loggedCalls = append(l.loggedCalls, statusCode) + l.apiResponses = append(l.apiResponses, bytes.Clone(apiResponse)) return nil } @@ -325,10 +339,113 @@ func (l *recordingRequestLogger) IsEnabled() bool { func (l *recordingRequestLogger) LogRequestWithOptions(url, method string, requestHeaders map[string][]string, body []byte, statusCode int, responseHeaders map[string][]string, response, websocketTimeline, apiRequest, apiResponse, apiWebsocketTimeline []byte, apiResponseErrors []*interfaces.ErrorMessage, force bool, requestID string, requestTimestamp, apiResponseTimestamp time.Time) error { if force || l.enabled { l.loggedCalls = append(l.loggedCalls, statusCode) + l.apiResponses = append(l.apiResponses, bytes.Clone(apiResponse)) } return nil } +type stubDeferredAPIResponse struct { + section []byte + renders int +} + +func (s *stubDeferredAPIResponse) HasPayload() bool { + return s != nil && len(s.section) > 0 +} + +func (s *stubDeferredAPIResponse) RenderAPIResponse() []byte { + if s == nil { + return nil + } + s.renders++ + return s.section +} + +func TestFinalizeForceLogUsesDeferredAPIResponse(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("error log uses deferred upstream response instead of fallback proxy error", func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + stub := &stubDeferredAPIResponse{ + section: []byte("=== API RESPONSE 1 ===\nTimestamp: 2026-11-11T00:45:05Z\n\nStatus: 502\n\nBody:\nupstream-error-body\n"), + } + c.Set(logging.DeferredAPIResponseContextKey, stub) + c.Set("API_RESPONSE", []byte(`{"error":{"message":"proxy synthesized error"}}`)) + + logger := &recordingRequestLogger{enabled: false} + wrapper := &ResponseWriterWrapper{ + ResponseWriter: c.Writer, + logger: logger, + logOnErrorOnly: true, + statusCode: http.StatusBadGateway, + requestInfo: &RequestInfo{URL: "/v1/chat/completions", Method: http.MethodPost, Timestamp: time.Now()}, + } + if errFinalize := wrapper.Finalize(c); errFinalize != nil { + t.Fatalf("Finalize error: %v", errFinalize) + } + if len(logger.apiResponses) != 1 { + t.Fatalf("logged apiResponses = %d, want 1", len(logger.apiResponses)) + } + got := string(logger.apiResponses[0]) + if !strings.Contains(got, "upstream-error-body") { + t.Fatalf("logged API response missing upstream body:\n%s", got) + } + if strings.Contains(got, "proxy synthesized error") { + t.Fatalf("logged API response should not include proxy synthesized fallback JSON:\n%s", got) + } + }) + + t.Run("local error without upstream attempt preserves fallback API_RESPONSE", func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + c.Set(logging.DeferredAPIResponseContextKey, &stubDeferredAPIResponse{}) + c.Set("API_RESPONSE", []byte(`{"error":{"message":"local cooldown"}}`)) + + logger := &recordingRequestLogger{enabled: false} + wrapper := &ResponseWriterWrapper{ + ResponseWriter: c.Writer, + logger: logger, + logOnErrorOnly: true, + statusCode: http.StatusTooManyRequests, + requestInfo: &RequestInfo{URL: "/v1/chat/completions", Method: http.MethodPost, Timestamp: time.Now()}, + } + if errFinalize := wrapper.Finalize(c); errFinalize != nil { + t.Fatalf("Finalize error: %v", errFinalize) + } + if len(logger.apiResponses) != 1 || !strings.Contains(string(logger.apiResponses[0]), "local cooldown") { + t.Fatalf("logged API response = %q, want fallback local error", logger.apiResponses) + } + }) + + t.Run("successful request neither logs nor renders deferred response", func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + stub := &stubDeferredAPIResponse{ + section: []byte("=== API RESPONSE 1 ===\n\nBody:\nupstream-ok\n"), + } + c.Set(logging.DeferredAPIResponseContextKey, stub) + + logger := &recordingRequestLogger{enabled: false} + wrapper := &ResponseWriterWrapper{ + ResponseWriter: c.Writer, + logger: logger, + logOnErrorOnly: true, + statusCode: http.StatusOK, + requestInfo: &RequestInfo{URL: "/v1/chat/completions", Method: http.MethodPost, Timestamp: time.Now()}, + } + if errFinalize := wrapper.Finalize(c); errFinalize != nil { + t.Fatalf("Finalize error: %v", errFinalize) + } + if len(logger.loggedCalls) != 0 || stub.renders != 0 { + t.Fatalf("loggedCalls=%d renders=%d, want 0 and 0", len(logger.loggedCalls), stub.renders) + } + }) +} + func TestFinalizeExcludes499FromForceLog(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() @@ -384,3 +501,143 @@ func TestFinalizeIncludes500InForceLog(t *testing.T) { t.Fatalf("expected 1 logged call for 500 status, got: %v", logger.loggedCalls) } } + +func TestFinalizeExcludesUnrouted404FromForceLog(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/files", nil) + + logger := &recordingRequestLogger{enabled: false} + wrapper := &ResponseWriterWrapper{ + ResponseWriter: c.Writer, + logger: logger, + logOnErrorOnly: true, + statusCode: http.StatusNotFound, + requestInfo: &RequestInfo{ + URL: "/v1/files", + Method: "POST", + RequestID: "req-404", + Timestamp: time.Now(), + }, + } + + if err := wrapper.Finalize(c); err != nil { + t.Fatalf("Finalize error: %v", err) + } + if len(logger.loggedCalls) != 0 { + t.Fatalf("expected 0 logged calls for unrouted 404, got %d: %v", len(logger.loggedCalls), logger.loggedCalls) + } +} + +func TestFinalizeLogsUnrouted404WhenUpstreamEvidenceOrPanicExists(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("deferred api request recorded", func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/files", nil) + c.Set(logging.DeferredAPIRequestContextKey, []logging.DeferredAPIRequest{ + func() []byte { return []byte("=== API REQUEST 1 ===\n") }, + }) + + logger := &recordingRequestLogger{enabled: false} + wrapper := &ResponseWriterWrapper{ + ResponseWriter: c.Writer, + logger: logger, + logOnErrorOnly: true, + statusCode: http.StatusNotFound, + requestInfo: &RequestInfo{URL: "/v1/files", Method: http.MethodPost, Timestamp: time.Now()}, + } + if err := wrapper.Finalize(c); err != nil { + t.Fatalf("Finalize error: %v", err) + } + if len(logger.loggedCalls) != 1 || logger.loggedCalls[0] != http.StatusNotFound { + t.Fatalf("expected 1 logged call when deferred API request exists, got: %v", logger.loggedCalls) + } + }) + + t.Run("deferred api response recorded", func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/files", nil) + c.Set(logging.DeferredAPIResponseContextKey, &stubDeferredAPIResponse{ + section: []byte("=== API RESPONSE 1 ===\n"), + }) + + logger := &recordingRequestLogger{enabled: false} + wrapper := &ResponseWriterWrapper{ + ResponseWriter: c.Writer, + logger: logger, + logOnErrorOnly: true, + statusCode: http.StatusNotFound, + requestInfo: &RequestInfo{URL: "/v1/files", Method: http.MethodPost, Timestamp: time.Now()}, + } + if errFinalize := wrapper.Finalize(c); errFinalize != nil { + t.Fatalf("Finalize error: %v", errFinalize) + } + if len(logger.loggedCalls) != 1 || logger.loggedCalls[0] != http.StatusNotFound { + t.Fatalf("expected 1 logged call when deferred API response exists, got: %v", logger.loggedCalls) + } + }) + + t.Run("file body source with payload recorded", func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/files", nil) + + source, errSource := logging.NewFileBodySourceInDir(t.TempDir(), "api-request") + if errSource != nil { + t.Fatalf("NewFileBodySourceInDir: %v", errSource) + } + defer func() { _ = source.Cleanup() }() + part, errPart := source.CreatePart("req") + if errPart != nil { + t.Fatalf("CreatePart: %v", errPart) + } + if _, errWrite := part.WriteString("upstream request payload"); errWrite != nil { + t.Fatalf("WriteString: %v", errWrite) + } + if errClose := part.Close(); errClose != nil { + t.Fatalf("Close: %v", errClose) + } + c.Set(logging.APIRequestSourceContextKey, source) + + logger := &recordingRequestLogger{enabled: false} + wrapper := &ResponseWriterWrapper{ + ResponseWriter: c.Writer, + logger: logger, + logOnErrorOnly: true, + statusCode: http.StatusNotFound, + requestInfo: &RequestInfo{URL: "/v1/files", Method: http.MethodPost, Timestamp: time.Now()}, + } + if err := wrapper.Finalize(c); err != nil { + t.Fatalf("Finalize error: %v", err) + } + if len(logger.loggedCalls) != 1 || logger.loggedCalls[0] != http.StatusNotFound { + t.Fatalf("expected 1 logged call when file body source payload exists, got: %v", logger.loggedCalls) + } + }) + + t.Run("panicked handler on 404 still logs", func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/files", nil) + + logger := &recordingRequestLogger{enabled: false} + wrapper := &ResponseWriterWrapper{ + ResponseWriter: c.Writer, + logger: logger, + logOnErrorOnly: true, + panicked: true, + statusCode: http.StatusNotFound, + requestInfo: &RequestInfo{URL: "/v1/files", Method: http.MethodPost, Timestamp: time.Now()}, + } + if err := wrapper.Finalize(c); err != nil { + t.Fatalf("Finalize error: %v", err) + } + if len(logger.loggedCalls) != 1 || logger.loggedCalls[0] != http.StatusNotFound { + t.Fatalf("expected 1 logged call when panicked=true, got: %v", logger.loggedCalls) + } + }) +} diff --git a/internal/api/server.go b/internal/api/server.go index 502f9fca02f..89dbe301472 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -21,12 +21,14 @@ import ( managementHandlers "github.com/router-for-me/CLIProxyAPI/v8/internal/api/handlers/management" "github.com/router-for-me/CLIProxyAPI/v8/internal/api/middleware" codexlive "github.com/router-for-me/CLIProxyAPI/v8/internal/client/codex/live" + "github.com/router-for-me/CLIProxyAPI/v8/internal/client/musecode" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/githubauth" "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/managementasset" "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" "github.com/router-for-me/CLIProxyAPI/v8/internal/redisqueue" + "github.com/router-for-me/CLIProxyAPI/v8/internal/wstunnel" sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers/openai" @@ -55,6 +57,8 @@ type Server struct { // handlers contains the API handlers for processing requests. handlers *handlers.BaseAPIHandler codexLiveHandler *codexlive.Handler + museCodeHandler *musecode.Handler + tunnelHub *wstunnel.Hub // cfg holds the current server configuration. cfgMu sync.RWMutex @@ -89,6 +93,13 @@ type Server struct { // pluginHost owns dynamic plugin Management API route dispatch. pluginHost *pluginhost.Host + // interceptorHost is the resolved PluginInterceptorHost installed on request + // handlers. When a caller provides their own host via + // WithPluginInterceptorHost, interceptor calls and capability detection + // delegate to that host while plugin model routing, lifecycle callbacks, and + // websocket observers stay delegated to pluginHost. + interceptorHost handlers.PluginInterceptorHost + // managementRoutesRegistered tracks whether the management routes have been attached to the engine. managementRoutesRegistered atomic.Bool // managementRoutesEnabled controls whether management endpoints serve real handlers. @@ -161,6 +172,7 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk s := &Server{ engine: engine, handlers: handlers.NewBaseAPIHandlers(effectiveSDKConfig(cfg), authManager), + tunnelHub: wstunnel.NewHub(wstunnel.Options{}), cfg: cfg, accessManager: accessManager, configFilePath: configFilePath, @@ -173,6 +185,22 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk runtimeAccessProviders: append([]sdkaccess.Provider(nil), optionState.runtimeAccessProviders...), } + // Resolve the interceptor host once so startup and reload share the same + // wiring. A caller-provided host keeps interceptor dispatch and capability + // detection on the embedder implementation while model routing, lifecycle + // callbacks, and websocket observers remain delegated to the internal + // plugin host. Typed-nil values are normalized first so they cannot defeat + // SetPluginHost's own nil-interface normalization. + + if custom := normalizeInterceptorHost(optionState.pluginInterceptorHost); custom != nil { + s.interceptorHost = &delegatedInterceptorHost{ + primary: custom, + pluginHost: optionState.pluginHost, + } + } else { + s.interceptorHost = optionState.pluginHost + } + // Add middleware engine.Use(logging.GinLogrusLogger()) engine.Use(logging.CPATraceIDMiddleware()) @@ -207,7 +235,7 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk openai.SetResponsesWebsocketCompressionEnabled(cfg.Codex.WebsocketCompressionEnabled()) s.wsAuthEnabled.Store(cfg.WebsocketAuth) s.exampleAPIKeySafeModeActive.Store(s.exampleAPIKeySafeModeRequired(cfg)) - s.handlers.SetPluginHost(optionState.pluginHost) + s.handlers.SetPluginHost(s.interceptorHost) if optionState.pluginHost != nil { optionState.pluginHost.SetModelExecutor(s.handlers) optionState.pluginHost.SetAuthManager(authManager) @@ -418,10 +446,14 @@ func (s *Server) Start() error { } } -// Stop closes listeners and immediately shuts down the API server without waiting for active connections. +// Stop closes listeners and shuts down the API server. +// When server.shutdown-timeout is a positive number of seconds, Stop first lets +// in-flight requests finish within that budget (http.Server.Shutdown), then +// forcibly closes whatever remains. The default 0 closes immediately, preserving +// the behavior introduced to prevent hanging on active requests (#6094). // // Parameters: -// - ctx: Context passed for compatibility. +// - ctx: Context bounding the whole stop operation. // // Returns: // - error: An error if the server fails to stop @@ -451,17 +483,41 @@ func (s *Server) Stop(ctx context.Context) error { } } - // Close the HTTP server immediately without graceful draining. + // Close the HTTP server. With a positive server.shutdown-timeout, drain + // in-flight requests for up to that many seconds first; otherwise close + // immediately without graceful draining. var errCloseServer error if s.server != nil { - errCloseServer = s.server.Close() - if errors.Is(errCloseServer, http.ErrServerClosed) || errors.Is(errCloseServer, net.ErrClosed) { - errCloseServer = nil + drainTimeout := 0 + if cfg := s.getConfig(); cfg != nil { + drainTimeout = cfg.ShutdownTimeoutSeconds + } + if drainTimeout > 0 { + // Bound the drain by the configured timeout even when the caller's + // context is more generous: shutdown must never hang longer than the + // operator chose. A tighter caller deadline still wins via parent ctx. + drainCtx, cancel := context.WithTimeout(ctx, time.Duration(drainTimeout)*time.Second) + defer cancel() + log.Debugf("draining HTTP connections for up to %ds", drainTimeout) + errShutdown := s.server.Shutdown(drainCtx) + if errShutdown != nil && !errors.Is(errShutdown, context.DeadlineExceeded) && !errors.Is(errShutdown, context.Canceled) { + errCloseServer = errShutdown + } + } + // Always force-close afterwards: this terminates anything that outlived + // the drain budget and is a no-op when Shutdown already returned cleanly. + // Hijacked connections (WebSocket sessions) are not tracked by the HTTP + // server; they are released by their own managers below. + if errClose := s.server.Close(); errClose != nil && !errors.Is(errClose, http.ErrServerClosed) && !errors.Is(errClose, net.ErrClosed) && errCloseServer == nil { + errCloseServer = errClose } } if s.codexLiveHandler != nil { s.codexLiveHandler.Close() } + if s.tunnelHub != nil { + s.tunnelHub.Close() + } if errCloseServer != nil { return fmt.Errorf("failed to shutdown HTTP server: %v", errCloseServer) } diff --git a/internal/api/server_issue7499_test.go b/internal/api/server_issue7499_test.go new file mode 100644 index 00000000000..397d2416465 --- /dev/null +++ b/internal/api/server_issue7499_test.go @@ -0,0 +1,333 @@ +package api + +import ( + "context" + "testing" + + proxyconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" +) + +type recordingInterceptorHost struct { + beforeAuthCalls int +} + +func (h *recordingInterceptorHost) InterceptRequestBeforeAuth(context.Context, pluginapi.RequestInterceptRequest) pluginapi.RequestInterceptResponse { + h.beforeAuthCalls++ + return pluginapi.RequestInterceptResponse{} +} + +func (h *recordingInterceptorHost) InterceptRequestAfterAuth(context.Context, pluginapi.RequestInterceptRequest) pluginapi.RequestInterceptResponse { + return pluginapi.RequestInterceptResponse{} +} + +func (h *recordingInterceptorHost) InterceptResponse(context.Context, pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + return pluginapi.ResponseInterceptResponse{} +} + +func (h *recordingInterceptorHost) InterceptStreamChunk(context.Context, pluginapi.StreamChunkInterceptRequest) pluginapi.StreamChunkInterceptResponse { + return pluginapi.StreamChunkInterceptResponse{} +} + +var _ handlers.PluginInterceptorHost = (*recordingInterceptorHost)(nil) + +// skipAwareInterceptorHost implements the pluginInterceptorSkipHost surface to +// prove the delegated host forwards skipPluginID instead of dropping it. +type skipAwareInterceptorHost struct { + recordingInterceptorHost + beforeAuthSkips []string + afterAuthSkips []string + responseSkips []string + streamSkips []string +} + +func (h *skipAwareInterceptorHost) InterceptRequestBeforeAuthExcept(_ context.Context, _ pluginapi.RequestInterceptRequest, skipPluginID string) pluginapi.RequestInterceptResponse { + h.beforeAuthSkips = append(h.beforeAuthSkips, skipPluginID) + return pluginapi.RequestInterceptResponse{} +} + +func (h *skipAwareInterceptorHost) InterceptRequestAfterAuthExcept(_ context.Context, _ pluginapi.RequestInterceptRequest, skipPluginID string) pluginapi.RequestInterceptResponse { + h.afterAuthSkips = append(h.afterAuthSkips, skipPluginID) + return pluginapi.RequestInterceptResponse{} +} + +func (h *skipAwareInterceptorHost) InterceptResponseExcept(_ context.Context, _ pluginapi.ResponseInterceptRequest, skipPluginID string) pluginapi.ResponseInterceptResponse { + h.responseSkips = append(h.responseSkips, skipPluginID) + return pluginapi.ResponseInterceptResponse{} +} + +func (h *skipAwareInterceptorHost) InterceptStreamChunkExcept(_ context.Context, _ pluginapi.StreamChunkInterceptRequest, skipPluginID string) pluginapi.StreamChunkInterceptResponse { + h.streamSkips = append(h.streamSkips, skipPluginID) + return pluginapi.StreamChunkInterceptResponse{} +} + +// noRequestInterceptorsHost implements the detector interface to confirm the +// delegated host honors a caller's opt-out of request interception. +type noRequestInterceptorsHost struct { + recordingInterceptorHost +} + +func (h *noRequestInterceptorsHost) HasRequestInterceptors() bool { return false } + +// TestServerDelegatesInterceptorCallsToEmbedderThroughWiredHost proves the +// host installed on server.handlers via WithPluginInterceptorHost actually +// reaches the embedder through the handler dispatch chain, not just that a +// wrapper object exists. The server's interceptorHost field is the resolved +// host BaseAPIHandler.interceptorHost() reads on every request. +func TestServerDelegatesInterceptorCallsToEmbedderThroughWiredHost(t *testing.T) { + custom := &recordingInterceptorHost{} + server := newTestServerWithOptions(t, WithPluginHost(pluginhost.New()), WithPluginInterceptorHost(custom)) + + if server.handlers == nil { + t.Fatal("server handlers = nil") + } + // The wired host on the handler must be the delegated wrapper. + wired, ok := server.handlers.PluginHost.(*delegatedInterceptorHost) + if !ok || wired == nil { + t.Fatalf("handler plugin host = %T, want *delegatedInterceptorHost", server.handlers.PluginHost) + } + // The same resolved host must be what the server holds for reloads. + if server.interceptorHost != wired { + t.Fatal("server.interceptorHost != handler plugin host; reload would rewire a different host") + } + // Exercise the host through the same call the handler makes per request. + wired.InterceptRequestBeforeAuth(context.Background(), pluginapi.RequestInterceptRequest{}) + if custom.beforeAuthCalls != 1 { + t.Fatalf("custom host before-auth calls = %d, want 1 through wired host", custom.beforeAuthCalls) + } + // Capability detection must report the embedder as active so the handler + // does not skip its interceptor. + if !wired.HasRequestInterceptors() { + t.Fatal("wired host HasRequestInterceptors() = false, want true for custom host") + } +} + +// TestNewServerWithPluginInterceptorHostInstallsCustomHost verifies the +// WithPluginInterceptorHost option wires the caller-provided host into request +// handlers at construction time. +func TestNewServerWithPluginInterceptorHostInstallsCustomHost(t *testing.T) { + custom := &recordingInterceptorHost{} + server := newTestServerWithOptions(t, WithPluginHost(pluginhost.New()), WithPluginInterceptorHost(custom)) + + if server.handlers == nil { + t.Fatal("server handlers = nil") + } + if server.handlers.PluginHost == nil { + t.Fatal("handler plugin host = nil, want wrapped custom interceptor host") + } + if _, ok := server.handlers.PluginHost.(*delegatedInterceptorHost); !ok { + t.Fatalf("handler plugin host type = %T, want *delegatedInterceptorHost", server.handlers.PluginHost) + } +} + +// TestUpdateClientsContextPreservesPluginInterceptorHost ensures a config +// reload keeps the caller-provided interceptor host instead of restoring the +// internal plugin host. +func TestUpdateClientsContextPreservesPluginInterceptorHost(t *testing.T) { + custom := &recordingInterceptorHost{} + pluginHost := pluginhost.New() + server := newTestServerWithOptions(t, WithPluginHost(pluginHost), WithPluginInterceptorHost(custom)) + + if server.handlers == nil { + t.Fatal("server handlers = nil") + } + if _, ok := server.handlers.PluginHost.(*delegatedInterceptorHost); !ok { + t.Fatalf("handler plugin host type = %T, want *delegatedInterceptorHost", server.handlers.PluginHost) + } + + server.UpdateClientsContext(context.Background(), &proxyconfig.Config{}) + + after, ok := server.handlers.PluginHost.(*delegatedInterceptorHost) + if !ok || after == nil { + t.Fatalf("handler plugin host after reload = %T, want *delegatedInterceptorHost", server.handlers.PluginHost) + } + if after.primary != custom { + t.Fatal("delegated host primary changed after reload; want same embedder host") + } + if after.pluginHost != pluginHost { + t.Fatal("delegated host pluginHost changed after reload; want internal plugin host") + } +} + +// TestDelegatedInterceptorHostInvokesEmbedderInterceptors verifies the +// capability detectors reflect the embedder's host rather than the internal +// plugin host, so an empty plugin host cannot disable the custom interceptors. +func TestDelegatedInterceptorHostInvokesEmbedderInterceptors(t *testing.T) { + custom := &recordingInterceptorHost{} + wrapped := &delegatedInterceptorHost{primary: custom, pluginHost: pluginhost.New()} + + if !wrapped.HasRequestInterceptors() { + t.Fatal("HasRequestInterceptors() = false for custom host without detector, want true") + } + if !wrapped.HasStreamInterceptors() { + t.Fatal("HasStreamInterceptors() = false for custom host without detector, want true") + } + + wrapped.InterceptRequestBeforeAuth(context.Background(), pluginapi.RequestInterceptRequest{}) + if custom.beforeAuthCalls != 1 { + t.Fatalf("custom host before-auth calls = %d, want 1", custom.beforeAuthCalls) + } + + disabled := &noRequestInterceptorsHost{} + wrappedDisabled := &delegatedInterceptorHost{primary: disabled, pluginHost: pluginhost.New()} + if wrappedDisabled.HasRequestInterceptors() { + t.Fatal("HasRequestInterceptors() = true when embedder disables it, want false") + } +} + +// TestDelegatedInterceptorHostForwardsSkipToEmbedder verifies that when the +// embedder's host implements the skip-aware interceptor interface, the +// delegated host passes skipPluginID through instead of dropping it. +func TestDelegatedInterceptorHostForwardsSkipToEmbedder(t *testing.T) { + custom := &skipAwareInterceptorHost{} + wrapped := &delegatedInterceptorHost{primary: custom, pluginHost: pluginhost.New()} + + wrapped.InterceptRequestBeforeAuthExcept(context.Background(), pluginapi.RequestInterceptRequest{}, "plugin-a") + wrapped.InterceptRequestAfterAuthExcept(context.Background(), pluginapi.RequestInterceptRequest{}, "plugin-b") + wrapped.InterceptResponseExcept(context.Background(), pluginapi.ResponseInterceptRequest{}, "plugin-c") + wrapped.InterceptStreamChunkExcept(context.Background(), pluginapi.StreamChunkInterceptRequest{}, "plugin-d") + + if len(custom.beforeAuthSkips) != 1 || custom.beforeAuthSkips[0] != "plugin-a" { + t.Fatalf("before-auth skips = %v, want [plugin-a]", custom.beforeAuthSkips) + } + if len(custom.afterAuthSkips) != 1 || custom.afterAuthSkips[0] != "plugin-b" { + t.Fatalf("after-auth skips = %v, want [plugin-b]", custom.afterAuthSkips) + } + if len(custom.responseSkips) != 1 || custom.responseSkips[0] != "plugin-c" { + t.Fatalf("response skips = %v, want [plugin-c]", custom.responseSkips) + } + if len(custom.streamSkips) != 1 || custom.streamSkips[0] != "plugin-d" { + t.Fatalf("stream skips = %v, want [plugin-d]", custom.streamSkips) + } + // A primary without the skip interface still gets invoked via the base methods. + plain := &recordingInterceptorHost{} + wrappedPlain := &delegatedInterceptorHost{primary: plain, pluginHost: pluginhost.New()} + wrappedPlain.InterceptRequestBeforeAuthExcept(context.Background(), pluginapi.RequestInterceptRequest{}, "plugin-a") + if plain.beforeAuthCalls != 1 { + t.Fatalf("plain host before-auth calls = %d, want 1", plain.beforeAuthCalls) + } +} + +// TestDelegatedInterceptorHostPluginCallbacksPreserveSkip verifies lifecycle +// and plugin-callback skip paths remain wired to the internal plugin host with +// the skip identifier intact. The wrapper's *Except methods are compile-time +// members of the same skip interfaces the handler type-asserts on, so a +// signature drift that dropped skipPluginID would fail to compile. +func TestDelegatedInterceptorHostPluginCallbacksPreserveSkip(t *testing.T) { + pluginHost := pluginhost.New() + custom := &recordingInterceptorHost{} + wrapped := &delegatedInterceptorHost{primary: custom, pluginHost: pluginHost} + + // Compile-time proof the wrapper still satisfies the same skip-aware + // interfaces the handler dispatches through; a regression that dropped the + // Except methods would silently route callbacks back to the initiating + // plugin and recurse. + var _ interface { + CompleteRequestExcept(context.Context, pluginapi.RequestCompletion, string) + } = wrapped + var _ interface { + ObserveWebSocketResponseEventExcept(context.Context, pluginapi.WebSocketResponseEvent, string) + } = wrapped + var _ interface { + RouteModelExcept(context.Context, pluginapi.ModelRouteRequest, string) (pluginapi.ModelRouteResponse, bool) + } = wrapped + + // Exercise skip-aware dispatch paths; they must reach the plugin host + // without error rather than dead-ending on the embedder's host. + wrapped.CompleteRequestExcept(context.Background(), pluginapi.RequestCompletion{}, "plugin-a") + wrapped.ObserveWebSocketResponseEventExcept(context.Background(), pluginapi.WebSocketResponseEvent{}, "plugin-a") + wrapped.RouteModelExcept(context.Background(), pluginapi.ModelRouteRequest{}, "plugin-a") + // Model routing must stay delegated to the internal plugin host so plugin + // executors remain reachable even with a custom interceptor installed. + if _, handled := wrapped.RouteModel(context.Background(), pluginapi.ModelRouteRequest{}); handled { + _ = handled + } + if wrapped.HasModelRouters() != pluginHost.HasModelRouters() { + t.Fatal("wrapper HasModelRouters diverged from internal plugin host") + } +} + +// TestNewServerWithoutPluginInterceptorHostKeepsInternalHost preserves the +// default behavior when no custom interceptor host is configured. +func TestNewServerWithoutPluginInterceptorHostKeepsInternalHost(t *testing.T) { + pluginHost := pluginhost.New() + server := newTestServerWithOptions(t, WithPluginHost(pluginHost)) + + if server.handlers == nil { + t.Fatal("server handlers = nil") + } + if server.handlers.PluginHost != pluginHost { + t.Fatalf("handler plugin host = %#v, want internal plugin host %#v", server.handlers.PluginHost, pluginHost) + } +} + +// TestNewServerWithTypedNilPluginInterceptorHostFallsBack ensures a typed-nil +// custom host is normalized to unset so the internal plugin host is used. +func TestNewServerWithTypedNilPluginInterceptorHostFallsBack(t *testing.T) { + pluginHost := pluginhost.New() + var typedNil *recordingInterceptorHost + server := newTestServerWithOptions(t, WithPluginHost(pluginHost), WithPluginInterceptorHost(typedNil)) + + if server.handlers == nil { + t.Fatal("server handlers = nil") + } + if server.handlers.PluginHost != pluginHost { + t.Fatalf("handler plugin host = %#v, want internal plugin host %#v for typed-nil custom host", server.handlers.PluginHost, pluginHost) + } +} + +// TestDelegatedInterceptorHostImplementsPluginExecutorHost verifies the +// wrapper satisfies the PluginExecutorHost contract so plugin model routes to +// a plugin executor do not regress to 502 when a custom interceptor host is +// installed. The wrapped host delegates execution to the internal pluginHost. +func TestDelegatedInterceptorHostImplementsPluginExecutorHost(t *testing.T) { + custom := &recordingInterceptorHost{} + pluginHost := pluginhost.New() + wrapped := &delegatedInterceptorHost{primary: custom, pluginHost: pluginHost} + + // Compile-time + runtime proof the wrapper still exposes the executor host + // interface the handler type-asserts on for plugin-executor routes. + executorHost, ok := any(wrapped).(interface { + ExecutePluginExecutor(context.Context, string, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) + ExecutePluginExecutorStream(context.Context, string, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, error) + CountPluginExecutor(context.Context, string, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) + }) + if !ok || executorHost == nil { + t.Fatal("delegated host does not implement PluginExecutorHost; plugin executor routes would 502") + } + // Nil-pluginHost delegates must return an explicit unavailable error rather + // than panic, matching the handler's unavailable-host contract. + safeWrapped := &delegatedInterceptorHost{primary: custom, pluginHost: nil} + if _, err := safeWrapped.ExecutePluginExecutor(context.Background(), "p", coreexecutor.Request{}, coreexecutor.Options{}); err == nil { + t.Fatal("ExecutePluginExecutor with nil plugin host = nil error, want unavailable") + } +} + +// TestDelegatedInterceptorHostNilPluginHostIsSafe ensures the delegated host is +// safe when no internal plugin host exists. +func TestDelegatedInterceptorHostNilPluginHostIsSafe(t *testing.T) { + custom := &recordingInterceptorHost{} + server := newTestServerWithOptions(t, WithPluginInterceptorHost(custom)) + + if server.handlers == nil { + t.Fatal("server handlers = nil") + } + wrapped, ok := server.handlers.PluginHost.(*delegatedInterceptorHost) + if !ok || wrapped == nil { + t.Fatalf("handler plugin host type = %T, want *delegatedInterceptorHost", server.handlers.PluginHost) + } + // Embedder interceptors remain enabled even without an internal plugin host. + if !wrapped.HasRequestInterceptors() { + t.Fatal("HasRequestInterceptors() = false with nil plugin host, want true for custom host") + } + if wrapped.HasModelRouters() { + t.Fatal("HasModelRouters() = true with nil plugin host, want false") + } + // Nil-pluginHost delegates must be no-ops rather than panics. + wrapped.RouteModel(context.Background(), pluginapi.ModelRouteRequest{}) + wrapped.CompleteRequest(context.Background(), pluginapi.RequestCompletion{}) + wrapped.ObserveWebSocketResponseEvent(context.Background(), pluginapi.WebSocketResponseEvent{}) +} diff --git a/internal/api/server_management_v8.go b/internal/api/server_management_v8.go index e73ad893132..2b4dee04084 100644 --- a/internal/api/server_management_v8.go +++ b/internal/api/server_management_v8.go @@ -41,6 +41,7 @@ func (s *Server) registerManagementV8Routes() { v8.GET("/observability/logs/requests/:id", s.mgmt.GetRequestLogByID) v8.GET("/observability/usage/api-keys", s.mgmt.GetAPIKeyUsage) v8.GET("/observability/usage/queue", s.mgmt.GetUsageQueue) + v8.GET("/observability/requests/in-flight", s.mgmt.GetInFlightRequests) v8.GET("/credentials", s.mgmt.ListAuthFiles) v8.POST("/credentials", s.mgmt.UploadAuthFileV8) diff --git a/internal/api/server_management_v8_test.go b/internal/api/server_management_v8_test.go index b59ad2b038d..2aa5e44a9ca 100644 --- a/internal/api/server_management_v8_test.go +++ b/internal/api/server_management_v8_test.go @@ -12,9 +12,12 @@ import ( "testing" "time" + "github.com/MoeForge/moego/ojson" "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/api/handlers/management" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" ) func TestManagementV8RoutesShareAccessControl(t *testing.T) { @@ -220,3 +223,67 @@ func TestManagementV8PluginOperationMigratesConfiguration(t *testing.T) { t.Fatal("missing configuration reload") } } + +func TestManagementV8PluginsExposesRuntimePriorityOnlyOnV8(t *testing.T) { + gin.SetMode(gin.TestMode) + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + raw := fmt.Sprintf("remote-management: {secret-key: test-password}\nplugins:\n enabled: true\n dir: %q\n configs:\n registered-plugin: {enabled: true, priority: 77}\n configured-only: {enabled: true, priority: 33}\n", filepath.ToSlash(dir)) + if errWrite := os.WriteFile(path, []byte(raw), 0o600); errWrite != nil { + t.Fatal(errWrite) + } + cfg, errLoad := config.LoadConfig(path) + if errLoad != nil { + t.Fatal(errLoad) + } + host := pluginhost.New() + host.RegisterPluginForTest("registered-plugin", pluginapi.Plugin{}) + host.RegisterPluginWithPriorityForTest("zero-plugin", 0, pluginapi.Plugin{}) + + h := management.NewHandler(cfg, path, nil) + h.SetLocalPassword("test-password") + h.SetPluginHost(host) + + s := &Server{cfg: cfg, engine: gin.New(), mgmt: h} + s.managementRoutesEnabled.Store(true) + s.registerManagementRoutes() + + queryPlugins := func(route string) map[string]ojson.Result { + t.Helper() + req := httptest.NewRequest(http.MethodGet, route, nil) + req.RemoteAddr = "127.0.0.1:1234" + req.Header.Set("Authorization", "Bearer test-password") + rec := httptest.NewRecorder() + s.engine.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || !ojson.ValidBytes(rec.Body.Bytes()) { + t.Fatalf("GET %s status=%d body=%s", route, rec.Code, rec.Body.String()) + } + out := make(map[string]ojson.Result) + for _, item := range ojson.Parse(rec.Body.String()).Get("plugins").Array() { + out[item.Get("id").String()] = item + } + return out + } + + v8Entries := queryPlugins("/v8/management/plugins") + if p := v8Entries["registered-plugin"].Get("priority"); !p.Exists() || p.Type != ojson.Number || p.Int() != 1 { + t.Fatalf("v8 registered-plugin priority = %s, want 1; entry=%s", p.Raw, v8Entries["registered-plugin"].Raw) + } + if p := v8Entries["zero-plugin"].Get("priority"); !p.Exists() || p.Type != ojson.Number || p.Int() != 0 { + t.Fatalf("v8 zero-plugin priority = %s, want 0; entry=%s", p.Raw, v8Entries["zero-plugin"].Raw) + } + if p := v8Entries["configured-only"].Get("priority"); p.Exists() { + t.Fatalf("v8 configured-only exposed priority = %s", p.Raw) + } + + v0Entries := queryPlugins("/v0/management/plugins") + if p := v0Entries["registered-plugin"].Get("priority"); p.Exists() { + t.Fatalf("deprecated v0 registered-plugin exposed priority = %s", p.Raw) + } + if p := v0Entries["zero-plugin"].Get("priority"); p.Exists() { + t.Fatalf("deprecated v0 zero-plugin exposed priority = %s", p.Raw) + } + if p := v0Entries["configured-only"].Get("priority"); p.Exists() { + t.Fatalf("deprecated v0 configured-only exposed priority = %s", p.Raw) + } +} diff --git a/internal/api/server_middleware.go b/internal/api/server_middleware.go index 945003859f4..ea9f8cda698 100644 --- a/internal/api/server_middleware.go +++ b/internal/api/server_middleware.go @@ -418,6 +418,8 @@ func isExampleAPIKeySafeModeProxyPath(path string) bool { return true case path == "/backend-api/codex" || strings.HasPrefix(path, "/backend-api/codex/"): return true + case path == "/muse-code" || strings.HasPrefix(path, "/muse-code/"): + return true default: return false } diff --git a/internal/api/server_muse_code_test.go b/internal/api/server_muse_code_test.go new file mode 100644 index 00000000000..5f46a07c388 --- /dev/null +++ b/internal/api/server_muse_code_test.go @@ -0,0 +1,759 @@ +package api + +import ( + "bufio" + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" + proxyconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/home" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" +) + +func registeredRouteEngine(t *testing.T, server *Server, method, path string) *gin.Engine { + t.Helper() + engine := gin.New() + found := false + for _, route := range server.engine.Routes() { + if route.Method == method && route.Path == path { + engine.Handle(method, path, route.HandlerFunc) + found = true + break + } + } + if !found { + t.Fatalf("route %s %s not registered on server engine", method, path) + } + return engine +} + +func newReadyHomeCatalogClient(t *testing.T, initialPayload string) (*home.Client, func(string), func() string) { + t.Helper() + listener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatalf("listen: %v", errListen) + } + + var payloadVal atomic.Value + payloadVal.Store(initialPayload) + var lastModelsReq atomic.Value + lastModelsReq.Store("") + + done := make(chan struct{}) + var connections sync.WaitGroup + go func() { + defer close(done) + for { + conn, errAccept := listener.Accept() + if errAccept != nil { + return + } + connections.Add(1) + go func() { + defer connections.Done() + defer func() { + _ = conn.Close() + }() + reader := bufio.NewReader(conn) + for { + args, errRead := readRESPArrayOfBulkStrings(reader) + if errRead != nil || len(args) == 0 { + return + } + cmd := strings.ToUpper(string(args[0])) + var response string + switch cmd { + case "HELLO": + response = "-ERR unknown command 'hello'\r\n" + case "PING": + if len(args) >= 2 { + msg := string(args[1]) + response = fmt.Sprintf("$%d\r\n%s\r\n", len(msg), msg) + } else { + response = "+PONG\r\n" + } + case "SUBSCRIBE": + ch := "config" + if len(args) >= 2 { + ch = string(args[1]) + } + response = fmt.Sprintf("*3\r\n$9\r\nsubscribe\r\n$%d\r\n%s\r\n:1\r\n", len(ch), ch) + case "GET": + if len(args) == 2 && ojson.GetBytesNoCopy(args[1], "type").String() == "models" { + lastModelsReq.Store(string(args[1])) + p, _ := payloadVal.Load().(string) + response = fmt.Sprintf("$%d\r\n%s\r\n", len(p), p) + } else { + response = "$2\r\n{}\r\n" + } + default: + response = "+OK\r\n" + } + if _, errWrite := io.WriteString(conn, response); errWrite != nil { + return + } + } + }() + } + }() + + host, portText, errSplit := net.SplitHostPort(listener.Addr().String()) + if errSplit != nil { + t.Fatalf("split Home test address: %v", errSplit) + } + port, errAtoi := strconv.Atoi(portText) + if errAtoi != nil { + t.Fatalf("parse Home test port: %v", errAtoi) + } + + client := home.New(proxyconfig.HomeConfig{Enabled: true, Host: host, Port: port, DisableClusterDiscovery: true}) + subCtx, cancelSub := context.WithCancel(context.Background()) + ready := make(chan struct{}) + var readyOnce sync.Once + subDone := make(chan struct{}) + go func() { + defer close(subDone) + _ = client.RunConfigSubscriberLifetime(subCtx, func([]byte) error { + return nil + }, func() { + readyOnce.Do(func() { close(ready) }) + }) + }() + + t.Cleanup(func() { + cancelSub() + client.Close() + _ = listener.Close() + <-subDone + <-done + connections.Wait() + }) + + select { + case <-ready: + case <-time.After(3 * time.Second): + t.Fatal("ready Home catalog client did not establish heartbeat") + } + + return client, func(next string) { payloadVal.Store(next) }, func() string { + v, _ := lastModelsReq.Load().(string) + return v + } +} + +func parseAPIMuseCodeEntriesByID(t *testing.T, raw []byte) map[string]ojson.Result { + t.Helper() + root := ojson.ParseBytes(raw) + data := root.Get("data") + if !data.IsArray() { + t.Fatalf("expected data array in response, got %s", string(raw)) + } + entries := make(map[string]ojson.Result) + data.ForEach(func(_, item ojson.Result) bool { + entries[item.Get("id").String()] = item + return true + }) + return entries +} + +func TestMuseCodeClientEndpointsRelayToMetaOrigin(t *testing.T) { + var seenMethod, seenPath, seenQuery, seenAuth, seenBody string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seenMethod = r.Method + seenPath = r.URL.Path + seenQuery = r.URL.RawQuery + seenAuth = r.Header.Get("Authorization") + raw, _ := io.ReadAll(r.Body) + seenBody = string(raw) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"ok":true}`) + })) + defer upstream.Close() + + server := newTestServer(t) + server.handlers.AuthManager.RegisterExecutor(executor.NewMetaExecutor(server.getConfig())) + cred := &auth.Auth{ + ID: "meta-muse-code-relay", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "meta-upstream-secret", + "base_url": upstream.URL + "/v1", + }, + } + registry.GetGlobalRegistry().RegisterClient(cred.ID, "meta", []*registry.ModelInfo{{ID: "muse-wonder-full-1.0"}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(cred.ID) + }) + if _, errRegister := server.handlers.AuthManager.Register(t.Context(), cred); errRegister != nil { + t.Fatalf("register Meta credential: %v", errRegister) + } + + for _, tc := range []struct { + name string + method string + target string + body string + wantPath string + wantQuery string + }{ + { + name: "config", + method: http.MethodGet, + target: "/muse-code/config?channel=public", + wantPath: "/muse-code/config", + wantQuery: "channel=public", + }, + { + name: "search", + method: http.MethodPost, + target: "/muse-code/search", + body: `{"query":"golang"}`, + wantPath: "/muse-code/search", + }, + { + name: "browser_open", + method: http.MethodPost, + target: "/muse-code/browser_open", + body: `{"url":"https://example.com"}`, + wantPath: "/muse-code/browser_open", + }, + } { + t.Run(tc.name, func(t *testing.T) { + seenMethod, seenPath, seenQuery, seenAuth, seenBody = "", "", "", "", "" + req := httptest.NewRequest(tc.method, tc.target, strings.NewReader(tc.body)) + req.Header.Set("Authorization", "Bearer test-key") + if tc.body != "" { + req.Header.Set("Content-Type", "application/json") + } + rec := httptest.NewRecorder() + server.engine.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%q", rec.Code, rec.Body.String()) + } + if seenMethod != tc.method || seenPath != tc.wantPath || seenQuery != tc.wantQuery { + t.Fatalf("upstream got %s %s?%s, want %s %s?%s", seenMethod, seenPath, seenQuery, tc.method, tc.wantPath, tc.wantQuery) + } + if seenAuth != "Bearer meta-upstream-secret" { + t.Fatalf("upstream Authorization = %q, want Bearer meta-upstream-secret", seenAuth) + } + if tc.body != "" && seenBody != tc.body { + t.Fatalf("upstream body = %q, want %q", seenBody, tc.body) + } + }) + } +} + +func TestMuseCodeModelsUsesFullCPACatalogWithoutUpstreamRelay(t *testing.T) { + var upstreamCalls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + w.WriteHeader(http.StatusInternalServerError) + })) + defer upstream.Close() + + server := newTestServer(t) + server.handlers.AuthManager.RegisterExecutor(executor.NewMetaExecutor(server.getConfig())) + cred := &auth.Auth{ + ID: "meta-muse-code-models-local", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "meta-upstream-secret", + "base_url": upstream.URL + "/v1", + }, + } + registry.GetGlobalRegistry().RegisterClient(cred.ID, "meta", []*registry.ModelInfo{ + {ID: "muse-wonder-1.0", DisplayName: "Muse Wonder 1.0", OwnedBy: "meta", Type: "meta", ContextLength: 1007997, MaxCompletionTokens: 128000, Thinking: ®istry.ThinkingSupport{Levels: []string{"minimal", "low", "medium", "high", "xhigh", "max"}}, SupportedInputModalities: []string{"text", "image", "video"}, SupportedOutputModalities: []string{"text"}}, + {ID: "muse-spark-1.3", DisplayName: "Muse Spark 1.3", OwnedBy: "meta", Type: "meta", ContextLength: 1007997, MaxCompletionTokens: 128000, Thinking: ®istry.ThinkingSupport{Levels: []string{"minimal", "low", "medium", "high", "xhigh", "max"}}, SupportedInputModalities: []string{"text", "image", "video"}, SupportedOutputModalities: []string{"text"}}, + {ID: "muse-image-1.0", DisplayName: "Muse Image 1.0", OwnedBy: "meta", Type: "meta", SupportedInputModalities: []string{"text", "image"}, SupportedOutputModalities: []string{"image"}}, + }) + registry.GetGlobalRegistry().RegisterClient("codex-muse-code-models-local", "codex", []*registry.ModelInfo{ + {ID: "gpt-6.1-sol", DisplayName: "GPT 6.1 Sol", OwnedBy: "openai", Type: "codex", ContextLength: 500000, MaxCompletionTokens: 128000, Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high", "xhigh"}}, SupportedInputModalities: []string{"text", "image"}, SupportedOutputModalities: []string{"text"}}, + }) + registry.GetGlobalRegistry().RegisterClient("claude-muse-code-models-local", "claude", []*registry.ModelInfo{ + {ID: "claude-sonnet-4-5-20250929", DisplayName: "Claude 4.5 Sonnet", OwnedBy: "anthropic", Type: "claude", ContextLength: 200000, MaxCompletionTokens: 64000, Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 128000, ZeroAllowed: true}, SupportedInputModalities: []string{"text", "image"}, SupportedOutputModalities: []string{"text"}}, + }) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(cred.ID) + registry.GetGlobalRegistry().UnregisterClient("codex-muse-code-models-local") + registry.GetGlobalRegistry().UnregisterClient("claude-muse-code-models-local") + }) + if _, errRegister := server.handlers.AuthManager.Register(t.Context(), cred); errRegister != nil { + t.Fatalf("register Meta credential: %v", errRegister) + } + + req := httptest.NewRequest(http.MethodGet, "/muse-code/models?channel=public", nil) + req.Header.Set("Authorization", "Bearer test-key") + rec := httptest.NewRecorder() + server.engine.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } + if upstreamCalls.Load() != 0 { + t.Fatalf("/muse-code/models must not call Meta upstream; calls=%d", upstreamCalls.Load()) + } + if ojson.GetBytesNoCopy(rec.Body.Bytes(), "object").String() != "list" { + t.Fatalf("object = %q, want list", ojson.GetBytesNoCopy(rec.Body.Bytes(), "object").String()) + } + + entries := parseAPIMuseCodeEntriesByID(t, rec.Body.Bytes()) + for _, wantID := range []string{"muse-wonder-1.0", "muse-spark-1.3", "muse-image-1.0", "gpt-6.1-sol", "claude-sonnet-4-5-20250929"} { + if _, ok := entries[wantID]; !ok { + t.Fatalf("missing expected model %q in /muse-code/models response: %s", wantID, rec.Body.String()) + } + } + if got := entries["muse-wonder-1.0"].Get("metadata.muse-code.background_agent_model").String(); got != "muse-spark-1.3" { + t.Fatalf("muse-wonder-1.0 background_agent_model = %q, want muse-spark-1.3", got) + } + museImg := entries["muse-image-1.0"].Get("metadata.muse-code") + if !museImg.Get("is_hidden").Bool() || museImg.Get("tool_call").Bool() { + t.Fatalf("muse-image-1.0 expected hidden with tool_call=false: %s", museImg.Raw) + } + if len(entries["claude-sonnet-4-5-20250929"].Get("metadata.muse-code.variants").Map()) == 0 { + t.Fatalf("claude-sonnet-4-5-20250929 should advertise derived reasoning variants") + } +} + +func TestHomeCodexBucketsAndPrecedenceForOAuthSettings(t *testing.T) { + cfg := &proxyconfig.Config{ + OAuthSettings: map[string][]proxyconfig.OAuthModelSetting{ + "codex": { + {Name: "shared-model", MaxContextLength: 524288}, + {Name: "upstream-sol", Alias: "public-sol", MaxContextLength: 750000}, + }, + "claude": { + {Name: "shared-model", MaxContextLength: 200000}, + {Name: "upstream-sol", Alias: "public-sol", MaxContextLength: 300000}, + }, + }, + } + + for _, tc := range []struct { + name string + entry homeModelEntry + wantLimit int + }{ + { + name: "codex-free bucket matches codex OAuthSettings", + entry: homeModelEntry{ + id: "shared-model", + providers: []string{"codex-free"}, + }, + wantLimit: 524288, + }, + { + name: "codex-plus bucket matches codex OAuthSettings", + entry: homeModelEntry{ + id: "shared-model", + providers: []string{"codex-plus"}, + }, + wantLimit: 524288, + }, + { + name: "codex-team bucket matches codex OAuthSettings", + entry: homeModelEntry{ + id: "shared-model", + providers: []string{"codex-team"}, + }, + wantLimit: 524288, + }, + { + name: "codex-pro bucket matches codex OAuthSettings", + entry: homeModelEntry{ + id: "shared-model", + providers: []string{"codex-pro"}, + }, + wantLimit: 524288, + }, + { + name: "multi-provider claude + codex-free prefers codex", + entry: homeModelEntry{ + id: "shared-model", + providers: []string{"claude", "codex-free"}, + routes: []homeModelRoute{ + {provider: "claude"}, + {provider: "codex-free"}, + }, + }, + wantLimit: 524288, + }, + { + name: "multi-provider alias claude + codex-team prefers codex", + entry: homeModelEntry{ + id: "public-sol", + metadataModelID: "upstream-sol", + modelName: "upstream-sol", + providers: []string{"claude", "codex-team"}, + routes: []homeModelRoute{ + {provider: "claude", metadataModelID: "upstream-sol", modelName: "upstream-sol"}, + {provider: "codex-team", metadataModelID: "upstream-sol", modelName: "upstream-sol"}, + }, + }, + wantLimit: 750000, + }, + { + name: "claude-only entry uses claude setting", + entry: homeModelEntry{ + id: "shared-model", + providers: []string{"claude"}, + routes: []homeModelRoute{{provider: "claude"}}, + }, + wantLimit: 200000, + }, + } { + t.Run(tc.name, func(t *testing.T) { + if got := resolveHomeModelMaxContextLength(tc.entry, cfg); got != tc.wantLimit { + t.Fatalf("resolveHomeModelMaxContextLength = %d, want %d", got, tc.wantLimit) + } + }) + } +} + +func TestMuseCodeModelsSupportsHomeModeOAuthSettingsHotReloadAndPluginInterceptor(t *testing.T) { + previousHome := home.Current() + home.ClearCurrent() + t.Cleanup(func() { home.SetCurrent(previousHome) }) + + localClientID := "local-only-muse-code-isolation" + registry.GetGlobalRegistry().RegisterClient(localClientID, "openai", []*registry.ModelInfo{{ID: "local-only-secret-model"}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(localClientID) }) + + // 1. Real server.engine rejects Home request with 503 when Home heartbeat is absent, without leaking local models. + cfgNoHome := &proxyconfig.Config{ + SDKConfig: sdkconfig.SDKConfig{APIKeys: []string{"test-key"}}, + Home: proxyconfig.HomeConfig{Enabled: true}, + } + serverNoHome := newTestServerWithConfig(t, cfgNoHome) + engineReq503 := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + engineReq503.Header.Set("Authorization", "Bearer test-key") + engineRec503 := httptest.NewRecorder() + serverNoHome.engine.ServeHTTP(engineRec503, engineReq503) + if engineRec503.Code != http.StatusServiceUnavailable { + t.Fatalf("server.engine status without home heartbeat = %d, want 503", engineRec503.Code) + } + if strings.Contains(engineRec503.Body.String(), "local-only-secret-model") { + t.Fatalf("server.engine 503 leaked local-only model: %s", engineRec503.Body.String()) + } + + routeNoHome := registeredRouteEngine(t, serverNoHome, http.MethodGet, "/muse-code/models") + req503 := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + req503.Header.Set("Authorization", "Bearer test-key") + rec503 := httptest.NewRecorder() + routeNoHome.ServeHTTP(rec503, req503) + if rec503.Code != http.StatusServiceUnavailable || !strings.Contains(rec503.Body.String(), "home control center unavailable") { + t.Fatalf("route handler without home client = %d %s, want 503 home control center unavailable", rec503.Code, rec503.Body.String()) + } + + // 2. Full server.engine middleware chain in healthy Home mode: + // - codex-free / codex-plus / codex-pro buckets match OAuthSettings["codex"] + // - cross-route identity isolation (claude id=gpt-6.1-sol name=claude-opus-4-6 + codex-pro id=gpt-6.1-sol name=gpt-6.1-sol -> 272000) + // - canonical upstream name enrichment without leaking internal fields + // - explicit empty supportedInputModalities: [] + // - conservative multi-section merge + // - query parameter forwarding & plugin interceptor + homePayload := `{ + "codex-free": [{ + "id": "gpt-free-model", + "name": "gpt-free-model", + "owned_by": "openai", + "type": "codex", + "context_length": 128000, + "max_completion_tokens": 16384 + }], + "codex-pro": [{ + "id": "gpt-6.1-sol", + "name": "gpt-6.1-sol" + }], + "codex-plus": [{ + "id": "gpt-plus-alias", + "name": "gpt-5.6-sol", + "display_name": "GPT Plus Alias" + }], + "claude": [{ + "id": "gpt-6.1-sol", + "name": "claude-opus-4-6" + }, { + "id": "my-claude-alias", + "name": "claude-opus-4-6", + "display_name": "Aliased Claude" + }, { + "id": "muse-wonder-1.0", + "owned_by": "meta", + "type": "meta", + "supportedInputModalities": [], + "supportedOutputModalities": ["text"] + }, { + "id": "shared-home-model", + "owned_by": "anthropic", + "type": "claude", + "context_length": 400000, + "max_completion_tokens": 64000, + "thinking": {"levels": ["low", "medium", "high"]}, + "supportedInputModalities": ["text", "image"], + "supportedOutputModalities": ["text"] + }], + "openai-compat": [{ + "id": "shared-home-model", + "owned_by": "openai", + "type": "openai", + "context_length": 128000, + "max_completion_tokens": 16384, + "thinking": {"levels": ["medium", "high"]}, + "supportedInputModalities": ["text"], + "supportedOutputModalities": ["text"] + }] + }` + homeClient, setHomePayload, getLastModelsReq := newReadyHomeCatalogClient(t, homePayload) + home.SetCurrent(homeClient) + + cfgWithHome := &proxyconfig.Config{ + SDKConfig: sdkconfig.SDKConfig{APIKeys: []string{"test-key"}}, + Home: proxyconfig.HomeConfig{Enabled: true}, + OAuthSettings: map[string][]proxyconfig.OAuthModelSetting{ + "codex": { + { + Name: "gpt-free-model", + MaxContextLength: 600000, + }, + { + Name: "gpt-5.6-sol", + MaxContextLength: 750000, + }, + }, + "claude": { + { + Name: "claude-opus-4-6", + MaxContextLength: 350000, + }, + }, + }, + } + server := newTestServerWithConfig(t, cfgWithHome) + + var intercepted bool + var capturedFormat string + server.handlers.SetPluginHost(&mockModelListInterceptorHost{ + interceptResponse: func(_ context.Context, req pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + intercepted = true + capturedFormat = req.SourceFormat + doc := ojson.NewDoc(req.Body) + if errSet := doc.Set("muse_intercepted", true); errSet != nil { + t.Fatalf("set muse_intercepted via ojson.Doc: %v", errSet) + } + return pluginapi.ResponseInterceptResponse{ + Headers: req.ResponseHeaders, + Body: doc.Bytes(), + } + }, + }) + + // Unauthorized request still blocked by real auth middleware on server.engine even when Home is healthy. + unauthRec := httptest.NewRecorder() + unauthReq := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + unauthReq.Header.Set("Authorization", "Bearer wrong-key") + server.engine.ServeHTTP(unauthRec, unauthReq) + if unauthRec.Code != http.StatusUnauthorized { + t.Fatalf("unauth Home request status = %d, want 401", unauthRec.Code) + } + + // Authorized request flows through the full server.engine middleware chain! + req := httptest.NewRequest(http.MethodGet, "/muse-code/models?channel=public", nil) + req.Header.Set("Authorization", "Bearer test-key") + rec := httptest.NewRecorder() + server.engine.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } + if !intercepted || capturedFormat != "openai" { + t.Fatalf("interceptor not invoked cleanly: intercepted=%v format=%q", intercepted, capturedFormat) + } + if strings.Contains(rec.Body.String(), "local-only-secret-model") { + t.Fatalf("Home response leaked local-only model: %s", rec.Body.String()) + } + if !ojson.GetBytesNoCopy(rec.Body.Bytes(), "muse_intercepted").Bool() { + t.Fatalf("response missing plugin interceptor marker: %s", rec.Body.String()) + } + if lastReq := getLastModelsReq(); !strings.Contains(lastReq, `"channel":"public"`) { + t.Fatalf("Home GetModels did not receive forwarded query param: %s", lastReq) + } + + entries := parseAPIMuseCodeEntriesByID(t, rec.Body.Bytes()) + if len(entries) != 6 { + t.Fatalf("len(entries) = %d, want 6; body=%s", len(entries), rec.Body.String()) + } + + // codex-free bucket matches OAuthSettings["codex"]. + if got := entries["gpt-free-model"].Get("metadata.muse-code.limit.context").Int(); got != 600000 { + t.Fatalf("codex-free gpt-free-model context = %d, want 600000", got) + } + // Cross-route identity isolation: claude (id=gpt-6.1-sol, name=claude-opus-4-6, 350k) + + // codex-pro (id=gpt-6.1-sol, name=gpt-6.1-sol, 272k) MUST cap context conservatively at 272000! + if got := entries["gpt-6.1-sol"].Get("metadata.muse-code.limit.context").Int(); got != 272000 { + t.Fatalf("cross-route Home gpt-6.1-sol context = %d, want 272000; entry=%s", got, entries["gpt-6.1-sol"].Raw) + } + // codex-plus + canonical name matches OAuthSettings["codex"] ("gpt-5.6-sol") and enriches static metadata. + plusAlias := entries["gpt-plus-alias"] + if plusAlias.Get("metadata.muse-code.limit.context").Int() != 750000 || !plusAlias.Get("metadata.muse-code.reasoning").Bool() { + t.Fatalf("codex-plus canonical name alias failed enrichment/settings: %s", plusAlias.Raw) + } + // claude canonical name ("claude-opus-4-6") enriches static metadata and matches OAuthSettings["claude"], without leaking internal keys. + claudeAlias := entries["my-claude-alias"] + if claudeAlias.Get("metadata.muse-code.limit.context").Int() != 350000 || !claudeAlias.Get("metadata.muse-code.variants.max").Exists() { + t.Fatalf("claude canonical name alias failed enrichment/settings: %s", claudeAlias.Raw) + } + if claudeAlias.Get("name").Exists() || claudeAlias.Get("MetadataModelID").Exists() { + t.Fatalf("public response must not expose internal canonical name or MetadataModelID: %s", claudeAlias.Raw) + } + // Explicit empty supportedInputModalities: [] in Home does not fall back to static attachment=true. + if entries["muse-wonder-1.0"].Get("metadata.muse-code.attachment").Bool() { + t.Fatalf("explicit empty supportedInputModalities in Home must keep attachment=false: %s", entries["muse-wonder-1.0"].Raw) + } + // Multi-section Home model merges conservatively across claude + openai-compat. + shared := entries["shared-home-model"].Get("metadata.muse-code") + if shared.Get("attachment").Bool() || shared.Get("limit.context").Int() != 128000 || shared.Get("limit.output").Int() != 16384 || shared.Get("variants.low").Exists() || !shared.Get("variants.medium").Exists() { + t.Fatalf("multi-section Home model did not merge conservatively: %s", shared.Raw) + } + + // 3. Home error envelopes and empty Home catalog via full server.engine. + for _, tc := range []struct { + name string + payload string + wantStatus int + }{ + {name: "no_credentials", payload: `{"error":{"type":"no_credentials","message":"Missing API key"}}`, wantStatus: http.StatusUnauthorized}, + {name: "internal_error", payload: `{"error":{"type":"internal_error","message":"Home failed"}}`, wantStatus: http.StatusBadGateway}, + {name: "malformed", payload: `{bad}`, wantStatus: http.StatusBadGateway}, + } { + t.Run("home_error_"+tc.name, func(t *testing.T) { + setHomePayload(tc.payload) + errRec := httptest.NewRecorder() + errReq := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + errReq.Header.Set("Authorization", "Bearer test-key") + server.engine.ServeHTTP(errRec, errReq) + if errRec.Code != tc.wantStatus { + t.Fatalf("%s status = %d, want %d; body=%s", tc.name, errRec.Code, tc.wantStatus, errRec.Body.String()) + } + }) + } + + server.handlers.SetPluginHost(nil) + setHomePayload(`{"openai":[]}`) + recEmpty := httptest.NewRecorder() + emptyReq := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + emptyReq.Header.Set("Authorization", "Bearer test-key") + server.engine.ServeHTTP(recEmpty, emptyReq) + if recEmpty.Code != http.StatusOK || strings.TrimSpace(recEmpty.Body.String()) != `{"object":"list","data":[]}` { + t.Fatalf("empty Home catalog got %d %s, want 200 {\"object\":\"list\",\"data\":[]}", recEmpty.Code, recEmpty.Body.String()) + } + + // 4. Config hot-reload toggling Home.Enabled from false -> true verified via full server.engine. + reloadServer := newTestServer(t) + + recLocal := httptest.NewRecorder() + reqLocal := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + reqLocal.Header.Set("Authorization", "Bearer test-key") + reloadServer.engine.ServeHTTP(recLocal, reqLocal) + if recLocal.Code != http.StatusOK || !strings.Contains(recLocal.Body.String(), "local-only-secret-model") { + t.Fatalf("expected local mode model before reload, got %d %s", recLocal.Code, recLocal.Body.String()) + } + + setHomePayload(`{"codex-team":[{"id":"reloaded-home-model"}]}`) + reloadCfg := reloadServer.getConfig().CloneForRuntime() + reloadCfg.Home.Enabled = true + reloadServer.UpdateClients(reloadCfg) + + recReloaded := httptest.NewRecorder() + reqReloaded := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + reqReloaded.Header.Set("Authorization", "Bearer test-key") + reloadServer.engine.ServeHTTP(recReloaded, reqReloaded) + if recReloaded.Code != http.StatusOK { + t.Fatalf("reloaded Home status = %d, want 200; body=%s", recReloaded.Code, recReloaded.Body.String()) + } + if strings.Contains(recReloaded.Body.String(), "local-only-secret-model") || !strings.Contains(recReloaded.Body.String(), "reloaded-home-model") { + t.Fatalf("hot-reload to Home mode did not switch source cleanly: %s", recReloaded.Body.String()) + } +} + +func TestMuseCodeRoutesEnforceAuthSafeModeAndDisallowedPaths(t *testing.T) { + var upstreamCalls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + w.WriteHeader(http.StatusOK) + })) + defer upstream.Close() + + // 1. Unknown client key returns 401; disallowed /muse-code/key returns 404. + server := newTestServer(t) + server.handlers.AuthManager.RegisterExecutor(executor.NewMetaExecutor(server.getConfig())) + cred := &auth.Auth{ + ID: "meta-server-auth-test", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "meta-secret", + "base_url": upstream.URL + "/v1", + }, + } + registry.GetGlobalRegistry().RegisterClient(cred.ID, "meta", []*registry.ModelInfo{{ID: "muse-wonder-1.0"}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(cred.ID) + }) + if _, errRegister := server.handlers.AuthManager.Register(t.Context(), cred); errRegister != nil { + t.Fatalf("register Meta credential: %v", errRegister) + } + + unauthReq := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + unauthReq.Header.Set("Authorization", "Bearer wrong-key") + unauthRec := httptest.NewRecorder() + server.engine.ServeHTTP(unauthRec, unauthReq) + if unauthRec.Code != http.StatusUnauthorized { + t.Fatalf("unknown client key status = %d, want 401", unauthRec.Code) + } + + keyReq := httptest.NewRequest(http.MethodPost, "/muse-code/key", nil) + keyReq.Header.Set("Authorization", "Bearer test-key") + keyRec := httptest.NewRecorder() + server.engine.ServeHTTP(keyRec, keyReq) + if keyRec.Code != http.StatusNotFound { + t.Fatalf("disallowed /muse-code/key status = %d, want 404", keyRec.Code) + } + + // 2. Example API key safe mode blocks /muse-code/models with 403. + safeCfg := &proxyconfig.Config{ + SDKConfig: sdkconfig.SDKConfig{ + APIKeys: []string{"your-api-key-1"}, + }, + } + safeServer := newTestServerWithConfig(t, safeCfg, WithExampleAPIKeySafeMode()) + safeReq := httptest.NewRequest(http.MethodGet, "/muse-code/models", nil) + safeReq.Header.Set("Authorization", "Bearer your-api-key-1") + safeRec := httptest.NewRecorder() + safeServer.engine.ServeHTTP(safeRec, safeReq) + if safeRec.Code != http.StatusForbidden { + t.Fatalf("safe mode status = %d, want 403; body=%s", safeRec.Code, safeRec.Body.String()) + } + if upstreamCalls.Load() != 0 { + t.Fatalf("upstream called %d times, want 0", upstreamCalls.Load()) + } +} diff --git a/internal/api/server_options.go b/internal/api/server_options.go index 88041b0ed57..66014065117 100644 --- a/internal/api/server_options.go +++ b/internal/api/server_options.go @@ -16,6 +16,7 @@ import ( ) type serverOptionConfig struct { + pluginInterceptorHost handlers.PluginInterceptorHost extraMiddleware []gin.HandlerFunc engineConfigurator func(*gin.Engine) routerConfigurator func(*gin.Engine, *handlers.BaseAPIHandler, *config.Config) @@ -138,6 +139,17 @@ func WithPostAuthPersistHook(hook auth.PostAuthHook) ServerOption { } } +// WithPluginInterceptorHost installs a caller-provided plugin interceptor host +// on request handlers. When set, the server forwards interceptor calls to this +// host while keeping model routing, lifecycle callbacks, and websocket observer +// dispatch delegated to the internal plugin host so plugin features stay +// functional across startup and config reloads. +func WithPluginInterceptorHost(host handlers.PluginInterceptorHost) ServerOption { + return func(cfg *serverOptionConfig) { + cfg.pluginInterceptorHost = host + } +} + // WithPluginHost registers dynamic plugin HTTP adapters with the server. func WithPluginHost(host *pluginhost.Host) ServerOption { return func(cfg *serverOptionConfig) { diff --git a/internal/api/server_reload.go b/internal/api/server_reload.go index 5ea113d9e03..8c2ad552323 100644 --- a/internal/api/server_reload.go +++ b/internal/api/server_reload.go @@ -25,7 +25,13 @@ import ( ) func (s *Server) applyAccessConfig(oldCfg, newCfg *config.Config) bool { - if s == nil || s.accessManager == nil || newCfg == nil { + if s == nil || newCfg == nil { + return false + } + if s.tunnelHub != nil { + s.tunnelHub.UpdateAllowedAPIKeys(newCfg.APIKeys) + } + if s.accessManager == nil { return false } if _, err := access.ApplyAccessProviders(s.accessManager, oldCfg, newCfg); err != nil { @@ -186,6 +192,9 @@ func (s *Server) UpdateClientsContext(ctx context.Context, cfg *config.Config) b log.WithError(errUpdate).Error("failed to update Codex Live media relay configuration") } } + if s.museCodeHandler != nil { + s.museCodeHandler.UpdateConfig(cfg) + } s.wsAuthEnabled.Store(cfg.WebsocketAuth) openai.SetResponsesWebsocketCompressionEnabled(cfg.Codex.WebsocketCompressionEnabled()) if oldCfg != nil && s.wsAuthChanged != nil && oldCfg.WebsocketAuth != cfg.WebsocketAuth { @@ -203,7 +212,7 @@ func (s *Server) UpdateClientsContext(ctx context.Context, cfg *config.Config) b s.cfgMu.Unlock() s.handlers.UpdateClients(effectiveSDKConfig(cfg)) - s.handlers.SetPluginHost(s.pluginHost) + s.handlers.SetPluginHost(s.interceptorHost) if s.pluginHost != nil { s.pluginHost.SetModelExecutor(s.handlers) s.pluginHost.SetAuthManager(s.handlers.AuthManager) diff --git a/internal/api/server_routes.go b/internal/api/server_routes.go index e2b039a8563..004081a26a9 100644 --- a/internal/api/server_routes.go +++ b/internal/api/server_routes.go @@ -19,6 +19,7 @@ import ( codexlive "github.com/router-for-me/CLIProxyAPI/v8/internal/client/codex/live" codexmodels "github.com/router-for-me/CLIProxyAPI/v8/internal/client/codex/models" "github.com/router-for-me/CLIProxyAPI/v8/internal/client/grokbuild" + "github.com/router-for-me/CLIProxyAPI/v8/internal/client/musecode" "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/home" @@ -61,6 +62,8 @@ func (s *Server) setupRoutes() { openaiResponsesHandlers := openai.NewOpenAIResponsesAPIHandler(s.handlers) openaiResponsesHandlers.AccessManager = s.accessManager s.codexLiveHandler = codexlive.NewHandler(s.handlers.AuthManager, s.cfg) + s.museCodeHandler = musecode.NewHandler(s.handlers.AuthManager, s.cfg) + s.museCodeHandler.SetModelListHooks(s.loadMuseCodeHomeModels, s.writeModelListResponse) // OpenAI compatible API routes v1 := s.engine.Group("/v1") @@ -92,6 +95,11 @@ func (s *Server) setupRoutes() { v1.GET("/live/:call_id", s.codexLiveHandler.HandleSideband) } + s.engine.GET("/v1/tunnel", s.handleWebsocketTunnel) + for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodTrace, http.MethodConnect} { + s.engine.Handle(method, "/v1/tunnel", s.handleWebsocketTunnel) + } + realtimeAuth := realtimeAuthMiddleware(s.accessManager, s.codexLiveHandler) standardAuth := realtimeStandardAuthMiddleware(s.accessManager) s.engine.GET("/v1/realtime", realtimeAuth, s.codexLiveHandler.HandleRealtimeWebsocket) @@ -127,6 +135,16 @@ func (s *Server) setupRoutes() { codexDirect.POST("/alpha/search", s.codexAlphaSearch) } + // Muse Code CLI direct endpoints (beside /v1) + museCode := s.engine.Group("/muse-code") + museCode.Use(AuthMiddleware(s.accessManager)) + { + museCode.GET("/models", s.museCodeHandler.HandleModels) + museCode.GET("/config", s.museCodeHandler.Handle) + museCode.POST("/search", s.museCodeHandler.Handle) + museCode.POST("/browser_open", s.museCodeHandler.Handle) + } + // Gemini compatible API routes v1beta := s.engine.Group("/v1beta") v1beta.Use(AuthMiddleware(s.accessManager)) @@ -608,6 +626,15 @@ func (s *Server) AttachWebsocketRoute(path string, handler http.Handler) { s.engine.GET(trimmed, conditionalAuth, finalHandler) } +func (s *Server) handleWebsocketTunnel(c *gin.Context) { + if s == nil || s.tunnelHub == nil { + c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "tunnel hub unavailable"}) + return + } + s.tunnelHub.ServeHTTP(c.Writer, c.Request) + c.Abort() +} + // isAnthropicModelsRequest reports whether a /v1/models request should be served in // Anthropic format. Anthropic API clients send the Anthropic-Version header; Claude // Code additionally uses a claude-cli User-Agent. @@ -853,29 +880,147 @@ func formatHomeCodexModel(entry homeModelEntry) map[string]any { func formatHomeCodexModelWithSettings(entry homeModelEntry, cfg *config.Config) map[string]any { model := formatHomeCodexModel(entry) + if maxCtx := resolveHomeModelMaxContextLength(entry, cfg); maxCtx > 0 && maxCtx != entry.maxContextLength { + model["max_context_length"] = maxCtx + } + return model +} + +func normalizeHomeProviderChannel(provider string) string { + channel := strings.ToLower(strings.TrimSpace(provider)) + switch channel { + case "codex", "codex-free", "codex-plus", "codex-team", "codex-pro": + return "codex" + default: + return channel + } +} + +func resolveHomeRouteMaxContextLength(modelID, metadataModelID, modelName, provider string, baseMaxContextLength int, cfg *config.Config) int { if cfg == nil || len(cfg.OAuthSettings) == 0 { - return model + return baseMaxContextLength + } + channel := normalizeHomeProviderChannel(provider) + if channel == "" { + return baseMaxContextLength + } + if channelSettings, okChannel := cfg.OAuthSettings[channel]; okChannel { + if setting := config.ResolveOAuthModelSetting(channelSettings, modelID, metadataModelID, modelName); setting != nil && setting.MaxContextLength > 0 { + return setting.MaxContextLength + } + } + return baseMaxContextLength +} + +func resolveHomeModelMaxContextLength(entry homeModelEntry, cfg *config.Config) int { + if cfg == nil || len(cfg.OAuthSettings) == 0 { + return entry.maxContextLength + } + if len(entry.routes) > 0 { + routes := append([]homeModelRoute(nil), entry.routes...) + sort.SliceStable(routes, func(i, j int) bool { + ci := normalizeHomeProviderChannel(routes[i].provider) + cj := normalizeHomeProviderChannel(routes[j].provider) + if ci == "codex" && cj != "codex" { + return true + } + if cj == "codex" && ci != "codex" { + return false + } + return ci < cj + }) + for _, route := range routes { + channel := normalizeHomeProviderChannel(route.provider) + if channelSettings, okChannel := cfg.OAuthSettings[channel]; okChannel { + if setting := config.ResolveOAuthModelSetting(channelSettings, entry.id, route.metadataModelID, route.modelName); setting != nil && setting.MaxContextLength > 0 { + return setting.MaxContextLength + } + } + } + return entry.maxContextLength } providers := append([]string(nil), entry.providers...) sort.SliceStable(providers, func(i, j int) bool { - if strings.EqualFold(providers[i], "codex") { + ci := normalizeHomeProviderChannel(providers[i]) + cj := normalizeHomeProviderChannel(providers[j]) + if ci == "codex" && cj != "codex" { return true } - if strings.EqualFold(providers[j], "codex") { + if cj == "codex" && ci != "codex" { return false } - return strings.ToLower(providers[i]) < strings.ToLower(providers[j]) + return ci < cj }) for _, p := range providers { - channel := strings.ToLower(strings.TrimSpace(p)) + channel := normalizeHomeProviderChannel(p) if channelSettings, okChannel := cfg.OAuthSettings[channel]; okChannel { - if setting := config.ResolveOAuthModelSetting(channelSettings, entry.id, "", ""); setting != nil && setting.MaxContextLength > 0 { - model["max_context_length"] = setting.MaxContextLength - break + if setting := config.ResolveOAuthModelSetting(channelSettings, entry.id, entry.metadataModelID, entry.modelName); setting != nil && setting.MaxContextLength > 0 { + return setting.MaxContextLength } } } - return model + return entry.maxContextLength +} + +func (s *Server) loadMuseCodeHomeModels(c *gin.Context) ([]musecode.ModelInput, bool) { + entries, ok := s.loadHomeModelEntries(c) + if !ok { + return nil, false + } + cfg := s.getConfig() + inputs := make([]musecode.ModelInput, 0, len(entries)) + for _, entry := range entries { + routes := make([]musecode.ModelRoute, 0, len(entry.routes)) + for _, route := range entry.routes { + routeType := route.modelType + if routeType == "" && route.provider == "openai-image" { + routeType = "openai-image" + } + routes = append(routes, musecode.ModelRoute{ + Provider: route.provider, + MetadataModelID: route.metadataModelID, + Created: route.created, + OwnedBy: route.ownedBy, + Type: routeType, + DisplayName: route.displayName, + Description: route.description, + ContextLength: route.contextLength, + MaxContextLength: resolveHomeRouteMaxContextLength(entry.id, route.metadataModelID, route.modelName, route.provider, route.maxContextLength, cfg), + MaxCompletionTokens: route.maxCompletionTokens, + Thinking: route.thinking, + ExplicitThinking: route.hasThinking, + SupportedInputModalities: append([]string(nil), route.supportedInputModalities...), + ExplicitInputModalities: route.hasInputModalities, + SupportedOutputModalities: append([]string(nil), route.supportedOutputModalities...), + HasOutputModalities: route.hasOutputModalities, + }) + } + modelType := entry.modelType + if modelType == "" && len(entry.providers) == 1 && entry.providers[0] == "openai-image" { + modelType = "openai-image" + } + metadataID := entry.metadataModelID + if len(routes) > 0 { + metadataID = "" + } + inputs = append(inputs, musecode.ModelInput{ + ID: entry.id, + MetadataModelID: metadataID, + Created: entry.created, + OwnedBy: entry.ownedBy, + Type: modelType, + DisplayName: entry.displayName, + Description: entry.description, + ContextLength: entry.contextLength, + MaxContextLength: resolveHomeModelMaxContextLength(entry, cfg), + MaxCompletionTokens: entry.maxCompletionTokens, + Thinking: entry.thinking, + SupportedInputModalities: append([]string(nil), entry.supportedInputModalities...), + SupportedOutputModalities: append([]string(nil), entry.supportedOutputModalities...), + Routes: routes, + }) + } + return inputs, true } func (s *Server) geminiModelsHandler(geminiHandler *gemini.GeminiAPIHandler) gin.HandlerFunc { @@ -900,17 +1045,44 @@ func (s *Server) geminiGetHandler(geminiHandler *gemini.GeminiAPIHandler) gin.Ha } } +type homeModelRoute struct { + provider string + modelName string + metadataModelID string + created int64 + ownedBy string + modelType string + displayName string + description string + contextLength int + maxContextLength int + maxCompletionTokens int + thinking *registry.ThinkingSupport + hasThinking bool + supportedInputModalities []string + hasInputModalities bool + supportedOutputModalities []string + hasOutputModalities bool +} + type homeModelEntry struct { - id string - created int64 - ownedBy string - displayName string - contextLength int - maxContextLength int - maxCompletionTokens int - thinking *registry.ThinkingSupport - providers []string - nativeCapabilityRoutes []registry.NativeCapabilityRoute + id string + modelName string + metadataModelID string + created int64 + ownedBy string + modelType string + displayName string + description string + contextLength int + maxContextLength int + maxCompletionTokens int + thinking *registry.ThinkingSupport + supportedInputModalities []string + supportedOutputModalities []string + providers []string + nativeCapabilityRoutes []registry.NativeCapabilityRoute + routes []homeModelRoute } func (s *Server) handleHomeModels(c *gin.Context) { @@ -1208,16 +1380,21 @@ func decodeHomeModels(raw []byte) ([]homeModelEntry, error) { hasModelRecords = hasModelRecords || len(models) > 0 provider := strings.ToLower(strings.TrimSpace(section)) for _, model := range models { + rawName, _ := model["name"].(string) + rawName = strings.TrimSpace(rawName) + trimmedName := strings.TrimPrefix(rawName, "models/") id, _ := model["id"].(string) id = strings.TrimSpace(id) if id == "" { - name, _ := model["name"].(string) - name = strings.TrimSpace(name) - id = strings.TrimPrefix(name, "models/") + id = trimmedName } if id == "" { continue } + metadataModelID := "" + if trimmedName != "" && trimmedName != id { + metadataModelID = trimmedName + } nativeCapabilities := homeModelNativeCapabilities(model) route := registry.NativeCapabilityRoute{ Provider: provider, @@ -1226,29 +1403,67 @@ func decodeHomeModels(raw []byte) ([]homeModelEntry, error) { created := homeModelInt64Value(model, "created") ownedBy, _ := model["owned_by"].(string) ownedBy = strings.TrimSpace(ownedBy) + modelType, _ := model["type"].(string) + modelType = strings.TrimSpace(modelType) displayName, _ := model["display_name"].(string) displayName = strings.TrimSpace(displayName) if displayName == "" { displayName, _ = model["displayName"].(string) displayName = strings.TrimSpace(displayName) } + description, _ := model["description"].(string) + description = strings.TrimSpace(description) contextLength := int(homeModelInt64Value(model, "context_length", "contextLength", "inputTokenLimit", "max_input_tokens")) maxContextLength := int(homeModelInt64Value(model, "max_context_length", "maxContextLength")) maxCompletionTokens := int(homeModelInt64Value(model, "max_completion_tokens", "maxCompletionTokens", "outputTokenLimit", "max_tokens")) - thinking := homeModelThinkingSupport(model) + thinking, hasThinking := homeModelThinkingSupport(model) + inputModalities, hasInputModalities := homeModelStringSlice(model, "supportedInputModalities", "supported_input_modalities") + outputModalities, hasOutputModalities := homeModelStringSlice(model, "supportedOutputModalities", "supported_output_modalities") + modelRoute := homeModelRoute{ + provider: provider, + modelName: rawName, + metadataModelID: metadataModelID, + created: created, + ownedBy: ownedBy, + modelType: modelType, + displayName: displayName, + description: description, + contextLength: contextLength, + maxContextLength: maxContextLength, + maxCompletionTokens: maxCompletionTokens, + thinking: thinking, + hasThinking: hasThinking, + supportedInputModalities: inputModalities, + hasInputModalities: hasInputModalities, + supportedOutputModalities: outputModalities, + hasOutputModalities: hasOutputModalities, + } if index, ok := indexByID[id]; ok { out[index].providers = appendUniqueHomeProvider(out[index].providers, provider) out[index].nativeCapabilityRoutes = append(out[index].nativeCapabilityRoutes, route) + out[index].routes = append(out[index].routes, modelRoute) + if out[index].modelName == "" && rawName != "" { + out[index].modelName = rawName + } + if out[index].metadataModelID == "" && metadataModelID != "" { + out[index].metadataModelID = metadataModelID + } if out[index].created <= 0 && created > 0 { out[index].created = created } if out[index].ownedBy == "" && ownedBy != "" { out[index].ownedBy = ownedBy } + if out[index].modelType == "" && modelType != "" { + out[index].modelType = modelType + } if out[index].displayName == "" && displayName != "" { out[index].displayName = displayName } + if out[index].description == "" && description != "" { + out[index].description = description + } if out[index].contextLength <= 0 && contextLength > 0 { out[index].contextLength = contextLength } @@ -1261,21 +1476,34 @@ func decodeHomeModels(raw []byte) ([]homeModelEntry, error) { if out[index].thinking == nil && thinking != nil { out[index].thinking = thinking } + if len(out[index].supportedInputModalities) == 0 && len(inputModalities) > 0 { + out[index].supportedInputModalities = inputModalities + } + if len(out[index].supportedOutputModalities) == 0 && len(outputModalities) > 0 { + out[index].supportedOutputModalities = outputModalities + } continue } indexByID[id] = len(out) out = append(out, homeModelEntry{ - id: id, - created: created, - ownedBy: ownedBy, - displayName: displayName, - contextLength: contextLength, - maxContextLength: maxContextLength, - maxCompletionTokens: maxCompletionTokens, - thinking: thinking, - providers: appendUniqueHomeProvider(nil, provider), - nativeCapabilityRoutes: []registry.NativeCapabilityRoute{route}, + id: id, + modelName: rawName, + metadataModelID: metadataModelID, + created: created, + ownedBy: ownedBy, + modelType: modelType, + displayName: displayName, + description: description, + contextLength: contextLength, + maxContextLength: maxContextLength, + maxCompletionTokens: maxCompletionTokens, + thinking: thinking, + supportedInputModalities: inputModalities, + supportedOutputModalities: outputModalities, + providers: appendUniqueHomeProvider(nil, provider), + nativeCapabilityRoutes: []registry.NativeCapabilityRoute{route}, + routes: []homeModelRoute{modelRoute}, }) } } @@ -1316,20 +1544,51 @@ func appendUniqueHomeProvider(providers []string, provider string) []string { return append(providers, provider) } -func homeModelThinkingSupport(model map[string]any) *registry.ThinkingSupport { - raw, ok := model["thinking"] - if !ok || raw == nil { - return nil +func homeModelThinkingSupport(model map[string]any) (*registry.ThinkingSupport, bool) { + raw, exists := model["thinking"] + if !exists { + return nil, false + } + if raw == nil { + return nil, true } data, errMarshal := json.Marshal(raw) if errMarshal != nil { - return nil + return nil, true } var thinking registry.ThinkingSupport if errUnmarshal := json.Unmarshal(data, &thinking); errUnmarshal != nil { - return nil + return nil, true + } + return &thinking, true +} + +func homeModelStringSlice(model map[string]any, keys ...string) ([]string, bool) { + for _, key := range keys { + raw, exists := model[key] + if !exists { + continue + } + if raw == nil { + continue + } + switch typed := raw.(type) { + case []string: + return append([]string(nil), typed...), true + case []any: + out := make([]string, 0, len(typed)) + for _, item := range typed { + if s, ok := item.(string); ok { + s = strings.TrimSpace(s) + if s != "" { + out = append(out, s) + } + } + } + return out, true + } } - return &thinking + return nil, false } func homeModelInt64Value(model map[string]any, keys ...string) int64 { diff --git a/internal/api/server_shutdown_timeout_test.go b/internal/api/server_shutdown_timeout_test.go new file mode 100644 index 00000000000..7bf2226d755 --- /dev/null +++ b/internal/api/server_shutdown_timeout_test.go @@ -0,0 +1,257 @@ +package api + +import ( + "context" + "io" + "net" + "net/http" + "sync" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" +) + +// shutdownTestFixture bundles a test server whose /slow handler blocks until +// release is closed (or the request context is canceled), mirroring the existing +// violent shutdown test setup while remaining deterministic. +type shutdownTestFixture struct { + server *Server + addr string + reqStarted <-chan struct{} + release chan struct{} + releaseOnce sync.Once +} + +func (fx *shutdownTestFixture) releaseHandler() { + fx.releaseOnce.Do(func() { close(fx.release) }) +} + +func newShutdownTestServer(t *testing.T) *shutdownTestFixture { + t.Helper() + gin.SetMode(gin.TestMode) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("failed to listen: %v", err) + } + if errClose := ln.Close(); errClose != nil { + t.Fatalf("failed to close probe listener: %v", errClose) + } + addr := ln.Addr().String() + + cfg := &config.Config{Host: "127.0.0.1", Port: ln.Addr().(*net.TCPAddr).Port} + server := NewServer(cfg, nil, nil, "") + + release := make(chan struct{}) + reqStarted := make(chan struct{}) + engine := gin.New() + engine.GET("/slow", func(c *gin.Context) { + close(reqStarted) + select { + case <-release: + case <-c.Request.Context().Done(): + } + c.String(http.StatusOK, "ok") + }) + engine.GET("/fast", func(c *gin.Context) { + c.String(http.StatusOK, "ok") + }) + server.server.Handler = engine + + serveLn, errListen := net.Listen("tcp", addr) + if errListen != nil { + t.Fatalf("failed to re-listen on %s: %v", addr, errListen) + } + go func() { + _ = server.server.Serve(serveLn) + }() + fx := &shutdownTestFixture{ + server: server, + addr: addr, + reqStarted: reqStarted, + release: release, + } + t.Cleanup(func() { + fx.releaseHandler() + _ = server.server.Close() + _ = serveLn.Close() + }) + + return fx +} + +// startSlowRequest issues a GET /slow and reports the terminal outcome: +// the error is nil only when the handler completed and a 200 body was read. +func startSlowRequest(t *testing.T, addr string) chan error { + t.Helper() + reqDone := make(chan error, 1) + go func() { + resp, errGet := http.Get("http://" + addr + "/slow") + if errGet != nil { + reqDone <- errGet + return + } + defer func() { + if errCloseBody := resp.Body.Close(); errCloseBody != nil { + t.Logf("response body close error: %v", errCloseBody) + } + }() + if _, errRead := io.ReadAll(resp.Body); errRead != nil { + reqDone <- errRead + return + } + if resp.StatusCode != http.StatusOK { + reqDone <- errUnexpectedStatus(resp.StatusCode) + return + } + reqDone <- nil + }() + return reqDone +} + +type errUnexpectedStatus int + +func (e errUnexpectedStatus) Error() string { return "unexpected status" } + +// TestServerStop_ShutdownTimeoutDrainsInFlightRequests verifies that a positive +// server.shutdown-timeout lets an in-flight request complete before the process +// exits, instead of being cut immediately. +func TestServerStop_ShutdownTimeoutDrainsInFlightRequests(t *testing.T) { + fx := newShutdownTestServer(t) + + // Opt in to a 5-second drain budget. + fx.server.getConfig().ShutdownTimeoutSeconds = 5 + + reqDone := startSlowRequest(t, fx.addr) + <-fx.reqStarted + + // Release the handler shortly after Stop begins: it must still be allowed to + // answer because the drain keeps the connection alive. + go func() { + time.Sleep(150 * time.Millisecond) + fx.releaseHandler() + }() + + stopCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if errStop := fx.server.Stop(stopCtx); errStop != nil { + t.Fatalf("server.Stop error = %v, want nil", errStop) + } + + select { + case errReq := <-reqDone: + if errReq != nil { + t.Fatalf("in-flight request failed during graceful drain: %v", errReq) + } + case <-time.After(3 * time.Second): + t.Fatal("in-flight request did not complete within the drain budget") + } +} + +// TestServerStop_ShutdownTimeoutFallsBackToClose verifies that an in-flight +// request outliving the configured drain budget is force-closed, and that Stop +// returns within that budget rather than the caller's more generous deadline. +func TestServerStop_ShutdownTimeoutFallsBackToClose(t *testing.T) { + fx := newShutdownTestServer(t) + + fx.server.getConfig().ShutdownTimeoutSeconds = 1 + + reqDone := startSlowRequest(t, fx.addr) + <-fx.reqStarted + + // Caller deadline is 60s, far beyond the 1s configured budget: Stop must be + // bounded by the configured value, not the parent context. + stopCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + stopStart := time.Now() + errStop := fx.server.Stop(stopCtx) + stopDuration := time.Since(stopStart) + + if errStop != nil { + t.Fatalf("server.Stop error = %v, want nil", errStop) + } + if stopDuration >= 10*time.Second { + t.Fatalf("server.Stop took %v, want bounded shutdown (~1s)", stopDuration) + } + if stopDuration < 500*time.Millisecond { + t.Fatalf("server.Stop returned in %v, faster than the 1s drain budget", stopDuration) + } + + // The request outlived the drain budget and must have been force-closed. + select { + case errReq := <-reqDone: + if errReq == nil { + t.Fatal("in-flight request completed after the drain budget expired; force Close did not interrupt it") + } + case <-time.After(2 * time.Second): + t.Fatal("in-flight request was not interrupted after the drain budget expired") + } +} + +// TestServerStop_ShutdownTimeoutTighterParentCtx verifies that a caller context +// tighter than the configured budget still wins, ending the drain early. +func TestServerStop_ShutdownTimeoutTighterParentCtx(t *testing.T) { + fx := newShutdownTestServer(t) + + fx.server.getConfig().ShutdownTimeoutSeconds = 30 + + reqDone := startSlowRequest(t, fx.addr) + <-fx.reqStarted + + stopCtx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + stopStart := time.Now() + errStop := fx.server.Stop(stopCtx) + stopDuration := time.Since(stopStart) + + if errStop != nil { + t.Fatalf("server.Stop error = %v, want nil", errStop) + } + if stopDuration >= 10*time.Second { + t.Fatalf("server.Stop took %v, want ~500ms bounded by parent ctx", stopDuration) + } + + select { + case errReq := <-reqDone: + if errReq == nil { + t.Fatal("in-flight request completed despite the tighter parent deadline") + } + case <-time.After(2 * time.Second): + t.Fatal("in-flight request was not interrupted after the parent deadline") + } +} + +// TestServerStop_ShutdownTimeoutZeroKeepsImmediateClose verifies that the default +// value 0 keeps today's immediate-close behavior even when the caller supplies a +// generous context deadline. +func TestServerStop_ShutdownTimeoutZeroKeepsImmediateClose(t *testing.T) { + fx := newShutdownTestServer(t) + + // Default: ShutdownTimeoutSeconds stays 0. + reqDone := startSlowRequest(t, fx.addr) + <-fx.reqStarted + + stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + stopStart := time.Now() + errStop := fx.server.Stop(stopCtx) + stopDuration := time.Since(stopStart) + + if errStop != nil { + t.Fatalf("server.Stop error = %v, want nil", errStop) + } + if stopDuration >= time.Second { + t.Fatalf("server.Stop took %v, want immediate close (<1s)", stopDuration) + } + + select { + case errReq := <-reqDone: + if errReq == nil { + t.Fatal("expected in-flight request to be interrupted immediately, but it completed") + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for in-flight request to be interrupted") + } +} diff --git a/internal/api/server_test.go b/internal/api/server_test.go index 26f993a6cb9..aa77c521553 100644 --- a/internal/api/server_test.go +++ b/internal/api/server_test.go @@ -3906,7 +3906,18 @@ func (e *serverResponsesWebsocketCaptureExecutor) HttpRequest(context.Context, * } func TestServerResponsesWebsocketReauthorizesEachTurn(t *testing.T) { - server := newTestServer(t) + for _, requestLog := range []bool{false, true} { + t.Run(fmt.Sprintf("request_log=%t", requestLog), func(t *testing.T) { + testServerResponsesWebsocketReauthorizesEachTurn(t, requestLog) + }) + } +} + +func testServerResponsesWebsocketReauthorizesEachTurn(t *testing.T, requestLog bool) { + t.Helper() + server := newTestServerWithConfig(t, &proxyconfig.Config{ + SDKConfig: sdkconfig.SDKConfig{RequestLog: requestLog}, + }) provider := &revocableServerAccessProvider{} server.accessManager.SetProviders([]sdkaccess.Provider{provider}) @@ -3947,7 +3958,11 @@ func TestServerResponsesWebsocketReauthorizesEachTurn(t *testing.T) { if errDial != nil { t.Fatalf("dial websocket: %v", errDial) } - defer func() { _ = conn.Close() }() + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close websocket: %v", errClose) + } + }() turn1 := []byte(`{"type":"response.create","model":"ws-reauth-model","input":[{"type":"message","role":"user","content":"turn 1"}]}`) if errWrite := conn.WriteMessage(websocket.TextMessage, turn1); errWrite != nil { @@ -3998,4 +4013,23 @@ func TestServerResponsesWebsocketReauthorizesEachTurn(t *testing.T) { if gotCalls := wsExec.calls.Load(); gotCalls != 1 { t.Fatalf("executor calls after revoked turn = %d, want 1", gotCalls) } + t.Cleanup(func() { + // Deferred connection shutdown and request draining must finish before inspecting logs. + entries, errReadDir := os.ReadDir(filepath.Join(server.cfg.AuthDir, "logs")) + if errReadDir != nil { + t.Fatalf("read request logs: %v", errReadDir) + } + var logCount int + for _, entry := range entries { + if strings.HasSuffix(entry.Name(), ".tmp") || strings.HasPrefix(entry.Name(), "request-log-parts-") { + t.Errorf("request log temporary entry remains after handler completion: %s", entry.Name()) + } + if strings.HasSuffix(entry.Name(), ".log") { + logCount++ + } + } + if logCount == 0 { + t.Error("expected a completed request log for the revoked credential") + } + }) } diff --git a/internal/api/server_tunnel_test.go b/internal/api/server_tunnel_test.go new file mode 100644 index 00000000000..91c25164c67 --- /dev/null +++ b/internal/api/server_tunnel_test.go @@ -0,0 +1,449 @@ +package api + +import ( + "bytes" + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/home" + "github.com/router-for-me/CLIProxyAPI/v8/internal/wstunnel" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func newTestTunnelAPIServer(t *testing.T, cfg *config.Config, opts ...ServerOption) *Server { + t.Helper() + gin.SetMode(gin.TestMode) + cfgPath := filepath.Join(t.TempDir(), "config.yaml") + allOpts := append([]ServerOption{WithRequestLoggerFactory(nil)}, opts...) + return NewServer(cfg, auth.NewManager(nil, nil, nil), sdkaccess.NewManager(), cfgPath, allOpts...) +} + +func dialServerTunnel(t *testing.T, baseURL, apiKey string, role wstunnel.Role, uuid, name string) *websocket.Conn { + t.Helper() + serverType := "" + if role == wstunnel.RoleServer { + serverType = "default-server" + } + return dialServerTunnelWithType(t, baseURL, apiKey, role, uuid, name, serverType) +} + +func dialServerTunnelWithType(t *testing.T, baseURL, apiKey string, role wstunnel.Role, uuid, name, serverType string) *websocket.Conn { + t.Helper() + q := url.Values{ + "role": {string(role)}, + "uuid": {uuid}, + "name": {name}, + } + if serverType != "" { + q.Set("type", serverType) + } + wsURL := "ws" + strings.TrimPrefix(baseURL, "http") + "/v1/tunnel?" + q.Encode() + headers := http.Header{} + if apiKey != "" { + headers.Set("Authorization", "Bearer "+apiKey) + } + conn, resp, errDial := websocket.DefaultDialer.Dial(wsURL, headers) + if resp != nil && resp.Body != nil { + if errClose := resp.Body.Close(); errClose != nil { + t.Logf("response body close error: %v", errClose) + } + } + if errDial != nil { + t.Fatalf("Dial(%s, %s) error = %v", role, uuid, errDial) + } + t.Cleanup(func() { + _ = conn.Close() + }) + return conn +} + +func readServerTunnelTestMessage(conn *websocket.Conn) (int, []byte, error) { + type result struct { + messageType int + raw []byte + err error + } + ch := make(chan result, 1) + go func() { + messageType, raw, errRead := conn.ReadMessage() + ch <- result{messageType, raw, errRead} + }() + select { + case res := <-ch: + return res.messageType, res.raw, res.err + case <-time.After(10 * time.Second): + _ = conn.Close() + return 0, nil, errors.New("test message read did not complete") + } +} + +func readServerTunnelJSON(t *testing.T, conn *websocket.Conn) ojson.Result { + t.Helper() + msgType, raw, errRead := readServerTunnelTestMessage(conn) + if errRead != nil { + t.Fatalf("ReadMessage() error = %v", errRead) + } + if msgType != websocket.TextMessage { + t.Fatalf("message type = %d, want TextMessage", msgType) + } + return ojson.ParseBytes(raw) +} + +func readServerTunnelBinary(t *testing.T, conn *websocket.Conn) wstunnel.DataFrameView { + t.Helper() + msgType, raw, errRead := readServerTunnelTestMessage(conn) + if errRead != nil { + t.Fatalf("ReadMessage() error = %v", errRead) + } + if msgType != websocket.BinaryMessage { + t.Fatalf("message type = %d (%s), want BinaryMessage", msgType, string(raw)) + } + view, code, errParse := wstunnel.ParseDataFrameHeader(raw) + if errParse != nil || code != "" { + t.Fatalf("ParseDataFrameHeader() = (%+v, %q, %v)", view, code, errParse) + } + return view +} + +func TestServerWebsocketTunnel_EndToEndAndTenantIsolation(t *testing.T) { + cfg := &config.Config{ + SDKConfig: config.SDKConfig{ + APIKeys: []string{"tenant-a", "tenant-b"}, + }, + } + apiSrv := newTestTunnelAPIServer(t, cfg) + t.Cleanup(func() { + _ = apiSrv.Stop(context.Background()) + }) + httpSrv := httptest.NewServer(apiSrv.Handler()) + t.Cleanup(httpSrv.Close) + + // Server role without a valid type (>= 1 non-whitespace char) must fail with 400. + missingTypeURL := "ws" + strings.TrimPrefix(httpSrv.URL, "http") + "/v1/tunnel?role=server&uuid=srv-missing-type&name=ServerMissingType" + _, badResp, errBadDial := websocket.DefaultDialer.Dial(missingTypeURL, http.Header{"Authorization": {"Bearer tenant-a"}}) + var badBody []byte + if badResp != nil && badResp.Body != nil { + badBody, _ = io.ReadAll(badResp.Body) + if errClose := badResp.Body.Close(); errClose != nil { + t.Logf("response body close error: %v", errClose) + } + } + if errBadDial == nil || badResp == nil || badResp.StatusCode != http.StatusBadRequest || ojson.GetBytes(badBody, "error").String() != "invalid or missing type" { + t.Fatalf("Dial server without type = (%v, %v, %s), want 400 invalid or missing type", badResp, errBadDial, string(badBody)) + } + + srvA1 := dialServerTunnelWithType(t, httpSrv.URL, "tenant-a", wstunnel.RoleServer, "srv-a1", "Server A1", "cpa-desktop") + _ = dialServerTunnelWithType(t, httpSrv.URL, "tenant-b", wstunnel.RoleServer, "srv-b1", "Server B1", "cpa-cloud") + + cliA := dialServerTunnel(t, httpSrv.URL, "tenant-a", wstunnel.RoleClient, "cli-a1", "Client A1") + initList := readServerTunnelJSON(t, cliA) + if initList.Get("type").String() != wstunnel.ControlTypeServerList || + initList.Get("servers.#").Int() != 1 || + initList.Get("servers.0.uuid").String() != "srv-a1" || + initList.Get("servers.0.type").String() != "cpa-desktop" { + t.Fatalf("unexpected initial server_list: %s", initList.Raw) + } + + srvA2 := dialServerTunnelWithType(t, httpSrv.URL, "tenant-a", wstunnel.RoleServer, "srv-a2", "Server A2", "build-runner") + online := readServerTunnelJSON(t, cliA) + if online.Get("type").String() != wstunnel.ControlTypeServerOnline || + online.Get("server.uuid").String() != "srv-a2" || + online.Get("server.type").String() != "build-runner" { + t.Fatalf("unexpected server_online event: %s", online.Raw) + } + + rawPayload := []byte{0x00, 0x10, 0x7f, 0x80, 0xff} + reqFrame, errEnc := wstunnel.EncodeDataFrame(wstunnel.PayloadTypeBinary, "cli-a1", "srv-a2", rawPayload) + if errEnc != nil { + t.Fatalf("EncodeDataFrame error = %v", errEnc) + } + if errWrite := cliA.WriteMessage(websocket.BinaryMessage, reqFrame); errWrite != nil { + t.Fatalf("cliA WriteMessage error = %v", errWrite) + } + + gotReq := readServerTunnelBinary(t, srvA2) + if gotReq.SrcUUID != "cli-a1" || gotReq.DstUUID != "srv-a2" || !bytes.Equal(gotReq.Payload, rawPayload) { + t.Fatalf("srvA2 received unexpected frame: %+v", gotReq) + } + + respFrame, errEncResp := wstunnel.EncodeDataFrame(wstunnel.PayloadTypeText, "srv-a2", "cli-a1", []byte("pong-from-a2")) + if errEncResp != nil { + t.Fatalf("EncodeDataFrame error = %v", errEncResp) + } + if errWrite := srvA2.WriteMessage(websocket.BinaryMessage, respFrame); errWrite != nil { + t.Fatalf("srvA2 WriteMessage error = %v", errWrite) + } + + gotResp := readServerTunnelBinary(t, cliA) + if gotResp.SrcUUID != "srv-a2" || gotResp.DstUUID != "cli-a1" || string(gotResp.Payload) != "pong-from-a2" { + t.Fatalf("cliA received unexpected frame: %+v", gotResp) + } + + _ = srvA2.Close() + offline := readServerTunnelJSON(t, cliA) + if offline.Get("type").String() != wstunnel.ControlTypeServerOffline || + offline.Get("server.uuid").String() != "srv-a2" || + offline.Get("server.type").String() != "build-runner" { + t.Fatalf("unexpected server_offline event: %s", offline.Raw) + } + _ = srvA1 +} + +func TestServerWebsocketTunnel_NonGetMethodsReturn405AndPreserveCORSOptions(t *testing.T) { + cfg := &config.Config{ + SDKConfig: config.SDKConfig{ + APIKeys: []string{"method-key"}, + }, + } + apiSrv := newTestTunnelAPIServer(t, cfg) + t.Cleanup(func() { + _ = apiSrv.Stop(context.Background()) + }) + httpSrv := httptest.NewServer(apiSrv.Handler()) + t.Cleanup(httpSrv.Close) + + for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead, http.MethodTrace, http.MethodConnect} { + req, errReq := http.NewRequest(method, httpSrv.URL+"/v1/tunnel", nil) + if errReq != nil { + t.Fatalf("NewRequest(%s) error = %v", method, errReq) + } + resp, errDo := http.DefaultClient.Do(req) + if errDo != nil { + t.Fatalf("Do(%s) error = %v", method, errDo) + } + body, _ := io.ReadAll(resp.Body) + if errClose := resp.Body.Close(); errClose != nil { + t.Logf("response body close error: %v", errClose) + } + if resp.StatusCode != http.StatusMethodNotAllowed { + t.Fatalf("%s /v1/tunnel status = %d, want 405 (body=%s)", method, resp.StatusCode, string(body)) + } + if gotAllow := resp.Header.Get("Allow"); gotAllow != http.MethodGet { + t.Fatalf("%s /v1/tunnel Allow = %q, want GET", method, gotAllow) + } + if method != http.MethodHead && ojson.GetBytes(body, "error").String() != "method not allowed" { + t.Fatalf("%s /v1/tunnel body = %s, want method not allowed", method, string(body)) + } + } + + optReq, errOpt := http.NewRequest(http.MethodOptions, httpSrv.URL+"/v1/tunnel", nil) + if errOpt != nil { + t.Fatalf("NewRequest(OPTIONS) error = %v", errOpt) + } + optReq.Header.Set("Origin", "https://app.example.com") + optReq.Header.Set("Access-Control-Request-Method", "GET") + optResp, errOptDo := http.DefaultClient.Do(optReq) + if errOptDo != nil { + t.Fatalf("Do(OPTIONS) error = %v", errOptDo) + } + if errClose := optResp.Body.Close(); errClose != nil { + t.Logf("response body close error: %v", errClose) + } + if optResp.StatusCode != http.StatusNoContent { + t.Fatalf("OPTIONS /v1/tunnel status = %d, want 204", optResp.StatusCode) + } +} + +func TestServerWebsocketTunnel_RejectsWhenAPIKeysEmptyOrSafeMode(t *testing.T) { + t.Run("empty access.api-keys rejects tunnel upgrade with 401", func(t *testing.T) { + apiSrv := newTestTunnelAPIServer(t, &config.Config{}) + t.Cleanup(func() { + _ = apiSrv.Stop(context.Background()) + }) + httpSrv := httptest.NewServer(apiSrv.Handler()) + t.Cleanup(httpSrv.Close) + + wsURL := "ws" + strings.TrimPrefix(httpSrv.URL, "http") + "/v1/tunnel?role=client&uuid=c1&name=Client1" + _, resp, errDial := websocket.DefaultDialer.Dial(wsURL, nil) + if resp != nil && resp.Body != nil { + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + t.Logf("response body close error: %v", errClose) + } + }() + } + if errDial == nil || resp == nil || resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("Dial with empty APIKeys = (%v, %v), want 401", resp, errDial) + } + }) + + t.Run("example api-key safe mode blocks /v1/tunnel with 403", func(t *testing.T) { + cfg := &config.Config{ + SDKConfig: config.SDKConfig{ + APIKeys: []string{"your-api-key-1"}, + }, + } + apiSrv := newTestTunnelAPIServer(t, cfg, WithExampleAPIKeySafeMode()) + t.Cleanup(func() { + _ = apiSrv.Stop(context.Background()) + }) + httpSrv := httptest.NewServer(apiSrv.Handler()) + t.Cleanup(httpSrv.Close) + + wsURL := "ws" + strings.TrimPrefix(httpSrv.URL, "http") + "/v1/tunnel?role=client&uuid=c1&name=Client1" + _, resp, errDial := websocket.DefaultDialer.Dial(wsURL, http.Header{"Authorization": {"Bearer your-api-key-1"}}) + if resp != nil && resp.Body != nil { + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + t.Logf("response body close error: %v", errClose) + } + }() + } + if errDial == nil || resp == nil || resp.StatusCode != http.StatusForbidden { + t.Fatalf("Dial in safe mode = (%v, %v), want 403", resp, errDial) + } + body, _ := io.ReadAll(resp.Body) + if ojson.GetBytes(body, "error").String() != "unsafe_example_api_key" { + t.Fatalf("safe mode body = %s, want unsafe_example_api_key", string(body)) + } + }) +} + +func TestServerWebsocketTunnel_ServiceUnavailableResponseBodies(t *testing.T) { + previousHome := home.Current() + home.SetCurrent(nil) + t.Cleanup(func() { home.SetCurrent(previousHome) }) + for _, tc := range []struct { + name string + homeEnabled bool + wantBody string + }{ + {"closed hub", false, `{"error":"tunnel hub is closed"}`}, + {"unhealthy Home heartbeat gate", true, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.Config{ + SDKConfig: config.SDKConfig{APIKeys: []string{"key"}}, + Home: config.HomeConfig{Enabled: tc.homeEnabled}, + } + apiSrv := newTestTunnelAPIServer(t, cfg) + t.Cleanup(func() { + if errStop := apiSrv.Stop(context.Background()); errStop != nil { + t.Errorf("stop test server: %v", errStop) + } + }) + if !tc.homeEnabled { + apiSrv.tunnelHub.Close() + } + req := httptest.NewRequest(http.MethodGet, "/v1/tunnel?key=key&role=client&uuid=device&name=Device", nil) + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "websocket") + req.Header.Set("Sec-WebSocket-Version", "13") + req.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + resp := httptest.NewRecorder() + apiSrv.Handler().ServeHTTP(resp, req) + if resp.Code != http.StatusServiceUnavailable || resp.Body.String() != tc.wantBody { + t.Fatalf("handshake = (%d, %q), want (503, %q)", resp.Code, resp.Body.String(), tc.wantBody) + } + }) + } +} + +func TestServerWebsocketTunnel_HotReloadRevokesRemovedKeyOnly(t *testing.T) { + cfg := &config.Config{ + SDKConfig: config.SDKConfig{ + APIKeys: []string{"key-keep", "key-revoke"}, + }, + } + apiSrv := newTestTunnelAPIServer(t, cfg) + t.Cleanup(func() { + _ = apiSrv.Stop(context.Background()) + }) + httpSrv := httptest.NewServer(apiSrv.Handler()) + t.Cleanup(httpSrv.Close) + + srvKeep := dialServerTunnel(t, httpSrv.URL, "key-keep", wstunnel.RoleServer, "s-keep", "Keep Server") + cliKeep := dialServerTunnel(t, httpSrv.URL, "key-keep", wstunnel.RoleClient, "c-keep", "Keep Client") + _ = readServerTunnelJSON(t, cliKeep) + + cliRevoke := dialServerTunnel(t, httpSrv.URL, "key-revoke", wstunnel.RoleClient, "c-revoke", "Revoke Client") + _ = readServerTunnelJSON(t, cliRevoke) + + updatedCfg := &config.Config{ + SDKConfig: config.SDKConfig{ + APIKeys: []string{"key-keep"}, + }, + } + apiSrv.UpdateClients(updatedCfg) + + _, _, errRead := readServerTunnelTestMessage(cliRevoke) + var closeErr *websocket.CloseError + if !errors.As(errRead, &closeErr) || closeErr.Code != websocket.ClosePolicyViolation { + t.Fatalf("expected revoked key tunnel to close with 1008, got %v", errRead) + } + + pkt, _ := wstunnel.EncodeDataFrame(wstunnel.PayloadTypeText, "c-keep", "s-keep", []byte("survives-reload")) + if errWrite := cliKeep.WriteMessage(websocket.BinaryMessage, pkt); errWrite != nil { + t.Fatalf("cliKeep WriteMessage error = %v", errWrite) + } + got := readServerTunnelBinary(t, srvKeep) + if string(got.Payload) != "survives-reload" { + t.Fatalf("srvKeep payload = %q, want survives-reload", string(got.Payload)) + } +} + +func TestServerWebsocketTunnel_ServerStopClosesConnections(t *testing.T) { + ln, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatalf("net.Listen error = %v", errListen) + } + port := ln.Addr().(*net.TCPAddr).Port + if errCloseLn := ln.Close(); errCloseLn != nil { + t.Fatalf("ln.Close error = %v", errCloseLn) + } + + cfg := &config.Config{ + Host: "127.0.0.1", + Port: port, + SDKConfig: config.SDKConfig{ + APIKeys: []string{"stop-key"}, + }, + } + apiSrv := newTestTunnelAPIServer(t, cfg) + serveDone := make(chan error, 1) + go func() { + serveDone <- apiSrv.Start() + }() + + // Wait deterministically for listener readiness by retrying /healthz with short backoffless dial attempts. + baseURL := "http://" + net.JoinHostPort("127.0.0.1", strings.TrimPrefix(strings.Split(ln.Addr().String(), ":")[1], "")) + deadline := time.Now().Add(5 * time.Second) + for { + resp, errHealth := http.Get(baseURL + "/healthz") + if errHealth == nil { + if resp.Body != nil { + _ = resp.Body.Close() + } + break + } + if time.Now().After(deadline) { + t.Fatalf("server did not start listening on %s: %v", baseURL, errHealth) + } + } + + cli := dialServerTunnel(t, baseURL, "stop-key", wstunnel.RoleClient, "c-stop", "Stop Client") + _ = readServerTunnelJSON(t, cli) + + if errStop := apiSrv.Stop(context.Background()); errStop != nil { + t.Fatalf("apiSrv.Stop error = %v", errStop) + } + + if _, _, errRead := readServerTunnelTestMessage(cli); errRead == nil { + t.Fatal("expected tunnel websocket to close on Server.Stop()") + } + <-serveDone +} diff --git a/internal/api/server_tunnel_transport_test.go b/internal/api/server_tunnel_transport_test.go new file mode 100644 index 00000000000..6efb36f2775 --- /dev/null +++ b/internal/api/server_tunnel_transport_test.go @@ -0,0 +1,225 @@ +package api + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "net" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/wstunnel" +) + +// tunnelTLSIngressConn tracks deadlines beneath TLS and deterministically stalls writes. +type tunnelTLSIngressConn struct { + net.Conn + postUpgrade atomic.Bool + finiteDeadlines atomic.Int64 + allowedWrites atomic.Int64 + blocked chan struct{} + closed chan struct{} + closeOnce sync.Once +} + +func (c *tunnelTLSIngressConn) recordDeadline(deadline time.Time) { + if c.postUpgrade.Load() && !deadline.IsZero() { + c.finiteDeadlines.Add(1) + } +} + +func (c *tunnelTLSIngressConn) SetDeadline(deadline time.Time) error { + c.recordDeadline(deadline) + return c.Conn.SetDeadline(deadline) +} + +func (c *tunnelTLSIngressConn) SetReadDeadline(deadline time.Time) error { + c.recordDeadline(deadline) + return c.Conn.SetReadDeadline(deadline) +} + +func (c *tunnelTLSIngressConn) SetWriteDeadline(deadline time.Time) error { + c.recordDeadline(deadline) + return c.Conn.SetWriteDeadline(deadline) +} + +func (c *tunnelTLSIngressConn) Write(raw []byte) (int, error) { + if c.postUpgrade.Load() && c.allowedWrites.Add(-1) < 0 { + select { + case c.blocked <- struct{}{}: + default: + } + <-c.closed + return 0, net.ErrClosed + } + return c.Conn.Write(raw) +} + +func (c *tunnelTLSIngressConn) Close() error { + var errClose error + c.closeOnce.Do(func() { + errClose = c.Conn.Close() + close(c.closed) + }) + return errClose +} + +type tunnelTLSIngressListener struct { + net.Listener + accepted chan *tunnelTLSIngressConn +} + +func (l *tunnelTLSIngressListener) Accept() (net.Conn, error) { + conn, errAccept := l.Listener.Accept() + if errAccept != nil { + return nil, errAccept + } + transport := &tunnelTLSIngressConn{ + Conn: conn, + blocked: make(chan struct{}, 1), + closed: make(chan struct{}), + } + l.accepted <- transport + return transport, nil +} + +func waitServerTunnelTransportSignal(t *testing.T, signal <-chan struct{}, description string) { + t.Helper() + select { + case <-signal: + case <-time.After(3 * time.Second): + t.Fatalf("timed out waiting for %s", description) + } +} + +func TestServerWebsocketTunnel_TLSWithoutALPNClosesRawTransport(t *testing.T) { + certificateServer := httptest.NewTLSServer(nil) + tlsConfig := certificateServer.TLS.Clone() + tlsConfig.NextProtos = []string{"h2", "http/1.1"} + roots := x509.NewCertPool() + roots.AddCert(certificateServer.Certificate()) + certificateServer.Close() + + for _, tc := range []struct { + name string + allowedWrites int64 + }{ + {"healthy WebSocket close with stalled TLS close_notify", 1}, + {"saturated WebSocket close", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + apiSrv := newTestTunnelAPIServer(t, &config.Config{ + SDKConfig: config.SDKConfig{APIKeys: []string{"key"}}, + }) + baseListener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatalf("listen: %v", errListen) + } + trackedListener := &tunnelTLSIngressListener{ + Listener: baseListener, + accepted: make(chan *tunnelTLSIngressConn, 1), + } + tlsListener := tls.NewListener(trackedListener, tlsConfig) + httpListener := newMuxListener(baseListener.Addr(), 1) + apiSrv.muxBaseListener = tlsListener + apiSrv.muxHTTPListener = httpListener + routed := make(chan net.Conn, 1) + apiSrv.server.ConnContext = func(ctx context.Context, conn net.Conn) context.Context { + routed <- conn + return ctx + } + serveDone := make(chan error, 1) + acceptDone := make(chan error, 1) + go func() { serveDone <- apiSrv.server.Serve(httpListener) }() + go func() { acceptDone <- apiSrv.acceptMuxConnections(tlsListener, httpListener) }() + t.Cleanup(func() { + if errStop := apiSrv.Stop(context.Background()); errStop != nil { + t.Errorf("stop test server: %v", errStop) + } + for _, done := range []<-chan error{serveDone, acceptDone} { + select { + case errDone := <-done: + if errDone != nil && !errors.Is(errDone, net.ErrClosed) && !errors.Is(errDone, http.ErrServerClosed) { + t.Errorf("server loop exit: %v", errDone) + } + case <-time.After(3 * time.Second): + t.Error("server loop did not exit") + } + } + }) + + dialer := websocket.Dialer{ + TLSClientConfig: &tls.Config{RootCAs: roots}, + HandshakeTimeout: 5 * time.Second, + } + client, resp, errDial := dialer.Dial( + "wss://"+baseListener.Addr().String()+"/v1/tunnel?role=client&uuid=device&name=Device", + http.Header{"Authorization": {"Bearer key"}}, + ) + if resp != nil && resp.Body != nil { + if errClose := resp.Body.Close(); errClose != nil { + t.Errorf("close handshake response body: %v", errClose) + } + } + if errDial != nil { + t.Fatalf("dial TLS tunnel: %v", errDial) + } + t.Cleanup(func() { + // Close the client TCP transport directly too; TLS Close installs deadlines. + if errClose := client.UnderlyingConn().(*tls.Conn).NetConn().Close(); errClose != nil { + t.Errorf("close client transport: %v", errClose) + } + }) + client.SetCloseHandler(func(int, string) error { return nil }) + if initial := readServerTunnelJSON(t, client); initial.Get("type").String() != wstunnel.ControlTypeServerList { + t.Fatalf("unexpected initial server_list: %s", initial.Raw) + } + transport := <-trackedListener.accepted + t.Cleanup(func() { + if errClose := transport.Close(); errClose != nil { + t.Errorf("close server transport: %v", errClose) + } + }) + buffered, okBuffered := (<-routed).(*bufferedConn) + if !okBuffered { + t.Fatal("TLS connection without ALPN did not take the buffered protocol-sniffing path") + } + tlsConn, okTLS := buffered.NetConn().(*tls.Conn) + if !okTLS || tlsConn.ConnectionState().NegotiatedProtocol != "" || tlsConn.NetConn() != transport { + t.Fatal("expected buffered TLS connection with no ALPN above the tracked raw transport") + } + // Let the healthy WebSocket close through, but stall any TLS close_notify. + transport.allowedWrites.Store(tc.allowedWrites) + transport.postUpgrade.Store(true) + closeReturned := make(chan struct{}) + go func() { + apiSrv.tunnelHub.Close() + close(closeReturned) + }() + waitServerTunnelTransportSignal(t, closeReturned, "non-blocking hub close") + if tc.allowedWrites == 0 { + waitServerTunnelTransportSignal(t, transport.blocked, "saturated WebSocket close write") + } + waitServerTunnelTransportSignal(t, transport.closed, "raw transport reclamation without TLS close_notify") + if calls := transport.finiteDeadlines.Load(); calls != 0 { + t.Fatalf("finite post-upgrade raw transport deadlines = %d, want zero", calls) + } + _, _, errRead := readServerTunnelTestMessage(client) + if tc.allowedWrites > 0 { + var closeErr *websocket.CloseError + if !errors.As(errRead, &closeErr) || closeErr.Code != websocket.CloseGoingAway { + t.Fatalf("healthy WebSocket close = %v, want 1001", errRead) + } + } else if errRead == nil { + t.Fatal("saturated tunnel remained open after raw transport reclamation") + } + }) + } +} diff --git a/internal/auth/claude/identity.go b/internal/auth/claude/identity.go index 3e4bde729c0..779f3ebf8a2 100644 --- a/internal/auth/claude/identity.go +++ b/internal/auth/claude/identity.go @@ -189,6 +189,283 @@ func ReadMetadataString(metadata *map[string]any, key string) string { return value } +// ReadMetadataStringMap reads a map[string]string metadata entry under the metadata +// lock, copying out string pairs from either map[string]string or map[string]any. +func ReadMetadataStringMap(metadata *map[string]any, key string) map[string]string { + if metadata == nil { + return nil + } + claudeDevicePoolMu.Lock() + defer claudeDevicePoolMu.Unlock() + + if *metadata == nil { + return nil + } + switch typed := (*metadata)[key].(type) { + case map[string]string: + if len(typed) == 0 { + return nil + } + out := make(map[string]string, len(typed)) + for k, v := range typed { + out[k] = v + } + return out + case map[string]any: + if len(typed) == 0 { + return nil + } + out := make(map[string]string, len(typed)) + for k, rawVal := range typed { + if strVal, ok := rawVal.(string); ok { + out[k] = strVal + } + } + if len(out) == 0 { + return nil + } + return out + default: + return nil + } +} + +func copyStringSliceFromAny(raw any) []string { + switch typed := raw.(type) { + case []string: + if len(typed) == 0 { + return nil + } + out := make([]string, 0, len(typed)) + for _, s := range typed { + if trimmed := strings.TrimSpace(s); trimmed != "" { + out = append(out, trimmed) + } + } + if len(out) == 0 { + return nil + } + return out + case []any: + if len(typed) == 0 { + return nil + } + out := make([]string, 0, len(typed)) + for _, elem := range typed { + if s, ok := elem.(string); ok { + if trimmed := strings.TrimSpace(s); trimmed != "" { + out = append(out, trimmed) + } + } + } + if len(out) == 0 { + return nil + } + return out + default: + return nil + } +} + +func copyStringMapFromAny(raw any) map[string]string { + switch typed := raw.(type) { + case map[string]string: + if len(typed) == 0 { + return nil + } + out := make(map[string]string, len(typed)) + for k, v := range typed { + out[k] = v + } + return out + case map[string]any: + if len(typed) == 0 { + return nil + } + out := make(map[string]string, len(typed)) + for k, rawVal := range typed { + if strVal, ok := rawVal.(string); ok { + out[k] = strVal + } + } + if len(out) == 0 { + return nil + } + return out + default: + return nil + } +} + +func copyPatternPairsFromAny(raw any) [][2]string { + switch typed := raw.(type) { + case [][2]string: + if len(typed) == 0 { + return nil + } + out := make([][2]string, len(typed)) + copy(out, typed) + return out + case []map[string]string: + if len(typed) == 0 { + return nil + } + out := make([][2]string, 0, len(typed)) + for _, item := range typed { + if p, ok := item["pattern"]; ok { + out = append(out, [2]string{p, item["replacement"]}) + } + } + if len(out) == 0 { + return nil + } + return out + case []map[string]any: + if len(typed) == 0 { + return nil + } + out := make([][2]string, 0, len(typed)) + for _, item := range typed { + p, ok := item["pattern"].(string) + if !ok { + continue + } + r, _ := item["replacement"].(string) + out = append(out, [2]string{p, r}) + } + if len(out) == 0 { + return nil + } + return out + case []any: + if len(typed) == 0 { + return nil + } + out := make([][2]string, 0, len(typed)) + for _, rawItem := range typed { + switch item := rawItem.(type) { + case map[string]string: + if p, ok := item["pattern"]; ok { + out = append(out, [2]string{p, item["replacement"]}) + } + case map[string]any: + p, ok := item["pattern"].(string) + if !ok { + continue + } + r, _ := item["replacement"].(string) + out = append(out, [2]string{p, r}) + } + } + if len(out) == 0 { + return nil + } + return out + default: + return nil + } +} + +// ReadMetadataPatternPairs reads a slice of [pattern, replacement] pairs from metadata under the metadata lock. +func ReadMetadataPatternPairs(metadata *map[string]any, key string) [][2]string { + if metadata == nil { + return nil + } + claudeDevicePoolMu.Lock() + defer claudeDevicePoolMu.Unlock() + + if *metadata == nil { + return nil + } + return copyPatternPairsFromAny((*metadata)[key]) +} + +// ReadMetadataHomeCloakPatterns extracts credential_options.cloak.sensitive-patterns-replace +// from metadata under the metadata lock. +func ReadMetadataHomeCloakPatterns(metadata *map[string]any) [][2]string { + if metadata == nil { + return nil + } + claudeDevicePoolMu.Lock() + defer claudeDevicePoolMu.Unlock() + + if *metadata == nil { + return nil + } + opts, ok := (*metadata)["credential_options"].(map[string]any) + if !ok || opts == nil { + return nil + } + rawCloak, exists := opts["cloak"] + if !exists || rawCloak == nil { + return nil + } + cloakMap, ok := rawCloak.(map[string]any) + if !ok { + return nil + } + return copyPatternPairsFromAny(cloakMap["sensitive-patterns-replace"]) +} + +// ReadMetadataStringSlice reads a []string metadata entry under the metadata lock, +// copying string elements from either []string or []any. +func ReadMetadataStringSlice(metadata *map[string]any, key string) []string { + if metadata == nil { + return nil + } + claudeDevicePoolMu.Lock() + defer claudeDevicePoolMu.Unlock() + + if *metadata == nil { + return nil + } + return copyStringSliceFromAny((*metadata)[key]) +} + +// ReadMetadataHomeCloak extracts credential_options.cloak from metadata under +// the metadata lock without JSON serialization. +func ReadMetadataHomeCloak(metadata *map[string]any) ( + mode string, + strictMode bool, + sensitiveWords []string, + sensitiveWordsReplace map[string]string, + cacheUserID *bool, + present bool, +) { + if metadata == nil { + return "", false, nil, nil, nil, false + } + claudeDevicePoolMu.Lock() + defer claudeDevicePoolMu.Unlock() + + if *metadata == nil { + return "", false, nil, nil, nil, false + } + opts, ok := (*metadata)["credential_options"].(map[string]any) + if !ok || opts == nil { + return "", false, nil, nil, nil, false + } + rawCloak, exists := opts["cloak"] + if !exists || rawCloak == nil { + return "", false, nil, nil, nil, false + } + cloakMap, ok := rawCloak.(map[string]any) + if !ok { + return "", false, nil, nil, nil, false + } + mode, _ = cloakMap["mode"].(string) + strictMode, _ = cloakMap["strict-mode"].(bool) + sensitiveWords = copyStringSliceFromAny(cloakMap["sensitive-words"]) + sensitiveWordsReplace = copyStringMapFromAny(cloakMap["sensitive-words-replace"]) + if rawCache, hasCache := cloakMap["cache-user-id"]; hasCache { + if b, okBool := rawCache.(bool); okBool { + cacheCopy := b + cacheUserID = &cacheCopy + } + } + return mode, strictMode, sensitiveWords, sensitiveWordsReplace, cacheUserID, true +} + // StoreMetadataString writes a string-valued metadata entry under the metadata // lock, initializing the map when needed. Empty values are skipped so callers can // forward optional fields without erasing a previously resolved value. diff --git a/internal/auth/codex/openai.go b/internal/auth/codex/openai.go index a942fd0d3fa..92cd6cbb783 100644 --- a/internal/auth/codex/openai.go +++ b/internal/auth/codex/openai.go @@ -31,16 +31,17 @@ type CodexTokenData struct { // CodexSIWCTokenData holds the OAuth token information obtained from OpenAI's Sign in with ChatGPT (SIWC) flow. type CodexSIWCTokenData struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - IDToken string `json:"id_token,omitempty"` - ClientID string `json:"client_id"` - Scope string `json:"scope,omitempty"` - Scopes []string `json:"scopes,omitempty"` - Expire string `json:"expired"` - ExpiresAt string `json:"expires_at,omitempty"` - LastRefresh string `json:"last_refresh"` - DeviceID string `json:"device_id,omitempty"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + IDToken string `json:"id_token,omitempty"` + ClientID string `json:"client_id"` + Scope string `json:"scope,omitempty"` + Scopes []string `json:"scopes,omitempty"` + Expire string `json:"expired"` + ExpiresAt string `json:"expires_at,omitempty"` + EarliestRefreshAt any `json:"earliest_refresh_at,omitempty"` + LastRefresh string `json:"last_refresh"` + DeviceID string `json:"device_id,omitempty"` } // ToMap converts CodexSIWCTokenData into a map suitable for credential metadata persistence. @@ -58,6 +59,9 @@ func (d *CodexSIWCTokenData) ToMap() map[string]any { if d.ExpiresAt != "" { out["expires_at"] = d.ExpiresAt } + if d.EarliestRefreshAt != nil { + out["earliest_refresh_at"] = d.EarliestRefreshAt + } if d.IDToken != "" { out["id_token"] = d.IDToken } diff --git a/internal/auth/codex/openai_auth.go b/internal/auth/codex/openai_auth.go index c1d8737de30..464d1df0cb3 100644 --- a/internal/auth/codex/openai_auth.go +++ b/internal/auth/codex/openai_auth.go @@ -7,6 +7,7 @@ package codex import ( "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -212,6 +213,9 @@ func (o *CodexAuth) RefreshTokens(ctx context.Context, refreshToken string) (*Co result, err, _ := codexRefreshGroup.Do(refreshToken, func() (interface{}, error) { refreshCtx, cancelRefresh := context.WithTimeout(context.WithoutCancel(ctx), codexRefreshTimeout) defer cancelRefresh() + if errReadiness := codexRefreshReadiness(refreshCtx, "Codex"); errReadiness != nil { + return nil, errReadiness + } return journalRefresh(refreshCtx, o.journal(ctx), ClientID, refreshToken, func() (*CodexTokenData, error) { return o.refreshTokensSingleFlight(refreshCtx, refreshToken) }, decodeRefreshReceipt) @@ -236,7 +240,7 @@ func (o *CodexAuth) refreshTokensSingleFlight(ctx context.Context, refreshToken req, errReq := http.NewRequestWithContext(ctx, "POST", TokenURL, strings.NewReader(data.Encode())) if errReq != nil { - return nil, &RefreshOutcomeUnknownError{Stage: "request-create", Cause: errReq} + return nil, &RefreshPreSendError{Stage: "request-create", Cause: errReq} } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") @@ -244,7 +248,7 @@ func (o *CodexAuth) refreshTokensSingleFlight(ctx context.Context, refreshToken resp, errDo := o.doRefreshRequest(req) if errDo != nil { - return nil, &RefreshOutcomeUnknownError{Stage: "transport", Cause: errDo} + return nil, errDo } defer func() { if errClose := resp.Body.Close(); errClose != nil { @@ -336,6 +340,9 @@ func (o *CodexAuth) CreateTokenStorage(bundle *CodexAuthBundle) *CodexTokenStora // It attempts to refresh the tokens up to a specified maximum number of retries, // with an exponential backoff strategy to handle transient network errors. func (o *CodexAuth) RefreshTokensWithRetry(ctx context.Context, refreshToken string, maxRetries int) (*CodexTokenData, error) { + if maxRetries <= 0 { + maxRetries = 1 + } var lastErr error for attempt := 0; attempt < maxRetries; attempt++ { @@ -352,6 +359,9 @@ func (o *CodexAuth) RefreshTokensWithRetry(ctx context.Context, refreshToken str if err == nil { return tokenData, nil } + if errors.Is(err, context.Canceled) || errors.Is(err, ErrSIWCRefreshDeferred) { + return nil, err + } if isNonRetryableRefreshErr(err) { log.Warnf("Token refresh attempt %d failed with non-retryable error: %v", attempt+1, err) return nil, err @@ -365,7 +375,7 @@ func (o *CodexAuth) RefreshTokensWithRetry(ctx context.Context, refreshToken str } func isNonRetryableRefreshErr(err error) bool { - if err == nil { + if err == nil || IsRefreshPreSendError(err) { return false } if IsRefreshOutcomeUnknown(err) { diff --git a/internal/auth/codex/refresh_journal.go b/internal/auth/codex/refresh_journal.go index e41cfa9881d..34e4d4372bb 100644 --- a/internal/auth/codex/refresh_journal.go +++ b/internal/auth/codex/refresh_journal.go @@ -5,9 +5,13 @@ import ( "crypto/sha256" "errors" "fmt" + "io" + "net" "net/http" + "net/http/httptrace" "strings" "sync" + "sync/atomic" "time" "github.com/MoeForge/moego/ojson" @@ -24,6 +28,60 @@ type RefreshJournal interface { RefreshClaim(context.Context, string) (bool, error) RefreshRead(context.Context, string) ([]byte, error) RefreshComplete(context.Context, string, []byte) error + RefreshRelease(context.Context, string) error +} + +// RefreshPreSendError reports a failure that occurred strictly before any +// refresh request bytes could be sent to the token endpoint. +type RefreshPreSendError struct { + Stage string + Cause error +} + +func (e *RefreshPreSendError) Error() string { + if e == nil { + return "" + } + if e.Cause != nil { + return fmt.Sprintf("token refresh failed before send (%s): %v", e.Stage, e.Cause) + } + return "token refresh failed before send: " + e.Stage +} + +func (e *RefreshPreSendError) Unwrap() error { + if e == nil { + return nil + } + return e.Cause +} + +// IsRefreshPreSendError reports whether err occurred strictly before sending +// the refresh grant, including wrapped partition errors when all failed +// partitions failed before send. +func IsRefreshPreSendError(err error) bool { + if err == nil || IsRefreshOutcomeUnknown(err) { + return false + } + var partitions interface { + OuterRefreshError() error + SIWCRefreshError() error + } + if errors.As(err, &partitions) && partitions != nil { + outerErr := partitions.OuterRefreshError() + siwcErr := partitions.SIWCRefreshError() + if outerErr == nil && siwcErr == nil { + return false + } + if outerErr != nil && !IsRefreshPreSendError(outerErr) { + return false + } + if siwcErr != nil && !IsRefreshPreSendError(siwcErr) { + return false + } + return true + } + var preSend *RefreshPreSendError + return errors.As(err, &preSend) } // RefreshOutcomeUnknownError preserves the stage without exposing transport URLs, @@ -91,8 +149,11 @@ func journalRefresh[T any](ctx context.Context, journal RefreshJournal, clientID if errRead != nil { return zero, &RefreshOutcomeUnknownError{Stage: "receipt-read", Cause: errRead} } - if len(receipt) == 0 && len(seen) > 1 { - return usableRefreshReceipt(value, expires) + if len(receipt) == 0 { + if len(seen) > 1 { + return usableRefreshReceipt(value, expires) + } + return zero, &RefreshPreSendError{Stage: "claim-released"} } if !ojson.ValidBytes(receipt) { return zero, &RefreshOutcomeUnknownError{Stage: "pending"} @@ -120,6 +181,14 @@ func journalRefresh[T any](ctx context.Context, journal RefreshJournal, clientID } value, errRun := run() + completeCtx, cancelComplete := context.WithTimeout(context.WithoutCancel(ctx), codexRefreshTimeout) + defer cancelComplete() + if errRun != nil && IsRefreshPreSendError(errRun) { + if errRelease := journal.RefreshRelease(completeCtx, key); errRelease != nil { + return zero, errors.Join(errRun, &RefreshOutcomeUnknownError{Stage: "claim-release", Cause: errRelease}) + } + return zero, errRun + } doc := ojson.NewDoc(nil) var errSet error if errRun == nil { @@ -137,7 +206,7 @@ func journalRefresh[T any](ctx context.Context, journal RefreshJournal, clientID } // Use an independent acquisition context for the receipt, just as for the // exchange itself. Caller cancellation must not discard a successful rotation. - if errComplete := journal.RefreshComplete(ctx, key, doc.Bytes()); errComplete != nil { + if errComplete := journal.RefreshComplete(completeCtx, key, doc.Bytes()); errComplete != nil { return zero, errors.Join(errRun, &RefreshOutcomeUnknownError{Stage: "receipt-write", Cause: errComplete}) } return value, errRun @@ -173,16 +242,17 @@ func decodeSIWCRefreshReceipt(value ojson.Result) (*CodexSIWCTokenData, error) { } scope := value.Get("scope").String() return &CodexSIWCTokenData{ - AccessToken: value.Get("access_token").String(), - RefreshToken: value.Get("refresh_token").String(), - IDToken: value.Get("id_token").String(), - ClientID: value.Get("client_id").String(), - Scope: scope, - Scopes: strings.Fields(scope), - Expire: value.Get("expired").String(), - ExpiresAt: value.Get("expires_at").String(), - LastRefresh: value.Get("last_refresh").String(), - DeviceID: value.Get("device_id").String(), + AccessToken: value.Get("access_token").String(), + RefreshToken: value.Get("refresh_token").String(), + IDToken: value.Get("id_token").String(), + ClientID: value.Get("client_id").String(), + Scope: scope, + Scopes: strings.Fields(scope), + Expire: value.Get("expired").String(), + ExpiresAt: value.Get("expires_at").String(), + EarliestRefreshAt: value.Get("earliest_refresh_at").Value(), + LastRefresh: value.Get("last_refresh").String(), + DeviceID: value.Get("device_id").String(), }, nil } @@ -235,9 +305,83 @@ func (j *memoryRefreshJournal) RefreshComplete(_ context.Context, key string, re return nil } -// doRefreshRequest forbids 307/308 redirects from silently replaying a POST body. +func (j *memoryRefreshJournal) RefreshRelease(_ context.Context, key string) error { + j.mu.Lock() + defer j.mu.Unlock() + receipt, exists := j.receipts[key] + if !exists { + return nil + } + if receipt != nil { + return fmt.Errorf("refresh receipt already exists") + } + delete(j.receipts, key) + return nil +} + +type refreshBodyReadTracker struct { + body io.ReadCloser + readSeen *atomic.Bool +} + +func (r *refreshBodyReadTracker) Read(p []byte) (int, error) { + r.readSeen.Store(true) + return r.body.Read(p) +} + +func (r *refreshBodyReadTracker) Close() error { + if r.body == nil { + return nil + } + return r.body.Close() +} + +func isTypedPreConnectRefreshError(err error) bool { + if err == nil { + return false + } + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) && dnsErr != nil { + return true + } + var opErr *net.OpError + return errors.As(err, &opErr) && opErr != nil && opErr.Op == "dial" +} + +// doRefreshRequest forbids 307/308 redirects from silently replaying a POST body +// and classifies errors that occurred strictly before a connection could carry +// any request bytes. func (o *CodexAuth) doRefreshRequest(req *http.Request) (*http.Response, error) { - client := *o.httpClient + var sawPreConn, sawConnReady, sawBodyRead atomic.Bool + if req != nil { + // Prevent net/http.Transport from internally replaying the POST body across connections. + req.GetBody = nil + if req.Body != nil && req.Body != http.NoBody { + req.Body = &refreshBodyReadTracker{body: req.Body, readSeen: &sawBodyRead} + } + trace := &httptrace.ClientTrace{ + GetConn: func(string) { sawPreConn.Store(true) }, + DNSStart: func(httptrace.DNSStartInfo) { sawPreConn.Store(true) }, + ConnectStart: func(string, string) { sawPreConn.Store(true) }, + TLSHandshakeStart: func() { sawPreConn.Store(true) }, + GotConn: func(httptrace.GotConnInfo) { sawConnReady.Store(true) }, + WroteHeaderField: func(string, []string) { sawConnReady.Store(true) }, + WroteHeaders: func() { sawConnReady.Store(true) }, + WroteRequest: func(httptrace.WroteRequestInfo) { sawConnReady.Store(true) }, + } + req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) + } + var client http.Client + if o != nil && o.httpClient != nil { + client = *o.httpClient + } client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } - return client.Do(req) + resp, errDo := client.Do(req) + if errDo != nil { + if !sawConnReady.Load() && !sawBodyRead.Load() && (sawPreConn.Load() || isTypedPreConnectRefreshError(errDo)) { + return nil, &RefreshPreSendError{Stage: "connect", Cause: errDo} + } + return nil, &RefreshOutcomeUnknownError{Stage: "transport", Cause: errDo} + } + return resp, nil } diff --git a/internal/auth/codex/refresh_journal_file.go b/internal/auth/codex/refresh_journal_file.go index e4d1c1195f8..9103e28d480 100644 --- a/internal/auth/codex/refresh_journal_file.go +++ b/internal/auth/codex/refresh_journal_file.go @@ -45,6 +45,9 @@ func (j *FileRefreshJournal) RefreshClaim(ctx context.Context, key string) (bool return false, errMkdir } if errSync := syncRefreshClaimDirectories(path); errSync != nil { + if errRemove := os.Remove(path); errRemove != nil && !errors.Is(errRemove, os.ErrNotExist) { + log.Warnf("remove unsynced refresh claim: %v", errRemove) + } return false, errSync } return true, nil @@ -101,6 +104,28 @@ func (j *FileRefreshJournal) RefreshComplete(ctx context.Context, key string, re return syncRefreshDirectory(path) } +func (j *FileRefreshJournal) RefreshRelease(ctx context.Context, key string) error { + if errContext := ctx.Err(); errContext != nil { + return errContext + } + path, errPath := j.path(key) + if errPath != nil { + return errPath + } + if _, errStat := os.Stat(filepath.Join(path, "receipt")); errStat == nil { + return fmt.Errorf("refresh receipt already exists") + } else if !errors.Is(errStat, os.ErrNotExist) { + return errStat + } + if errRemove := os.Remove(path); errRemove != nil { + if errors.Is(errRemove, os.ErrNotExist) { + return nil + } + return errRemove + } + return syncRefreshDirectory(filepath.Dir(path)) +} + // Sync every directory entry that can have been created by MkdirAll before // permitting an exchange. Canonicalize symlinks so newly-created target // ancestors, rather than just the spelling of the configured path, are durable. diff --git a/internal/auth/codex/refresh_journal_file_test.go b/internal/auth/codex/refresh_journal_file_test.go index 49a71e9bfb1..189aaca17c6 100644 --- a/internal/auth/codex/refresh_journal_file_test.go +++ b/internal/auth/codex/refresh_journal_file_test.go @@ -46,4 +46,17 @@ func TestFileRefreshClaimCreatesDurableAncestorDirectories(t *testing.T) { if claimed || errClaim != nil { t.Fatalf("claim was recreated: %v, %v", claimed, errClaim) } + if errRelease := journal.RefreshRelease(context.Background(), key); errRelease != nil { + t.Fatalf("release pending file claim: %v", errRelease) + } + reclaimed, errReclaim := journal.RefreshClaim(context.Background(), key) + if !reclaimed || errReclaim != nil { + t.Fatalf("reclaim after release failed: %v, %v", reclaimed, errReclaim) + } + if errComplete := journal.RefreshComplete(context.Background(), key, []byte(`{"stage":"transport"}`)); errComplete != nil { + t.Fatalf("complete receipt: %v", errComplete) + } + if errReleaseCompleted := journal.RefreshRelease(context.Background(), key); errReleaseCompleted == nil { + t.Fatal("completed file receipt must never be released") + } } diff --git a/internal/auth/codex/refresh_patch.go b/internal/auth/codex/refresh_patch.go index 2e831dbfddf..ee0631f7d32 100644 --- a/internal/auth/codex/refresh_patch.go +++ b/internal/auth/codex/refresh_patch.go @@ -4,7 +4,7 @@ import "reflect" var codexSIWCCredentialKeys = []string{ "access_token", "refresh_token", "id_token", "client_id", "device_id", - "expired", "expires_at", "last_refresh", "scope", "scopes", + "expired", "expires_at", "earliest_refresh_at", "last_refresh", "scope", "scopes", } // CredentialRefreshPatch is an immutable, partition-specific refresh result. @@ -119,9 +119,11 @@ func applyCredentialFields(disk, before, after map[string]any) { disk[key] = value } } - if _, hadExpiresAt := before["expires_at"]; hadExpiresAt { - if _, hasExpiresAt := after["expires_at"]; !hasExpiresAt { - delete(disk, "expires_at") + for _, key := range []string{"expires_at", "earliest_refresh_at"} { + if _, had := before[key]; had { + if _, has := after[key]; !has { + delete(disk, key) + } } } } diff --git a/internal/auth/codex/refresh_presend_recovery_test.go b/internal/auth/codex/refresh_presend_recovery_test.go new file mode 100644 index 00000000000..3cd5ba8904a --- /dev/null +++ b/internal/auth/codex/refresh_presend_recovery_test.go @@ -0,0 +1,403 @@ +package codex + +import ( + "bufio" + "context" + "crypto/tls" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" +) + +func closeTestConn(t *testing.T, c io.Closer) { + t.Helper() + if errClose := c.Close(); errClose != nil && !errors.Is(errClose, net.ErrClosed) { + t.Logf("close test connection: %v", errClose) + } +} + +func newRedirectedTransport(t *testing.T, server *httptest.Server, dialOverride func(ctx context.Context, network, addr string) (net.Conn, error)) *http.Transport { + t.Helper() + parsed, errParse := url.Parse(server.URL) + if errParse != nil { + t.Fatal(errParse) + } + clientTransport, ok := server.Client().Transport.(*http.Transport) + if !ok || clientTransport == nil { + t.Fatal("expected *http.Transport from TLS test server") + } + cloned := clientTransport.Clone() + if cloned.TLSClientConfig == nil { + cloned.TLSClientConfig = &tls.Config{} + } else { + cloned.TLSClientConfig = cloned.TLSClientConfig.Clone() + } + cloned.TLSClientConfig.ServerName = "127.0.0.1" + cloned.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { + if dialOverride != nil { + return dialOverride(ctx, network, parsed.Host) + } + var dialer net.Dialer + return dialer.DialContext(ctx, network, parsed.Host) + } + t.Cleanup(cloned.CloseIdleConnections) + return cloned +} + +func TestRefreshTokensReleasesClaimAfterPreSendFailures(t *testing.T) { + resetCodexRefreshGroupForTest() + t.Cleanup(resetCodexRefreshGroupForTest) + + newTokenServer := func(t *testing.T, calls *atomic.Int32) *httptest.Server { + t.Helper() + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + calls.Add(1) + if errParse := req.ParseForm(); errParse != nil { + t.Errorf("parse form: %v", errParse) + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"recovered-access","refresh_token":"recovered-refresh","expires_in":3600}`) + })) + t.Cleanup(server.Close) + return server + } + + t.Run("dns_failure", func(t *testing.T) { + resetCodexRefreshGroupForTest() + var serverCalls atomic.Int32 + server := newTokenServer(t, &serverCalls) + cfg := &config.Config{AuthDir: t.TempDir()} + + var failDNS atomic.Bool + failDNS.Store(true) + transport := newRedirectedTransport(t, server, func(ctx context.Context, network, targetAddr string) (net.Conn, error) { + if failDNS.Load() { + return nil, &net.DNSError{Err: "no such host", Name: "auth.openai.com", IsNotFound: true} + } + var dialer net.Dialer + return dialer.DialContext(ctx, network, targetAddr) + }) + + firstAuth := NewCodexAuth(cfg) + firstAuth.httpClient.Transport = transport + _, errFirst := firstAuth.RefreshTokens(context.Background(), "wake-dns-grant") + if errFirst == nil { + t.Fatal("expected pre-send DNS failure") + } + if IsRefreshOutcomeUnknown(errFirst) { + t.Fatalf("pre-send DNS failure was classified as unknown outcome: %v", errFirst) + } + if serverCalls.Load() != 0 { + t.Fatalf("server calls during DNS failure = %d, want 0", serverCalls.Load()) + } + + failDNS.Store(false) + secondAuth := NewCodexAuth(cfg) + secondAuth.httpClient.Transport = transport + tokens, errSecond := secondAuth.RefreshTokens(context.Background(), "wake-dns-grant") + if errSecond != nil || tokens == nil || tokens.AccessToken != "recovered-access" || tokens.RefreshToken != "recovered-refresh" { + t.Fatalf("retry after pre-send DNS failure failed: tokens=%+v, err=%v", tokens, errSecond) + } + if serverCalls.Load() != 1 { + t.Fatalf("server calls after recovery = %d, want 1", serverCalls.Load()) + } + }) + + t.Run("dial_connection_refused", func(t *testing.T) { + resetCodexRefreshGroupForTest() + var serverCalls atomic.Int32 + server := newTokenServer(t, &serverCalls) + cfg := &config.Config{AuthDir: t.TempDir()} + + closedListener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + closedAddr := closedListener.Addr().String() + if errClose := closedListener.Close(); errClose != nil { + t.Fatal(errClose) + } + + var useClosedPort atomic.Bool + useClosedPort.Store(true) + transport := newRedirectedTransport(t, server, func(ctx context.Context, network, targetAddr string) (net.Conn, error) { + var dialer net.Dialer + if useClosedPort.Load() { + return dialer.DialContext(ctx, network, closedAddr) + } + return dialer.DialContext(ctx, network, targetAddr) + }) + + firstAuth := NewCodexAuth(cfg) + firstAuth.httpClient.Transport = transport + _, errFirst := firstAuth.RefreshTokens(context.Background(), "wake-dial-grant") + if errFirst == nil { + t.Fatal("expected connection refused error") + } + if IsRefreshOutcomeUnknown(errFirst) { + t.Fatalf("pre-send dial failure was classified as unknown outcome: %v", errFirst) + } + + useClosedPort.Store(false) + secondAuth := NewCodexAuth(cfg) + secondAuth.httpClient.Transport = transport + tokens, errSecond := secondAuth.RefreshTokens(context.Background(), "wake-dial-grant") + if errSecond != nil || tokens == nil || tokens.AccessToken != "recovered-access" { + t.Fatalf("retry after dial failure failed: tokens=%+v, err=%v", tokens, errSecond) + } + if serverCalls.Load() != 1 { + t.Fatalf("server calls = %d, want 1", serverCalls.Load()) + } + }) + + t.Run("tls_handshake_failure", func(t *testing.T) { + resetCodexRefreshGroupForTest() + var serverCalls atomic.Int32 + server := newTokenServer(t, &serverCalls) + cfg := &config.Config{AuthDir: t.TempDir()} + + dropTLSListener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + t.Cleanup(func() { closeTestConn(t, dropTLSListener) }) + go func() { + for { + conn, errAccept := dropTLSListener.Accept() + if errAccept != nil { + return + } + closeTestConn(t, conn) + } + }() + + var dropTLS atomic.Bool + dropTLS.Store(true) + transport := newRedirectedTransport(t, server, func(ctx context.Context, network, targetAddr string) (net.Conn, error) { + var dialer net.Dialer + if dropTLS.Load() { + return dialer.DialContext(ctx, network, dropTLSListener.Addr().String()) + } + return dialer.DialContext(ctx, network, targetAddr) + }) + + firstAuth := NewCodexAuth(cfg) + firstAuth.httpClient.Transport = transport + _, errFirst := firstAuth.RefreshTokens(context.Background(), "wake-tls-grant") + if errFirst == nil { + t.Fatal("expected TLS handshake error") + } + if IsRefreshOutcomeUnknown(errFirst) { + t.Fatalf("pre-send TLS handshake failure was classified as unknown outcome: %v", errFirst) + } + + dropTLS.Store(false) + secondAuth := NewCodexAuth(cfg) + secondAuth.httpClient.Transport = transport + tokens, errSecond := secondAuth.RefreshTokens(context.Background(), "wake-tls-grant") + if errSecond != nil || tokens == nil || tokens.AccessToken != "recovered-access" { + t.Fatalf("retry after TLS handshake failure failed: tokens=%+v, err=%v", tokens, errSecond) + } + if serverCalls.Load() != 1 { + t.Fatalf("server calls = %d, want 1", serverCalls.Load()) + } + }) + + t.Run("proxy_connect_401_is_retryable_and_releases_claim", func(t *testing.T) { + resetCodexRefreshGroupForTest() + var serverCalls atomic.Int32 + server := newTokenServer(t, &serverCalls) + cfg := &config.Config{AuthDir: t.TempDir()} + + proxyListener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + t.Cleanup(func() { closeTestConn(t, proxyListener) }) + var proxyAttempts atomic.Int32 + go func() { + for { + conn, errAccept := proxyListener.Accept() + if errAccept != nil { + return + } + go func(c net.Conn) { + defer func() { closeTestConn(t, c) }() + reader := bufio.NewReader(c) + if _, errReadReq := http.ReadRequest(reader); errReadReq != nil { + return + } + attempt := proxyAttempts.Add(1) + if attempt == 1 { + _, _ = io.WriteString(c, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n") + return + } + parsedTarget, errParse := url.Parse(server.URL) + if errParse != nil { + return + } + upstream, errDial := net.Dial("tcp", parsedTarget.Host) + if errDial != nil { + return + } + defer func() { closeTestConn(t, upstream) }() + _, _ = io.WriteString(c, "HTTP/1.1 200 Connection Established\r\n\r\n") + done := make(chan struct{}, 2) + go func() { _, _ = io.Copy(upstream, reader); done <- struct{}{} }() + go func() { _, _ = io.Copy(c, upstream); done <- struct{}{} }() + <-done + }(conn) + } + }() + + proxyURL, errProxyURL := url.Parse("http://" + proxyListener.Addr().String()) + if errProxyURL != nil { + t.Fatal(errProxyURL) + } + clientTransport := server.Client().Transport.(*http.Transport).Clone() + clientTransport.TLSClientConfig = clientTransport.TLSClientConfig.Clone() + clientTransport.TLSClientConfig.ServerName = "127.0.0.1" + clientTransport.Proxy = http.ProxyURL(proxyURL) + t.Cleanup(clientTransport.CloseIdleConnections) + + auth := NewCodexAuth(cfg) + auth.httpClient.Transport = clientTransport + tokens, errRefresh := auth.RefreshTokensWithRetry(context.Background(), "wake-proxy-grant", 2) + if errRefresh != nil || tokens == nil || tokens.AccessToken != "recovered-access" { + t.Fatalf("proxy CONNECT 401 aborted refresh or locked grant: tokens=%+v, err=%v", tokens, errRefresh) + } + if proxyAttempts.Load() != 2 || serverCalls.Load() != 1 { + t.Fatalf("proxyAttempts=%d, serverCalls=%d, want 2 and 1", proxyAttempts.Load(), serverCalls.Load()) + } + }) + + t.Run("post_gotconn_disconnect_stays_unknown_outcome", func(t *testing.T) { + resetCodexRefreshGroupForTest() + var serverCalls atomic.Int32 + server := newTokenServer(t, &serverCalls) + cfg := &config.Config{AuthDir: t.TempDir()} + + tlsCert := server.TLS.Certificates[0] + postHandshakeListener, errListen := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{tlsCert}}) + if errListen != nil { + t.Fatal(errListen) + } + t.Cleanup(func() { closeTestConn(t, postHandshakeListener) }) + var accepted atomic.Int32 + go func() { + for { + conn, errAccept := postHandshakeListener.Accept() + if errAccept != nil { + return + } + go func(c net.Conn) { + defer func() { closeTestConn(t, c) }() + tlsConn := c.(*tls.Conn) + if errHS := tlsConn.Handshake(); errHS != nil { + return + } + accepted.Add(1) + var buf [64]byte + _, _ = tlsConn.Read(buf[:]) + }(conn) + } + }() + + transport := newRedirectedTransport(t, server, func(ctx context.Context, network, _ string) (net.Conn, error) { + var dialer net.Dialer + return dialer.DialContext(ctx, network, postHandshakeListener.Addr().String()) + }) + auth := NewCodexAuth(cfg) + auth.httpClient.Transport = transport + _, errFirst := auth.RefreshTokensWithRetry(context.Background(), "post-send-grant", 3) + if !IsRefreshOutcomeUnknown(errFirst) { + t.Fatalf("post-handshake disconnect must remain unknown outcome, got: %v", errFirst) + } + if accepted.Load() != 1 { + t.Fatalf("post-handshake transport calls = %d, want 1", accepted.Load()) + } + }) +} + +func TestSIWCRefreshReleasesClaimAfterPreSendFailure(t *testing.T) { + resetCodexRefreshGroupForTest() + t.Cleanup(resetCodexRefreshGroupForTest) + + var serverCalls atomic.Int32 + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + serverCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"siwc-recovered","refresh_token":"siwc-next","expires_in":3600,"scope":"openid chatgpt.tokens.use.direct"}`) + })) + t.Cleanup(server.Close) + + previousEndpoint := siwcTokenEndpointURL + siwcTokenEndpointURL = strings.TrimRight(server.URL, "/") + "/api/accounts/oauth/token" + t.Cleanup(func() { siwcTokenEndpointURL = previousEndpoint }) + + cfg := &config.Config{AuthDir: t.TempDir()} + var failDNS atomic.Bool + failDNS.Store(true) + transport := newRedirectedTransport(t, server, func(ctx context.Context, network, targetAddr string) (net.Conn, error) { + if failDNS.Load() { + return nil, &net.DNSError{Err: "temporary failure in name resolution", Name: "auth.openai.com", IsTemporary: true} + } + var dialer net.Dialer + return dialer.DialContext(ctx, network, targetAddr) + }) + + auth := NewCodexAuth(cfg) + auth.httpClient.Transport = transport + _, errFirst := auth.RefreshSIWCTokens(context.Background(), "siwc-wake-grant", "oaiapp_wake", "550e8400-e29b-41d4-a716-446655440000") + if errFirst == nil || IsRefreshOutcomeUnknown(errFirst) { + t.Fatalf("expected retryable pre-send SIWC error, got: %v", errFirst) + } + + failDNS.Store(false) + tokens, errSecond := auth.RefreshSIWCTokens(context.Background(), "siwc-wake-grant", "oaiapp_wake", "550e8400-e29b-41d4-a716-446655440000") + if errSecond != nil || tokens == nil || tokens.AccessToken != "siwc-recovered" { + t.Fatalf("SIWC retry after pre-send DNS failure failed: tokens=%+v, err=%v", tokens, errSecond) + } + if serverCalls.Load() != 1 { + t.Fatalf("SIWC server calls = %d, want 1", serverCalls.Load()) + } +} + +type peerReleasedClaimJournal struct { + memoryRefreshJournal + releasedBeforeRead bool +} + +func (j *peerReleasedClaimJournal) RefreshClaim(ctx context.Context, key string) (bool, error) { + if !j.releasedBeforeRead { + j.releasedBeforeRead = true + return false, nil + } + return j.memoryRefreshJournal.RefreshClaim(ctx, key) +} + +func TestJournalRefreshTreatsPeerReleasedClaimAsPreSendRetryable(t *testing.T) { + journal := &peerReleasedClaimJournal{} + _, errFirst := journalRefresh(context.Background(), journal, ClientID, "peer-released-grant", func() (string, error) { + t.Fatal("run must not execute when RefreshClaim returned false") + return "", nil + }, func(v ojson.Result) (string, error) { return v.String(), nil }) + if !IsRefreshPreSendError(errFirst) || IsRefreshOutcomeUnknown(errFirst) { + t.Fatalf("peer-released claim returned %v, want retryable RefreshPreSendError", errFirst) + } + got, errSecond := journalRefresh(context.Background(), journal, ClientID, "peer-released-grant", func() (string, error) { + return "rotated", nil + }, func(v ojson.Result) (string, error) { return v.String(), nil }) + if errSecond != nil || got != "rotated" { + t.Fatalf("second attempt after peer release: got=%q, err=%v", got, errSecond) + } +} diff --git a/internal/auth/codex/siwc_auth.go b/internal/auth/codex/siwc_auth.go index 6f28e3ca27e..ec07622ee98 100644 --- a/internal/auth/codex/siwc_auth.go +++ b/internal/auth/codex/siwc_auth.go @@ -3,18 +3,20 @@ package codex import ( "context" "crypto/rand" - "encoding/json" "errors" "fmt" - "github.com/MoeForge/moego/base64" "io" + "math" "net/http" "net/url" "regexp" "slices" + "strconv" "strings" "time" + "github.com/MoeForge/moego/base64" + "github.com/MoeForge/moego/ojson" log "github.com/sirupsen/logrus" "golang.org/x/sync/singleflight" ) @@ -42,6 +44,15 @@ var ( siwcRefreshGroup singleflight.Group ) +// OverrideSIWCTokenEndpointURLForTest overrides the SIWC token endpoint URL for tests and returns a restore function. +func OverrideSIWCTokenEndpointURLForTest(endpoint string) func() { + previous := siwcTokenEndpointURL + siwcTokenEndpointURL = endpoint + return func() { + siwcTokenEndpointURL = previous + } +} + // IsValidUUID reports whether raw is a canonical 36-char UUID string. func IsValidUUID(raw string) bool { return siwcUUIDPattern.MatchString(strings.TrimSpace(raw)) @@ -95,24 +106,41 @@ func (o *CodexAuth) GenerateSIWCAuthURL(state, nonce, deviceID, redirectURI stri return fmt.Sprintf("%s?%s", SIWCAuthorizeURL, params.Encode()), nil } -type siwcTokenResponse struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - IDToken string `json:"id_token"` - Scope string `json:"scope"` - ExpiresIn int `json:"expires_in"` +// GenerateSIWCReauthURL reuses the issued registration when replacing an unusable grant. +func (o *CodexAuth) GenerateSIWCReauthURL(clientID, state, nonce, deviceID, redirectURI string, pkceCodes *PKCECodes) (string, error) { + clientID = strings.TrimSpace(clientID) + if clientID == "" || clientID == SIWCDynamicClientID { + return "", fmt.Errorf("SIWC reauthorization requires the saved issued client ID") + } + rawURL, errGenerate := o.GenerateSIWCAuthURL(state, nonce, deviceID, redirectURI, pkceCodes) + if errGenerate != nil { + return "", errGenerate + } + parsed, errParse := url.Parse(rawURL) + if errParse != nil { + return "", fmt.Errorf("failed to parse SIWC authorization URL: %w", errParse) + } + query := parsed.Query() + query.Set("client_id", clientID) + query.Del("agent_name_hint") + parsed.RawQuery = query.Encode() + return parsed.String(), nil } func (o *CodexAuth) requestSIWCToken(ctx context.Context, form url.Values, clientID, deviceID string, requireIDToken bool) (result *CodexSIWCTokenData, errResult error) { stage := "request-create" defer func() { - if form.Get("grant_type") == "refresh_token" && errResult != nil && !isNonRetryableRefreshErr(errResult) { + if form.Get("grant_type") == "refresh_token" && errResult != nil && !isNonRetryableRefreshErr(errResult) && !IsRefreshPreSendError(errResult) && !IsRefreshOutcomeUnknown(errResult) { errResult = &RefreshOutcomeUnknownError{Stage: stage, Cause: errResult} } }() req, errReq := http.NewRequestWithContext(ctx, http.MethodPost, siwcTokenEndpointURL, strings.NewReader(form.Encode())) if errReq != nil { - return nil, fmt.Errorf("failed to create SIWC token request: %w", errReq) + errCreate := fmt.Errorf("failed to create SIWC token request: %w", errReq) + if form.Get("grant_type") == "refresh_token" { + return nil, &RefreshPreSendError{Stage: "request-create", Cause: errCreate} + } + return nil, errCreate } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") @@ -139,53 +167,93 @@ func (o *CodexAuth) requestSIWCToken(ctx context.Context, form url.Values, clien } if resp.StatusCode != http.StatusOK { stage = "response-status" + if requestID := strings.TrimSpace(resp.Header.Get("x-request-id")); requestID != "" { + return nil, fmt.Errorf("OpenAI OAuth token request failed (%d, request_id=%q): %s", resp.StatusCode, requestID, strings.TrimSpace(string(body))) + } return nil, fmt.Errorf("OpenAI OAuth token request failed (%d): %s", resp.StatusCode, strings.TrimSpace(string(body))) } stage = "response-decode" - var tokenResp siwcTokenResponse - if errUnmarshal := json.Unmarshal(body, &tokenResp); errUnmarshal != nil { - return nil, fmt.Errorf("failed to parse SIWC token response: %w", errUnmarshal) + tokenResp := ojson.ParseBytes(body) + if !ojson.ValidBytes(body) || !tokenResp.IsObject() { + return nil, fmt.Errorf("failed to parse SIWC token response: expected a JSON object") } - if strings.TrimSpace(tokenResp.AccessToken) == "" { + accessToken := tokenResp.Get("access_token") + if accessToken.Type != ojson.String || strings.TrimSpace(accessToken.Str) == "" { return nil, fmt.Errorf("OpenAI OAuth token response has invalid access_token") } - if strings.TrimSpace(tokenResp.RefreshToken) == "" { + refreshToken := tokenResp.Get("refresh_token") + if refreshToken.Type != ojson.String || strings.TrimSpace(refreshToken.Str) == "" { return nil, fmt.Errorf("OpenAI OAuth token response has invalid refresh_token") } - if requireIDToken && strings.TrimSpace(tokenResp.IDToken) == "" { + idToken := tokenResp.Get("id_token") + if idToken.Type != ojson.Null && idToken.Type != ojson.String { + return nil, fmt.Errorf("OpenAI OAuth token response has invalid id_token") + } + if requireIDToken && strings.TrimSpace(idToken.Str) == "" { return nil, fmt.Errorf("OpenAI OAuth token response did not contain an ID token") } - if strings.TrimSpace(tokenResp.Scope) == "" { + scope := tokenResp.Get("scope") + // An omitted, unchanged scope on refresh must not discard a rotated refresh token. + if (requireIDToken || scope.Exists()) && (scope.Type != ojson.String || strings.TrimSpace(scope.Str) == "") { return nil, fmt.Errorf("OpenAI OAuth token response has invalid scope") } - if tokenResp.ExpiresIn <= 0 { + expiresInResult := tokenResp.Get("expires_in") + maxExpiresInSeconds := int64(^uint64(0)>>1) / int64(time.Second) + var expiresIn int64 + switch expiresInResult.Type { + case ojson.Number: + f, errParse := strconv.ParseFloat(expiresInResult.Raw, 64) + if errParse != nil || f <= 0 || math.IsInf(f, 0) || math.IsNaN(f) || f != math.Trunc(f) || f > float64(maxExpiresInSeconds) { + return nil, fmt.Errorf("OpenAI OAuth token response has invalid expires_in") + } + expiresIn = int64(f) + case ojson.String: + raw := strings.TrimSpace(expiresInResult.Str) + if raw == "" { + return nil, fmt.Errorf("OpenAI OAuth token response has invalid expires_in") + } + i, errParse := strconv.ParseInt(raw, 10, 64) + if errParse == nil { + if i <= 0 || i > maxExpiresInSeconds { + return nil, fmt.Errorf("OpenAI OAuth token response has invalid expires_in") + } + expiresIn = i + break + } + f, errParse := strconv.ParseFloat(raw, 64) + if errParse != nil || f <= 0 || math.IsInf(f, 0) || math.IsNaN(f) || f != math.Trunc(f) || f > float64(maxExpiresInSeconds) { + return nil, fmt.Errorf("OpenAI OAuth token response has invalid expires_in") + } + expiresIn = int64(f) + default: return nil, fmt.Errorf("OpenAI OAuth token response has invalid expires_in") } - scopes := strings.Fields(tokenResp.Scope) - if !slices.Contains(scopes, SIWCDirectTokenScope) { + scopes := strings.Fields(scope.Str) + if scope.Exists() && !slices.Contains(scopes, SIWCDirectTokenScope) { return nil, fmt.Errorf("OpenAI OAuth grant did not include %s", SIWCDirectTokenScope) } now := time.Now() - rawTTL := time.Duration(tokenResp.ExpiresIn) * time.Second + rawTTL := time.Duration(expiresIn) * time.Second ttl := rawTTL - SIWCExpiryMargin if ttl <= 0 { ttl = rawTTL } return &CodexSIWCTokenData{ - AccessToken: tokenResp.AccessToken, - RefreshToken: tokenResp.RefreshToken, - IDToken: tokenResp.IDToken, - ClientID: strings.TrimSpace(clientID), - Scope: strings.TrimSpace(tokenResp.Scope), - Scopes: scopes, - Expire: now.Add(ttl).Format(time.RFC3339), - ExpiresAt: now.Add(rawTTL).Format(time.RFC3339), - LastRefresh: now.Format(time.RFC3339), - DeviceID: strings.TrimSpace(deviceID), + AccessToken: accessToken.Str, + RefreshToken: refreshToken.Str, + IDToken: idToken.Str, + ClientID: strings.TrimSpace(clientID), + Scope: strings.TrimSpace(scope.Str), + Scopes: scopes, + Expire: now.Add(ttl).Format(time.RFC3339), + ExpiresAt: now.Add(rawTTL).Format(time.RFC3339), + EarliestRefreshAt: tokenResp.Get("earliest_refresh_at").Value(), + LastRefresh: now.Format(time.RFC3339), + DeviceID: strings.TrimSpace(deviceID), }, nil } @@ -271,6 +339,9 @@ func (o *CodexAuth) RefreshSIWCTokens(ctx context.Context, refreshToken, clientI result, errSF, _ := siwcRefreshGroup.Do(sfKey, func() (any, error) { refreshCtx, cancelRefresh := context.WithTimeout(context.WithoutCancel(ctx), codexRefreshTimeout) defer cancelRefresh() + if errReadiness := siwcRefreshReadiness(refreshCtx); errReadiness != nil { + return nil, errReadiness + } form := url.Values{ "grant_type": {"refresh_token"}, "client_id": {clientID}, @@ -309,6 +380,9 @@ func (o *CodexAuth) RefreshSIWCTokensWithRetry(ctx context.Context, refreshToken if errRefresh == nil { return tokenData, nil } + if errors.Is(errRefresh, context.Canceled) || errors.Is(errRefresh, ErrSIWCRefreshDeferred) { + return nil, errRefresh + } if isNonRetryableRefreshErr(errRefresh) { log.Warnf("SIWC token refresh attempt %d failed with non-retryable error: %v", attempt+1, errRefresh) return nil, errRefresh diff --git a/internal/auth/codex/siwc_power_darwin.go b/internal/auth/codex/siwc_power_darwin.go new file mode 100644 index 00000000000..115decd28cd --- /dev/null +++ b/internal/auth/codex/siwc_power_darwin.go @@ -0,0 +1,51 @@ +package codex + +import ( + "context" + "fmt" + "os/exec" + "slices" + "strings" + "time" +) + +// ReadSIWCSystemState reads the macOS power capabilities used by SIWC renewal. +var ReadSIWCSystemState = func(ctx context.Context) ([]byte, error) { + return exec.CommandContext(ctx, "/usr/bin/pmset", "-g", "systemstate").Output() +} + +func siwcRefreshReadiness(ctx context.Context) error { + return codexRefreshReadiness(ctx, "SIWC") +} + +func codexRefreshReadiness(ctx context.Context, label string) error { + probeCtx, cancelProbe := context.WithTimeout(ctx, 2*time.Second) + defer cancelProbe() + // shortcut: checks entry state; use native sleep coordination if in-flight sleep still breaks renewal. + state, errState := ReadSIWCSystemState(probeCtx) + if errState != nil { + return fmt.Errorf("%s renewal deferred: macOS power state unavailable: %w: %w", label, errState, ErrSIWCRefreshDeferred) + } + foundCapabilities := false + var fields []string + for _, line := range strings.Split(string(state), "\n") { + capabilities, ok := strings.CutPrefix(strings.TrimSpace(line), "Current System Capabilities are:") + if !ok { + continue + } + foundCapabilities = true + fields = strings.Fields(capabilities) + if slices.Contains(fields, "Graphics") && slices.Contains(fields, "Network") { + return nil + } + } + if !foundCapabilities { + raw := strings.TrimSpace(string(state)) + raw = strings.Join(strings.Fields(strings.ReplaceAll(raw, "\n", " ")), " ") + if len(raw) > 200 { + raw = raw[:200] + "..." + } + return fmt.Errorf("%s renewal deferred: unexpected pmset output: %q: %w", label, raw, ErrSIWCRefreshDeferred) + } + return fmt.Errorf("%s renewal deferred until interactive macOS wake: missing Graphics/Network (%v): %w", label, fields, ErrSIWCRefreshDeferred) +} diff --git a/internal/auth/codex/siwc_power_darwin_test.go b/internal/auth/codex/siwc_power_darwin_test.go new file mode 100644 index 00000000000..28cfb3cafcb --- /dev/null +++ b/internal/auth/codex/siwc_power_darwin_test.go @@ -0,0 +1,139 @@ +package codex + +import ( + "context" + "errors" + "io" + "net/http" + "os" + "strings" + "testing" +) + +func TestMain(m *testing.M) { + ReadSIWCSystemState = func(context.Context) ([]byte, error) { + return []byte("Current System Capabilities are: CPU Graphics Audio Network\nCurrent Power State: 4\n"), nil + } + os.Exit(m.Run()) +} + +func TestSIWCRefreshDefersDuringMaintenanceWakeThenRenews(t *testing.T) { + for _, state := range []string{ + "Current System Capabilities are: CPU Network\nCurrent Power State: 2\n", + "Current System Capabilities are: CPU Graphics Audio\n", + "Graphics Network", + } { + t.Run(strings.TrimSpace(state), func(t *testing.T) { + previous := ReadSIWCSystemState + t.Cleanup(func() { ReadSIWCSystemState = previous }) + currentState := state + checks := 0 + ReadSIWCSystemState = func(context.Context) ([]byte, error) { + checks++ + return []byte(currentState), nil + } + calls := 0 + auth := &CodexAuth{httpClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + calls++ + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600,"scope":"chatgpt.tokens.use.direct"}`))}, nil + })}} + auth.SetRefreshJournal(&memoryRefreshJournal{}) + token, errRefresh := auth.RefreshSIWCTokensWithRetry(context.Background(), "sleep-refresh", "oaiapp_sleep", "", 3) + if token != nil || errRefresh == nil || calls != 0 || checks != 1 { + t.Fatalf("maintenance wake: token returned = %t, error = %v, requests = %d, checks = %d; want deferral without token requests or retries", token != nil, errRefresh, calls, checks) + } + if errors.Is(errRefresh, context.Canceled) { + t.Fatalf("maintenance wake: refresh returned context.Canceled; want a dedicated deferral error: %v", errRefresh) + } + if strings.TrimSpace(state) == "Graphics Network" && !strings.Contains(errRefresh.Error(), "unexpected pmset output") { + t.Fatalf("maintenance wake: error = %v; want parse diagnostics for unexpected pmset output", errRefresh) + } + var partition *SIWCRefreshError + if !errors.As(errRefresh, &partition) { + t.Fatalf("deferral lost the SIWC error partition: %v", errRefresh) + } + currentState = "Current System Capabilities are: CPU Graphics Audio Network\nCurrent Power State: 4\n" + token, errRefresh = auth.RefreshSIWCTokensWithRetry(context.Background(), "sleep-refresh", "oaiapp_sleep", "", 3) + if errRefresh != nil || token == nil || token.RefreshToken != "new-refresh" || calls != 1 { + t.Fatalf("interactive wake: token returned = %t, error = %v, requests = %d; want successful renewal", token != nil, errRefresh, calls) + } + }) + } +} + +func TestSIWCRefreshDoesNotConsumeGrantWhenPowerStateUnavailable(t *testing.T) { + previous := ReadSIWCSystemState + t.Cleanup(func() { ReadSIWCSystemState = previous }) + errProbe := errors.New("power-state probe unavailable") + ReadSIWCSystemState = func(context.Context) ([]byte, error) { return nil, errProbe } + auth := &CodexAuth{httpClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + t.Fatal("token request sent without a known power state") + return nil, nil + })}} + _, errRefresh := auth.RefreshSIWCTokens(context.Background(), "refresh", "oaiapp_probe", "") + if !errors.Is(errRefresh, errProbe) { + t.Fatalf("power-state error was lost: %v", errRefresh) + } +} + +func TestOrdinaryCodexRefreshDefersDuringMaintenanceWakeThenRenews(t *testing.T) { + for _, tc := range []struct { + name string + state string + probeErr error + }{ + {name: "darkwake_missing_graphics", state: "Current System Capabilities are: CPU Network\nCurrent Power State: 2\n"}, + {name: "missing_network", state: "Current System Capabilities are: CPU Graphics Audio\n"}, + {name: "unexpected_pmset_output", state: "Graphics Network"}, + {name: "power_probe_unavailable", probeErr: errors.New("pmset unavailable")}, + } { + t.Run(tc.name, func(t *testing.T) { + resetCodexRefreshGroupForTest() + t.Cleanup(resetCodexRefreshGroupForTest) + + previous := ReadSIWCSystemState + t.Cleanup(func() { ReadSIWCSystemState = previous }) + currentState := tc.state + currentErr := tc.probeErr + checks := 0 + ReadSIWCSystemState = func(context.Context) ([]byte, error) { + checks++ + if currentErr != nil { + return nil, currentErr + } + return []byte(currentState), nil + } + + calls := 0 + auth := NewCodexAuth(nil) + auth.SetRefreshJournal(&FileRefreshJournal{Dir: t.TempDir()}) + auth.httpClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + calls++ + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"access_token":"ordinary-new-access","refresh_token":"ordinary-new-refresh","expires_in":3600}`)), + Request: req, + }, nil + })} + + token, errRefresh := auth.RefreshTokensWithRetry(context.Background(), "ordinary-sleep-refresh", 3) + if token != nil || errRefresh == nil || calls != 0 || checks != 1 { + t.Fatalf("maintenance wake: token=%v, err=%v, calls=%d, checks=%d; want deferral without HTTP calls or retries", token, errRefresh, calls, checks) + } + if !errors.Is(errRefresh, ErrSIWCRefreshDeferred) { + t.Fatalf("maintenance wake error %v did not wrap ErrSIWCRefreshDeferred", errRefresh) + } + if tc.probeErr != nil && !errors.Is(errRefresh, tc.probeErr) { + t.Fatalf("power probe error lost: %v", errRefresh) + } + + currentErr = nil + currentState = "Current System Capabilities are: CPU Graphics Audio Network\nCurrent Power State: 4\n" + token, errRefresh = auth.RefreshTokensWithRetry(context.Background(), "ordinary-sleep-refresh", 3) + if errRefresh != nil || token == nil || token.AccessToken != "ordinary-new-access" || token.RefreshToken != "ordinary-new-refresh" || calls != 1 { + t.Fatalf("interactive wake renewal failed: token=%+v, err=%v, calls=%d", token, errRefresh, calls) + } + }) + } +} diff --git a/internal/auth/codex/siwc_power_other.go b/internal/auth/codex/siwc_power_other.go new file mode 100644 index 00000000000..901456348bd --- /dev/null +++ b/internal/auth/codex/siwc_power_other.go @@ -0,0 +1,9 @@ +//go:build !darwin + +package codex + +import "context" + +func siwcRefreshReadiness(context.Context) error { return nil } + +func codexRefreshReadiness(context.Context, string) error { return nil } diff --git a/internal/auth/codex/siwc_refresh_deferral.go b/internal/auth/codex/siwc_refresh_deferral.go new file mode 100644 index 00000000000..e364ac1315a --- /dev/null +++ b/internal/auth/codex/siwc_refresh_deferral.go @@ -0,0 +1,6 @@ +package codex + +import "errors" + +// ErrSIWCRefreshDeferred indicates SIWC renewal should be deferred and retried later. +var ErrSIWCRefreshDeferred = errors.New("siwc refresh deferred") diff --git a/internal/auth/codex/siwc_renewal_test.go b/internal/auth/codex/siwc_renewal_test.go new file mode 100644 index 00000000000..6002a4234a4 --- /dev/null +++ b/internal/auth/codex/siwc_renewal_test.go @@ -0,0 +1,140 @@ +package codex + +import ( + "context" + "io" + "net/http" + "reflect" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" +) + +func TestSIWCTokenResponseValidatesScope(t *testing.T) { + for _, tc := range []struct { + name, scope string + exchange bool + wantError bool + }{ + {name: "refresh omits unchanged scope"}, + {name: "refresh explicitly clears scope", scope: `""`, wantError: true}, + {name: "refresh returns null scope", scope: `null`, wantError: true}, + {name: "refresh removes direct permission", scope: `"openid profile"`, wantError: true}, + {name: "refresh returns malformed scope", scope: `123`, wantError: true}, + {name: "refresh grants direct permission", scope: `"openid chatgpt.tokens.use.direct"`}, + {name: "exchange requires explicit scope", exchange: true, wantError: true}, + {name: "exchange grants direct permission", exchange: true, scope: `"openid chatgpt.tokens.use.direct"`}, + } { + t.Run(tc.name, func(t *testing.T) { + doc := ojson.NewDocString(`{"access_token":"access","refresh_token":"refresh","id_token":"id","expires_in":3600}`) + if tc.scope != "" { + if errSet := doc.SetRaw("scope", tc.scope); errSet != nil { + t.Fatal(errSet) + } + } + body := doc.String() + auth := &CodexAuth{httpClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil + })}} + auth.SetRefreshJournal(&memoryRefreshJournal{}) + var err error + if tc.exchange { + _, err = auth.ExchangeSIWCCodeForTokens(context.Background(), "code", "oaiapp_scope", "", "", &PKCECodes{CodeVerifier: "verifier"}) + } else { + _, err = auth.RefreshSIWCTokens(context.Background(), "refresh", "oaiapp_scope", "") + } + if (err != nil) != tc.wantError { + t.Fatalf("error = %v, wantError = %v", err, tc.wantError) + } + }) + } +} + +func TestSIWCTokenResponseValidatesExpiresIn(t *testing.T) { + for _, tc := range []struct { + name string + expiresInRaw string + wantError bool + }{ + {name: "accept float json number", expiresInRaw: "3600.0"}, + {name: "accept scientific notation", expiresInRaw: "3.6e3"}, + {name: "reject fractional value", expiresInRaw: "3600.5", wantError: true}, + {name: "reject oversized seconds", expiresInRaw: "1e20", wantError: true}, + {name: "reject infinity string", expiresInRaw: `"Inf"`, wantError: true}, + } { + t.Run(tc.name, func(t *testing.T) { + doc := ojson.NewDocString(`{"access_token":"access","refresh_token":"refresh","expires_in":3600}`) + if errSet := doc.SetRaw("expires_in", tc.expiresInRaw); errSet != nil { + t.Fatal(errSet) + } + body := doc.String() + auth := &CodexAuth{httpClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil + })}} + auth.SetRefreshJournal(&memoryRefreshJournal{}) + token, errRefresh := auth.RefreshSIWCTokens(context.Background(), "refresh", "oaiapp_expires_in", "") + if tc.wantError { + if errRefresh == nil || token != nil { + t.Fatalf("error = %v, token returned = %t; want error", errRefresh, token != nil) + } + return + } + if errRefresh != nil || token == nil { + t.Fatalf("error = %v, token returned = %t; want success", errRefresh, token != nil) + } + }) + } +} + +func TestSIWCRefreshReceiptPreservesServerWindow(t *testing.T) { + for _, window := range []string{`"2026-11-07T13:07:09Z"`, `1794056829`, `null`} { + t.Run(window, func(t *testing.T) { + doc := ojson.NewDocString(`{"access_token":"access","refresh_token":"rotated","expires_in":3600}`) + if errSet := doc.SetRaw("earliest_refresh_at", window); errSet != nil { + t.Fatal(errSet) + } + body := doc.String() + calls := 0 + auth := &CodexAuth{httpClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + calls++ + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil + })}} + auth.SetRefreshJournal(&memoryRefreshJournal{}) + for attempt := 0; attempt < 2; attempt++ { + token, errRefresh := auth.RefreshSIWCTokens(context.Background(), "receipt-grant", "oaiapp_receipt", "") + if errRefresh != nil { + t.Fatal(errRefresh) + } + if !reflect.DeepEqual(token.EarliestRefreshAt, ojson.Parse(window).Value()) { + t.Fatalf("attempt %d: earliest_refresh_at = %v, want %s", attempt, token.EarliestRefreshAt, window) + } + } + if calls != 1 { + t.Fatalf("receipt was not reused: requests = %d, want 1", calls) + } + }) + } +} + +func TestSIWCRefreshErrorRetainsRequestID(t *testing.T) { + auth := &CodexAuth{httpClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"X-Request-Id": []string{"req-siwc-test"}}, + Body: io.NopCloser(strings.NewReader(`{"error":"invalid_grant"}`)), + }, nil + })}} + _, errRefresh := auth.RefreshSIWCTokens(context.Background(), "refresh", "oaiapp_request_id", "") + if errRefresh == nil || !strings.Contains(errRefresh.Error(), "req-siwc-test") || !strings.Contains(errRefresh.Error(), "invalid_grant") { + t.Fatalf("upstream correlation details missing: %v", errRefresh) + } +} + +func TestGenerateSIWCReauthURLRejectsUnissuedClient(t *testing.T) { + for _, clientID := range []string{"", " ", SIWCDynamicClientID} { + if _, errGenerate := (&CodexAuth{}).GenerateSIWCReauthURL(clientID, "state", "nonce", "e61bbe28-07ef-466d-8e5d-a344f94ab305", "", &PKCECodes{CodeChallenge: "challenge"}); errGenerate == nil { + t.Errorf("accepted an unissued client ID %q", clientID) + } + } +} diff --git a/internal/cache/antigravity_reasoning_replay_cache.go b/internal/cache/antigravity_reasoning_replay_cache.go index a53017f400f..d1aaad73e9d 100644 --- a/internal/cache/antigravity_reasoning_replay_cache.go +++ b/internal/cache/antigravity_reasoning_replay_cache.go @@ -4,13 +4,13 @@ import ( "bytes" "context" "crypto/rand" - "encoding/json" "fmt" "sort" "strings" "sync" "time" + "github.com/MoeForge/moego/base64" "github.com/MoeForge/moego/ojson" homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" @@ -165,9 +165,28 @@ func GetAntigravityReasoningReplayItemsRequired(ctx context.Context, modelName, return items, found, errGet } +// PeekAntigravityReasoningReplayItemsRequired retrieves existing replay items +// without creating an absence reservation tombstone on a cache miss. Use this +// for read-only paths such as CountTokens that never commit or delete a turn. +func PeekAntigravityReasoningReplayItemsRequired(ctx context.Context, modelName, sessionKey string) ([][]byte, bool, error) { + items, _, found, errGet := getAntigravityReasoningReplayItemsWithSnapshot(ctx, modelName, sessionKey, false) + return items, found, errGet +} + +// PeekAntigravityReasoningReplayItemsWithSnapshotRequired retrieves existing +// replay items and their snapshot without creating an absence reservation +// tombstone on a cache miss. +func PeekAntigravityReasoningReplayItemsWithSnapshotRequired(ctx context.Context, modelName, sessionKey string) ([][]byte, AntigravityReasoningReplaySnapshot, bool, error) { + return getAntigravityReasoningReplayItemsWithSnapshot(ctx, modelName, sessionKey, false) +} + // GetAntigravityReasoningReplayItemsWithSnapshotRequired retrieves replay items // and the exact cache state that guarded this request. func GetAntigravityReasoningReplayItemsWithSnapshotRequired(ctx context.Context, modelName, sessionKey string) ([][]byte, AntigravityReasoningReplaySnapshot, bool, error) { + return getAntigravityReasoningReplayItemsWithSnapshot(ctx, modelName, sessionKey, true) +} + +func getAntigravityReasoningReplayItemsWithSnapshot(ctx context.Context, modelName, sessionKey string, reserveOnMiss bool) ([][]byte, AntigravityReasoningReplaySnapshot, bool, error) { key := antigravityReasoningReplayCacheKey(modelName, sessionKey) if key == "" { return nil, AntigravityReasoningReplaySnapshot{}, false, nil @@ -190,6 +209,9 @@ func GetAntigravityReasoningReplayItemsWithSnapshotRequired(ctx context.Context, found = true break } + if !reserveOnMiss { + return nil, AntigravityReasoningReplaySnapshot{loaded: true}, false, nil + } reservation := newAntigravityReasoningReplayTombstone() swapped, errReserve := client.KVCompareAndSwap(ctx, kvKey, nil, false, reservation, AntigravityReasoningReplayCacheTTL) if errReserve != nil { @@ -233,11 +255,17 @@ func GetAntigravityReasoningReplayItemsWithSnapshotRequired(ctx context.Context, defer antigravityReasoningReplayMu.Unlock() entry, ok := antigravityReasoningReplayEntries[key] if !ok { + if !reserveOnMiss { + return nil, AntigravityReasoningReplaySnapshot{loaded: true, evictionEpoch: antigravityReasoningReplayEvictionEpoch}, false, nil + } return nil, reserveAntigravityReasoningReplayAbsentLocked(key, now), false, nil } if now.Sub(entry.Timestamp) > AntigravityReasoningReplayCacheTTL { antigravityReasoningReplayEvictionEpoch++ delete(antigravityReasoningReplayEntries, key) + if !reserveOnMiss { + return nil, AntigravityReasoningReplaySnapshot{loaded: true, evictionEpoch: antigravityReasoningReplayEvictionEpoch}, false, nil + } return nil, reserveAntigravityReasoningReplayAbsentLocked(key, now), false, nil } entry.Timestamp = now @@ -425,6 +453,48 @@ func newAntigravityReasoningReplayGeneration() string { return fmt.Sprintf("%x", nonce[:]) } +func marshalReasoningReplayRawJSONArray(items [][]byte) ([]byte, error) { + doc := ojson.NewDocString("[]") + for i, item := range items { + trimmed := bytes.TrimSpace(item) + if len(trimmed) == 0 || !ojson.ValidBytes(trimmed) { + return nil, fmt.Errorf("invalid replay item json at index %d", i) + } + if errSet := doc.SetRawBytes("-1", trimmed); errSet != nil { + return nil, errSet + } + } + return doc.Bytes(), nil +} + +func unmarshalReasoningReplayRawJSONArray(raw []byte) ([][]byte, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || !ojson.ValidBytes(trimmed) { + return nil, fmt.Errorf("invalid reasoning replay KV payload (please upgrade CLIProxyAPI to a matching version)") + } + root := util.ParseGJSONBytesNoCopy(trimmed) + if !root.IsArray() { + return nil, fmt.Errorf("unsupported reasoning replay KV format (please upgrade CLIProxyAPI to a matching version)") + } + elems := root.Array() + items := make([][]byte, 0, len(elems)) + for _, elem := range elems { + switch { + case elem.IsObject(): + items = append(items, []byte(elem.Raw)) + case elem.Type == ojson.String: + decoded, errDecode := base64.StdEncoding.DecodeString(elem.String()) + if errDecode != nil { + return nil, fmt.Errorf("invalid legacy base64 reasoning replay item (please upgrade CLIProxyAPI): %w", errDecode) + } + items = append(items, decoded) + default: + return nil, fmt.Errorf("unsupported reasoning replay KV element type (please upgrade CLIProxyAPI to a matching version)") + } + } + return items, nil +} + func marshalAntigravityReasoningReplayHomeValue(items [][]byte, branch string) ([]byte, error) { if branch == "" { branch = newAntigravityReasoningReplayGeneration() @@ -436,11 +506,14 @@ func marshalAntigravityReasoningReplayHomeValue(items [][]byte, branch string) ( stored := make([][]byte, 0, len(items)+1) stored = append(stored, doc.Bytes()) stored = append(stored, items...) - return json.Marshal(stored) + return marshalReasoningReplayRawJSONArray(stored) } func decodeAntigravityReasoningReplayHomeValue(raw []byte) (items [][]byte, deleted bool, generation, branch string, ok bool) { - if errUnmarshal := json.Unmarshal(raw, &items); errUnmarshal != nil { + var errUnmarshal error + items, errUnmarshal = unmarshalReasoningReplayRawJSONArray(raw) + if errUnmarshal != nil { + log.Warnf("antigravity reasoning replay KV decode failed: %v", errUnmarshal) return nil, false, "", "", false } if len(items) == 0 || strings.TrimSpace(ojson.GetBytesNoCopy(items[0], "type").String()) != antigravityReasoningReplayGenerationItemType { @@ -470,7 +543,7 @@ func newAntigravityReasoningReplayTombstone() []byte { _ = doc.Set("type", antigravityReasoningReplayGenerationItemType) _ = doc.Set("generation", newAntigravityReasoningReplayGeneration()) _ = doc.Set("branch", newAntigravityReasoningReplayGeneration()) - raw, _ := json.Marshal([][]byte{doc.Bytes()}) + raw, _ := marshalReasoningReplayRawJSONArray([][]byte{doc.Bytes()}) return raw } diff --git a/internal/cache/antigravity_reasoning_replay_cache_test.go b/internal/cache/antigravity_reasoning_replay_cache_test.go index c0215c7f919..9cef703e984 100644 --- a/internal/cache/antigravity_reasoning_replay_cache_test.go +++ b/internal/cache/antigravity_reasoning_replay_cache_test.go @@ -3,12 +3,12 @@ package cache import ( "bytes" "context" - "encoding/json" "fmt" "sync" "testing" "time" + "github.com/MoeForge/moego/base64" "github.com/MoeForge/moego/ojson" homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home" ) @@ -494,21 +494,29 @@ func TestAntigravityReasoningReplayLocalAbsenceReservationsStayWithinEntryBound( } } -func TestAntigravityReasoningReplayHomeWritesRemainLegacyArrayReadable(t *testing.T) { +func TestAntigravityReasoningReplayHomeWritesUnwrappedJSONArrayAndReadsLegacyBase64(t *testing.T) { client := newFakeAntigravityReasoningReplayKVClient() useFakeAntigravityReasoningReplayKVClient(t, client, true) - const model, session = "gemini-3.6-flash-high", "home-legacy-readable" + const model, session = "gemini-3.6-flash-high", "home-unwrapped-json-array" item := antigravityReplayTestItem("legacy-readable-signature-123456") if !CacheAntigravityReasoningReplayItems(model, session, [][]byte{item}) { t.Fatal("Home write failed") } raw := client.values[antigravityReasoningReplayKVKey(model, session)] - var legacyItems [][]byte - if errUnmarshal := json.Unmarshal(raw, &legacyItems); errUnmarshal != nil { - t.Fatalf("new Home value is not readable as legacy [][]byte: %v", errUnmarshal) + root := ojson.ParseBytes(raw) + if !root.IsArray() || len(root.Array()) != 2 || !root.Get("0").IsObject() || !root.Get("1").IsObject() { + t.Fatalf("new Home value must be an unwrapped JSON object array without base64 double encoding: %s", raw) } - if len(legacyItems) != 2 || ojson.GetBytes(legacyItems[0], "type").String() != antigravityReasoningReplayGenerationItemType || !bytes.Contains(legacyItems[1], []byte("legacy-readable-signature")) { - t.Fatalf("legacy-readable Home array malformed: %q", legacyItems) + if root.Get("0.type").String() != antigravityReasoningReplayGenerationItemType || root.Get("1.thoughtSignature").String() != "legacy-readable-signature-123456" { + t.Fatalf("unwrapped Home array malformed: %s", raw) + } + + // Verify backward-compatible decoding of legacy base64-encoded [][]byte arrays. + legacyRaw := []byte(`["` + base64.StdEncoding.EncodeToString(item) + `"]`) + client.values[antigravityReasoningReplayKVKey(model, session)] = legacyRaw + gotLegacy, _, foundLegacy, errLegacy := GetAntigravityReasoningReplayItemsWithSnapshotRequired(context.Background(), model, session) + if errLegacy != nil || !foundLegacy || len(gotLegacy) != 1 || ojson.GetBytes(gotLegacy[0], "thoughtSignature").String() != "legacy-readable-signature-123456" { + t.Fatalf("legacy base64 Home array read = %q, found=%v err=%v", gotLegacy, foundLegacy, errLegacy) } } @@ -518,7 +526,7 @@ func TestAntigravityReasoningReplayHomeReadNormalizesAndRejectsMixedInvalidChain const model, session = "gemini-3.6-flash-high", "home-validation" key := antigravityReasoningReplayKVKey(model, session) valid := []byte(`{"type":"function_call_part","name":"run","args":{"b":2,"a":1},"targetOccurrence":1,"thoughtSignature":"valid-home-signature-123456"}`) - raw, errMarshal := json.Marshal([][]byte{valid}) + raw, errMarshal := marshalReasoningReplayRawJSONArray([][]byte{valid}) if errMarshal != nil { t.Fatal(errMarshal) } @@ -534,7 +542,7 @@ func TestAntigravityReasoningReplayHomeReadNormalizesAndRejectsMixedInvalidChain t.Fatalf("valid Home read expire count = %d, want 1", client.expireCount) } - invalidRaw, errInvalidMarshal := json.Marshal([][]byte{valid, []byte(`{"type":"unknown"}`)}) + invalidRaw, errInvalidMarshal := marshalReasoningReplayRawJSONArray([][]byte{valid, []byte(`{"type":"unknown"}`)}) if errInvalidMarshal != nil { t.Fatal(errInvalidMarshal) } diff --git a/internal/cache/codex_reasoning_replay_cache.go b/internal/cache/codex_reasoning_replay_cache.go index f9898789816..8ff8d640f95 100644 --- a/internal/cache/codex_reasoning_replay_cache.go +++ b/internal/cache/codex_reasoning_replay_cache.go @@ -2,7 +2,6 @@ package cache import ( "context" - "encoding/json" "sort" "strings" "sync" @@ -88,7 +87,7 @@ func CacheCodexReasoningReplayItemsBestEffort(ctx context.Context, modelName, se log.Errorf("home kv best-effort codex reasoning replay set failed prefix=cpa:codex:*: %v", errClient) return false } - raw, errMarshal := json.Marshal(normalized) + raw, errMarshal := marshalReasoningReplayRawJSONArray(normalized) if errMarshal != nil { log.Errorf("home kv best-effort codex reasoning replay set failed prefix=cpa:codex:*: %v", errMarshal) return false @@ -146,13 +145,15 @@ func AppendCodexReasoningReplayItemsBestEffort(ctx context.Context, modelName, s } var existing [][]byte if found { - if errUnmarshal := json.Unmarshal(existingRaw, &existing); errUnmarshal != nil { - log.Errorf("home kv best-effort codex reasoning replay append failed prefix=cpa:codex:*: %v", errUnmarshal) + var errUnmarshal error + existing, errUnmarshal = unmarshalReasoningReplayRawJSONArray(existingRaw) + if errUnmarshal != nil { + log.Errorf("home kv best-effort codex reasoning replay append failed prefix=cpa:codex:* (please upgrade CLIProxyAPI): %v", errUnmarshal) return false } } combined := appendCodexReasoningReplayTurn(existing, normalized) - raw, errMarshal := json.Marshal(combined) + raw, errMarshal := marshalReasoningReplayRawJSONArray(combined) if errMarshal != nil { log.Errorf("home kv best-effort codex reasoning replay append failed prefix=cpa:codex:*: %v", errMarshal) return false @@ -267,8 +268,9 @@ func GetCodexReasoningReplayItemsRequired(ctx context.Context, modelName, sessio if errGet != nil || !found { return nil, false, errGet } - var homeItems [][]byte - if errUnmarshal := json.Unmarshal(raw, &homeItems); errUnmarshal != nil { + homeItems, errUnmarshal := unmarshalReasoningReplayRawJSONArray(raw) + if errUnmarshal != nil { + log.Warnf("codex reasoning replay KV decode failed (please upgrade CLIProxyAPI): %v", errUnmarshal) return nil, false, errUnmarshal } if _, errExpire := client.KVExpire(ctx, codexReasoningReplayKVKey(modelName, sessionKey), CodexReasoningReplayCacheTTL); errExpire != nil { diff --git a/internal/cache/codex_reasoning_replay_cache_test.go b/internal/cache/codex_reasoning_replay_cache_test.go index 441a2d928d4..3a01a89a07e 100644 --- a/internal/cache/codex_reasoning_replay_cache_test.go +++ b/internal/cache/codex_reasoning_replay_cache_test.go @@ -3,14 +3,13 @@ package cache import ( "bytes" "context" - "encoding/json" "errors" "fmt" - "github.com/MoeForge/moego/base64" "sync" "testing" "time" + "github.com/MoeForge/moego/base64" "github.com/MoeForge/moego/ojson" homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home" ) @@ -130,7 +129,7 @@ func validCodexReasoningReplayItemForTest(seed byte) []byte { func mustCodexReasoningReplayJSON(t *testing.T, items [][]byte) []byte { t.Helper() - raw, errMarshal := json.Marshal(items) + raw, errMarshal := marshalReasoningReplayRawJSONArray(items) if errMarshal != nil { t.Fatalf("marshal replay items: %v", errMarshal) } diff --git a/internal/cache/xai_reasoning_replay_cache.go b/internal/cache/xai_reasoning_replay_cache.go index b786aeba711..b33614cc2b9 100644 --- a/internal/cache/xai_reasoning_replay_cache.go +++ b/internal/cache/xai_reasoning_replay_cache.go @@ -2,7 +2,6 @@ package cache import ( "context" - "encoding/json" "sort" "strings" "sync" @@ -101,7 +100,7 @@ func StoreXAIReasoningReplayItems(ctx context.Context, modelName, sessionKey str log.Errorf("home kv best-effort xai reasoning replay set failed prefix=cpa:xai:*: %v", errClient) return XAIReasoningReplayStoreBackendError } - raw, errMarshal := json.Marshal(normalized) + raw, errMarshal := marshalReasoningReplayRawJSONArray(normalized) if errMarshal != nil { log.Errorf("home kv best-effort xai reasoning replay set failed prefix=cpa:xai:*: %v", errMarshal) return XAIReasoningReplayStoreBackendError @@ -164,8 +163,9 @@ func GetXAIReasoningReplayItemsRequired(ctx context.Context, modelName, sessionK if errGet != nil || !found { return nil, false, errGet } - var homeItems [][]byte - if errUnmarshal := json.Unmarshal(raw, &homeItems); errUnmarshal != nil { + homeItems, errUnmarshal := unmarshalReasoningReplayRawJSONArray(raw) + if errUnmarshal != nil { + log.Warnf("xai reasoning replay KV decode failed (please upgrade CLIProxyAPI): %v", errUnmarshal) return nil, false, errUnmarshal } if _, errExpire := client.KVExpire(ctx, xaiReasoningReplayKVKey(modelName, sessionKey), XAIReasoningReplayCacheTTL); errExpire != nil { diff --git a/internal/cache/xai_reasoning_replay_cache_test.go b/internal/cache/xai_reasoning_replay_cache_test.go index e3faf53fd42..cdeefe1388c 100644 --- a/internal/cache/xai_reasoning_replay_cache_test.go +++ b/internal/cache/xai_reasoning_replay_cache_test.go @@ -3,12 +3,11 @@ package cache import ( "context" "crypto/sha256" - "encoding/json" "errors" - "github.com/MoeForge/moego/base64" "testing" "time" + "github.com/MoeForge/moego/base64" "github.com/MoeForge/moego/ojson" homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home" ) @@ -90,7 +89,7 @@ func useFakeXAIReasoningReplayKVClient(t *testing.T, client *fakeXAIReasoningRep func mustXAIReasoningReplayJSON(t *testing.T, items [][]byte) []byte { t.Helper() - raw, err := json.Marshal(items) + raw, err := marshalReasoningReplayRawJSONArray(items) if err != nil { t.Fatalf("marshal replay items: %v", err) } diff --git a/internal/client/musecode/models.go b/internal/client/musecode/models.go new file mode 100644 index 00000000000..b09ff16b0d3 --- /dev/null +++ b/internal/client/musecode/models.go @@ -0,0 +1,1232 @@ +package musecode + +import ( + "net/http" + "sort" + "strings" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" +) + +// HomeModelsLoader loads scoped models when Home mode is active. +// Returning false indicates the loader has already written an HTTP error response. +type HomeModelsLoader func(c *gin.Context) ([]ModelInput, bool) + +// ModelListWriter writes the final serialized model catalog response. +type ModelListWriter func(c *gin.Context, sourceFormat string, payload any) + +// ModelRoute describes one provider-specific route serving a public model ID. +type ModelRoute struct { + Provider string + MetadataModelID string + Created int64 + OwnedBy string + Type string + DisplayName string + Description string + ContextLength int + MaxContextLength int + MaxCompletionTokens int + InputTokenLimit int + OutputTokenLimit int + Thinking *registry.ThinkingSupport + ExplicitThinking bool + SupportedInputModalities []string + ExplicitInputModalities bool + SupportedOutputModalities []string + HasOutputModalities bool +} + +// ModelInput represents a normalized available model entry used to construct +// the Muse Code /muse-code/models catalog. +type ModelInput struct { + ID string + MetadataModelID string + Created int64 + OwnedBy string + Type string + DisplayName string + Description string + ContextLength int + MaxContextLength int + MaxCompletionTokens int + InputTokenLimit int + OutputTokenLimit int + Thinking *registry.ThinkingSupport + ExplicitThinking bool + SupportedInputModalities []string + ExplicitInputModalities bool + SupportedOutputModalities []string + HasOutputModalities bool + Routes []ModelRoute +} + +// Response represents the /muse-code/models response envelope. +type Response struct { + Object string `json:"object"` + Data []ModelEntry `json:"data"` +} + +// ModelEntry represents a single model record inside Response.Data. +type ModelEntry struct { + ID string `json:"id"` + Object string `json:"object"` + Created int64 `json:"created"` + OwnedBy string `json:"owned_by"` + Metadata ModelMetadata `json:"metadata"` +} + +// ModelMetadata wraps provider-client metadata for a model entry. +type ModelMetadata struct { + MuseCode MuseCodeMetadata `json:"muse-code"` +} + +// MuseCodeMetadata describes model capabilities and defaults consumed by Muse Code CLI. +type MuseCodeMetadata struct { + Name string `json:"name"` + Family string `json:"family"` + ReleaseDate string `json:"release_date"` + IsHidden bool `json:"is_hidden"` + Attachment bool `json:"attachment"` + Reasoning bool `json:"reasoning"` + Temperature bool `json:"temperature"` + ToolCall bool `json:"tool_call"` + Modalities Modalities `json:"modalities"` + Limit *Limits `json:"limit,omitempty"` + Options Options `json:"options"` + Variants map[string]EffortVariant `json:"variants,omitempty"` + Description *string `json:"description"` + BackgroundAgentModel string `json:"background_agent_model,omitempty"` +} + +// Modalities lists supported input and output content modalities. +type Modalities struct { + Input []string `json:"input"` + Output []string `json:"output"` +} + +// Limits describes context window and max output token limits. +type Limits struct { + Context int `json:"context,omitempty"` + Output int `json:"output,omitempty"` +} + +// Options contains default request options injected by Muse Code CLI. +type Options struct { + ReasoningEffort string `json:"reasoningEffort,omitempty"` + ForceReasoning bool `json:"forceReasoning,omitempty"` + Include []string `json:"include,omitempty"` + Temperature *float64 `json:"temperature,omitempty"` + TopP *float64 `json:"top_p,omitempty"` +} + +// EffortVariant describes a selectable reasoning effort variant. +type EffortVariant struct { + ReasoningEffort string `json:"reasoningEffort"` +} + +var canonicalReasoningOrder = []string{ + "minimal", + "low", + "medium", + "high", + "xhigh", + "max", + "ultra", +} + +var allowedReasoningLevels = map[string]struct{}{ + "minimal": {}, + "low": {}, + "medium": {}, + "high": {}, + "xhigh": {}, + "max": {}, + "ultra": {}, +} + +var budgetCandidateLevels = []string{ + "minimal", + "low", + "medium", + "high", + "xhigh", + "max", +} + +// SetModelListHooks configures optional hooks for loading Home-mode models and +// writing intercepted model catalog responses. +func (h *Handler) SetModelListHooks(homeLoader HomeModelsLoader, responseWriter ModelListWriter) { + if h == nil { + return + } + h.mu.Lock() + h.homeModelsLoader = homeLoader + h.modelListWriter = responseWriter + h.mu.Unlock() +} + +// HandleModels serves GET /muse-code/models from CPA's available model catalog +// (or the configured Home loader when Home mode is enabled). +func (h *Handler) HandleModels(c *gin.Context) { + if c == nil || c.Request == nil { + return + } + if c.Request.Method != http.MethodGet { + c.AbortWithStatus(http.StatusNotFound) + return + } + + var homeEnabled bool + var homeLoader HomeModelsLoader + var listWriter ModelListWriter + + if h != nil { + h.mu.RLock() + cfg := h.cfg + authManager := h.authManager + homeLoader = h.homeModelsLoader + listWriter = h.modelListWriter + h.mu.RUnlock() + homeEnabled = (authManager != nil && authManager.HomeEnabled()) || (cfg != nil && cfg.Home.Enabled) + } + + var inputs []ModelInput + if homeEnabled { + if homeLoader == nil { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "home control center unavailable"}) + return + } + var ok bool + inputs, ok = homeLoader(c) + if !ok { + return + } + } else { + inputs = ModelInputsFromGlobalRegistry(registry.GetGlobalRegistry()) + } + + payload := BuildModelsResponse(inputs) + body, errMarshal := MarshalCompact(payload) + if errMarshal != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": errMarshal.Error()}) + return + } + + if listWriter != nil { + listWriter(c, "openai", body) + return + } + c.Data(http.StatusOK, "application/json; charset=utf-8", body) +} + +// ModelInputsFromGlobalRegistry extracts ModelInput entries from reg, preserving +// per-provider route metadata so conflicting capabilities merge conservatively. +func ModelInputsFromGlobalRegistry(reg *registry.ModelRegistry) []ModelInput { + if reg == nil { + return nil + } + infos := reg.GetAvailableModelInfos() + inputs := ModelInputsFromRegistry(infos) + for i := range inputs { + providers := reg.GetModelProviders(inputs[i].ID) + if len(providers) == 0 { + continue + } + routes := make([]ModelRoute, 0, len(providers)) + for _, provider := range providers { + pInfo := reg.GetModelInfo(inputs[i].ID, provider) + if pInfo == nil { + continue + } + routes = append(routes, ModelRoute{ + Provider: provider, + MetadataModelID: pInfo.MetadataModelID, + Created: pInfo.Created, + OwnedBy: pInfo.OwnedBy, + Type: pInfo.Type, + DisplayName: pInfo.DisplayName, + Description: pInfo.Description, + ContextLength: pInfo.ContextLength, + MaxContextLength: pInfo.MaxContextLength, + MaxCompletionTokens: pInfo.MaxCompletionTokens, + InputTokenLimit: pInfo.InputTokenLimit, + OutputTokenLimit: pInfo.OutputTokenLimit, + Thinking: pInfo.Thinking, + ExplicitThinking: pInfo.ExplicitThinking, + SupportedInputModalities: append([]string(nil), pInfo.SupportedInputModalities...), + ExplicitInputModalities: pInfo.ExplicitInputModalities, + SupportedOutputModalities: append([]string(nil), pInfo.SupportedOutputModalities...), + HasOutputModalities: len(pInfo.SupportedOutputModalities) > 0, + }) + } + if len(routes) > 0 { + inputs[i].Routes = routes + } + } + return inputs +} + +// ModelInputsFromRegistry converts registry ModelInfo records into ModelInput entries. +func ModelInputsFromRegistry(infos []*registry.ModelInfo) []ModelInput { + if len(infos) == 0 { + return nil + } + inputs := make([]ModelInput, 0, len(infos)) + for _, info := range infos { + if info == nil || strings.TrimSpace(info.ID) == "" { + continue + } + inputs = append(inputs, ModelInput{ + ID: info.ID, + MetadataModelID: info.MetadataModelID, + Created: info.Created, + OwnedBy: info.OwnedBy, + Type: info.Type, + DisplayName: info.DisplayName, + Description: info.Description, + ContextLength: info.ContextLength, + MaxContextLength: info.MaxContextLength, + MaxCompletionTokens: info.MaxCompletionTokens, + InputTokenLimit: info.InputTokenLimit, + OutputTokenLimit: info.OutputTokenLimit, + Thinking: info.Thinking, + ExplicitThinking: info.ExplicitThinking, + SupportedInputModalities: append([]string(nil), info.SupportedInputModalities...), + ExplicitInputModalities: info.ExplicitInputModalities, + SupportedOutputModalities: append([]string(nil), info.SupportedOutputModalities...), + HasOutputModalities: len(info.SupportedOutputModalities) > 0, + }) + } + return inputs +} + +// BuildModelsResponse builds a Muse Code compatible model catalog from the given inputs. +func BuildModelsResponse(inputs []ModelInput) Response { + deduped := make([]ModelInput, 0, len(inputs)) + seen := make(map[string]struct{}, len(inputs)) + availableIDs := make(map[string]struct{}, len(inputs)) + + for _, input := range inputs { + id := strings.TrimSpace(input.ID) + if id == "" { + continue + } + input.ID = id + if _, exists := seen[id]; exists { + continue + } + seen[id] = struct{}{} + availableIDs[id] = struct{}{} + deduped = append(deduped, input) + } + + sort.Slice(deduped, func(i, j int) bool { + return deduped[i].ID < deduped[j].ID + }) + + data := make([]ModelEntry, 0, len(deduped)) + for _, input := range deduped { + data = append(data, buildModelEntry(input, availableIDs)) + } + + return Response{ + Object: "list", + Data: data, + } +} + +// MarshalCompact encodes resp as compact JSON via *ojson.Doc. +func MarshalCompact(resp Response) ([]byte, error) { + doc := ojson.NewDocString(`{"object":"list","data":[]}`) + object := strings.TrimSpace(resp.Object) + if object == "" { + object = "list" + } + if errSet := doc.Set("object", object); errSet != nil { + return nil, errSet + } + + for _, entry := range resp.Data { + entryDoc, errEntry := marshalModelEntryDoc(entry) + if errEntry != nil { + return nil, errEntry + } + if errAppend := doc.SetRawBytes("data.-1", entryDoc.Bytes()); errAppend != nil { + return nil, errAppend + } + } + + return doc.Bytes(), nil +} + +func marshalModelEntryDoc(entry ModelEntry) (*ojson.Doc, error) { + entryDoc := ojson.NewDocString(`{"id":"","object":"model","created":0,"owned_by":"","metadata":{"muse-code":{}}}`) + if err := entryDoc.Set("id", entry.ID); err != nil { + return nil, err + } + obj := entry.Object + if obj == "" { + obj = "model" + } + if err := entryDoc.Set("object", obj); err != nil { + return nil, err + } + if err := entryDoc.Set("created", entry.Created); err != nil { + return nil, err + } + if err := entryDoc.Set("owned_by", entry.OwnedBy); err != nil { + return nil, err + } + + mc := entry.Metadata.MuseCode + mcDoc := ojson.NewDocString(`{}`) + if err := mcDoc.Set("name", mc.Name); err != nil { + return nil, err + } + if err := mcDoc.Set("family", mc.Family); err != nil { + return nil, err + } + if err := mcDoc.Set("release_date", mc.ReleaseDate); err != nil { + return nil, err + } + if err := mcDoc.Set("is_hidden", mc.IsHidden); err != nil { + return nil, err + } + if err := mcDoc.Set("attachment", mc.Attachment); err != nil { + return nil, err + } + if err := mcDoc.Set("reasoning", mc.Reasoning); err != nil { + return nil, err + } + if err := mcDoc.Set("temperature", mc.Temperature); err != nil { + return nil, err + } + if err := mcDoc.Set("tool_call", mc.ToolCall); err != nil { + return nil, err + } + + modalitiesDoc := ojson.NewDocString(`{"input":[],"output":[]}`) + for _, mod := range mc.Modalities.Input { + if err := modalitiesDoc.Set("input.-1", mod); err != nil { + return nil, err + } + } + for _, mod := range mc.Modalities.Output { + if err := modalitiesDoc.Set("output.-1", mod); err != nil { + return nil, err + } + } + if err := mcDoc.SetRawBytes("modalities", modalitiesDoc.Bytes()); err != nil { + return nil, err + } + + if mc.Limit != nil { + limitDoc := ojson.NewDocString(`{}`) + if mc.Limit.Context > 0 { + if err := limitDoc.Set("context", mc.Limit.Context); err != nil { + return nil, err + } + } + if mc.Limit.Output > 0 { + if err := limitDoc.Set("output", mc.Limit.Output); err != nil { + return nil, err + } + } + if err := mcDoc.SetRawBytes("limit", limitDoc.Bytes()); err != nil { + return nil, err + } + } + + optsDoc := ojson.NewDocString(`{}`) + if mc.Options.ReasoningEffort != "" { + if err := optsDoc.Set("reasoningEffort", mc.Options.ReasoningEffort); err != nil { + return nil, err + } + } + if mc.Options.ForceReasoning { + if err := optsDoc.Set("forceReasoning", true); err != nil { + return nil, err + } + } + for _, inc := range mc.Options.Include { + if err := optsDoc.Set("include.-1", inc); err != nil { + return nil, err + } + } + if mc.Options.Temperature != nil { + if err := optsDoc.Set("temperature", *mc.Options.Temperature); err != nil { + return nil, err + } + } + if mc.Options.TopP != nil { + if err := optsDoc.Set("top_p", *mc.Options.TopP); err != nil { + return nil, err + } + } + if err := mcDoc.SetRawBytes("options", optsDoc.Bytes()); err != nil { + return nil, err + } + + if len(mc.Variants) > 0 { + varDoc := ojson.NewDocString(`{}`) + for _, key := range orderedVariantKeys(mc.Variants) { + vDoc := ojson.NewDocString(`{}`) + if err := vDoc.Set("reasoningEffort", mc.Variants[key].ReasoningEffort); err != nil { + return nil, err + } + if err := varDoc.SetRawBytes(ojson.Escape(key), vDoc.Bytes()); err != nil { + return nil, err + } + } + if err := mcDoc.SetRawBytes("variants", varDoc.Bytes()); err != nil { + return nil, err + } + } + + if mc.Description != nil { + if err := mcDoc.Set("description", *mc.Description); err != nil { + return nil, err + } + } else { + if err := mcDoc.Set("description", nil); err != nil { + return nil, err + } + } + + if mc.BackgroundAgentModel != "" { + if err := mcDoc.Set("background_agent_model", mc.BackgroundAgentModel); err != nil { + return nil, err + } + } + + if err := entryDoc.SetRawBytes("metadata.muse-code", mcDoc.Bytes()); err != nil { + return nil, err + } + return entryDoc, nil +} + +func orderedVariantKeys(variants map[string]EffortVariant) []string { + keys := make([]string, 0, len(variants)) + seen := make(map[string]struct{}, len(variants)) + for _, level := range canonicalReasoningOrder { + if _, exists := variants[level]; exists { + keys = append(keys, level) + seen[level] = struct{}{} + } + } + var extra []string + for key := range variants { + if _, exists := seen[key]; !exists { + extra = append(extra, key) + } + } + sort.Strings(extra) + return append(keys, extra...) +} + +type resolvedRoute struct { + metadataModelID string + ownedBy string + modelType string + displayName string + description string + created int64 + inputModalities []string + outputModalities []string + isHidden bool + contextLimit int + outputLimit int + reasoningLevels []string +} + +func buildModelEntry(input ModelInput, availableIDs map[string]struct{}) ModelEntry { + routes := input.Routes + if len(routes) == 0 { + routes = []ModelRoute{ + { + MetadataModelID: input.MetadataModelID, + Created: input.Created, + OwnedBy: input.OwnedBy, + Type: input.Type, + DisplayName: input.DisplayName, + Description: input.Description, + ContextLength: input.ContextLength, + MaxContextLength: input.MaxContextLength, + MaxCompletionTokens: input.MaxCompletionTokens, + InputTokenLimit: input.InputTokenLimit, + OutputTokenLimit: input.OutputTokenLimit, + Thinking: input.Thinking, + ExplicitThinking: input.ExplicitThinking, + SupportedInputModalities: input.SupportedInputModalities, + ExplicitInputModalities: input.ExplicitInputModalities, + SupportedOutputModalities: input.SupportedOutputModalities, + HasOutputModalities: input.HasOutputModalities, + }, + } + } + + resolved := make([]resolvedRoute, 0, len(routes)) + for _, route := range routes { + resolved = append(resolved, resolveSingleRoute(input.ID, route)) + } + + var created int64 + for _, r := range resolved { + if created <= 0 && r.created > 0 { + created = r.created + } + } + if created <= 0 { + created = input.Created + } + + var ownedBy string + for _, r := range resolved { + if ownedBy == "" && r.ownedBy != "" { + ownedBy = r.ownedBy + } + } + if ownedBy == "" { + ownedBy = strings.TrimSpace(input.OwnedBy) + } + + var modelType string + for _, r := range resolved { + if modelType == "" && r.modelType != "" { + modelType = r.modelType + } + } + if modelType == "" { + modelType = strings.TrimSpace(input.Type) + } + + // Only propagate a canonical identity when every route agrees on it. + canonicalID := strings.TrimSpace(resolved[0].metadataModelID) + for i := 1; i < len(resolved); i++ { + if !strings.EqualFold(strings.TrimSpace(resolved[i].metadataModelID), canonicalID) { + canonicalID = "" + break + } + } + + if ownedBy == "" { + ownedBy = inferOwnedBy(input.ID, canonicalID, modelType, "") + } + + var displayName string + for _, r := range resolved { + if displayName == "" && r.displayName != "" { + displayName = r.displayName + } + } + if displayName == "" { + displayName = strings.TrimSpace(input.DisplayName) + } + if displayName == "" { + displayName = input.ID + } + + var descriptionText string + for _, r := range resolved { + if descriptionText == "" && r.description != "" { + descriptionText = r.description + } + } + if descriptionText == "" { + descriptionText = strings.TrimSpace(input.Description) + } + var description *string + if descriptionText != "" { + description = &descriptionText + } + + // Merge capabilities conservatively across all routes so no unavailable + // capability or excess context limit is advertised. + inputModalities := append([]string(nil), resolved[0].inputModalities...) + outputModalities := append([]string(nil), resolved[0].outputModalities...) + reasoningLevels := append([]string(nil), resolved[0].reasoningLevels...) + contextLimit := resolved[0].contextLimit + outputLimit := resolved[0].outputLimit + anyHidden := resolved[0].isHidden + + for i := 1; i < len(resolved); i++ { + r := resolved[i] + inputModalities = intersectStringSlices(inputModalities, r.inputModalities) + outputModalities = intersectStringSlices(outputModalities, r.outputModalities) + reasoningLevels = intersectStringSlices(reasoningLevels, r.reasoningLevels) + contextLimit = minPositive(contextLimit, r.contextLimit) + outputLimit = minPositive(outputLimit, r.outputLimit) + if r.isHidden { + anyHidden = true + } + } + + if len(inputModalities) == 0 { + inputModalities = []string{"text"} + } + + isHidden := false + if len(outputModalities) > 0 { + isHidden = !containsModality(outputModalities, "text") + } else { + // Disjoint output modalities across routes (for example text vs image): + // hide the model conservatively and keep output modalities consistent with isHidden. + isHidden = anyHidden || true + for _, r := range resolved { + if !containsModality(r.outputModalities, "text") && len(r.outputModalities) > 0 { + outputModalities = append([]string(nil), r.outputModalities...) + break + } + } + if len(outputModalities) == 0 { + outputModalities = []string{"image"} + } + } + + if isHidden { + reasoningLevels = nil + } + + toolCall := !isHidden + attachment := hasNonTextModality(inputModalities) + family := inferFamily(input.ID, canonicalID, ownedBy, modelType, isHidden) + + releaseDate := "" + if created > 0 { + releaseDate = time.Unix(created, 0).UTC().Format("2006-01-02") + } + + var limit *Limits + if contextLimit > 0 || outputLimit > 0 { + limit = &Limits{ + Context: contextLimit, + Output: outputLimit, + } + } + + reasoning := len(reasoningLevels) > 0 + temperature := !reasoning && !isHidden + + var variants map[string]EffortVariant + var options Options + if reasoning { + variants = make(map[string]EffortVariant, len(reasoningLevels)) + for _, level := range reasoningLevels { + variants[level] = EffortVariant{ReasoningEffort: level} + } + defaultEffort := selectDefaultEffort(reasoningLevels, family) + options = Options{ + ReasoningEffort: defaultEffort, + ForceReasoning: true, + Include: []string{"reasoning.encrypted_content"}, + } + if family == "avocado" { + defaultTemp := 0.9 + defaultTopP := 0.9 + options.Temperature = &defaultTemp + options.TopP = &defaultTopP + } + } + + backgroundAgentModel := "" + if strings.HasPrefix(strings.ToLower(input.ID), "muse-wonder-") { + if _, exists := availableIDs["muse-spark-1.3"]; exists { + backgroundAgentModel = "muse-spark-1.3" + } + } + + return ModelEntry{ + ID: input.ID, + Object: "model", + Created: created, + OwnedBy: ownedBy, + Metadata: ModelMetadata{ + MuseCode: MuseCodeMetadata{ + Name: displayName, + Family: family, + ReleaseDate: releaseDate, + IsHidden: isHidden, + Attachment: attachment, + Reasoning: reasoning, + Temperature: temperature, + ToolCall: toolCall, + Modalities: Modalities{Input: inputModalities, Output: outputModalities}, + Limit: limit, + Options: options, + Variants: variants, + Description: description, + BackgroundAgentModel: backgroundAgentModel, + }, + }, + } +} + +func resolveSingleRoute(modelID string, route ModelRoute) resolvedRoute { + metaID := strings.TrimSpace(route.MetadataModelID) + staticInfo := resolveStaticModelInfo(modelID, metaID) + + created := route.Created + if created <= 0 && staticInfo != nil { + created = staticInfo.Created + } + + modelType := strings.TrimSpace(route.Type) + if modelType == "" && staticInfo != nil { + modelType = strings.TrimSpace(staticInfo.Type) + } + + ownedBy := strings.TrimSpace(route.OwnedBy) + if ownedBy == "" && staticInfo != nil { + ownedBy = strings.TrimSpace(staticInfo.OwnedBy) + } + if ownedBy == "" { + ownedBy = inferOwnedBy(modelID, metaID, modelType, route.Provider) + } + + displayName := strings.TrimSpace(route.DisplayName) + if displayName == "" && staticInfo != nil { + displayName = strings.TrimSpace(staticInfo.DisplayName) + } + + description := strings.TrimSpace(route.Description) + if description == "" && staticInfo != nil { + description = strings.TrimSpace(staticInfo.Description) + } + + var inputModalities []string + switch { + case route.ExplicitInputModalities: + inputModalities = normalizeModalities(route.SupportedInputModalities) + case len(route.SupportedInputModalities) > 0: + inputModalities = normalizeModalities(route.SupportedInputModalities) + case staticInfo != nil && len(staticInfo.SupportedInputModalities) > 0: + inputModalities = normalizeModalities(staticInfo.SupportedInputModalities) + } + if len(inputModalities) == 0 { + inputModalities = []string{"text"} + } + + var outputModalities []string + explicitOutput := false + switch { + case len(route.SupportedOutputModalities) > 0: + outputModalities = normalizeModalities(route.SupportedOutputModalities) + explicitOutput = len(outputModalities) > 0 + case route.HasOutputModalities: + outputModalities = []string{"text"} + explicitOutput = true + case staticInfo != nil && len(staticInfo.SupportedOutputModalities) > 0: + outputModalities = normalizeModalities(staticInfo.SupportedOutputModalities) + explicitOutput = len(outputModalities) > 0 + default: + outputModalities = inferOutputModalities(modelID, metaID, modelType) + } + + isHidden := !containsModality(outputModalities, "text") + if !explicitOutput && isNonChatModelType(modelType) { + isHidden = true + } + + contextLimit := firstPositive( + route.MaxContextLength, + route.ContextLength, + route.InputTokenLimit, + ) + if contextLimit <= 0 && staticInfo != nil { + contextLimit = firstPositive( + staticInfo.MaxContextLength, + staticInfo.ContextLength, + staticInfo.InputTokenLimit, + ) + } + outputLimit := firstPositive( + route.MaxCompletionTokens, + route.OutputTokenLimit, + ) + if outputLimit <= 0 && staticInfo != nil { + outputLimit = firstPositive( + staticInfo.MaxCompletionTokens, + staticInfo.OutputTokenLimit, + ) + } + + thinkingSupport := route.Thinking + if !route.ExplicitThinking && thinkingSupport == nil && staticInfo != nil { + thinkingSupport = staticInfo.Thinking + } + + var reasoningLevels []string + if !isHidden { + reasoningLevels = resolveReasoningLevels(thinkingSupport) + } + + return resolvedRoute{ + metadataModelID: metaID, + ownedBy: ownedBy, + modelType: modelType, + displayName: displayName, + description: description, + created: created, + inputModalities: inputModalities, + outputModalities: outputModalities, + isHidden: isHidden, + contextLimit: contextLimit, + outputLimit: outputLimit, + reasoningLevels: reasoningLevels, + } +} + +func resolveStaticModelInfo(id, metadataModelID string) *registry.ModelInfo { + id = strings.TrimSpace(id) + metaID := strings.TrimSpace(metadataModelID) + if metaID != "" { + if info := registry.LookupStaticModelInfo(metaID); info != nil { + return info + } + if !strings.EqualFold(metaID, id) { + return nil + } + } + return registry.LookupStaticModelInfo(id) +} + +func inferOwnedBy(id, metadataModelID, modelType, provider string) string { + lowerType := strings.ToLower(strings.TrimSpace(modelType)) + lowerProvider := normalizeProviderName(provider) + lowerCanonical := strings.ToLower(strings.TrimSpace(metadataModelID)) + lowerID := strings.ToLower(strings.TrimSpace(id)) + + if owned := inferOwnedByFromType(lowerType); owned != "" { + return owned + } + if owned := inferOwnedByFromType(lowerProvider); owned != "" { + return owned + } + if owned := inferOwnedByFromName(lowerCanonical); owned != "" { + return owned + } + if owned := inferOwnedByFromName(lowerID); owned != "" { + return owned + } + if lowerType != "" { + return lowerType + } + if lowerProvider != "" { + return lowerProvider + } + return "custom" +} + +func normalizeProviderName(provider string) string { + p := strings.ToLower(strings.TrimSpace(provider)) + switch p { + case "codex", "codex-free", "codex-plus", "codex-team", "codex-pro": + return "codex" + default: + return p + } +} + +func inferOwnedByFromType(t string) string { + switch t { + case "meta": + return "meta" + case "devin": + return "devin" + case "claude", "antigravity": + return "anthropic" + case "gemini", "vertex", "aistudio", "gemini-cli": + return "google" + case "xai": + return "xai" + case "kimi", "kimi-ai", "kimi.ai", "kimi.com": + return "moonshot" + case "codex", "openai", "openai-image": + return "openai" + default: + return "" + } +} + +func inferOwnedByFromName(name string) string { + if name == "" { + return "" + } + switch { + case strings.HasPrefix(name, "muse-") || strings.HasPrefix(name, "agnes-"): + return "meta" + case strings.HasPrefix(name, "devin/"): + return "devin" + case strings.HasPrefix(name, "claude-"): + return "anthropic" + case strings.HasPrefix(name, "gemini-") || strings.HasPrefix(name, "imagen-"): + return "google" + case strings.HasPrefix(name, "grok-"): + return "xai" + case strings.HasPrefix(name, "kimi-"): + return "moonshot" + case strings.HasPrefix(name, "gpt-") || strings.HasPrefix(name, "o1") || strings.HasPrefix(name, "o3") || strings.HasPrefix(name, "o4") || strings.Contains(name, "codex"): + return "openai" + default: + return "" + } +} + +func inferFamily(id, metadataModelID, ownedBy, modelType string, isHidden bool) string { + lowerID := strings.ToLower(strings.TrimSpace(id)) + lowerCanonical := strings.ToLower(strings.TrimSpace(metadataModelID)) + lowerOwned := strings.ToLower(strings.TrimSpace(ownedBy)) + lowerType := strings.ToLower(strings.TrimSpace(modelType)) + + if isMetaIdentity(lowerCanonical, lowerID, lowerOwned, lowerType) { + if isHidden { + if strings.HasPrefix(lowerCanonical, "muse-image") || strings.HasPrefix(lowerID, "muse-image") { + return "muse-image" + } + if strings.HasPrefix(lowerCanonical, "agnes-image") || strings.HasPrefix(lowerID, "agnes-image") { + return "agnes-image" + } + } + return "avocado" + } + if lowerOwned != "" && lowerOwned != "custom" { + return lowerOwned + } + if lowerType != "" { + return lowerType + } + if lowerOwned != "" { + return lowerOwned + } + return "openai" +} + +func isMetaIdentity(canonical, id, ownedBy, modelType string) bool { + if ownedBy == "meta" || modelType == "meta" { + return true + } + if canonical != "" { + return strings.HasPrefix(canonical, "muse-") || strings.HasPrefix(canonical, "agnes-") + } + return strings.HasPrefix(id, "muse-") || strings.HasPrefix(id, "agnes-") +} + +func normalizeModalities(modalities []string) []string { + if len(modalities) == 0 { + return nil + } + out := make([]string, 0, len(modalities)) + seen := make(map[string]struct{}, len(modalities)) + for _, raw := range modalities { + mod := strings.ToLower(strings.TrimSpace(raw)) + if mod == "" { + continue + } + if _, exists := seen[mod]; exists { + continue + } + seen[mod] = struct{}{} + out = append(out, mod) + } + return out +} + +func inferOutputModalities(id, metadataModelID, modelType string) []string { + lowerType := strings.ToLower(strings.TrimSpace(modelType)) + switch lowerType { + case "openai-image", "image": + return []string{"image"} + case "video": + return []string{"video"} + case "audio", "tts": + return []string{"audio"} + } + + if canonical := strings.ToLower(strings.TrimSpace(metadataModelID)); canonical != "" { + if inferred := inferOutputModalitiesFromName(canonical); len(inferred) > 0 { + return inferred + } + return []string{"text"} + } + + if inferred := inferOutputModalitiesFromName(strings.ToLower(strings.TrimSpace(id))); len(inferred) > 0 { + return inferred + } + return []string{"text"} +} + +func inferOutputModalitiesFromName(name string) []string { + switch { + case strings.HasPrefix(name, "muse-image") || + strings.HasPrefix(name, "agnes-image") || + strings.HasPrefix(name, "gpt-image") || + strings.HasPrefix(name, "imagen-") || + strings.HasPrefix(name, "grok-imagine-image") || + strings.HasPrefix(name, "dall-e"): + return []string{"image"} + case strings.HasPrefix(name, "grok-imagine-video"): + return []string{"video"} + case strings.HasPrefix(name, "grok-tts") || + strings.HasPrefix(name, "grok-voice-tts") || + strings.HasPrefix(name, "tts-"): + return []string{"audio"} + default: + return nil + } +} + +func isNonChatModelType(modelType string) bool { + switch strings.ToLower(strings.TrimSpace(modelType)) { + case "openai-image", "image", "video", "audio", "tts": + return true + default: + return false + } +} + +func containsModality(modalities []string, target string) bool { + for _, mod := range modalities { + if mod == target { + return true + } + } + return false +} + +func hasNonTextModality(modalities []string) bool { + for _, mod := range modalities { + if mod != "text" { + return true + } + } + return false +} + +func resolveReasoningLevels(support *registry.ThinkingSupport) []string { + if support == nil { + return nil + } + if len(support.Levels) > 0 { + out := make([]string, 0, len(support.Levels)) + seen := make(map[string]struct{}, len(support.Levels)) + for _, raw := range support.Levels { + level := strings.ToLower(strings.TrimSpace(raw)) + if _, ok := allowedReasoningLevels[level]; !ok { + continue + } + if _, exists := seen[level]; exists { + continue + } + seen[level] = struct{}{} + out = append(out, level) + } + return out + } + + // Align with thinking.detectModelCapability: budget support requires Min > 0 or Max > 0. + if support.Min <= 0 && support.Max <= 0 { + return nil + } + + type budgetChoice struct { + level string + distance int + } + byClamped := make(map[int]budgetChoice, len(budgetCandidateLevels)) + clampedOrder := make([]int, 0, len(budgetCandidateLevels)) + + for _, level := range budgetCandidateLevels { + rawBudget, ok := thinking.ConvertLevelToBudget(level) + if !ok || rawBudget <= 0 { + continue + } + clamped := rawBudget + if support.Min > 0 && clamped < support.Min { + clamped = support.Min + } + if support.Max > 0 && clamped > support.Max { + clamped = support.Max + } + dist := rawBudget - clamped + if dist < 0 { + dist = -dist + } + if prev, exists := byClamped[clamped]; exists { + if dist < prev.distance { + byClamped[clamped] = budgetChoice{level: level, distance: dist} + } + continue + } + byClamped[clamped] = budgetChoice{level: level, distance: dist} + clampedOrder = append(clampedOrder, clamped) + } + + out := make([]string, 0, len(clampedOrder)) + for _, clamped := range clampedOrder { + out = append(out, byClamped[clamped].level) + } + return out +} + +func selectDefaultEffort(levels []string, family string) string { + preferredOrder := []string{"medium", "high"} + if family == "avocado" { + preferredOrder = []string{"high", "medium"} + } + for _, pref := range preferredOrder { + for _, level := range levels { + if level == pref { + return pref + } + } + } + return levels[0] +} + +func intersectStringSlices(a, b []string) []string { + if len(a) == 0 || len(b) == 0 { + return nil + } + bSet := make(map[string]struct{}, len(b)) + for _, item := range b { + bSet[item] = struct{}{} + } + out := make([]string, 0, len(a)) + seen := make(map[string]struct{}, len(a)) + for _, item := range a { + if _, inB := bSet[item]; inB { + if _, inSeen := seen[item]; !inSeen { + seen[item] = struct{}{} + out = append(out, item) + } + } + } + return out +} + +func firstPositive(values ...int) int { + for _, value := range values { + if value > 0 { + return value + } + } + return 0 +} + +func minPositive(a, b int) int { + switch { + case a <= 0: + return b + case b <= 0: + return a + case b < a: + return b + default: + return a + } +} diff --git a/internal/client/musecode/models_test.go b/internal/client/musecode/models_test.go new file mode 100644 index 00000000000..55fa3a33496 --- /dev/null +++ b/internal/client/musecode/models_test.go @@ -0,0 +1,648 @@ +package musecode + +import ( + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func parseModelsByID(t *testing.T, raw []byte) (string, map[string]ojson.Result) { + t.Helper() + root := ojson.ParseBytes(raw) + obj := root.Get("object").String() + data := root.Get("data") + if !data.IsArray() { + t.Fatalf("expected data array in JSON, got %s", string(raw)) + } + byID := make(map[string]ojson.Result) + data.ForEach(func(_, item ojson.Result) bool { + id := item.Get("id").String() + byID[id] = item + return true + }) + return obj, byID +} + +func stringSliceFromResult(res ojson.Result) []string { + arr := res.Array() + out := make([]string, 0, len(arr)) + for _, item := range arr { + out = append(out, item.String()) + } + return out +} + +func TestBuildModelsResponseSchemaAndVariants(t *testing.T) { + createdTS := time.Date(2026, 11, 8, 0, 0, 0, 0, time.UTC).Unix() + inputs := []ModelInput{ + { + ID: "muse-wonder-1.0", + Created: createdTS, + OwnedBy: "meta", + Type: "meta", + DisplayName: "Muse Wonder 1.0", + Description: "Reasoning flagship ", + ContextLength: 1007997, + MaxCompletionTokens: 128000, + Thinking: ®istry.ThinkingSupport{Levels: []string{"minimal", "low", "medium", "high", "xhigh", "max"}}, + SupportedInputModalities: []string{"text", "image", "video"}, + SupportedOutputModalities: []string{"text"}, + }, + { + ID: "muse-spark-1.3", + Created: createdTS, + OwnedBy: "meta", + Type: "meta", + DisplayName: "Muse Spark 1.3", + ContextLength: 1007997, + MaxCompletionTokens: 128000, + Thinking: ®istry.ThinkingSupport{Levels: []string{"minimal", "low", "medium", "high", "xhigh", "max"}}, + SupportedInputModalities: []string{"text", "image", "video"}, + SupportedOutputModalities: []string{"text"}, + }, + { + ID: "gpt-6.1-sol", + Created: createdTS, + OwnedBy: "openai", + Type: "codex", + DisplayName: "GPT 6.1 Sol", + ContextLength: 500000, + MaxCompletionTokens: 128000, + Thinking: ®istry.ThinkingSupport{Levels: []string{"none", "low", "medium", "high", "xhigh", "max", "ultra"}}, + SupportedInputModalities: []string{"text", "image"}, + SupportedOutputModalities: []string{"text"}, + }, + { + ID: "claude-sonnet-4-5-20250929", + Created: createdTS, + OwnedBy: "anthropic", + Type: "claude", + DisplayName: "Claude 4.5 Sonnet", + ContextLength: 200000, + MaxCompletionTokens: 64000, + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 128000, ZeroAllowed: true}, + SupportedInputModalities: []string{"text", "image"}, + SupportedOutputModalities: []string{"text"}, + }, + { + ID: "gemini-2.5-flash", + Created: createdTS, + OwnedBy: "google", + Type: "gemini", + DisplayName: "Gemini 2.5 Flash", + ContextLength: 1048576, + MaxCompletionTokens: 65536, + Thinking: ®istry.ThinkingSupport{Max: 24576, ZeroAllowed: true, DynamicAllowed: true}, + SupportedInputModalities: []string{"text", "image", "audio", "video"}, + SupportedOutputModalities: []string{"text"}, + }, + { + ID: "kimi-k2", + Created: createdTS, + OwnedBy: "moonshot", + Type: "kimi", + DisplayName: "Kimi K2", + ContextLength: 131072, + MaxCompletionTokens: 32768, + SupportedInputModalities: []string{"text"}, + SupportedOutputModalities: []string{"text"}, + }, + { + ID: "custom-text-model", + Created: createdTS, + OwnedBy: "custom", + DisplayName: "Custom Text Model", + }, + { + ID: "muse-image-1.0", + Created: createdTS, + OwnedBy: "meta", + Type: "meta", + DisplayName: "Muse Image 1.0", + SupportedInputModalities: []string{"text", "image"}, + SupportedOutputModalities: []string{"image"}, + }, + { + ID: "gpt-image-2", + Created: createdTS, + OwnedBy: "openai", + Type: "openai-image", + }, + // Duplicate and blank IDs must be normalized away. + {ID: " "}, + {ID: "kimi-k2", DisplayName: "Duplicate Should Be Ignored"}, + } + + resp := BuildModelsResponse(inputs) + if resp.Object != "list" { + t.Fatalf("Object = %q, want list", resp.Object) + } + if len(resp.Data) != 9 { + t.Fatalf("len(Data) = %d, want 9", len(resp.Data)) + } + + raw, errMarshal := MarshalCompact(resp) + if errMarshal != nil { + t.Fatalf("MarshalCompact: %v", errMarshal) + } + if !ojson.ValidBytes(raw) { + t.Fatalf("MarshalCompact produced invalid JSON: %s", string(raw)) + } + if strings.Contains(string(raw), `\u003c`) { + t.Fatalf("MarshalCompact escaped HTML unexpectedly: %s", string(raw)) + } + + obj, entries := parseModelsByID(t, raw) + if obj != "list" { + t.Fatalf("top-level object = %q, want list", obj) + } + for id, entry := range entries { + if entry.Get("object").String() != "model" { + t.Fatalf("model %s object = %q, want model", id, entry.Get("object").String()) + } + if !entry.Get("metadata.muse-code").Exists() { + t.Fatalf("model %s missing metadata.muse-code: %s", id, entry.Raw) + } + } + + // 1. Meta flagship chat model. + wonder := entries["muse-wonder-1.0"].Get("metadata.muse-code") + if wonder.Get("family").String() != "avocado" || wonder.Get("release_date").String() != "2026-11-08" { + t.Fatalf("unexpected wonder family/release_date: %s", wonder.Raw) + } + if wonder.Get("is_hidden").Bool() || !wonder.Get("attachment").Bool() || !wonder.Get("reasoning").Bool() || wonder.Get("temperature").Bool() || !wonder.Get("tool_call").Bool() { + t.Fatalf("unexpected wonder capability flags: %s", wonder.Raw) + } + if wonder.Get("background_agent_model").String() != "muse-spark-1.3" { + t.Fatalf("background_agent_model = %q, want muse-spark-1.3", wonder.Get("background_agent_model").String()) + } + wonderOpts := wonder.Get("options") + if wonderOpts.Get("reasoningEffort").String() != "high" || !wonderOpts.Get("forceReasoning").Bool() || + wonderOpts.Get("temperature").Float() != 0.9 || wonderOpts.Get("top_p").Float() != 0.9 { + t.Fatalf("unexpected wonder options: %s", wonderOpts.Raw) + } + + // 2. Codex model filters "none", keeps "ultra", omits temperature/top_p in options. + sol := entries["gpt-6.1-sol"].Get("metadata.muse-code") + if sol.Get("family").String() != "openai" || !sol.Get("reasoning").Bool() || sol.Get("temperature").Bool() { + t.Fatalf("unexpected sol metadata: %s", sol.Raw) + } + solVariants := sol.Get("variants") + if solVariants.Get("none").Exists() { + t.Fatalf("sol variants must exclude none: %s", solVariants.Raw) + } + for _, wantLevel := range []string{"low", "medium", "high", "xhigh", "max", "ultra"} { + if !solVariants.Get(wantLevel).Exists() { + t.Fatalf("sol variants missing %q: %s", wantLevel, solVariants.Raw) + } + } + solOpts := sol.Get("options") + if solOpts.Get("reasoningEffort").String() != "medium" || !solOpts.Get("forceReasoning").Bool() { + t.Fatalf("unexpected sol options: %s", solOpts.Raw) + } + if solOpts.Get("temperature").Exists() { + t.Fatalf("non-meta model should not inject options.temperature: %s", solOpts.Raw) + } + + // 3. Budget-only Claude 4.5 & Gemini 2.5 Flash derive discrete variants. + claude45 := entries["claude-sonnet-4-5-20250929"].Get("metadata.muse-code.variants") + for _, wantLevel := range []string{"low", "medium", "high", "xhigh", "max"} { + if !claude45.Get(wantLevel).Exists() { + t.Fatalf("claude 4.5 missing derived variant %q: %s", wantLevel, claude45.Raw) + } + } + if claude45.Get("minimal").Exists() { + t.Fatalf("claude 4.5 (min=1024) should not expose redundant minimal tier: %s", claude45.Raw) + } + + flashVariants := entries["gemini-2.5-flash"].Get("metadata.muse-code.variants") + for _, wantLevel := range []string{"minimal", "low", "medium", "high"} { + if !flashVariants.Get(wantLevel).Exists() { + t.Fatalf("gemini 2.5 flash missing derived variant %q: %s", wantLevel, flashVariants.Raw) + } + } + if flashVariants.Get("max").Exists() || flashVariants.Get("xhigh").Exists() { + t.Fatalf("gemini 2.5 flash (max=24576) should not expose xhigh/max tiers: %s", flashVariants.Raw) + } + + // 4. Non-reasoning text model (static description enriched) & custom model (description: null). + kimi := entries["kimi-k2"].Get("metadata.muse-code") + if kimi.Get("reasoning").Bool() || !kimi.Get("temperature").Bool() || kimi.Get("attachment").Bool() || !kimi.Get("tool_call").Bool() || kimi.Get("is_hidden").Bool() { + t.Fatalf("unexpected kimi metadata: %s", kimi.Raw) + } + if kimi.Get("variants").Exists() { + t.Fatalf("non-reasoning model must omit variants: %s", kimi.Raw) + } + if kimi.Get("description").Type != ojson.String { + t.Fatalf("kimi-k2 should receive static description when input description is empty: %s", kimi.Raw) + } + if kimi.Get("options").Raw != "{}" { + t.Fatalf("non-reasoning options must be {}, got %s", kimi.Get("options").Raw) + } + + custom := entries["custom-text-model"].Get("metadata.muse-code") + if !custom.Get("description").Exists() || custom.Get("description").Type != ojson.Null { + t.Fatalf("empty description with no static match must serialize as null, got %s", custom.Raw) + } + + // 5. Hidden image models. + museImg := entries["muse-image-1.0"].Get("metadata.muse-code") + if museImg.Get("family").String() != "muse-image" || !museImg.Get("is_hidden").Bool() || museImg.Get("tool_call").Bool() { + t.Fatalf("unexpected muse-image-1.0 metadata: %s", museImg.Raw) + } + if museImg.Get("limit").Exists() { + t.Fatalf("muse-image-1.0 with no limits must omit limit: %s", museImg.Raw) + } + + gptImg := entries["gpt-image-2"].Get("metadata.muse-code") + if !gptImg.Get("is_hidden").Bool() || gptImg.Get("tool_call").Bool() { + t.Fatalf("unexpected gpt-image-2 metadata: %s", gptImg.Raw) + } + outMods := stringSliceFromResult(gptImg.Get("modalities.output")) + if len(outMods) != 1 || outMods[0] != "image" { + t.Fatalf("gpt-image-2 output modalities = %v, want [image]", outMods) + } +} + +func TestBuildModelsResponseAliasCollisionAndExplicitEmptyModalities(t *testing.T) { + resp := BuildModelsResponse([]ModelInput{ + { + // Aliased Claude model sharing public ID with built-in gpt-6.1-sol must use Claude metadata. + ID: "gpt-6.1-sol", + MetadataModelID: "claude-opus-4-6", + }, + { + // Explicit alias to unknown upstream must NOT inherit built-in gpt-5.5 metadata. + ID: "gpt-5.5", + MetadataModelID: "custom-unknown-upstream", + }, + { + // Public alias starting with gpt-image-* but explicitly returning text must NOT be hidden. + ID: "gpt-image-chat", + MetadataModelID: "gpt-5.5", + OwnedBy: "openai", + SupportedOutputModalities: []string{"text"}, + HasOutputModalities: true, + }, + { + // Explicit empty input modalities must NOT fall back to static image/video attachment. + ID: "muse-wonder-1.0", + OwnedBy: "meta", + Thinking: nil, + ExplicitThinking: true, + SupportedInputModalities: []string{}, + ExplicitInputModalities: true, + }, + }) + + raw, errMarshal := MarshalCompact(resp) + if errMarshal != nil { + t.Fatalf("MarshalCompact: %v", errMarshal) + } + _, entries := parseModelsByID(t, raw) + + aliasedClaude := entries["gpt-6.1-sol"].Get("metadata.muse-code") + if aliasedClaude.Get("family").String() != "anthropic" || entries["gpt-6.1-sol"].Get("owned_by").String() != "anthropic" { + t.Fatalf("alias colliding with gpt-6.1-sol must use claude-opus-4-6 identity, got %s", entries["gpt-6.1-sol"].Raw) + } + if aliasedClaude.Get("variants.xhigh").Exists() || !aliasedClaude.Get("variants.max").Exists() { + t.Fatalf("alias must inherit claude-opus-4-6 variants (low/medium/high/max), got %s", aliasedClaude.Get("variants").Raw) + } + + unknownAlias := entries["gpt-5.5"].Get("metadata.muse-code") + if unknownAlias.Get("limit").Exists() || unknownAlias.Get("reasoning").Bool() { + t.Fatalf("unknown upstream alias must not fall back to colliding gpt-5.5 static limits/reasoning: %s", unknownAlias.Raw) + } + + mediaNamedChat := entries["gpt-image-chat"].Get("metadata.muse-code") + if mediaNamedChat.Get("is_hidden").Bool() || !mediaNamedChat.Get("tool_call").Bool() { + t.Fatalf("chat model aliased as gpt-image-chat must remain visible with tool_call=true: %s", mediaNamedChat.Raw) + } + if gotOut := stringSliceFromResult(mediaNamedChat.Get("modalities.output")); len(gotOut) != 1 || gotOut[0] != "text" { + t.Fatalf("gpt-image-chat output modalities = %v, want [text]", gotOut) + } + + explicitEmpty := entries["muse-wonder-1.0"].Get("metadata.muse-code") + if explicitEmpty.Get("reasoning").Bool() { + t.Fatalf("ExplicitThinking=true with nil Thinking must keep reasoning=false") + } + if explicitEmpty.Get("attachment").Bool() { + t.Fatalf("ExplicitInputModalities=true with empty slice must keep attachment=false") + } + if gotIn := stringSliceFromResult(explicitEmpty.Get("modalities.input")); len(gotIn) != 1 || gotIn[0] != "text" { + t.Fatalf("explicit empty input modalities = %v, want [text]", gotIn) + } + if explicitEmpty.Get("background_agent_model").Exists() { + t.Fatalf("background_agent_model must be omitted when muse-spark-1.3 is absent") + } +} + +func TestBuildModelsResponseBudgetClampingAndConservativeMultiRouteMerge(t *testing.T) { + resp := BuildModelsResponse([]ModelInput{ + { + ID: "budget-pinned-32k", + OwnedBy: "anthropic", + Thinking: ®istry.ThinkingSupport{Min: 32768, Max: 32768}, + }, + { + ID: "budget-narrow-range", + OwnedBy: "anthropic", + Thinking: ®istry.ThinkingSupport{Min: 2000, Max: 4000}, + }, + { + ID: "budget-antigravity-64k", + OwnedBy: "anthropic", + Thinking: ®istry.ThinkingSupport{Min: 1024, Max: 64000}, + }, + { + ID: "dynamic-only-no-bounds", + OwnedBy: "google", + Thinking: ®istry.ThinkingSupport{DynamicAllowed: true}, + }, + { + ID: "multi-route-conservative", + Routes: []ModelRoute{ + { + Provider: "codex", + OwnedBy: "openai", + ContextLength: 500000, + MaxCompletionTokens: 128000, + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}}, + SupportedInputModalities: []string{"text", "image"}, + ExplicitInputModalities: true, + SupportedOutputModalities: []string{"text"}, + HasOutputModalities: true, + }, + { + Provider: "compat", + OwnedBy: "openai", + ContextLength: 128000, + MaxCompletionTokens: 32000, + Thinking: ®istry.ThinkingSupport{Levels: []string{"medium", "high", "max"}}, + SupportedInputModalities: []string{"text"}, + ExplicitInputModalities: true, + SupportedOutputModalities: []string{"text"}, + HasOutputModalities: true, + }, + }, + }, + { + ID: "multi-route-disjoint-media", + Routes: []ModelRoute{ + { + Provider: "openai-image", + Type: "openai-image", + SupportedOutputModalities: []string{"image"}, + HasOutputModalities: true, + }, + { + Provider: "openai", + Type: "openai", + SupportedOutputModalities: []string{"text"}, + HasOutputModalities: true, + }, + }, + }, + { + // Claude route aliases claude-opus-4-6 (1M context) as gpt-6.1-sol alongside + // native Codex gpt-6.1-sol (272k context). Codex route must keep its own + // identity and cap context conservatively at 272000. + ID: "gpt-6.1-sol", + MetadataModelID: "claude-opus-4-6", + Routes: []ModelRoute{ + { + Provider: "claude", + MetadataModelID: "claude-opus-4-6", + }, + { + Provider: "codex", + MetadataModelID: "", + }, + }, + }, + }) + + raw, errMarshal := MarshalCompact(resp) + if errMarshal != nil { + t.Fatalf("MarshalCompact: %v", errMarshal) + } + _, entries := parseModelsByID(t, raw) + + // Min=32768, Max=32768 collapses to a single deduplicated tier ("xhigh"). + pinned := entries["budget-pinned-32k"].Get("metadata.muse-code.variants") + if pinned.Get("low").Exists() || pinned.Get("high").Exists() || !pinned.Get("xhigh").Exists() || len(pinned.Map()) != 1 { + t.Fatalf("budget-pinned-32k variants = %s, want only xhigh", pinned.Raw) + } + + // Min=2000, Max=4000 produces low (clamped 2000) and medium (clamped 4000). + narrow := entries["budget-narrow-range"].Get("metadata.muse-code.variants") + if !narrow.Get("low").Exists() || !narrow.Get("medium").Exists() || len(narrow.Map()) != 2 { + t.Fatalf("budget-narrow-range variants = %s, want [low, medium]", narrow.Raw) + } + + // Min=1024, Max=64000 includes max clamped to 64000. + ag64 := entries["budget-antigravity-64k"].Get("metadata.muse-code.variants") + for _, want := range []string{"low", "medium", "high", "xhigh", "max"} { + if !ag64.Get(want).Exists() { + t.Fatalf("budget-antigravity-64k missing %q in %s", want, ag64.Raw) + } + } + + // DynamicAllowed with Min=0, Max=0 matches thinking.detectModelCapability -> CapabilityNone. + dynOnly := entries["dynamic-only-no-bounds"].Get("metadata.muse-code") + if dynOnly.Get("reasoning").Bool() || dynOnly.Get("variants").Exists() { + t.Fatalf("dynamic-only-no-bounds must not advertise reasoning: %s", dynOnly.Raw) + } + + // Multi-route conservative intersection: text-only input, medium+high variants, min limits 128000/32000. + merged := entries["multi-route-conservative"].Get("metadata.muse-code") + if merged.Get("attachment").Bool() { + t.Fatalf("multi-route must intersect input modalities to text-only: %s", merged.Raw) + } + if merged.Get("variants.low").Exists() || merged.Get("variants.max").Exists() || + !merged.Get("variants.medium").Exists() || !merged.Get("variants.high").Exists() { + t.Fatalf("multi-route variants = %s, want intersection [medium, high]", merged.Get("variants").Raw) + } + if merged.Get("limit.context").Int() != 128000 || merged.Get("limit.output").Int() != 32000 { + t.Fatalf("multi-route limit = %s, want 128000/32000", merged.Get("limit").Raw) + } + + // Disjoint output modalities remain hidden and consistent with non-text output. + disjoint := entries["multi-route-disjoint-media"].Get("metadata.muse-code") + if !disjoint.Get("is_hidden").Bool() || disjoint.Get("tool_call").Bool() { + t.Fatalf("disjoint text/image routes must conservatively hide model: %s", disjoint.Raw) + } + if out := stringSliceFromResult(disjoint.Get("modalities.output")); len(out) != 1 || out[0] != "image" { + t.Fatalf("disjoint output modalities = %v, want [image]", out) + } + + // Cross-route identity isolation: Codex route keeps gpt-6.1-sol (272k) instead of inheriting claude-opus-4-6 (1M). + iso := entries["gpt-6.1-sol"].Get("metadata.muse-code") + if iso.Get("limit.context").Int() != 272000 { + t.Fatalf("cross-route gpt-6.1-sol context = %d, want 272000", iso.Get("limit.context").Int()) + } + if iso.Get("variants.xhigh").Exists() || iso.Get("variants.ultra").Exists() || !iso.Get("variants.high").Exists() { + t.Fatalf("cross-route gpt-6.1-sol variants = %s, want intersection [low, medium, high, max]", iso.Get("variants").Raw) + } +} + +func TestBuildModelsResponseEmptyList(t *testing.T) { + resp := BuildModelsResponse(nil) + raw, errMarshal := MarshalCompact(resp) + if errMarshal != nil { + t.Fatalf("MarshalCompact: %v", errMarshal) + } + if string(raw) != `{"object":"list","data":[]}` { + t.Fatalf("empty catalog JSON = %s, want {\"object\":\"list\",\"data\":[]}", string(raw)) + } +} + +func TestHandleModelsLocalRegistryMultiProviderAndMethodValidation(t *testing.T) { + var upstreamCalls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + w.WriteHeader(http.StatusInternalServerError) + })) + defer upstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + + metaCred := &auth.Auth{ + ID: "meta-local-models-test", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "meta-secret", + "base_url": upstream.URL + "/v1", + }, + } + registerMetaTestCred(t, manager, metaCred, "muse-wonder-1.0") + + // Register a shared model across two local providers with different capabilities. + registry.GetGlobalRegistry().RegisterClient("codex-local-models-test", "codex", []*registry.ModelInfo{ + { + ID: "shared-local-model", + DisplayName: "Shared Local", + OwnedBy: "openai", + Type: "codex", + ContextLength: 500000, + MaxCompletionTokens: 128000, + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}}, + SupportedInputModalities: []string{"text", "image"}, + ExplicitInputModalities: true, + SupportedOutputModalities: []string{"text"}, + }, + }) + registry.GetGlobalRegistry().RegisterClient("compat-local-models-test", "openai-compat", []*registry.ModelInfo{ + { + ID: "shared-local-model", + DisplayName: "Shared Local", + OwnedBy: "openai", + Type: "openai", + ContextLength: 128000, + MaxCompletionTokens: 32000, + Thinking: nil, + ExplicitThinking: true, + SupportedInputModalities: []string{"text"}, + ExplicitInputModalities: true, + SupportedOutputModalities: []string{"text"}, + }, + }) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient("codex-local-models-test") + registry.GetGlobalRegistry().UnregisterClient("compat-local-models-test") + }) + + handler := NewHandler(manager, cfg) + router := newTestRouter(handler) + + // Query params must still serve local catalog cleanly. + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/muse-code/models?channel=public", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } + if upstreamCalls.Load() != 0 { + t.Fatalf("/muse-code/models must not call Meta upstream; calls=%d", upstreamCalls.Load()) + } + + obj, entries := parseModelsByID(t, rec.Body.Bytes()) + if obj != "list" { + t.Fatalf("Object = %q, want list", obj) + } + if !entries["muse-wonder-1.0"].Exists() || !entries["shared-local-model"].Exists() { + t.Fatalf("expected both Meta and shared multi-provider model; got %s", rec.Body.String()) + } + shared := entries["shared-local-model"].Get("metadata.muse-code") + if shared.Get("attachment").Bool() || shared.Get("reasoning").Bool() || shared.Get("limit.context").Int() != 128000 { + t.Fatalf("multi-provider local model did not merge conservatively: %s", shared.Raw) + } + + // Direct HandleModels invocation must reject non-GET methods with 404. + directEngine := gin.New() + directEngine.Any("/muse-code/models", handler.HandleModels) + postRec := httptest.NewRecorder() + directEngine.ServeHTTP(postRec, httptest.NewRequest(http.MethodPost, "/muse-code/models", nil)) + if postRec.Code != http.StatusNotFound { + t.Fatalf("POST HandleModels status = %d, want 404", postRec.Code) + } +} + +func TestHandleModelsHomeModeHookAndFallback(t *testing.T) { + gin.SetMode(gin.TestMode) + + // Without homeModelsLoader, Home mode returns 503. + cfg := &config.Config{Home: config.HomeConfig{Enabled: true}} + hNoLoader := NewHandler(nil, cfg) + routerNoLoader := newTestRouter(hNoLoader) + rec503 := httptest.NewRecorder() + routerNoLoader.ServeHTTP(rec503, httptest.NewRequest(http.MethodGet, "/muse-code/models", nil)) + if rec503.Code != http.StatusServiceUnavailable { + t.Fatalf("status without home loader = %d, want 503; body=%s", rec503.Code, rec503.Body.String()) + } + + // With homeModelsLoader and custom writer, Home models are returned cleanly. + hWithHooks := NewHandler(nil, cfg) + var writerFormat string + hWithHooks.SetModelListHooks( + func(c *gin.Context) ([]ModelInput, bool) { + return []ModelInput{ + {ID: "claude-opus-4-6", OwnedBy: "anthropic", Type: "claude"}, + }, true + }, + func(c *gin.Context, sourceFormat string, payload any) { + writerFormat = sourceFormat + body, _ := payload.([]byte) + c.Data(http.StatusOK, "application/json; charset=utf-8", body) + }, + ) + routerWithHooks := newTestRouter(hWithHooks) + recOK := httptest.NewRecorder() + routerWithHooks.ServeHTTP(recOK, httptest.NewRequest(http.MethodGet, "/muse-code/models", nil)) + if recOK.Code != http.StatusOK { + t.Fatalf("status with hooks = %d, want 200; body=%s", recOK.Code, recOK.Body.String()) + } + if writerFormat != "openai" { + t.Fatalf("writer sourceFormat = %q, want openai", writerFormat) + } + + _, entries := parseModelsByID(t, recOK.Body.Bytes()) + if !entries["claude-opus-4-6"].Exists() { + t.Fatalf("missing claude-opus-4-6 in Home hook response: %s", recOK.Body.String()) + } + if !entries["claude-opus-4-6"].Get("metadata.muse-code.reasoning").Bool() { + t.Fatalf("expected claude-opus-4-6 enriched with static reasoning metadata") + } +} diff --git a/internal/client/musecode/relay.go b/internal/client/musecode/relay.go new file mode 100644 index 00000000000..a0cb882722b --- /dev/null +++ b/internal/client/musecode/relay.go @@ -0,0 +1,641 @@ +// Package musecode serves Muse Code CLI client endpoints, generating /muse-code/models +// from CPA's available models and relaying auxiliary endpoints to the selected Meta upstream. +package musecode + +import ( + "context" + "errors" + "fmt" + "io" + "math" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/gin-gonic/gin" + metaauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/meta" + "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + log "github.com/sirupsen/logrus" +) + +const maxBodySize = 16 << 20 + +var errBodyTooLarge = errors.New("muse code: body exceeds 16 MiB limit") + +var allowedEndpoints = map[string]string{ + "/muse-code/config": http.MethodGet, + "/muse-code/search": http.MethodPost, + "/muse-code/browser_open": http.MethodPost, +} + +var allowedRequestHeaders = []string{ + "Accept", + "Content-Type", + "Traceparent", + "If-None-Match", +} + +var allowedResponseHeaders = []string{ + "Content-Type", + "Cache-Control", + "Etag", + "Last-Modified", + "Retry-After", +} + +// Handler serves Muse Code CLI endpoints, generating /muse-code/models locally +// and relaying allowlisted auxiliary endpoints to Meta using managed Meta credentials. +type Handler struct { + mu sync.RWMutex + authManager *auth.Manager + cfg *config.Config + homeModelsLoader HomeModelsLoader + modelListWriter ModelListWriter +} + +// NewHandler constructs a Muse Code endpoint relay handler. +func NewHandler(authManager *auth.Manager, cfg *config.Config) *Handler { + return &Handler{ + authManager: authManager, + cfg: cfg, + } +} + +// UpdateConfig updates the handler's runtime configuration snapshot. +func (h *Handler) UpdateConfig(cfg *config.Config) { + if h == nil { + return + } + h.mu.Lock() + h.cfg = cfg + h.mu.Unlock() +} + +func (h *Handler) currentConfig() *config.Config { + if h == nil { + return nil + } + h.mu.RLock() + cfg := h.cfg + h.mu.RUnlock() + return cfg +} + +type relayAttemptResponse struct { + statusCode int + headers http.Header + body []byte +} + +func writeRelayAttemptResponse(c *gin.Context, resp *relayAttemptResponse) { + if c == nil || resp == nil { + return + } + writeRelayResponseHeaders(c.Writer.Header(), resp.headers) + c.Status(resp.statusCode) + if len(resp.body) > 0 { + _, _ = c.Writer.Write(resp.body) + } +} + +func isRequestScopedContinue(action string, okAction bool) bool { + return okAction && (action == auth.RequestScopedActionContinue || action == auth.RequestScopedActionContinueAndCooldown) +} + +// Handle serves GET /muse-code/models locally and forwards allowlisted /muse-code/* +// relay requests to the selected Meta origin. +func (h *Handler) Handle(c *gin.Context) { + if c == nil || c.Request == nil || c.Request.URL == nil { + return + } + if c.Request.Method == http.MethodGet && c.Request.URL.Path == "/muse-code/models" { + h.HandleModels(c) + return + } + if !isAllowedEndpoint(c.Request.Method, c.Request.URL.Path) { + c.AbortWithStatus(http.StatusNotFound) + return + } + if h == nil || h.authManager == nil { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Meta auth manager unavailable"}) + return + } + if h.authManager.HomeEnabled() { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Muse Code endpoints are unavailable while Home mode is enabled"}) + return + } + + reqBody, errRead := readLimitedBody(c.Request.Body) + if errRead != nil { + if errors.Is(errRead, errBodyTooLarge) { + c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": errRead.Error()}) + return + } + c.JSON(clienterror.HTTPStatusFromErrorOr(errRead, http.StatusBadRequest), gin.H{"error": "Failed to read Muse Code request"}) + return + } + + ctx := context.WithValue(c.Request.Context(), "gin", c) + cfg := h.currentConfig() + if cfg != nil && auth.RequestScopedErrorConfigFromContext(ctx) == nil { + ctx = auth.WithRequestScopedErrorConfig(ctx, cfg) + } + selectionOpts := coreexecutor.Options{ + Headers: c.Request.Header.Clone(), + OriginalRequest: reqBody, + } + sanitizedQuery := sanitizeQuery(c.Request.URL.RawQuery) + baseReqHeaders := relayRequestHeaders(c.Request.Header) + maxRetryCreds := h.authManager.MaxRetryCredentials() + tried := make(map[string]struct{}) + var lastResp *relayAttemptResponse + var lastErr error + + for attempt := 0; maxRetryCreds <= 0 || attempt < maxRetryCreds; attempt++ { + selected, errSelect := h.selectMetaAuthExcluding(ctx, selectionOpts, tried) + if errSelect != nil { + if lastResp != nil { + writeRelayAttemptResponse(c, lastResp) + return + } + if lastErr != nil { + c.JSON(clienterror.HTTPStatusFromErrorOr(lastErr, http.StatusBadGateway), gin.H{"error": lastErr.Error()}) + return + } + status := clienterror.HTTPStatusFromErrorOr(errSelect, http.StatusServiceUnavailable) + for _, value := range auth.SafeResponseHeaders(errSelect).Values("Retry-After") { + c.Writer.Header().Add("Retry-After", value) + } + c.JSON(status, gin.H{"error": errSelect.Error()}) + return + } + if selected == nil { + if lastResp != nil { + writeRelayAttemptResponse(c, lastResp) + return + } + if lastErr != nil { + c.JSON(clienterror.HTTPStatusFromErrorOr(lastErr, http.StatusBadGateway), gin.H{"error": lastErr.Error()}) + return + } + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Meta auth unavailable"}) + return + } + tried[selected.ID] = struct{}{} + + if exec, okExec := h.authManager.Executor("meta"); okExec && exec != nil { + if preparer, okPrep := exec.(auth.RequestAuthPreparer); okPrep && preparer.ShouldPrepareRequestAuth(selected) { + prepareSeq := h.authManager.NextExecutionSeq() + prepared, errPrep := h.authManager.PrepareRequestAuth(ctx, preparer, selected) + if errPrep != nil { + if errCtx := ctx.Err(); errCtx != nil { + c.JSON(clienterror.HTTPStatusFromErrorOr(errCtx, http.StatusBadGateway), gin.H{"error": errCtx.Error()}) + return + } + action, okAction := h.markFailure(ctx, selected, errPrep, nil, prepareSeq) + if isRequestScopedContinue(action, okAction) { + lastResp = nil + lastErr = errPrep + continue + } + c.JSON(clienterror.HTTPStatusFromErrorOr(errPrep, http.StatusBadGateway), gin.H{"error": errPrep.Error()}) + return + } + if prepared != nil { + selected = prepared + } + } + } + + logging.SetGinCPATraceID(c, selected.EnsureIndex()) + respAttempt, action, okAction, errAttempt := h.forwardWithCredential(ctx, cfg, selected, c.Request.Method, c.Request.URL.Path, sanitizedQuery, reqBody, baseReqHeaders, c.Request.Header) + if errAttempt != nil { + if errCtx := ctx.Err(); errCtx != nil { + c.JSON(clienterror.HTTPStatusFromErrorOr(errCtx, http.StatusBadGateway), gin.H{"error": errCtx.Error()}) + return + } + if isRequestScopedContinue(action, okAction) { + lastResp = nil + lastErr = errAttempt + continue + } + c.JSON(clienterror.HTTPStatusFromErrorOr(errAttempt, http.StatusBadGateway), gin.H{"error": errAttempt.Error()}) + return + } + if isRequestScopedContinue(action, okAction) { + lastResp = respAttempt + lastErr = nil + continue + } + writeRelayAttemptResponse(c, respAttempt) + return + } + + if lastResp != nil { + writeRelayAttemptResponse(c, lastResp) + return + } + if lastErr != nil { + c.JSON(clienterror.HTTPStatusFromErrorOr(lastErr, http.StatusBadGateway), gin.H{"error": lastErr.Error()}) + return + } + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Meta auth unavailable"}) +} + +func (h *Handler) forwardWithCredential( + ctx context.Context, + cfg *config.Config, + selected *auth.Auth, + method string, + requestPath string, + sanitizedQuery string, + reqBody []byte, + baseReqHeaders http.Header, + clientHeaders http.Header, +) (*relayAttemptResponse, string, bool, error) { + alreadyRefreshed := false + for { + origin, errOrigin := originFromAuth(selected) + if errOrigin != nil { + return nil, "", false, errOrigin + } + + upstreamURL := origin + requestPath + if sanitizedQuery != "" { + upstreamURL += "?" + sanitizedQuery + } + + upstreamReq, errReq := h.authManager.NewHttpRequest(ctx, selected, method, upstreamURL, reqBody, baseReqHeaders) + if errReq != nil { + return nil, "", false, errReq + } + + authType, authValue := selected.AccountInfo() + helps.RecordAPIRequest(ctx, cfg, helps.UpstreamRequestLog{ + URL: upstreamURL, + Method: method, + Headers: upstreamReq.Header.Clone(), + Body: reqBody, + Provider: "meta", + AuthID: selected.ID, + AuthLabel: selected.Label, + AuthType: authType, + AuthValue: authValue, + }) + + executionSeq := h.authManager.NextExecutionSeq() + resp, errDo := h.authManager.HttpRequest(ctx, selected, upstreamReq) + if errDo != nil { + helps.RecordAPIResponseError(ctx, cfg, errDo) + if errCtx := ctx.Err(); errCtx != nil { + return nil, "", false, errCtx + } + action, okAction := h.markFailure(ctx, selected, errDo, nil, executionSeq) + return nil, action, okAction, errDo + } + + respBody, errRespRead := readLimitedBody(resp.Body) + if errClose := resp.Body.Close(); errClose != nil { + log.Errorf("muse code relay: close response body error: %v", errClose) + } + helps.RecordAPIResponseMetadata(ctx, cfg, resp.StatusCode, resp.Header.Clone()) + helps.AppendAPIResponseChunk(ctx, cfg, respBody) + if errRespRead != nil { + helps.RecordAPIResponseError(ctx, cfg, errRespRead) + if errCtx := ctx.Err(); errCtx != nil { + return nil, "", false, errCtx + } + if errors.Is(errRespRead, errBodyTooLarge) { + return nil, "", false, errors.New("Meta response body exceeds 16 MiB limit") + } + action, okAction := h.markFailure(ctx, selected, errRespRead, nil, executionSeq) + return nil, action, okAction, errors.New("Failed to read Meta response") + } + + if resp.StatusCode == http.StatusUnauthorized && !alreadyRefreshed { + unauthErr := &auth.Error{HTTPStatus: resp.StatusCode, Message: string(respBody)} + if refreshed, okRefresh := h.authManager.RefreshAfterUnauthorized(ctx, selected, unauthErr, false, clientHeaders); okRefresh && refreshed != nil { + selected = refreshed + alreadyRefreshed = true + continue + } + } + + var action string + var okAction bool + if resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusBadRequest { + h.markSuccess(ctx, selected, executionSeq) + } else if resp.StatusCode >= http.StatusBadRequest { + logging.SetResponseHeaders(ctx, resp.Header.Clone()) + retryAfter := parseRetryAfterHeader(resp.Header, time.Now()) + action, okAction = h.markHTTPResponseFailure(ctx, selected, resp.StatusCode, string(respBody), retryAfter, executionSeq) + } + + return &relayAttemptResponse{ + statusCode: resp.StatusCode, + headers: resp.Header.Clone(), + body: respBody, + }, action, okAction, nil + } +} + +func (h *Handler) selectMetaAuthExcluding(ctx context.Context, opts coreexecutor.Options, tried map[string]struct{}) (*auth.Auth, error) { + models := metaCandidateModels(h.authManager) + if len(models) == 0 { + return nil, &auth.Error{ + Code: "auth_not_found", + Message: "no available Meta credential", + HTTPStatus: http.StatusServiceUnavailable, + } + } + + var firstErr error + for _, modelID := range models { + selected, errSelect := h.authManager.SelectAuthExcluding(ctx, "meta", modelID, opts, tried) + if errSelect == nil && selected != nil { + return selected, nil + } + if errSelect != nil { + if firstErr == nil || !isAuthNotFoundError(errSelect) { + firstErr = errSelect + } + } + } + if firstErr != nil { + return nil, firstErr + } + return nil, &auth.Error{ + Code: "auth_not_found", + Message: "no available Meta credential", + HTTPStatus: http.StatusServiceUnavailable, + } +} + +func metaCandidateModels(manager *auth.Manager) []string { + if manager == nil { + return nil + } + reg := registry.GetGlobalRegistry() + if reg == nil { + return nil + } + auths := manager.List() + seen := make(map[string]struct{}) + models := make([]string, 0, len(auths)*4) + for _, candidate := range auths { + if candidate == nil || candidate.Disabled || candidate.Status == auth.StatusDisabled { + continue + } + if !strings.EqualFold(strings.TrimSpace(candidate.Provider), "meta") { + continue + } + for _, info := range reg.GetModelsForClient(candidate.ID) { + if info == nil { + continue + } + id := strings.TrimSpace(info.ID) + if id == "" { + continue + } + if _, exists := seen[id]; exists { + continue + } + seen[id] = struct{}{} + models = append(models, id) + } + } + sort.Strings(models) + return models +} + +func isAuthNotFoundError(err error) bool { + var authErr *auth.Error + if errors.As(err, &authErr) && authErr != nil { + return authErr.Code == "auth_not_found" + } + return false +} + +func isAllowedEndpoint(method, path string) bool { + wantMethod, ok := allowedEndpoints[path] + return ok && strings.EqualFold(strings.TrimSpace(method), wantMethod) +} + +func originFromAuth(a *auth.Auth) (string, error) { + rawBaseURL := "" + if a != nil { + if a.Attributes != nil { + rawBaseURL = strings.TrimSpace(a.Attributes["base_url"]) + } + if rawBaseURL == "" && a.Metadata != nil { + if b, ok := a.Metadata["base_url"].(string); ok && strings.TrimSpace(b) != "" { + rawBaseURL = strings.TrimSpace(b) + } else if b, ok := a.Metadata["api_base_url"].(string); ok && strings.TrimSpace(b) != "" { + rawBaseURL = strings.TrimSpace(b) + } + } + } + if rawBaseURL == "" { + rawBaseURL = metaauth.DefaultAPIBaseURL + } + parsed, errParse := url.Parse(rawBaseURL) + if errParse != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || strings.TrimSpace(parsed.Host) == "" { + return "", fmt.Errorf("muse code: invalid Meta base_url %q", rawBaseURL) + } + return (&url.URL{Scheme: parsed.Scheme, Host: parsed.Host}).String(), nil +} + +func sanitizeQuery(rawQuery string) string { + if strings.TrimSpace(rawQuery) == "" { + return "" + } + values, errParse := url.ParseQuery(rawQuery) + if errParse != nil { + return "" + } + values.Del("key") + values.Del("auth_token") + return values.Encode() +} + +func relayRequestHeaders(in http.Header) http.Header { + out := make(http.Header) + if in == nil { + return out + } + for _, name := range allowedRequestHeaders { + for _, value := range in.Values(name) { + out.Add(name, value) + } + } + for name, values := range in { + canonical := http.CanonicalHeaderKey(name) + if strings.HasPrefix(canonical, "X-Tbh-") || strings.HasPrefix(canonical, "X-Meta-Ai-") { + for _, value := range values { + out.Add(canonical, value) + } + } + } + return out +} + +func writeRelayResponseHeaders(dst, src http.Header) { + if dst == nil || src == nil { + return + } + for _, name := range allowedResponseHeaders { + for _, value := range src.Values(name) { + dst.Add(name, value) + } + } +} + +func readLimitedBody(body io.ReadCloser) ([]byte, error) { + if body == nil || body == http.NoBody { + return nil, nil + } + data, errRead := io.ReadAll(io.LimitReader(body, maxBodySize+1)) + if errRead != nil { + var maxBytesErr *http.MaxBytesError + if errors.As(errRead, &maxBytesErr) { + return nil, errBodyTooLarge + } + return nil, errRead + } + if len(data) > maxBodySize { + return nil, errBodyTooLarge + } + return data, nil +} + +func shouldMarkCredentialFailure(status int) bool { + if status >= http.StatusInternalServerError { + return true + } + switch status { + case http.StatusUnauthorized, http.StatusPaymentRequired, http.StatusForbidden, http.StatusTooManyRequests: + return true + default: + return false + } +} + +func parseRetryAfterHeader(headers http.Header, now time.Time) *time.Duration { + if headers == nil { + return nil + } + raw := strings.TrimSpace(headers.Get("Retry-After")) + if raw == "" { + return nil + } + if seconds, errParse := strconv.ParseInt(raw, 10, 64); errParse == nil && seconds >= 0 { + if seconds > int64(math.MaxInt64)/int64(time.Second) { + delay := time.Duration(math.MaxInt64) + return &delay + } + delay := time.Duration(seconds) * time.Second + return &delay + } + if deadline, errParse := http.ParseTime(raw); errParse == nil { + delay := deadline.Sub(now) + if delay < 0 { + delay = 0 + } + return &delay + } + return nil +} + +func metaAccessToken(a *auth.Auth) string { + if a == nil { + return "" + } + if a.Metadata != nil { + for _, key := range []string{"access_token", "accessToken", "api_key"} { + if value, ok := a.Metadata[key].(string); ok && strings.TrimSpace(value) != "" && !strings.HasPrefix(strings.TrimSpace(value), "dca:") { + return strings.TrimSpace(value) + } + } + } + if a.Attributes != nil { + for _, key := range []string{"api_key", "access_token"} { + if value := strings.TrimSpace(a.Attributes[key]); value != "" && !strings.HasPrefix(value, "dca:") { + return value + } + } + } + return "" +} + +func (h *Handler) markSuccess(ctx context.Context, current *auth.Auth, executionSeq uint64) { + if h == nil || h.authManager == nil || current == nil { + return + } + h.authManager.MarkResult(ctx, auth.Result{ + AuthID: current.ID, + Provider: "meta", + Success: true, + AccessToken: metaAccessToken(current), + CredentialVersion: current.CredentialVersion, + RegistrationEpoch: current.RegistrationEpoch, + ExecutionSeq: executionSeq, + }) +} + +func (h *Handler) markHTTPResponseFailure(ctx context.Context, current *auth.Auth, statusCode int, body string, retryAfter *time.Duration, executionSeq uint64) (string, bool) { + if h == nil || h.authManager == nil || current == nil { + return "", false + } + rawErr := &auth.Error{HTTPStatus: statusCode, Message: body} + result := auth.Result{ + AuthID: current.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + AccessToken: metaAccessToken(current), + RetryAfter: retryAfter, + Error: &auth.Error{HTTPStatus: statusCode, Message: body}, + CredentialVersion: current.CredentialVersion, + RegistrationEpoch: current.RegistrationEpoch, + ExecutionSeq: executionSeq, + } + action, okAction := h.authManager.ApplyRequestScopedErrorResult(ctx, current, rawErr, &result) + isForceCooldown := okAction && (action == auth.RequestScopedActionStopAndCooldown || action == auth.RequestScopedActionContinueAndCooldown) + if !shouldMarkCredentialFailure(statusCode) && !isForceCooldown { + return action, okAction + } + h.authManager.MarkResult(ctx, result) + return action, okAction +} + +func (h *Handler) markFailure(ctx context.Context, current *auth.Auth, err error, retryAfter *time.Duration, executionSeq uint64) (string, bool) { + if h == nil || h.authManager == nil || current == nil || err == nil { + return "", false + } + authErr := auth.ResultErrorFromError(err) + result := auth.Result{ + AuthID: current.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + AccessToken: metaAccessToken(current), + RetryAfter: retryAfter, + Error: authErr, + CredentialVersion: current.CredentialVersion, + RegistrationEpoch: current.RegistrationEpoch, + ExecutionSeq: executionSeq, + } + action, okAction := h.authManager.ApplyRequestScopedErrorResult(ctx, current, err, &result) + h.authManager.MarkResult(ctx, result) + return action, okAction +} diff --git a/internal/client/musecode/relay_test.go b/internal/client/musecode/relay_test.go new file mode 100644 index 00000000000..e7cd804fc0a --- /dev/null +++ b/internal/client/musecode/relay_test.go @@ -0,0 +1,1240 @@ +package musecode + +import ( + "bytes" + "context" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "syscall" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func newTestRouter(handler *Handler) *gin.Engine { + gin.SetMode(gin.TestMode) + engine := gin.New() + engine.Any("/muse-code/*path", handler.Handle) + return engine +} + +func registerMetaTestCred(t *testing.T, manager *auth.Manager, cred *auth.Auth, models ...string) { + t.Helper() + if len(models) > 0 { + infos := make([]*registry.ModelInfo, 0, len(models)) + for _, id := range models { + infos = append(infos, ®istry.ModelInfo{ID: id}) + } + registry.GetGlobalRegistry().RegisterClient(cred.ID, "meta", infos) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(cred.ID) + }) + } + if _, errReg := manager.Register(context.Background(), cred); errReg != nil { + t.Fatalf("register cred %s: %v", cred.ID, errReg) + } +} + +func TestRelayHeadersQueryAndDisallowedPaths(t *testing.T) { + var upstreamCalls atomic.Int32 + var gotHeaders http.Header + var gotQuery string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + gotHeaders = r.Header.Clone() + gotQuery = r.URL.RawQuery + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "max-age=60") + w.Header().Set("Etag", `"v3"`) + w.Header().Set("Last-Modified", "Wed, 21 Oct 2015 07:28:00 GMT") + w.Header().Set("Retry-After", "12") + w.Header().Set("Set-Cookie", "secret=cookie") + w.Header().Set("X-Internal-Leak", "nope") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"ok":true}`) + })) + defer upstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-headers-test", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "meta-secret", + "base_url": upstream.URL + "/api/v1", + }, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + + router := newTestRouter(NewHandler(manager, cfg)) + + // Disallowed endpoints must return 404 without calling upstream. + for _, tc := range []struct { + method string + path string + }{ + {http.MethodPost, "/muse-code/key"}, + {http.MethodGet, "/muse-code/key"}, + {http.MethodPost, "/muse-code/telemetry"}, + {http.MethodPost, "/muse-code/models"}, + {http.MethodGet, "/muse-code/search"}, + } { + rec := httptest.NewRecorder() + req := httptest.NewRequest(tc.method, tc.path, nil) + router.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound { + t.Fatalf("%s %s status = %d, want 404", tc.method, tc.path, rec.Code) + } + } + if upstreamCalls.Load() != 0 { + t.Fatalf("disallowed endpoints reached upstream %d times", upstreamCalls.Load()) + } + + // Allowed request strips proxy auth query params & unsafe headers. + req := httptest.NewRequest(http.MethodGet, "/muse-code/config?channel=public&key=proxy-secret&auth_token=proxy-tok&extra=1", nil) + req.Header.Set("Authorization", "Bearer client-proxy-secret") + req.Header.Set("Cookie", "session=bad") + req.Header.Set("X-Api-Key", "proxy-key") + req.Header.Set("Accept", "application/json") + req.Header.Set("Traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") + req.Header.Set("If-None-Match", `"v2"`) + req.Header.Set("X-Tbh-Custom", "tbh-val") + req.Header.Set("X-Meta-Ai-Custom", "meta-val") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } + if gotQuery != "channel=public&extra=1" { + t.Fatalf("upstream query = %q, want channel=public&extra=1", gotQuery) + } + if got := gotHeaders.Get("Authorization"); got != "Bearer meta-secret" { + t.Fatalf("upstream Authorization = %q, want Bearer meta-secret", got) + } + if got := gotHeaders.Get("Cookie"); got != "" { + t.Fatalf("upstream leaked Cookie = %q", got) + } + if got := gotHeaders.Get("X-Api-Key"); got != "" { + t.Fatalf("upstream leaked X-Api-Key = %q", got) + } + if gotHeaders.Get("Traceparent") == "" || gotHeaders.Get("If-None-Match") != `"v2"` || + gotHeaders.Get("X-Tbh-Custom") != "tbh-val" || gotHeaders.Get("X-Meta-Ai-Custom") != "meta-val" { + t.Fatalf("missing allowlisted request headers: %#v", gotHeaders) + } + if rec.Header().Get("Set-Cookie") != "" || rec.Header().Get("X-Internal-Leak") != "" { + t.Fatalf("response leaked disallowed headers: %#v", rec.Header()) + } + if rec.Header().Get("Cache-Control") != "max-age=60" || rec.Header().Get("Etag") != `"v3"` || + rec.Header().Get("Last-Modified") == "" || rec.Header().Get("Retry-After") != "12" { + t.Fatalf("missing allowlisted response headers: %#v", rec.Header()) + } +} + +func TestRelayBodySizeCaps(t *testing.T) { + var upstreamCalls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(bytes.Repeat([]byte("a"), maxBodySize+1)) + })) + defer upstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-size-test", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "meta-secret", + "base_url": upstream.URL + "/v1", + }, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + // Oversized request returns 413 without calling upstream. + oversizedReq := httptest.NewRequest(http.MethodPost, "/muse-code/search", bytes.NewReader(bytes.Repeat([]byte("x"), maxBodySize+1))) + recReq := httptest.NewRecorder() + router.ServeHTTP(recReq, oversizedReq) + if recReq.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("oversized request status = %d, want 413", recReq.Code) + } + if upstreamCalls.Load() != 0 { + t.Fatalf("oversized request reached upstream %d times", upstreamCalls.Load()) + } + + // Oversized response returns 502 without truncation. + recResp := httptest.NewRecorder() + router.ServeHTTP(recResp, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if recResp.Code != http.StatusBadGateway { + t.Fatalf("oversized response status = %d, want 502", recResp.Code) + } +} + +func TestRelayExcludesStarExcludedAndHomeMode(t *testing.T) { + var upstreamCalls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + w.WriteHeader(http.StatusOK) + })) + defer upstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + // Credential with excluded-models: ["*"] has no models registered in registry. + credExcluded := &auth.Auth{ + ID: "meta-excluded-all", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "meta-secret", + "base_url": upstream.URL + "/v1", + "excluded_models": "*", + }, + } + registerMetaTestCred(t, manager, credExcluded) + router := newTestRouter(NewHandler(manager, cfg)) + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("excluded-all status = %d, want 503; body=%s", rec.Code, rec.Body.String()) + } + if upstreamCalls.Load() != 0 { + t.Fatalf("excluded-all reached upstream") + } + + // Home mode enabled returns 503 without calling upstream. + homeManager := auth.NewManager(nil, nil, nil) + homeManager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + registerMetaTestCred(t, homeManager, &auth.Auth{ + ID: "meta-home-cred", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "meta-secret", + "base_url": upstream.URL + "/v1", + }, + }, "muse-wonder-1.0") + homeManager.SetConfig(&config.Config{Home: config.HomeConfig{Enabled: true}}) + + homeRouter := newTestRouter(NewHandler(homeManager, cfg)) + recHome := httptest.NewRecorder() + homeRouter.ServeHTTP(recHome, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if recHome.Code != http.StatusServiceUnavailable { + t.Fatalf("home mode status = %d, want 503; body=%s", recHome.Code, recHome.Body.String()) + } + if upstreamCalls.Load() != 0 { + t.Fatalf("home mode reached upstream") + } +} + +func TestRelayDCAOnlyMintsOnceAndUsesMintedOrigin(t *testing.T) { + var mintCalls atomic.Int32 + var apiCalls atomic.Int32 + var seenAuths []string + + apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + apiCalls.Add(1) + seenAuths = append(seenAuths, r.Header.Get("Authorization")) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"models":[]}`) + })) + defer apiServer.Close() + + mintServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mintCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"api_key":"minted-key-1","base_url":"`+apiServer.URL+`/v1"}`) + })) + defer mintServer.Close() + t.Setenv("META_MINT_URL", mintServer.URL) + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-dca-only", + Provider: "meta", + Status: auth.StatusActive, + Metadata: map[string]any{ + "type": "meta", + "access_token": "dca:initial-device-token", + "dca_token": "dca:initial-device-token", + }, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + for i := 0; i < 2; i++ { + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("call %d status = %d, want 200; body=%s", i, rec.Code, rec.Body.String()) + } + } + if mintCalls.Load() != 1 { + t.Fatalf("mintCalls = %d, want 1", mintCalls.Load()) + } + if apiCalls.Load() != 2 { + t.Fatalf("apiCalls = %d, want 2", apiCalls.Load()) + } + for i, got := range seenAuths { + if got != "Bearer minted-key-1" { + t.Fatalf("call %d Authorization = %q, want Bearer minted-key-1", i, got) + } + } +} + +func TestRelayRefreshesOnceOn401AndRetiresOnSecond401(t *testing.T) { + var mintCalls atomic.Int32 + var seenTokens []string + + var apiURL string + apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + seenTokens = append(seenTokens, tok) + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":"invalid_api_key"}`) + })) + defer apiServer.Close() + apiURL = apiServer.URL + + mintServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mintCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"api_key":"fresh-minted-key","base_url":"`+apiURL+`/v1"}`) + })) + defer mintServer.Close() + t.Setenv("META_MINT_URL", mintServer.URL) + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-refresh-test", + Provider: "meta", + Status: auth.StatusActive, + Metadata: map[string]any{ + "type": "meta", + "access_token": "stale-key", + "api_key": "stale-key", + "dca_token": "dca:valid", + "base_url": apiURL + "/v1", + }, + Attributes: map[string]string{ + "api_key": "stale-key", + "base_url": apiURL + "/v1", + }, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + // First request gets 401 -> refreshes once -> retries -> gets 401 -> retires credential. + rec1 := httptest.NewRecorder() + router.ServeHTTP(rec1, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec1.Code != http.StatusUnauthorized { + t.Fatalf("first status = %d, want 401", rec1.Code) + } + if mintCalls.Load() != 1 { + t.Fatalf("mintCalls = %d, want 1", mintCalls.Load()) + } + if len(seenTokens) != 2 || seenTokens[0] != "stale-key" || seenTokens[1] != "fresh-minted-key" { + t.Fatalf("seenTokens = %#v, want [stale-key fresh-minted-key]", seenTokens) + } + + // Subsequent requests must NOT re-mint on every request once retired. + rec2 := httptest.NewRecorder() + router.ServeHTTP(rec2, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec2.Code == http.StatusOK { + t.Fatalf("second request unexpectedly succeeded") + } + if mintCalls.Load() != 1 { + t.Fatalf("second request triggered extra mint: mintCalls = %d, want 1", mintCalls.Load()) + } +} + +func TestRelaySkipsRateLimitedCredentialAndPassesRetryAfter(t *testing.T) { + var badCalls atomic.Int32 + badUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + badCalls.Add(1) + w.Header().Set("Retry-After", "45") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, `{"error":"rate_limited"}`) + })) + defer badUpstream.Close() + + var goodCalls atomic.Int32 + goodUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + goodCalls.Add(1) + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"models":["ok"]}`) + })) + defer goodUpstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, &auth.FillFirstSelector{}, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + credHigh := &auth.Auth{ + ID: "meta-high-429", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "bad-key", + "base_url": badUpstream.URL + "/v1", + "priority": "10", + }, + } + credBackup := &auth.Auth{ + ID: "meta-backup-ok", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "good-key", + "base_url": goodUpstream.URL + "/v1", + "priority": "1", + }, + } + registerMetaTestCred(t, manager, credHigh, "muse-wonder-1.0") + registerMetaTestCred(t, manager, credBackup, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + // Request 1 hits credHigh -> 429 with Retry-After: 45, cools credHigh. + rec1 := httptest.NewRecorder() + router.ServeHTTP(rec1, httptest.NewRequest(http.MethodPost, "/muse-code/search", strings.NewReader(`{"q":"go"}`))) + if rec1.Code != http.StatusTooManyRequests || rec1.Header().Get("Retry-After") != "45" { + t.Fatalf("first response = status %d Retry-After %q, want 429 / 45", rec1.Code, rec1.Header().Get("Retry-After")) + } + + // Request 2 skips cooled credHigh and routes to credBackup. + rec2 := httptest.NewRecorder() + router.ServeHTTP(rec2, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec2.Code != http.StatusOK { + t.Fatalf("second response = status %d, want 200; body=%s", rec2.Code, rec2.Body.String()) + } + if badCalls.Load() != 1 || goodCalls.Load() != 1 { + t.Fatalf("calls bad=%d good=%d, want 1 and 1", badCalls.Load(), goodCalls.Load()) + } +} + +func TestRelayModelCooldownDoesNotHideOtherHealthyCredential(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"ok":true}`) + })) + defer upstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + + credA := &auth.Auth{ + ID: "meta-cred-a", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "key-a", + "base_url": upstream.URL + "/v1", + }, + } + credB := &auth.Auth{ + ID: "meta-cred-b", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "key-b", + "base_url": upstream.URL + "/v1", + }, + } + registerMetaTestCred(t, manager, credA, "muse-spark-1.3") + registerMetaTestCred(t, manager, credB, "muse-wonder-1.0") + + // Cool down muse-spark-1.3 on credA; credB serving muse-wonder-1.0 must still work. + manager.MarkResult(context.Background(), auth.Result{ + AuthID: credA.ID, + Provider: "meta", + Model: "muse-spark-1.3", + Success: false, + Error: &auth.Error{HTTPStatus: http.StatusTooManyRequests, Message: "quota"}, + }) + + router := newTestRouter(NewHandler(manager, cfg)) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } +} + +func TestOriginFromAuth(t *testing.T) { + for _, tc := range []struct { + name string + auth *auth.Auth + want string + wantErr bool + }{ + { + name: "default", + auth: &auth.Auth{}, + want: "https://api.meta.ai", + }, + { + name: "attribute base_url", + auth: &auth.Auth{Attributes: map[string]string{"base_url": "https://regional.meta.ai/api/v1"}}, + want: "https://regional.meta.ai", + }, + { + name: "metadata api_base_url", + auth: &auth.Auth{Metadata: map[string]any{"api_base_url": "http://127.0.0.1:8080/v1"}}, + want: "http://127.0.0.1:8080", + }, + { + name: "empty metadata base_url falls back to api_base_url", + auth: &auth.Auth{Metadata: map[string]any{"base_url": "", "api_base_url": "https://regional.example/v1"}}, + want: "https://regional.example", + }, + { + name: "whitespace metadata base_url falls back to api_base_url", + auth: &auth.Auth{Metadata: map[string]any{"base_url": " \t ", "api_base_url": "https://regional.example/v1"}}, + want: "https://regional.example", + }, + { + name: "invalid url", + auth: &auth.Auth{Attributes: map[string]string{"base_url": "ftp://invalid.example/v1"}}, + wantErr: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + got, errOrigin := originFromAuth(tc.auth) + if tc.wantErr { + if errOrigin == nil { + t.Fatalf("expected error, got %q", got) + } + return + } + if errOrigin != nil { + t.Fatalf("unexpected error: %v", errOrigin) + } + if got != tc.want { + t.Fatalf("origin = %q, want %q", got, tc.want) + } + }) + } +} + +type museCodeRoundTripper func(*http.Request) (*http.Response, error) + +func (fn museCodeRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + return fn(req) +} + +type errUnexpectedEOFBody struct{} + +func (errUnexpectedEOFBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF } +func (errUnexpectedEOFBody) Close() error { return nil } + +func TestRelayTransportDropsAndClientCancelDoNotCooldownCredential(t *testing.T) { + assertHealthy := func(t *testing.T, manager *auth.Manager, id string) { + t.Helper() + cred, ok := manager.GetByID(id) + if !ok || cred == nil { + t.Fatalf("credential %s missing", id) + } + if cred.Unavailable || cred.Status != auth.StatusActive || !cred.NextRetryAfter.IsZero() || cred.Quota.Exceeded { + t.Fatalf("credential %s was unexpectedly cooled down: status=%s unavailable=%v retry=%v quota=%+v", + id, cred.Status, cred.Unavailable, cred.NextRetryAfter, cred.Quota) + } + } + + t.Run("client_cancel", func(t *testing.T) { + inFlight := make(chan struct{}) + release := make(chan struct{}) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(inFlight) + select { + case <-r.Context().Done(): + case <-release: + } + })) + defer func() { + close(release) + upstream.Close() + }() + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-cancel-test", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{"api_key": "meta-secret", "base_url": upstream.URL + "/v1"}, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + ctx, cancel := context.WithCancel(context.Background()) + req := httptest.NewRequest(http.MethodGet, "/muse-code/config", nil).WithContext(ctx) + rec := httptest.NewRecorder() + done := make(chan struct{}) + go func() { + defer close(done) + router.ServeHTTP(rec, req) + }() + <-inFlight + cancel() + <-done + + if rec.Code != 499 { + t.Fatalf("client cancel status = %d, want 499", rec.Code) + } + assertHealthy(t, manager, cred.ID) + }) + + t.Run("connection_reset", func(t *testing.T) { + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-connreset-test", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{"api_key": "meta-secret", "base_url": "https://api.meta.ai/v1"}, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", museCodeRoundTripper(func(req *http.Request) (*http.Response, error) { + return nil, &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET} + })) + req := httptest.NewRequest(http.MethodGet, "/muse-code/config", nil).WithContext(ctx) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + if rec.Code != http.StatusBadGateway { + t.Fatalf("connection reset status = %d, want 502; body=%s", rec.Code, rec.Body.String()) + } + assertHealthy(t, manager, cred.ID) + }) + + t.Run("response_body_unexpected_eof", func(t *testing.T) { + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-eof-test", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{"api_key": "meta-secret", "base_url": "https://api.meta.ai/v1"}, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", museCodeRoundTripper(func(req *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: errUnexpectedEOFBody{}, + Request: req, + }, nil + })) + req := httptest.NewRequest(http.MethodGet, "/muse-code/config", nil).WithContext(ctx) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + if rec.Code != http.StatusBadGateway { + t.Fatalf("unexpected eof status = %d, want 502; body=%s", rec.Code, rec.Body.String()) + } + assertHealthy(t, manager, cred.ID) + }) +} + +func TestRelayConcurrent200DoesNotClearNewer429Cooldown(t *testing.T) { + configStarted := make(chan struct{}) + releaseConfig := make(chan struct{}) + var configOnce sync.Once + var upstreamCalls atomic.Int32 + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + switch r.URL.Path { + case "/muse-code/config": + configOnce.Do(func() { close(configStarted) }) + <-releaseConfig + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"ok":true}`) + case "/muse-code/search": + w.Header().Set("Retry-After", "45") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, `{"error":"rate_limited"}`) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer upstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-seq-race-test", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{"api_key": "meta-secret", "base_url": upstream.URL + "/v1"}, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + // 1. Start config request and hold it mid-flight before its 200 completes. + rec1 := httptest.NewRecorder() + done1 := make(chan struct{}) + go func() { + defer close(done1) + router.ServeHTTP(rec1, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + }() + <-configStarted + + // 2. While request 1 is in flight, search request receives 429 and records cooldown. + rec2 := httptest.NewRecorder() + router.ServeHTTP(rec2, httptest.NewRequest(http.MethodPost, "/muse-code/search", strings.NewReader(`{"q":"test"}`))) + if rec2.Code != http.StatusTooManyRequests { + close(releaseConfig) + <-done1 + t.Fatalf("search status = %d, want 429", rec2.Code) + } + + // 3. Release request 1 so its stale 200 arrives after the 429 cooldown. + close(releaseConfig) + <-done1 + if rec1.Code != http.StatusOK { + t.Fatalf("config status = %d, want 200", rec1.Code) + } + + // 4. Cooldown must remain intact; a follow-up request must not call upstream. + snap, ok := manager.GetByID(cred.ID) + if !ok || snap == nil { + t.Fatalf("credential missing") + } + if !snap.Unavailable || !snap.Quota.Exceeded || !snap.NextRetryAfter.After(time.Now()) { + t.Fatalf("stale 200 cleared newer 429 cooldown: unavailable=%v quota=%+v nextRetry=%v", + snap.Unavailable, snap.Quota, snap.NextRetryAfter) + } + + callsBefore := upstreamCalls.Load() + rec3 := httptest.NewRecorder() + router.ServeHTTP(rec3, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec3.Code != http.StatusTooManyRequests { + t.Fatalf("follow-up status = %d, want 429; body=%s", rec3.Code, rec3.Body.String()) + } + if upstreamCalls.Load() != callsBefore { + t.Fatalf("cooled credential was called again (%d -> %d)", callsBefore, upstreamCalls.Load()) + } +} + +func TestRelayRespectsRequestScopedErrorRulesOn401And429(t *testing.T) { + var mintCalls atomic.Int32 + mintServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mintCalls.Add(1) + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"api_key":"should-not-mint"}`) + })) + defer mintServer.Close() + t.Setenv("META_MINT_URL", mintServer.URL) + + var upstreamStatus atomic.Int32 + var upstreamBody atomic.Value + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + status := int(upstreamStatus.Load()) + if status == http.StatusTooManyRequests { + w.Header().Set("Retry-After", "60") + } + w.WriteHeader(status) + body, _ := upstreamBody.Load().(string) + _, _ = io.WriteString(w, body) + })) + defer upstream.Close() + + cfg := &config.Config{ + OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{ + "meta": { + { + Status: 401, + Match: []string{"scoped_unauthorized"}, + Action: auth.RequestScopedActionStop, + }, + { + Status: 429, + Match: []string{"scoped_rate_limit"}, + Action: auth.RequestScopedActionStop, + }, + }, + }, + } + manager := auth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + cred := &auth.Auth{ + ID: "meta-request-scoped-test", + Provider: "meta", + Status: auth.StatusActive, + Metadata: map[string]any{ + "type": "meta", + "access_token": "valid-oauth-key", + "api_key": "valid-oauth-key", + "dca_token": "dca:valid", + "base_url": upstream.URL + "/v1", + }, + Attributes: map[string]string{ + "auth_kind": "oauth", + "api_key": "valid-oauth-key", + "base_url": upstream.URL + "/v1", + }, + } + registerMetaTestCred(t, manager, cred, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + assertHealthy := func(t *testing.T) { + t.Helper() + snap, ok := manager.GetByID(cred.ID) + if !ok || snap == nil { + t.Fatalf("credential missing") + } + if snap.Unavailable || snap.Status != auth.StatusActive || !snap.NextRetryAfter.IsZero() || snap.Quota.Exceeded || snap.RejectedAccessToken != "" { + t.Fatalf("request-scoped stop altered credential state: status=%s unavailable=%v retry=%v quota=%+v rejected=%q", + snap.Status, snap.Unavailable, snap.NextRetryAfter, snap.Quota, snap.RejectedAccessToken) + } + } + + // 1. 401 matching request-scoped stop skips refresh, keeps token unrejected, keeps credential active. + upstreamStatus.Store(http.StatusUnauthorized) + upstreamBody.Store(`{"error":"scoped_unauthorized"}`) + rec401 := httptest.NewRecorder() + router.ServeHTTP(rec401, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec401.Code != http.StatusUnauthorized { + t.Fatalf("401 status = %d, want 401", rec401.Code) + } + if mintCalls.Load() != 0 { + t.Fatalf("mintCalls = %d, want 0 on request-scoped 401", mintCalls.Load()) + } + assertHealthy(t) + + // 2. 429 matching request-scoped stop skips quota cooldown and keeps credential active. + upstreamStatus.Store(http.StatusTooManyRequests) + upstreamBody.Store(`{"error":"scoped_rate_limit"}`) + rec429 := httptest.NewRecorder() + router.ServeHTTP(rec429, httptest.NewRequest(http.MethodPost, "/muse-code/search", strings.NewReader(`{"q":"test"}`))) + if rec429.Code != http.StatusTooManyRequests { + t.Fatalf("429 status = %d, want 429", rec429.Code) + } + assertHealthy(t) + + // 3. Subsequent request still uses the same credential without cooldown blocking. + upstreamStatus.Store(http.StatusOK) + upstreamBody.Store(`{"models":[]}`) + rec200 := httptest.NewRecorder() + router.ServeHTTP(rec200, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec200.Code != http.StatusOK { + t.Fatalf("follow-up status = %d, want 200; body=%s", rec200.Code, rec200.Body.String()) + } + assertHealthy(t) +} + +func TestRelay429AfterPriorGenerationModelStateFailsOverToBackup(t *testing.T) { + var primaryCalls atomic.Int32 + primaryUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + primaryCalls.Add(1) + w.Header().Set("Retry-After", "45") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, `{"error":"rate_limited"}`) + })) + defer primaryUpstream.Close() + + var backupCalls atomic.Int32 + backupUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + backupCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"models":["backup"]}`) + })) + defer backupUpstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, &auth.FillFirstSelector{}, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + + credPrimary := &auth.Auth{ + ID: "meta-primary-with-model-state", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "primary-key", + "base_url": primaryUpstream.URL + "/v1", + "priority": "10", + }, + } + credBackup := &auth.Auth{ + ID: "meta-backup-healthy", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "backup-key", + "base_url": backupUpstream.URL + "/v1", + "priority": "1", + }, + } + registerMetaTestCred(t, manager, credPrimary, "muse-wonder-1.0") + registerMetaTestCred(t, manager, credBackup, "muse-wonder-1.0") + + // Seed an active model state on credPrimary as left by prior /v1/responses generation. + manager.MarkResult(context.Background(), auth.Result{ + AuthID: credPrimary.ID, + Provider: "meta", + Model: "muse-wonder-1.0", + Success: true, + CompletedResponse: true, + }) + seeded, _ := manager.GetByID(credPrimary.ID) + if seeded == nil || len(seeded.ModelStates) == 0 { + t.Fatalf("expected seeded ModelStates on primary credential") + } + + router := newTestRouter(NewHandler(manager, cfg)) + + // 1. /muse-code/search hits credPrimary and receives 429. + recSearch := httptest.NewRecorder() + router.ServeHTTP(recSearch, httptest.NewRequest(http.MethodPost, "/muse-code/search", strings.NewReader(`{"q":"go"}`))) + if recSearch.Code != http.StatusTooManyRequests { + t.Fatalf("search status = %d, want 429; body=%s", recSearch.Code, recSearch.Body.String()) + } + + // Verify credential_quota is recorded and propagated to existing model states. + after429, _ := manager.GetByID(credPrimary.ID) + if after429 == nil || !after429.Quota.Exceeded || after429.Quota.Reason != auth.ErrorCodeCredentialQuota { + t.Fatalf("primary quota = %+v, want Exceeded=true Reason=credential_quota", after429.Quota) + } + if ms := after429.ModelStates["muse-wonder-1.0"]; ms == nil || !ms.Quota.Exceeded || ms.Quota.Reason != auth.ErrorCodeCredentialQuota { + t.Fatalf("primary model state = %+v, want propagated credential_quota", ms) + } + + // 2. Subsequent /muse-code/config must skip cooled credPrimary and hit credBackup. + recConfig := httptest.NewRecorder() + router.ServeHTTP(recConfig, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if recConfig.Code != http.StatusOK { + t.Fatalf("config status = %d, want 200; body=%s", recConfig.Code, recConfig.Body.String()) + } + if primaryCalls.Load() != 1 || backupCalls.Load() != 1 { + t.Fatalf("calls primary=%d backup=%d, want 1 and 1", primaryCalls.Load(), backupCalls.Load()) + } +} + +func TestRelayNon429CredentialCooldownBlocksAllModelsEvenStatelessOnes(t *testing.T) { + var primaryCalls atomic.Int32 + primaryUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + primaryCalls.Add(1) + w.WriteHeader(http.StatusForbidden) + _, _ = io.WriteString(w, `{"error":"forbidden"}`) + })) + defer primaryUpstream.Close() + + var backupCalls atomic.Int32 + backupUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + backupCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"models":["backup"]}`) + })) + defer backupUpstream.Close() + + cfg := &config.Config{} + manager := auth.NewManager(nil, &auth.FillFirstSelector{}, nil) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + + credPrimary := &auth.Auth{ + ID: "meta-primary-403-partial-state", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "primary-key", + "base_url": primaryUpstream.URL + "/v1", + "priority": "10", + }, + } + credBackup := &auth.Auth{ + ID: "meta-backup-403-healthy", + Provider: "meta", + Status: auth.StatusActive, + Attributes: map[string]string{ + "api_key": "backup-key", + "base_url": backupUpstream.URL + "/v1", + "priority": "1", + }, + } + // Register two models; seed ModelStates ONLY for muse-wonder-1.0 so muse-spark-1.3 remains stateless. + registerMetaTestCred(t, manager, credPrimary, "muse-spark-1.3", "muse-wonder-1.0") + registerMetaTestCred(t, manager, credBackup, "muse-spark-1.3", "muse-wonder-1.0") + + manager.MarkResult(context.Background(), auth.Result{ + AuthID: credPrimary.ID, + Provider: "meta", + Model: "muse-wonder-1.0", + Success: true, + CompletedResponse: true, + }) + + router := newTestRouter(NewHandler(manager, cfg)) + + recSearch := httptest.NewRecorder() + router.ServeHTTP(recSearch, httptest.NewRequest(http.MethodPost, "/muse-code/search", strings.NewReader(`{"q":"go"}`))) + if recSearch.Code != http.StatusForbidden { + t.Fatalf("search status = %d, want 403; body=%s", recSearch.Code, recSearch.Body.String()) + } + + // Next request sorts models and tries stateless muse-spark-1.3 first: credPrimary must still be blocked. + recConfig := httptest.NewRecorder() + router.ServeHTTP(recConfig, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if recConfig.Code != http.StatusOK { + t.Fatalf("config status = %d, want 200; body=%s", recConfig.Code, recConfig.Body.String()) + } + if primaryCalls.Load() != 1 || backupCalls.Load() != 1 { + t.Fatalf("calls primary=%d backup=%d, want 1 and 1", primaryCalls.Load(), backupCalls.Load()) + } +} + +func TestRelayRequestScopedContinueAndCooldownFailover(t *testing.T) { + t.Run("continue_fails_over_without_cooling_primary", func(t *testing.T) { + var primaryCalls atomic.Int32 + primaryUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + primaryCalls.Add(1) + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":"scoped_continue_401"}`) + })) + defer primaryUpstream.Close() + + var backupCalls atomic.Int32 + backupUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + backupCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"models":["from-backup"]}`) + })) + defer backupUpstream.Close() + + cfg := &config.Config{ + OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{ + "meta": { + { + Status: 401, + Match: []string{"scoped_continue_401"}, + Action: auth.RequestScopedActionContinue, + }, + }, + }, + } + manager := auth.NewManager(nil, &auth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + + credPrimary := &auth.Auth{ + ID: "meta-continue-primary", + Provider: "meta", + Status: auth.StatusActive, + Metadata: map[string]any{"type": "meta", "access_token": "p-key", "api_key": "p-key", "dca_token": "dca:p", "base_url": primaryUpstream.URL + "/v1"}, + Attributes: map[string]string{ + "auth_kind": "oauth", + "api_key": "p-key", + "base_url": primaryUpstream.URL + "/v1", + "priority": "10", + }, + } + credBackup := &auth.Auth{ + ID: "meta-continue-backup", + Provider: "meta", + Status: auth.StatusActive, + Metadata: map[string]any{"type": "meta", "access_token": "b-key", "api_key": "b-key", "base_url": backupUpstream.URL + "/v1"}, + Attributes: map[string]string{ + "auth_kind": "oauth", + "api_key": "b-key", + "base_url": backupUpstream.URL + "/v1", + "priority": "1", + }, + } + registerMetaTestCred(t, manager, credPrimary, "muse-wonder-1.0") + registerMetaTestCred(t, manager, credBackup, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "from-backup") { + t.Fatalf("status=%d body=%q, want 200 from backup", rec.Code, rec.Body.String()) + } + if primaryCalls.Load() != 1 || backupCalls.Load() != 1 { + t.Fatalf("calls primary=%d backup=%d, want 1 and 1", primaryCalls.Load(), backupCalls.Load()) + } + snap, _ := manager.GetByID(credPrimary.ID) + if snap == nil || snap.Unavailable || snap.Status != auth.StatusActive || snap.RejectedAccessToken != "" { + t.Fatalf("continue must not cool or reject primary credential: %+v", snap) + } + }) + + t.Run("continue_bounded_by_max_retry_credentials", func(t *testing.T) { + var primaryCalls, backupCalls atomic.Int32 + primaryUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + primaryCalls.Add(1) + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":"scoped_continue_401"}`) + })) + defer primaryUpstream.Close() + backupUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + backupCalls.Add(1) + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"models":["backup"]}`) + })) + defer backupUpstream.Close() + + cfg := &config.Config{ + OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{ + "meta": {{Status: 401, Match: []string{"scoped_continue_401"}, Action: auth.RequestScopedActionContinue}}, + }, + } + manager := auth.NewManager(nil, &auth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(0, 0, 1) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + + registerMetaTestCred(t, manager, &auth.Auth{ + ID: "meta-bound-p", Provider: "meta", Status: auth.StatusActive, + Attributes: map[string]string{"auth_kind": "oauth", "api_key": "p-key", "base_url": primaryUpstream.URL + "/v1", "priority": "10"}, + }, "muse-wonder-1.0") + registerMetaTestCred(t, manager, &auth.Auth{ + ID: "meta-bound-b", Provider: "meta", Status: auth.StatusActive, + Attributes: map[string]string{"auth_kind": "oauth", "api_key": "b-key", "base_url": backupUpstream.URL + "/v1", "priority": "1"}, + }, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401 when MaxRetryCredentials=1", rec.Code) + } + if primaryCalls.Load() != 1 || backupCalls.Load() != 0 { + t.Fatalf("calls primary=%d backup=%d, want 1 and 0", primaryCalls.Load(), backupCalls.Load()) + } + }) + + t.Run("continue_and_cooldown_cools_primary_and_fails_over_to_backup", func(t *testing.T) { + var primaryCalls, backupCalls atomic.Int32 + primaryUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + primaryCalls.Add(1) + w.Header().Set("Retry-After", "60") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, `{"error":"scoped_continue_cooldown"}`) + })) + defer primaryUpstream.Close() + backupUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + backupCalls.Add(1) + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, `{"models":["from-backup"]}`) + })) + defer backupUpstream.Close() + + cfg := &config.Config{ + DisableCooling: true, + OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{ + "meta": {{Status: 429, Match: []string{"scoped_continue_cooldown"}, Action: auth.RequestScopedActionContinueAndCooldown}}, + }, + } + manager := auth.NewManager(nil, &auth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + + credPrimary := &auth.Auth{ + ID: "meta-cc-primary", Provider: "meta", Status: auth.StatusActive, + Attributes: map[string]string{"auth_kind": "oauth", "api_key": "p-key", "base_url": primaryUpstream.URL + "/v1", "priority": "10"}, + } + credBackup := &auth.Auth{ + ID: "meta-cc-backup", Provider: "meta", Status: auth.StatusActive, + Attributes: map[string]string{"auth_kind": "oauth", "api_key": "b-key", "base_url": backupUpstream.URL + "/v1", "priority": "1"}, + } + registerMetaTestCred(t, manager, credPrimary, "muse-wonder-1.0") + registerMetaTestCred(t, manager, credBackup, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + // First request fails over from primary to backup and force-cools primary. + rec1 := httptest.NewRecorder() + router.ServeHTTP(rec1, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec1.Code != http.StatusOK || !strings.Contains(rec1.Body.String(), "from-backup") { + t.Fatalf("first status=%d body=%q, want 200 from backup", rec1.Code, rec1.Body.String()) + } + snap, _ := manager.GetByID(credPrimary.ID) + if snap == nil || !snap.Unavailable || !snap.Quota.Exceeded || snap.Quota.Reason != auth.ErrorCodeCredentialQuota { + t.Fatalf("expected primary to be force-cooled, got %+v", snap) + } + + // Second request skips cooled primary and goes directly to backup. + rec2 := httptest.NewRecorder() + router.ServeHTTP(rec2, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec2.Code != http.StatusOK { + t.Fatalf("second status=%d, want 200", rec2.Code) + } + if primaryCalls.Load() != 1 || backupCalls.Load() != 2 { + t.Fatalf("calls primary=%d backup=%d, want 1 and 2", primaryCalls.Load(), backupCalls.Load()) + } + }) + + t.Run("continue_exhausts_all_tried_credentials_once_and_returns_last_response", func(t *testing.T) { + var calls atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":"scoped_continue_401"}`) + })) + defer upstream.Close() + + cfg := &config.Config{ + OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{ + "meta": {{Status: 401, Match: []string{"scoped_continue_401"}, Action: auth.RequestScopedActionContinue}}, + }, + } + manager := auth.NewManager(nil, &auth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + + registerMetaTestCred(t, manager, &auth.Auth{ + ID: "meta-exhaust-1", Provider: "meta", Status: auth.StatusActive, + Attributes: map[string]string{"auth_kind": "oauth", "api_key": "k1", "base_url": upstream.URL + "/v1", "priority": "10"}, + }, "muse-wonder-1.0") + registerMetaTestCred(t, manager, &auth.Auth{ + ID: "meta-exhaust-2", Provider: "meta", Status: auth.StatusActive, + Attributes: map[string]string{"auth_kind": "oauth", "api_key": "k2", "base_url": upstream.URL + "/v1", "priority": "1"}, + }, "muse-wonder-1.0") + router := newTestRouter(NewHandler(manager, cfg)) + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/muse-code/config", nil)) + if rec.Code != http.StatusUnauthorized || !strings.Contains(rec.Body.String(), "scoped_continue_401") { + t.Fatalf("status=%d body=%q, want final 401 upstream error", rec.Code, rec.Body.String()) + } + if calls.Load() != 2 { + t.Fatalf("calls = %d, want 2 (each credential tried once)", calls.Load()) + } + }) +} diff --git a/internal/cmd/anthropic_login.go b/internal/cmd/anthropic_login.go index e2d240b1fbe..f01aa344451 100644 --- a/internal/cmd/anthropic_login.go +++ b/internal/cmd/anthropic_login.go @@ -34,6 +34,7 @@ func DoClaudeLogin(cfg *config.Config, options *LoginOptions) { authOpts := &sdkAuth.LoginOptions{ NoBrowser: options.NoBrowser, CallbackPort: options.CallbackPort, + ProxyURL: options.ProxyURL, Metadata: map[string]string{}, Prompt: promptFn, } diff --git a/internal/cmd/antigravity_login.go b/internal/cmd/antigravity_login.go index e5f06262e13..7dac2c47528 100644 --- a/internal/cmd/antigravity_login.go +++ b/internal/cmd/antigravity_login.go @@ -24,6 +24,7 @@ func DoAntigravityLogin(cfg *config.Config, options *LoginOptions) { authOpts := &sdkAuth.LoginOptions{ NoBrowser: options.NoBrowser, CallbackPort: options.CallbackPort, + ProxyURL: options.ProxyURL, Metadata: map[string]string{}, Prompt: promptFn, } diff --git a/internal/cmd/devin_login.go b/internal/cmd/devin_login.go index b12e8ffc002..284000b3ae7 100644 --- a/internal/cmd/devin_login.go +++ b/internal/cmd/devin_login.go @@ -24,6 +24,7 @@ func DoDevinLogin(cfg *config.Config, options *LoginOptions) { authOpts := &sdkAuth.LoginOptions{ NoBrowser: options.NoBrowser, CallbackPort: options.CallbackPort, + ProxyURL: options.ProxyURL, Metadata: map[string]string{}, Prompt: promptFn, } diff --git a/internal/cmd/kimi_login.go b/internal/cmd/kimi_login.go index 870986130fa..c69382dc823 100644 --- a/internal/cmd/kimi_login.go +++ b/internal/cmd/kimi_login.go @@ -39,6 +39,7 @@ func doKimiLoginWithProvider(cfg *config.Config, options *LoginOptions, provider NoBrowser: options.NoBrowser, Metadata: map[string]string{}, Prompt: options.Prompt, + ProxyURL: options.ProxyURL, } record, savedPath, err := manager.Login(context.Background(), provider, cfg, authOpts) diff --git a/internal/cmd/meta_login.go b/internal/cmd/meta_login.go index 365b6c01b54..37641c25d90 100644 --- a/internal/cmd/meta_login.go +++ b/internal/cmd/meta_login.go @@ -24,6 +24,7 @@ func DoMetaLogin(cfg *config.Config, options *LoginOptions) { authOpts := &sdkAuth.LoginOptions{ NoBrowser: options.NoBrowser, CallbackPort: options.CallbackPort, + ProxyURL: options.ProxyURL, Metadata: map[string]string{}, Prompt: promptFn, } diff --git a/internal/cmd/openai_device_login.go b/internal/cmd/openai_device_login.go index 57415669cbe..040c82f1cb3 100644 --- a/internal/cmd/openai_device_login.go +++ b/internal/cmd/openai_device_login.go @@ -34,6 +34,7 @@ func DoCodexDeviceLogin(cfg *config.Config, options *LoginOptions) { authOpts := &sdkAuth.LoginOptions{ NoBrowser: options.NoBrowser, CallbackPort: options.CallbackPort, + ProxyURL: options.ProxyURL, Metadata: map[string]string{ codexLoginModeMetadataKey: codexLoginModeDevice, }, diff --git a/internal/cmd/openai_login.go b/internal/cmd/openai_login.go index a9574e10c4e..f0b1b2e52f6 100644 --- a/internal/cmd/openai_login.go +++ b/internal/cmd/openai_login.go @@ -24,6 +24,8 @@ type LoginOptions struct { // Prompt allows the caller to provide interactive input when needed. Prompt func(prompt string) (string, error) + + ProxyURL string } // DoCodexLogin triggers the Codex OAuth flow through the shared authentication manager. @@ -48,6 +50,7 @@ func DoCodexLogin(cfg *config.Config, options *LoginOptions) { authOpts := &sdkAuth.LoginOptions{ NoBrowser: options.NoBrowser, CallbackPort: options.CallbackPort, + ProxyURL: options.ProxyURL, Metadata: map[string]string{}, Prompt: promptFn, } diff --git a/internal/cmd/run.go b/internal/cmd/run.go index 8ea9f5e5baa..f390e12418e 100644 --- a/internal/cmd/run.go +++ b/internal/cmd/run.go @@ -37,12 +37,13 @@ type HostOptions struct { // - cfg: The application configuration // - configPath: The path to the configuration file // - localPassword: Optional password accepted for local management requests -func StartService(cfg *config.Config, configPath string, localPassword string) { - StartServiceWithPluginHost(cfg, configPath, localPassword, nil, HostOptions{}) +func StartService(cfg *config.Config, configPath string, localPassword string) error { + return StartServiceWithPluginHost(cfg, configPath, localPassword, nil, HostOptions{}) } // StartServiceWithPluginHost builds and runs the proxy service with a shared plugin host. -func StartServiceWithPluginHost(cfg *config.Config, configPath string, localPassword string, host *pluginhost.Host, hostOptions HostOptions, serverOptions ...api.ServerOption) { +// Startup and runtime failures are returned after cleanup; cancellation is a normal shutdown. +func StartServiceWithPluginHost(cfg *config.Config, configPath string, localPassword string, host *pluginhost.Host, hostOptions HostOptions, serverOptions ...api.ServerOption) error { builder := cliproxy.NewBuilder(). WithConfig(cfg). WithConfigPath(configPath). @@ -63,7 +64,7 @@ func StartServiceWithPluginHost(cfg *config.Config, configPath string, localPass builder, errHostOptions = applyHostOptions(builder, hostOptions, runCtx, cancelRun) if errHostOptions != nil { log.Errorf("invalid host options: %v", errHostOptions) - return + return errHostOptions } if localPassword != "" { @@ -78,13 +79,15 @@ func StartServiceWithPluginHost(cfg *config.Config, configPath string, localPass service, err := builder.Build() if err != nil { log.Errorf("failed to build proxy service: %v", err) - return + return err } err = service.Run(runCtx) if err != nil && !errors.Is(err, context.Canceled) { log.Errorf("proxy service exited with error: %v", err) + return err } + return nil } func applyHostOptions(builder *cliproxy.Builder, hostOptions HostOptions, runCtx context.Context, cancelRun context.CancelFunc) (*cliproxy.Builder, error) { diff --git a/internal/cmd/run_test.go b/internal/cmd/run_test.go index 83ca09524f9..c37be86f8c0 100644 --- a/internal/cmd/run_test.go +++ b/internal/cmd/run_test.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "strconv" + "strings" "testing" "time" @@ -102,3 +103,15 @@ func waitForBackgroundServer(t *testing.T, client *http.Client, url, key string) } t.Fatal("background service did not become ready") } + +func TestStartServiceReturnsBuildError(t *testing.T) { + if errStart := StartService(nil, "", ""); errStart == nil || !strings.Contains(errStart.Error(), "configuration is required") { + t.Fatalf("expected missing configuration error, got %v", errStart) + } +} + +func TestStartServiceWithPluginHostReturnsBuildError(t *testing.T) { + if errStart := StartServiceWithPluginHost(nil, "", "", nil, HostOptions{}); errStart == nil || !strings.Contains(errStart.Error(), "configuration is required") { + t.Fatalf("expected missing configuration error, got %v", errStart) + } +} diff --git a/internal/cmd/siwc_bind.go b/internal/cmd/siwc_bind.go index f186fb0ee0c..fe476b1a053 100644 --- a/internal/cmd/siwc_bind.go +++ b/internal/cmd/siwc_bind.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/MoeForge/moego/ojson" "github.com/google/uuid" "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" "github.com/router-for-me/CLIProxyAPI/v8/internal/browser" @@ -157,6 +158,17 @@ func DoSIWCBind(cfg *config.Config, target string, options *LoginOptions) { log.Errorf("siwc-bind: %v", errDevice) return } + credentialBytes, errRead := os.ReadFile(authFilePath) + if errRead != nil { + log.Errorf("siwc-bind: failed to read saved registration: %v", errRead) + return + } + registration := ojson.GetBytes(credentialBytes, "siwc.client_id") + if !ojson.ValidBytes(credentialBytes) || (registration.Exists() && registration.Type != ojson.String) { + log.Error("siwc-bind: invalid saved registration") + return + } + savedClientID := strings.TrimSpace(registration.Str) callbackPort := codex.SIWCCallbackPort if options.CallbackPort > 0 { @@ -200,6 +212,9 @@ func DoSIWCBind(cfg *config.Config, target string, options *LoginOptions) { authSvc := codex.NewCodexAuth(cfg) authURL, errURL := authSvc.GenerateSIWCAuthURL(state, nonce, deviceID, redirectURI, pkceCodes) + if savedClientID != "" { + authURL, errURL = authSvc.GenerateSIWCReauthURL(savedClientID, state, nonce, deviceID, redirectURI, pkceCodes) + } if errURL != nil { log.Errorf("siwc-bind: failed to generate authorization URL: %v", errURL) return @@ -305,12 +320,20 @@ waitForCallback: fmt.Println("Sign in with ChatGPT authentication failed: state mismatch") return } - if strings.TrimSpace(result.ClientID) == "" { + issuedClientID := strings.TrimSpace(result.ClientID) + if savedClientID != "" { + if issuedClientID != "" && issuedClientID != savedClientID { + fmt.Println("Sign in with ChatGPT authentication failed: callback client ID does not match the saved registration") + return + } + issuedClientID = savedClientID + } + if issuedClientID == "" || issuedClientID == codex.SIWCDynamicClientID { fmt.Println("Sign in with ChatGPT authentication failed: callback did not contain an issued client ID") return } - siwcData, errExchange := authSvc.ExchangeSIWCCodeForTokens(context.Background(), result.Code, result.ClientID, redirectURI, deviceID, pkceCodes) + siwcData, errExchange := authSvc.ExchangeSIWCCodeForTokens(context.Background(), result.Code, issuedClientID, redirectURI, deviceID, pkceCodes) if errExchange != nil { fmt.Printf("Sign in with ChatGPT token exchange failed: %v\n", errExchange) return diff --git a/internal/cmd/siwc_reauth_test.go b/internal/cmd/siwc_reauth_test.go new file mode 100644 index 00000000000..5f32f348b11 --- /dev/null +++ b/internal/cmd/siwc_reauth_test.go @@ -0,0 +1,143 @@ +package cmd + +import ( + "bufio" + "context" + "io" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" +) + +type siwcBindRoundTripper func(*http.Request) (*http.Response, error) + +func (f siwcBindRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } + +func TestDoSIWCBindReusesSavedRegistration(t *testing.T) { + for _, tc := range []struct { + name, returned string + wantSuccess bool + }{ + {"callback omits unchanged client", "", true}, + {"callback confirms saved client", "oaiapp_saved", true}, + {"callback changes client", "oaiapp_other", false}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "codex.json") + const initial = `{"type":"codex","access_token":"outer","refresh_token":"outer-refresh","siwc":{"access_token":"old","refresh_token":"old-refresh","client_id":"oaiapp_saved","device_id":"e61bbe28-07ef-466d-8e5d-a344f94ab305"}}` + if errWrite := os.WriteFile(path, []byte(initial), 0o600); errWrite != nil { + t.Fatal(errWrite) + } + listener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + port := listener.Addr().(*net.TCPAddr).Port + if errClose := listener.Close(); errClose != nil { + t.Fatal(errClose) + } + previousTransport := http.DefaultTransport + t.Cleanup(func() { http.DefaultTransport = previousTransport }) + exchanges := 0 + http.DefaultTransport = siwcBindRoundTripper(func(req *http.Request) (*http.Response, error) { + if req.URL.String() != codex.SIWCTokenURL { + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("127.0.0.1"))}, nil + } + exchanges++ + if errParse := req.ParseForm(); errParse != nil { + return nil, errParse + } + if req.Form.Get("client_id") != "oaiapp_saved" { + t.Errorf("token exchange did not use the saved registration") + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"access_token":"new","refresh_token":"new-refresh","id_token":"id","expires_in":3600,"scope":"openid chatgpt.tokens.use.direct"}`))}, nil + }) + reader, writer, errPipe := os.Pipe() + if errPipe != nil { + t.Fatal(errPipe) + } + previousStdout := os.Stdout + os.Stdout = writer + t.Cleanup(func() { + os.Stdout = previousStdout + if errClose := reader.Close(); errClose != nil { + t.Error(errClose) + } + }) + done := make(chan struct{}) + go func() { + defer close(done) + defer func() { + if errClose := writer.Close(); errClose != nil { + t.Error(errClose) + } + }() + DoSIWCBind(&config.Config{AuthDir: dir}, path, &LoginOptions{NoBrowser: true, CallbackPort: port}) + }() + scanner := bufio.NewScanner(reader) + foundURL := false + for scanner.Scan() { + if !strings.HasPrefix(scanner.Text(), codex.SIWCAuthorizeURL+"?") { + continue + } + foundURL = true + authURL, errParse := url.Parse(scanner.Text()) + if errParse != nil { + t.Fatal(errParse) + } + query := authURL.Query() + if query.Get("client_id") != "oaiapp_saved" || query.Has("agent_name_hint") || query.Get("ext_agent_host_id") != "urn:uuid:e61bbe28-07ef-466d-8e5d-a344f94ab305" || query.Get("code_challenge") == "" { + t.Error("authorization URL did not preserve the issued registration, host identity, and PKCE") + } + callback := "http://127.0.0.1:" + strconv.Itoa(port) + codex.SIWCCallbackPath + values := url.Values{"code": {"code"}, "state": {query.Get("state")}, "client_id": {tc.returned}} + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + req, errRequest := http.NewRequestWithContext(ctx, http.MethodGet, callback+"?"+values.Encode(), nil) + if errRequest != nil { + cancel() + t.Fatal(errRequest) + } + callbackClient := &http.Client{Transport: previousTransport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + response, errCallback := callbackClient.Do(req) + if errCallback == nil { + if errClose := response.Body.Close(); errClose != nil { + t.Error(errClose) + } + } + cancel() + if errCallback != nil { + t.Fatal(errCallback) + } + } + if errScan := scanner.Err(); errScan != nil { + t.Fatal(errScan) + } + <-done + if !foundURL { + t.Fatal("authorization URL was not printed") + } + raw, errRead := os.ReadFile(path) + if errRead != nil { + t.Fatal(errRead) + } + if tc.wantSuccess { + if exchanges != 1 || ojson.GetBytes(raw, "siwc.refresh_token").String() != "new-refresh" || ojson.GetBytes(raw, "siwc.client_id").String() != "oaiapp_saved" { + t.Fatal("reauthorization did not persist the replacement under the saved client") + } + } else if exchanges != 0 || string(raw) != initial { + t.Fatal("mismatched callback exchanged tokens or changed the credential") + } + }) + } +} diff --git a/internal/cmd/xai_login.go b/internal/cmd/xai_login.go index ee4e9e8a545..0cba7b04941 100644 --- a/internal/cmd/xai_login.go +++ b/internal/cmd/xai_login.go @@ -24,6 +24,7 @@ func DoXAILogin(cfg *config.Config, options *LoginOptions) { authOpts := &sdkAuth.LoginOptions{ NoBrowser: options.NoBrowser, CallbackPort: options.CallbackPort, + ProxyURL: options.ProxyURL, Metadata: map[string]string{}, Prompt: promptFn, } diff --git a/internal/config/claude_code_test.go b/internal/config/claude_code_test.go index ff40947028f..5b8e901609e 100644 --- a/internal/config/claude_code_test.go +++ b/internal/config/claude_code_test.go @@ -182,3 +182,28 @@ func TestParseConfigBytesClaudeToolSearch(t *testing.T) { }) } } + +func TestParseConfigBytesClaudeServerSideFallback(t *testing.T) { + tests := []struct { + name string + yaml string + want bool + }{ + {name: "defaults to false", yaml: "port: 8317\n", want: false}, + {name: "legacy layout", yaml: "claude:\n server-side-fallback: true\n", want: true}, + {name: "v8 layout", yaml: "config-version: 8\nupstream:\n claude:\n server-side-fallback: true\n", want: true}, + {name: "v8 explicit false", yaml: "config-version: 8\nupstream:\n claude:\n server-side-fallback: false\n", want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg, errParse := ParseConfigBytes([]byte(tt.yaml)) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + if got := cfg.Claude.ServerSideFallback; got != tt.want { + t.Fatalf("cfg.Claude.ServerSideFallback = %t, want %t", got, tt.want) + } + }) + } +} diff --git a/internal/config/cloak_save_test.go b/internal/config/cloak_save_test.go index 3f97d060b19..8844decb948 100644 --- a/internal/config/cloak_save_test.go +++ b/internal/config/cloak_save_test.go @@ -295,3 +295,205 @@ claude-api-key: t.Errorf("saved YAML lost 'allow-remote: true'; got:\n%s", savedText) } } + +func TestSaveConfigPreserveComments_SensitiveWordsReplaceEmptyValueAndPruning(t *testing.T) { + for _, v8Layout := range []bool{false, true} { + name := "legacy" + initialYAML := "port: 8317\nclaude-api-key:\n - api-key: sk-ant-test\n" + if v8Layout { + name = "v8" + initialYAML = "config-version: 8\nserver:\n port: 8317\napi-keys:\n claude:\n - name: claude-1\n keys:\n - api-key: sk-ant-test\n" + } + t.Run(name, func(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.yaml") + if errWrite := os.WriteFile(configPath, []byte(initialYAML), 0o600); errWrite != nil { + t.Fatalf("os.WriteFile() error = %v", errWrite) + } + cfg, errLoad := LoadConfigOptional(configPath, false) + if errLoad != nil { + t.Fatalf("initial LoadConfigOptional() error = %v", errLoad) + } + + // Step 1: Save empty-string deletion entries in all three scopes. + cfg.Antigravity.SensitiveWordsReplace = map[string]string{ + "You are Codex, an agent based on GPT-5.": "", + "TempAntigrav": "Keep", + } + cfg.Devin.SensitiveWordsReplace = map[string]string{ + "DropDevinPhrase": "", + } + cfg.ClaudeKey[0].Cloak = &CloakConfig{ + SensitiveWordsReplace: map[string]string{ + "DropClaudePhrase": "", + "OldClaudeTarget": "OldRepl", + }, + } + if errSave := SaveConfigPreserveComments(configPath, cfg); errSave != nil { + t.Fatalf("SaveConfigPreserveComments() step 1 error = %v", errSave) + } + reloaded, errReload := LoadConfigOptional(configPath, false) + if errReload != nil { + t.Fatalf("reload step 1 error = %v", errReload) + } + if val, ok := reloaded.Antigravity.SensitiveWordsReplace["You are Codex, an agent based on GPT-5."]; !ok || val != "" { + t.Fatalf("Antigravity empty replacement lost: %#v", reloaded.Antigravity.SensitiveWordsReplace) + } + if val, ok := reloaded.Devin.SensitiveWordsReplace["DropDevinPhrase"]; !ok || val != "" { + t.Fatalf("Devin empty replacement lost: %#v", reloaded.Devin.SensitiveWordsReplace) + } + if reloaded.ClaudeKey[0].Cloak == nil { + t.Fatal("Claude Cloak is nil after step 1") + } + if val, ok := reloaded.ClaudeKey[0].Cloak.SensitiveWordsReplace["DropClaudePhrase"]; !ok || val != "" { + t.Fatalf("Claude empty replacement lost: %#v", reloaded.ClaudeKey[0].Cloak.SensitiveWordsReplace) + } + + // Step 2: Prune individual keys and clear Devin replacements completely. + delete(reloaded.Antigravity.SensitiveWordsReplace, "TempAntigrav") + reloaded.Devin.SensitiveWordsReplace = nil + delete(reloaded.ClaudeKey[0].Cloak.SensitiveWordsReplace, "OldClaudeTarget") + if errSave2 := SaveConfigPreserveComments(configPath, reloaded); errSave2 != nil { + t.Fatalf("SaveConfigPreserveComments() step 2 error = %v", errSave2) + } + reloaded2, errReload2 := LoadConfigOptional(configPath, false) + if errReload2 != nil { + t.Fatalf("reload step 2 error = %v", errReload2) + } + if _, exists := reloaded2.Antigravity.SensitiveWordsReplace["TempAntigrav"]; exists { + t.Fatalf("deleted Antigravity key persisted: %#v", reloaded2.Antigravity.SensitiveWordsReplace) + } + if len(reloaded2.Devin.SensitiveWordsReplace) != 0 { + t.Fatalf("cleared Devin replacements persisted: %#v", reloaded2.Devin.SensitiveWordsReplace) + } + if _, exists := reloaded2.ClaudeKey[0].Cloak.SensitiveWordsReplace["OldClaudeTarget"]; exists { + t.Fatalf("deleted Claude replacement key persisted: %#v", reloaded2.ClaudeKey[0].Cloak.SensitiveWordsReplace) + } + }) + } +} + +func TestSaveConfigPreserveComments_SensitivePatternsReplaceEmptyValueAndPruning(t *testing.T) { + for _, v8Layout := range []bool{false, true} { + name := "legacy" + initialYAML := "port: 8317\nclaude-api-key:\n - api-key: sk-ant-test\n" + if v8Layout { + name = "v8" + initialYAML = "config-version: 8\nserver:\n port: 8317\napi-keys:\n claude:\n - name: claude-1\n keys:\n - api-key: sk-ant-test\n" + } + t.Run(name, func(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.yaml") + if errWrite := os.WriteFile(configPath, []byte(initialYAML), 0o600); errWrite != nil { + t.Fatalf("os.WriteFile() error = %v", errWrite) + } + cfg, errLoad := LoadConfigOptional(configPath, false) + if errLoad != nil { + t.Fatalf("initial LoadConfigOptional() error = %v", errLoad) + } + + cfg.Antigravity.SensitivePatternsReplace = []SensitivePatternRule{ + {Pattern: `(?m)^RFC 2119[^\n]*\n?`, Replacement: ""}, + } + cfg.Devin.SensitivePatternsReplace = []SensitivePatternRule{ + {Pattern: `(?m)^You are omp[^\n]*\n?`, Replacement: ""}, + } + cfg.ClaudeKey[0].Cloak = &CloakConfig{ + SensitivePatternsReplace: []SensitivePatternRule{ + {Pattern: `(?s).*?\n?`, Replacement: ""}, + }, + } + if errSave := SaveConfigPreserveComments(configPath, cfg); errSave != nil { + t.Fatalf("SaveConfigPreserveComments() step 1 error = %v", errSave) + } + reloaded, errReload := LoadConfigOptional(configPath, false) + if errReload != nil { + t.Fatalf("reload step 1 error = %v", errReload) + } + if len(reloaded.Antigravity.SensitivePatternsReplace) != 1 || reloaded.Antigravity.SensitivePatternsReplace[0].Replacement != "" { + t.Fatalf("Antigravity patterns = %#v", reloaded.Antigravity.SensitivePatternsReplace) + } + if len(reloaded.Devin.SensitivePatternsReplace) != 1 || reloaded.Devin.SensitivePatternsReplace[0].Replacement != "" { + t.Fatalf("Devin patterns = %#v", reloaded.Devin.SensitivePatternsReplace) + } + if reloaded.ClaudeKey[0].Cloak == nil || len(reloaded.ClaudeKey[0].Cloak.SensitivePatternsReplace) != 1 { + t.Fatalf("Claude patterns = %#v", reloaded.ClaudeKey[0].Cloak) + } + + reloaded.Antigravity.SensitivePatternsReplace = nil + reloaded.Devin.SensitivePatternsReplace = nil + reloaded.ClaudeKey[0].Cloak.SensitivePatternsReplace = nil + if errSave2 := SaveConfigPreserveComments(configPath, reloaded); errSave2 != nil { + t.Fatalf("SaveConfigPreserveComments() step 2 error = %v", errSave2) + } + reloaded2, errReload2 := LoadConfigOptional(configPath, false) + if errReload2 != nil { + t.Fatalf("reload step 2 error = %v", errReload2) + } + if len(reloaded2.Antigravity.SensitivePatternsReplace) != 0 { + t.Fatalf("cleared Antigravity patterns persisted: %#v", reloaded2.Antigravity.SensitivePatternsReplace) + } + if len(reloaded2.Devin.SensitivePatternsReplace) != 0 { + t.Fatalf("cleared Devin patterns persisted: %#v", reloaded2.Devin.SensitivePatternsReplace) + } + if reloaded2.ClaudeKey[0].Cloak != nil && len(reloaded2.ClaudeKey[0].Cloak.SensitivePatternsReplace) != 0 { + t.Fatalf("cleared Claude patterns persisted: %#v", reloaded2.ClaudeKey[0].Cloak.SensitivePatternsReplace) + } + }) + } +} + +func TestSaveConfigPreserveComments_SensitivePatternsReplacePreservesComments(t *testing.T) { + for _, v8Layout := range []bool{false, true} { + name := "legacy" + initialYAML := `port: 8317 +antigravity: + # keep section comment + sensitive-patterns-replace: + # keep rule comment + - pattern: '(?m)^RFC 2119[^\n]*\n?' # keep pattern comment + replacement: "" # keep replacement comment +` + if v8Layout { + name = "v8" + initialYAML = `config-version: 8 +server: + port: 8317 +oauth: + providers: + antigravity: + # keep section comment + sensitive-patterns-replace: + # keep rule comment + - pattern: '(?m)^RFC 2119[^\n]*\n?' # keep pattern comment + replacement: "" # keep replacement comment +` + } + t.Run(name, func(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.yaml") + if errWrite := os.WriteFile(configPath, []byte(initialYAML), 0o600); errWrite != nil { + t.Fatalf("os.WriteFile() error = %v", errWrite) + } + cfg, errLoad := LoadConfigOptional(configPath, false) + if errLoad != nil { + t.Fatalf("LoadConfigOptional() error = %v", errLoad) + } + if errSave := SaveConfigPreserveComments(configPath, cfg); errSave != nil { + t.Fatalf("SaveConfigPreserveComments() error = %v", errSave) + } + savedBytes, errRead := os.ReadFile(configPath) + if errRead != nil { + t.Fatalf("os.ReadFile() error = %v", errRead) + } + saved := string(savedBytes) + for _, comment := range []string{ + "# keep section comment", + "# keep rule comment", + "# keep pattern comment", + "# keep replacement comment", + } { + if !strings.Contains(saved, comment) { + t.Fatalf("saved YAML lost comment %q:\n%s", comment, saved) + } + } + }) + } +} diff --git a/internal/config/clone_test.go b/internal/config/clone_test.go index 45a94a72fea..4dcc5971f8a 100644 --- a/internal/config/clone_test.go +++ b/internal/config/clone_test.go @@ -164,6 +164,20 @@ func sampleCloneRuntimeConfig() *Config { }, AntigravitySignatureCacheEnabled: &cacheStrict, AntigravitySignatureBypassStrict: &bypassStrict, + Antigravity: AntigravityConfig{ + SensitiveWords: []string{"Codex"}, + SensitiveWordsReplace: map[string]string{"You are Codex": "You are an assistant"}, + SensitivePatternsReplace: []SensitivePatternRule{ + {Pattern: `(?m)^RFC 2119[^\n]*\n?`, Replacement: ""}, + }, + }, + Devin: DevinConfig{ + SensitiveWords: []string{"DevinWord"}, + SensitiveWordsReplace: map[string]string{"Claude Code": "Devin"}, + SensitivePatternsReplace: []SensitivePatternRule{ + {Pattern: `(?m)^You are omp[^\n]*\n?`, Replacement: ""}, + }, + }, GeminiKey: []GeminiKey{{ APIKey: "gemini-key", Models: []GeminiModel{{Name: "gemini-upstream", Alias: "gemini-upstream-alias"}}, @@ -182,8 +196,12 @@ func sampleCloneRuntimeConfig() *Config { Headers: map[string]string{"X-Claude": "one"}, ExcludedModels: []string{"claude-hidden"}, Cloak: &CloakConfig{ - SensitiveWords: []string{"secret"}, - CacheUserID: &cacheUserID, + SensitiveWords: []string{"secret"}, + SensitiveWordsReplace: map[string]string{"Claude Code": "Claude"}, + SensitivePatternsReplace: []SensitivePatternRule{ + {Pattern: `Claude\s+Code`, Replacement: "Claude"}, + }, + CacheUserID: &cacheUserID, }, }}, OpenAICompatibility: []OpenAICompatibility{{ @@ -366,3 +384,88 @@ func TestParseConfigBytes_ProxyConnectionPool(t *testing.T) { t.Fatal("clone shares enabled pointer") } } + +func TestV8Validate_SensitiveWordsReplace(t *testing.T) { + v8YAML := []byte(`config-version: 8 +oauth: + providers: + antigravity: + sensitive-words: + - "Codex" + sensitive-words-replace: + "You are Codex, an agent based on GPT-5.": "You are a helpful coding assistant." + devin: + sensitive-words: + - "API" + sensitive-words-replace: + "Claude Code": "Devin Assistant" +api-keys: + claude: + - name: claude-1 + keys: + - api-key: sk-ant-test + cloak: + sensitive-words: + - "proxy" + sensitive-words-replace: + "Claude Code": "Claude" +`) + if err := ValidateV8Config(v8YAML); err != nil { + t.Fatalf("ValidateV8Config() error = %v", err) + } + cfg, errParse := ParseConfigBytes(v8YAML) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + if got := cfg.Antigravity.SensitiveWordsReplace["You are Codex, an agent based on GPT-5."]; got != "You are a helpful coding assistant." { + t.Fatalf("Antigravity.SensitiveWordsReplace = %#v", cfg.Antigravity.SensitiveWordsReplace) + } + if got := cfg.Devin.SensitiveWordsReplace["Claude Code"]; got != "Devin Assistant" { + t.Fatalf("Devin.SensitiveWordsReplace = %#v", cfg.Devin.SensitiveWordsReplace) + } + if len(cfg.ClaudeKey) != 1 || cfg.ClaudeKey[0].Cloak == nil || cfg.ClaudeKey[0].Cloak.SensitiveWordsReplace["Claude Code"] != "Claude" { + t.Fatalf("ClaudeKey[0].Cloak = %#v", cfg.ClaudeKey) + } +} + +func TestV8Validate_SensitivePatternsReplaceAndInvalidDrop(t *testing.T) { + v8YAML := []byte(`config-version: 8 +oauth: + providers: + antigravity: + sensitive-patterns-replace: + - pattern: '(?m)^RFC 2119[^\n]*\n?' + replacement: "" + - pattern: '[invalid' + replacement: "ignored" + devin: + sensitive-patterns-replace: + - pattern: '(?m)^You are omp[^\n]*\n?' + replacement: "" +api-keys: + claude: + - name: claude-1 + keys: + - api-key: sk-ant-test + cloak: + sensitive-patterns-replace: + - pattern: 'Claude\s+Code' + replacement: "Claude" +`) + if err := ValidateV8Config(v8YAML); err != nil { + t.Fatalf("ValidateV8Config() error = %v", err) + } + cfg, errParse := ParseConfigBytes(v8YAML) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + if len(cfg.Antigravity.SensitivePatternsReplace) != 1 || cfg.Antigravity.SensitivePatternsReplace[0].Pattern != `(?m)^RFC 2119[^\n]*\n?` || cfg.Antigravity.SensitivePatternsReplace[0].Replacement != "" { + t.Fatalf("Antigravity.SensitivePatternsReplace = %#v", cfg.Antigravity.SensitivePatternsReplace) + } + if len(cfg.Devin.SensitivePatternsReplace) != 1 || cfg.Devin.SensitivePatternsReplace[0].Pattern != `(?m)^You are omp[^\n]*\n?` { + t.Fatalf("Devin.SensitivePatternsReplace = %#v", cfg.Devin.SensitivePatternsReplace) + } + if len(cfg.ClaudeKey) != 1 || cfg.ClaudeKey[0].Cloak == nil || len(cfg.ClaudeKey[0].Cloak.SensitivePatternsReplace) != 1 || cfg.ClaudeKey[0].Cloak.SensitivePatternsReplace[0].Replacement != "Claude" { + t.Fatalf("ClaudeKey[0].Cloak.SensitivePatternsReplace = %#v", cfg.ClaudeKey) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index dad8d4354d5..9cd301bb767 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -35,6 +35,12 @@ type Config struct { // TLS config controls HTTPS server settings. TLS TLSConfig `yaml:"tls" json:"tls"` + // ShutdownTimeoutSeconds controls how long the API server waits for in-flight + // requests to finish during shutdown before forcibly closing connections. + // 0 (the default) keeps the legacy behavior of closing immediately without draining. + // Values are in seconds. + ShutdownTimeoutSeconds int `yaml:"shutdown-timeout" json:"shutdown-timeout"` + // Home config is runtime-only and is populated from -home-jwt. Home HomeConfig `yaml:"-" json:"-"` diff --git a/internal/config/config_load.go b/internal/config/config_load.go index c4ea79e5a35..4f9daa2e697 100644 --- a/internal/config/config_load.go +++ b/internal/config/config_load.go @@ -318,6 +318,10 @@ func LoadConfigOptional(configFile string, optional bool) (*Config, error) { // Sanitize Claude key headers cfg.SanitizeClaudeKeys() + // Sanitize Antigravity and Devin sensitive-word replacement maps. + cfg.SanitizeAntigravity() + cfg.SanitizeDevin() + // Sanitize OpenAI compatibility providers: drop entries without base-url cfg.SanitizeOpenAICompatibility() diff --git a/internal/config/config_normalization.go b/internal/config/config_normalization.go index 163f300a112..411f1361e01 100644 --- a/internal/config/config_normalization.go +++ b/internal/config/config_normalization.go @@ -1,6 +1,7 @@ package config import ( + "regexp" "sort" "strconv" "strings" @@ -379,6 +380,82 @@ func sanitizeCodexKeyEntries(entries []CodexKey) []CodexKey { return out } +// NormalizeSensitiveWordsReplace trims replacement target keys, drops blank keys, +// and preserves replacement values (including empty strings for phrase deletion). +func NormalizeSensitiveWordsReplace(in map[string]string) map[string]string { + if len(in) == 0 { + return nil + } + keys := make([]string, 0, len(in)) + for k := range in { + keys = append(keys, k) + } + sort.Strings(keys) + out := make(map[string]string, len(in)) + for _, rawKey := range keys { + trimmedKey := strings.TrimSpace(rawKey) + if trimmedKey == "" { + continue + } + if _, exists := out[trimmedKey]; exists && rawKey != trimmedKey { + continue + } + out[trimmedKey] = in[rawKey] + } + if len(out) == 0 { + return nil + } + return out +} + +// NormalizeSensitivePatternsReplace validates Go RE2 regex rules, logs and drops +// invalid or blank patterns, and preserves replacement values (including empty strings). +func NormalizeSensitivePatternsReplace(in []SensitivePatternRule) []SensitivePatternRule { + if len(in) == 0 { + return nil + } + out := make([]SensitivePatternRule, 0, len(in)) + for i, rule := range in { + if strings.TrimSpace(rule.Pattern) == "" { + continue + } + if _, errCompile := regexp.Compile(rule.Pattern); errCompile != nil { + log.WithFields(log.Fields{ + "rule_index": i + 1, + "pattern": rule.Pattern, + "error": errCompile, + }).Warn("sensitive-patterns-replace rule dropped: invalid regex") + continue + } + out = append(out, SensitivePatternRule{ + Pattern: rule.Pattern, + Replacement: rule.Replacement, + }) + } + if len(out) == 0 { + return nil + } + return out +} + +// SanitizeAntigravity normalizes Antigravity sensitive-word settings. +func (cfg *Config) SanitizeAntigravity() { + if cfg == nil { + return + } + cfg.Antigravity.SensitiveWordsReplace = NormalizeSensitiveWordsReplace(cfg.Antigravity.SensitiveWordsReplace) + cfg.Antigravity.SensitivePatternsReplace = NormalizeSensitivePatternsReplace(cfg.Antigravity.SensitivePatternsReplace) +} + +// SanitizeDevin normalizes Devin sensitive-word settings. +func (cfg *Config) SanitizeDevin() { + if cfg == nil { + return + } + cfg.Devin.SensitiveWordsReplace = NormalizeSensitiveWordsReplace(cfg.Devin.SensitiveWordsReplace) + cfg.Devin.SensitivePatternsReplace = NormalizeSensitivePatternsReplace(cfg.Devin.SensitivePatternsReplace) +} + // NormalizeCloakConfig trims strings and removes blank sensitive words. func NormalizeCloakConfig(cloak *CloakConfig) *CloakConfig { if cloak == nil { @@ -400,6 +477,8 @@ func NormalizeCloakConfig(cloak *CloakConfig) *CloakConfig { } else { cloak.SensitiveWords = nil } + cloak.SensitiveWordsReplace = NormalizeSensitiveWordsReplace(cloak.SensitiveWordsReplace) + cloak.SensitivePatternsReplace = NormalizeSensitivePatternsReplace(cloak.SensitivePatternsReplace) return cloak } diff --git a/internal/config/config_types.go b/internal/config/config_types.go index 7c77b7cdabf..540ca6a569f 100644 --- a/internal/config/config_types.go +++ b/internal/config/config_types.go @@ -122,6 +122,12 @@ type ClaudeConfig struct { // translation elsewhere, and per-credential search advertising in the Codex // catalog. Default false keeps the translation that predates tool_search support. ToolSearch bool `yaml:"tool-search" json:"tool-search"` + // ServerSideFallback opts cloaked Claude requests into Anthropic server-side + // refusal fallback injection (claude-opus-5-5 -> claude-opus-4-8 and + // claude-fable-5-1 -> claude-opus-5) when the request body does not already + // specify fallbacks. Default false leaves cross-model fallbacks omitted unless + // explicitly configured by the caller or payload rules. + ServerSideFallback bool `yaml:"server-side-fallback" json:"server-side-fallback"` // SessionDatePinDays retains the cloaked currentDate pin per session for // this many days in in-memory mode (server.kv-store.disabled: true without // Home), independently of continuity expiry and credential switches. A nil @@ -202,10 +208,25 @@ type XAIConfig struct { InjectXSearch bool `yaml:"inject-x-search" json:"inject-x-search"` } +// SensitivePatternRule defines a Go RE2 regular expression replacement rule. +type SensitivePatternRule struct { + // Pattern is the Go RE2 regular expression to match. + Pattern string `yaml:"pattern" json:"pattern"` + + // Replacement is the substitution string (empty string deletes matches). + Replacement string `yaml:"replacement" json:"replacement"` +} + // DevinConfig configures provider-wide Devin request behavior. type DevinConfig struct { // SensitiveWords is a list of words to obfuscate with zero-width characters in system prompts and messages. SensitiveWords []string `yaml:"sensitive-words,omitempty" json:"sensitive-words,omitempty"` + + // SensitiveWordsReplace maps sensitive words or phrases to literal replacements in system prompts. + SensitiveWordsReplace map[string]string `yaml:"sensitive-words-replace,omitempty" json:"sensitive-words-replace,omitempty"` + + // SensitivePatternsReplace defines ordered Go RE2 regex replacement rules for system prompts. + SensitivePatternsReplace []SensitivePatternRule `yaml:"sensitive-patterns-replace,omitempty" json:"sensitive-patterns-replace,omitempty"` } // ProxyConnectionPoolConfig configures upstream connection reuse for one api-key @@ -237,11 +258,23 @@ type ProxyConnectionPoolConfig struct { // AntigravityConfig configures provider-wide Antigravity request behavior. type AntigravityConfig struct { - // SensitiveWords is a list of words to obfuscate with zero-width characters in system instructions. + // SensitiveWords is a list of words to obfuscate with invisible combining grapheme joiners in system instructions. SensitiveWords []string `yaml:"sensitive-words,omitempty" json:"sensitive-words,omitempty"` + // SensitiveWordsReplace maps sensitive words or phrases to literal replacements in system instructions. + SensitiveWordsReplace map[string]string `yaml:"sensitive-words-replace,omitempty" json:"sensitive-words-replace,omitempty"` + + // SensitivePatternsReplace defines ordered Go RE2 regex replacement rules for system instructions. + SensitivePatternsReplace []SensitivePatternRule `yaml:"sensitive-patterns-replace,omitempty" json:"sensitive-patterns-replace,omitempty"` + // ConnectionPool configures upstream HTTP connection pooling behavior for Antigravity. ConnectionPool AntigravityConnectionPoolConfig `yaml:"connection-pool,omitempty" json:"connection-pool,omitempty"` + + // TOSPauseWindow controls the pool-wide protective pause armed after the first + // 403 TOS_VIOLATION. Accepts a Go duration string (default "6h"). Set to "0", + // "off", "false", "none", or "disabled" to disable the pause entirely; the + // credential itself is always deactivated regardless of this setting. + TOSPauseWindow string `yaml:"tos-pause-window,omitempty" json:"tos-pause-window,omitempty"` } // AntigravityConnectionPoolConfig controls upstream HTTP/1.1 connection pooling behavior for Antigravity. @@ -535,9 +568,13 @@ type RoutingConfig struct { Strategy string `yaml:"strategy,omitempty" json:"strategy,omitempty"` // SessionAffinity enables universal session-sticky routing for all clients. - // Explicit Claude Code, Codex, OpenCode, and pi session headers are preferred, - // followed by prompt_cache_key, Responses conversation IDs, legacy body IDs, - // execution or derived session identity, and the existing message-content hash fallback. + // Explicit Claude Code, Codex, OpenCode, pi, and generic (X-Session-ID) session headers + // are preferred, followed by prompt_cache_key, Responses conversation IDs, legacy body IDs, + // execution session identity, Merkle LCP prefix/compaction matching, derived session + // identity, and the existing message-content hash fallback. + // LCP compaction matching requires at least 2 shared trailing turns; clients whose + // compaction replaces all earlier turns with a summary should send X-Session-ID (or + // another explicit session ID), or affinity starts a new binding at every compaction. // Automatic failover is always enabled when bound auth becomes unavailable. SessionAffinity bool `yaml:"session-affinity,omitempty" json:"session-affinity,omitempty"` @@ -559,6 +596,8 @@ type RoutingConfig struct { // - "quota": transient errors (408, 5xx, empty stream, buffer limit) fail over for that // request only while keeping the session bound to its original credential; quota and // auth errors (429, 401/402/403, 404/model support, invalid_grant) rebind as normal. + // - "never": never move or fail over an established session to another credential; + // keep the binding and return the error (or retry the same credential) instead. // Ignored when SessionAffinity is false. SessionAffinityRebindOn string `yaml:"session-affinity-rebind-on,omitempty" json:"session-affinity-rebind-on,omitempty"` } @@ -701,6 +740,12 @@ type CloakConfig struct { // This can help bypass certain content filters. SensitiveWords []string `yaml:"sensitive-words,omitempty" json:"sensitive-words,omitempty"` + // SensitiveWordsReplace maps sensitive words or phrases to literal replacements. + SensitiveWordsReplace map[string]string `yaml:"sensitive-words-replace,omitempty" json:"sensitive-words-replace,omitempty"` + + // SensitivePatternsReplace defines ordered Go RE2 regex replacement rules. + SensitivePatternsReplace []SensitivePatternRule `yaml:"sensitive-patterns-replace,omitempty" json:"sensitive-patterns-replace,omitempty"` + // CacheUserID controls whether Claude user_id values are cached per API key. // When false, a fresh random user_id is generated for every request. CacheUserID *bool `yaml:"cache-user-id,omitempty" json:"cache-user-id,omitempty"` @@ -921,6 +966,7 @@ type CodexModel struct { // Use this for third-party Responses-compatible endpoints that do not accept // native agent_message items or empty-signature thinking blocks. Default false // keeps the native behavior unchanged. + // When enabled, compaction_trigger items also use local summary compaction. IsCompat bool `yaml:"is-compat,omitempty" json:"is-compat,omitempty"` // SupportConfigurationUpdate enables configuration_update for this API-key model. diff --git a/internal/config/config_v8.go b/internal/config/config_v8.go index b484a47dd86..72de903941d 100644 --- a/internal/config/config_v8.go +++ b/internal/config/config_v8.go @@ -75,7 +75,7 @@ func buildV8Paths() []configPath { prefixes := []configPath{ {"host", "server.host"}, {"port", "server.port"}, {"max-request-body-bytes", "server.max-request-body-bytes"}, {"trusted-proxies", "server.trusted-proxies"}, {"github-token", "server.github-token"}, - {"tls", "server.tls"}, {"commercial-mode", "server.commercial-mode"}, {"discovery", "server.discovery"}, {"kv-store", "server.kv-store"}, + {"tls", "server.tls"}, {"shutdown-timeout", "server.shutdown-timeout"}, {"commercial-mode", "server.commercial-mode"}, {"discovery", "server.discovery"}, {"kv-store", "server.kv-store"}, {"remote-management", "management"}, {"api-keys", "access.api-keys"}, {"credential-concurrency", "credentials.concurrency"}, {"credential-in-flight", "credentials.in-flight"}, {"force-model-prefix", "routing.force-model-prefix"}, diff --git a/internal/config/config_v8_test.go b/internal/config/config_v8_test.go index e8c66625c35..3f1b696b84e 100644 --- a/internal/config/config_v8_test.go +++ b/internal/config/config_v8_test.go @@ -104,6 +104,28 @@ func TestV8ExampleLoadsAndRoundTrips(t *testing.T) { } } +func TestV8ShutdownTimeoutParse(t *testing.T) { + for _, tc := range []struct { + name string + raw string + want int + }{ + {"v8 nested", "server:\n shutdown-timeout: 15\n", 15}, + {"legacy top-level", "shutdown-timeout: 7\n", 7}, + {"absent defaults to zero", "server:\n port: 8317\n", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg, err := ParseConfigBytes([]byte(tc.raw)) + if err != nil { + t.Fatal(err) + } + if cfg.ShutdownTimeoutSeconds != tc.want { + t.Fatalf("ShutdownTimeoutSeconds = %d, want %d", cfg.ShutdownTimeoutSeconds, tc.want) + } + }) + } +} + func TestV8PresencePrecedenceAndCleanup(t *testing.T) { for _, tc := range []struct { name, raw string @@ -933,3 +955,33 @@ func TestV8SecretHashResolvesReferences(t *testing.T) { }) } } + +func TestV8ExampleDocumentsSessionAffinityCompactionGuidance(t *testing.T) { + example, errRead := os.ReadFile(filepath.Join("..", "..", "config.example.yaml")) + if errRead != nil { + t.Fatal(errRead) + } + var doc yaml.Node + if errUnmarshal := yaml.Unmarshal(example, &doc); errUnmarshal != nil { + t.Fatal(errUnmarshal) + } + routing := yamlPath(doc.Content[0], "routing") + if routing == nil { + t.Fatal("config.example.yaml is missing routing block") + } + idx := findMapKeyIndex(routing, "session-affinity") + if idx < 0 { + t.Fatal("config.example.yaml is missing routing.session-affinity") + } + comment := routing.Content[idx].HeadComment + for _, required := range []string{ + "Merkle LCP prefix/compaction matching", + "2 shared trailing turns", + "replaces all earlier turns with a summary", + "send X-Session-ID", + } { + if !strings.Contains(comment, required) { + t.Fatalf("routing.session-affinity comment in config.example.yaml is missing %q; got:\n%s", required, comment) + } + } +} diff --git a/internal/config/config_yaml.go b/internal/config/config_yaml.go index 2ee6c1db287..bd168b9e7b9 100644 --- a/internal/config/config_yaml.go +++ b/internal/config/config_yaml.go @@ -70,6 +70,10 @@ func SaveConfigPreserveComments(configFile string, cfg *Config, migrateV8 ...boo pruneMappingToGeneratedKeys(original.Content[0], generated.Content[0], "oauth-model-alias") pruneMappingToGeneratedKeys(original.Content[0], generated.Content[0], "oauth-request-scoped-errors") pruneMappingToGeneratedKeys(original.Content[0], generated.Content[0], "oauth-settings") + pruneMappingToGeneratedKeys(original.Content[0], generated.Content[0], "antigravity", "sensitive-words-replace") + pruneMappingToGeneratedKeys(original.Content[0], generated.Content[0], "antigravity", "sensitive-patterns-replace") + pruneMappingToGeneratedKeys(original.Content[0], generated.Content[0], "devin", "sensitive-words-replace") + pruneMappingToGeneratedKeys(original.Content[0], generated.Content[0], "devin", "sensitive-patterns-replace") replacePluginConfigsSubtree(original.Content[0], generated.Content[0]) // Merge generated into original in-place, preserving comments/order of existing nodes. @@ -382,8 +386,64 @@ func appendPath(path []string, key string) []string { // an SDK embedder adds through sdk/config.SaveConfigPreserveComments to a file that // never carried it: pruning drops those zero-valued sub-keys. No management // endpoint mutates ProxyConnectionPool, so that path is reachable only from code. +func isSensitiveWordsReplaceEntryPath(path []string) bool { + for i, part := range path { + if part == "sensitive-words-replace" && i < len(path)-1 { + return true + } + } + return false +} + +func isSensitivePatternsReplaceEntryPath(path []string) bool { + for i, part := range path { + if part == "sensitive-patterns-replace" && i < len(path)-1 { + return true + } + } + return false +} + +func hasNonEmptySensitiveWordsReplace(node *yaml.Node) bool { + if node == nil { + return false + } + switch node.Kind { + case yaml.MappingNode: + for i := 0; i+1 < len(node.Content); i += 2 { + k := node.Content[i] + v := node.Content[i+1] + if k != nil && k.Value == "sensitive-words-replace" && v != nil && v.Kind == yaml.MappingNode && len(v.Content) > 0 { + return true + } + if k != nil && k.Value == "sensitive-patterns-replace" && v != nil && v.Kind == yaml.SequenceNode && len(v.Content) > 0 { + return true + } + if hasNonEmptySensitiveWordsReplace(v) { + return true + } + } + case yaml.SequenceNode: + for _, child := range node.Content { + if hasNonEmptySensitiveWordsReplace(child) { + return true + } + } + } + return false +} + func isKnownDefaultValue(path []string, node *yaml.Node) bool { - if isPluginConfigsSubtreePath(path) { + if isPluginConfigsSubtreePath(path) || isSensitiveWordsReplaceEntryPath(path) || isSensitivePatternsReplaceEntryPath(path) { + return false + } + if len(path) > 0 && path[len(path)-1] == "sensitive-words-replace" && node != nil && node.Kind == yaml.MappingNode && len(node.Content) > 0 { + return false + } + if len(path) > 0 && path[len(path)-1] == "sensitive-patterns-replace" && node != nil && node.Kind == yaml.SequenceNode && len(node.Content) > 0 { + return false + } + if hasNonEmptySensitiveWordsReplace(node) { return false } if len(path) == 1 && path[0] == "plugins" && node != nil && node.Kind == yaml.MappingNode { @@ -462,7 +522,10 @@ func isKnownDefaultValue(path []string, node *yaml.Node) bool { // pruneKnownDefaultsInNewNode removes default-valued descendants from a new node // before it is appended into the destination YAML tree. func pruneKnownDefaultsInNewNode(path []string, node *yaml.Node) { - if node == nil || isPluginConfigsSubtreePath(path) { + if node == nil || isPluginConfigsSubtreePath(path) || isSensitiveWordsReplaceEntryPath(path) || isSensitivePatternsReplaceEntryPath(path) { + return + } + if len(path) > 0 && (path[len(path)-1] == "sensitive-words-replace" || path[len(path)-1] == "sensitive-patterns-replace") { return } @@ -812,6 +875,9 @@ func pruneMappingToGeneratedKeys(dstRoot, srcRoot *yaml.Node, keyPath ...string) return } if srcVal.Kind != yaml.MappingNode { + if srcVal.Kind == yaml.SequenceNode && dstVal != nil && dstVal.Kind == yaml.SequenceNode { + return + } dstRoot.Content[dstIdx+1] = deepCopyNode(srcVal) return } @@ -869,6 +935,9 @@ func shouldPruneNestedMappingKeys(path []string) bool { } parent := path[len(path)-2] last := path[len(path)-1] + if last == "sensitive-words-replace" && (parent == "antigravity" || parent == "devin" || parent == "cloak") { + return true + } switch parent { case "claude-api-key": return last == "cloak" || last == "headers" diff --git a/internal/config/parse.go b/internal/config/parse.go index bf12a836793..d3a586a6f26 100644 --- a/internal/config/parse.go +++ b/internal/config/parse.go @@ -121,6 +121,8 @@ func ParseConfigBytes(data []byte) (*Config, error) { cfg.SanitizeCodexHeaderDefaults() cfg.SanitizeClaudeHeaderDefaults() cfg.SanitizeClaudeKeys() + cfg.SanitizeAntigravity() + cfg.SanitizeDevin() cfg.SanitizeOpenAICompatibility() cfg.OAuthExcludedModels = NormalizeOAuthExcludedModels(cfg.OAuthExcludedModels) cfg.SanitizeOAuthModelAlias() diff --git a/internal/home/client.go b/internal/home/client.go index 8934fbe170c..8c2d49c7908 100644 --- a/internal/home/client.go +++ b/internal/home/client.go @@ -2018,6 +2018,7 @@ func (c *Client) RunConfigSubscriberLifetime(ctx context.Context, onConfig func( } return c.endConfigSubscriberLifetimeWithSubscription(errACK, pubsub, "failed ACK") } + heartbeatStarted := time.Now() // A protocol-one ACK means Home already committed this membership. Preserve it if the command probe fails. if len(args) > 1 { c.markMembershipTakeoverEligible() @@ -2065,10 +2066,16 @@ func (c *Client) RunConfigSubscriberLifetime(ctx context.Context, onConfig func( }() go func() { defer close(receiveDone) + lastHeartbeat := heartbeatStarted for { _, timeout := c.subscriptionParameters() - event, errReceive := receiveSubscriptionEvent(receiveCtx, pubsub, sampler, timeout) + event, errReceive := receiveSubscriptionEvent(receiveCtx, pubsub, sampler, lastHeartbeat.Add(timeout)) if errReceive == nil { + // Only a persisted heartbeat PONG renews liveness. Config, cluster traffic, + // and RTT echoes cannot extend the deadline while the consumer is busy. + if pong, ok := event.(*redis.Pong); ok && pong != nil && pong.Payload == "" { + lastHeartbeat = time.Now() + } select { case events <- event: continue @@ -2144,16 +2151,17 @@ func (c *Client) RunConfigSubscriberLifetime(ctx context.Context, onConfig func( log.Warn("failed to apply config update from home control center, ignoring") } case *redis.Pong: - c.resetReconnectFailures() + if msg != nil && msg.Payload == "" { + c.resetReconnectFailures() + } default: log.Debugf("home subscription returned unsupported message type %T", event) } } } -// receiveSubscriptionEvent consumes telemetry without extending the heartbeat deadline. -func receiveSubscriptionEvent(ctx context.Context, pubsub *redis.PubSub, sampler *clusterRTTSampler, timeout time.Duration) (any, error) { - deadline := time.Now().Add(timeout) +// receiveSubscriptionEvent preserves the absolute heartbeat deadline across ordinary messages. +func receiveSubscriptionEvent(ctx context.Context, pubsub *redis.PubSub, sampler *clusterRTTSampler, deadline time.Time) (any, error) { for { remaining := time.Until(deadline) if remaining <= 0 { @@ -2163,6 +2171,9 @@ func receiveSubscriptionEvent(ctx context.Context, pubsub *redis.PubSub, sampler if errReceive != nil { return nil, errReceive } + if !time.Now().Before(deadline) { + return nil, os.ErrDeadlineExceeded + } if _, ok := event.(*redis.Subscription); ok { return nil, fmt.Errorf("unexpected Home subscription ACK after initialization") } diff --git a/internal/home/client_heartbeat_deadline_test.go b/internal/home/client_heartbeat_deadline_test.go new file mode 100644 index 00000000000..e3c77a5329f --- /dev/null +++ b/internal/home/client_heartbeat_deadline_test.go @@ -0,0 +1,126 @@ +package home + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "strings" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/redis/go-redis/v9" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" +) + +func TestManagedSubscriberOrdinaryTrafficDoesNotRenewHeartbeat(t *testing.T) { + for _, mode := range []string{"config", "cluster", "blocked config consumer"} { + t.Run(mode, func(t *testing.T) { + client, _ := newRedisCommandTestClient(t, func(args []string) string { + if strings.EqualFold(args[0], "GET") { + return "$2\r\n{}\r\n" + } + return balanceTestRedisReply(args) + }) + client.SetManagedLifetime(true) + synctest.Test(t, func(t *testing.T) { + defer client.Close() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + releaseConsumer := make(chan struct{}) + var messages atomic.Int32 + sub := redis.NewClient(&redis.Options{ + Addr: "127.0.0.1:8327", Protocol: 2, DisableIdentity: true, MaxRetries: -1, + Dialer: func(context.Context, string, string) (net.Conn, error) { + local, peer := net.Pipe() + go serveRedisCommandTestConn(peer, &redisCommandLog{}, func(args []string) string { + if !strings.EqualFold(args[0], "SUBSCRIBE") { + return balanceTestRedisReply(args) + } + go func() { + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + channel, payload := redisChannelConfig, "{}" + if mode == "cluster" { + channel, payload = redisChannelCluster, `{"ok":true,"nodes":[]}` + } + frame := fmt.Sprintf("*3\r\n$7\r\nmessage\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n", len(channel), channel, len(payload), payload) + if _, errWrite := io.WriteString(peer, frame); errWrite != nil { + if !errors.Is(errWrite, io.ErrClosedPipe) && !errors.Is(errWrite, net.ErrClosed) { + t.Errorf("write ordinary subscription message: %v", errWrite) + } + return + } + messages.Add(1) + } + }() + return "*3\r\n$9\r\nsubscribe\r\n$6\r\nconfig\r\n:1\r\n" + }) + return local, nil + }, + }) + defer func() { + if errClose := sub.Close(); errClose != nil { + t.Error(errClose) + } + }() + ready := make(chan struct{}) + done := make(chan error, 1) + go func() { + initial := true + done <- client.RunConfigSubscriberLifetime(ctx, func([]byte) error { + if !initial { + if mode == "blocked config consumer" { + <-releaseConsumer + } + return nil + } + initial = false + if errConfig := client.SetLifecycleConfig(config.CredentialConcurrencyConfig{ + LifecycleConfigRevision: 1, CPAHeartbeatTimeout: time.Minute, + }); errConfig != nil { + return errConfig + } + client.mu.Lock() + previousSub := client.sub + client.sub = sub + client.mu.Unlock() + if errClose := previousSub.Close(); errClose != nil { + return fmt.Errorf("close bootstrap subscription: %w", errClose) + } + return nil + }, func() { close(ready) }) + }() + select { + case <-ready: + case errRun := <-done: + close(releaseConsumer) + t.Fatalf("subscription did not become ready: %v", errRun) + } + // Virtual time keeps this deadline test independent of wall-clock scheduling. + time.Sleep(time.Minute) + synctest.Wait() + heartbeatOK := client.HeartbeatOK() + fenced := client.dispatchFenced.Load() && client.releaseFenced.Load() + close(releaseConsumer) + synctest.Wait() + errRun := <-done + if heartbeatOK || !fenced || !isTimeoutError(errRun) || ctx.Err() != nil { + t.Fatalf("ordinary traffic extended heartbeat liveness: healthy=%t fenced=%t error=%v context=%v", heartbeatOK, fenced, errRun, ctx.Err()) + } + if messages.Load() < 5 { + t.Fatalf("insufficient ordinary traffic before heartbeat expiry: %d messages", messages.Load()) + } + }) + }) + } +} diff --git a/internal/home/client_latency_failure_test.go b/internal/home/client_latency_failure_test.go index bf0175ea933..0eba5188244 100644 --- a/internal/home/client_latency_failure_test.go +++ b/internal/home/client_latency_failure_test.go @@ -92,7 +92,7 @@ func TestClusterLatencyPingFailureBetweenReceives(t *testing.T) { t.Fatalf("failed PING was not invalidated: %+v", samples) } // The new ACK cannot silently keep the old lifetime alive, even if reception wins the race. - event, errReceive := receiveSubscriptionEvent(ctx, pubsub, sampler, time.Second) + event, errReceive := receiveSubscriptionEvent(ctx, pubsub, sampler, time.Now().Add(time.Second)) if errReceive == nil || isTimeoutError(errReceive) || event != nil { t.Fatalf("replacement ACK was accepted: event=%v error=%v", event, errReceive) } diff --git a/internal/home/client_latency_test.go b/internal/home/client_latency_test.go index c2c028622b3..177bf9834a7 100644 --- a/internal/home/client_latency_test.go +++ b/internal/home/client_latency_test.go @@ -21,11 +21,15 @@ func TestSubscriptionTelemetryPreservesHeartbeatDeadline(t *testing.T) { interval time.Duration stale bool heartbeats bool + traffic string }{ {name: "default timeout", timeout: homeSubscriptionReceiveTimeout, interval: 30 * time.Second}, {name: "timeout longer than sampling interval", timeout: 75 * time.Second, interval: 30 * time.Second}, {name: "stale telemetry", timeout: homeSubscriptionReceiveTimeout, interval: time.Second, stale: true}, {name: "normal heartbeats renew deadline", timeout: homeSubscriptionReceiveTimeout, interval: time.Second, heartbeats: true}, + {name: "config traffic cannot renew deadline", timeout: 75 * time.Second, interval: 30 * time.Second, traffic: redisChannelConfig}, + {name: "cluster traffic cannot renew deadline", timeout: 75 * time.Second, interval: 30 * time.Second, traffic: redisChannelCluster}, + {name: "unrelated pong cannot renew deadline", timeout: 75 * time.Second, interval: 30 * time.Second, traffic: "unrelated-pong"}, } { t.Run(test.name, func(t *testing.T) { synctest.Test(t, func(t *testing.T) { @@ -83,13 +87,19 @@ func TestSubscriptionTelemetryPreservesHeartbeatDeadline(t *testing.T) { return } token := "" - if !test.heartbeats || (elapsed != 2*time.Second && elapsed != 4*time.Second) { + if test.traffic == "" && (!test.heartbeats || (elapsed != 2*time.Second && elapsed != 4*time.Second)) { token = sampler.begin(time.Now()) if test.stale { sampler.expire(time.Now(), true) } } - if _, errWrite := io.WriteString(peer, fmt.Sprintf("*2\r\n$4\r\npong\r\n$%d\r\n%s\r\n", len(token), token)); errWrite != nil { + frame := fmt.Sprintf("*2\r\n$4\r\npong\r\n$%d\r\n%s\r\n", len(token), token) + if test.traffic == "unrelated-pong" { + frame = "*2\r\n$4\r\npong\r\n$5\r\nother\r\n" + } else if test.traffic != "" { + frame = fmt.Sprintf("*3\r\n$7\r\nmessage\r\n$%d\r\n%s\r\n$2\r\n{}\r\n", len(test.traffic), test.traffic) + } + if _, errWrite := io.WriteString(peer, frame); errWrite != nil { // The receiver closes the pipe when its heartbeat deadline expires. if !errors.Is(errWrite, io.ErrClosedPipe) && !errors.Is(errWrite, net.ErrClosed) { t.Errorf("write telemetry PONG: %v", errWrite) @@ -100,24 +110,29 @@ func TestSubscriptionTelemetryPreservesHeartbeatDeadline(t *testing.T) { } }() heartbeats := 0 + deadline := started.Add(test.timeout) for { - event, errReceive := receiveSubscriptionEvent(ctx, pubsub, sampler, test.timeout) + event, errReceive := receiveSubscriptionEvent(ctx, pubsub, sampler, deadline) if errReceive != nil { if !isTimeoutError(errReceive) { t.Fatalf("receive error = %v, want heartbeat timeout", errReceive) } break } + if test.traffic != "" { + continue + } pong, ok := event.(*redis.Pong) if !ok || pong.Payload != "" { t.Fatalf("telemetry escaped to the heartbeat consumer: %#v", event) } heartbeats++ + deadline = time.Now().Add(test.timeout) } if elapsed := time.Since(started); elapsed != wantElapsed || heartbeats != wantHeartbeats { t.Fatalf("elapsed=%v heartbeats=%d, want %v and %d", elapsed, heartbeats, wantElapsed, wantHeartbeats) } - if samples := sampler.history.report(time.Now()); len(samples) != 1 || samples[0].Valid == test.stale { + if samples := sampler.history.report(time.Now()); test.traffic == "" && (len(samples) != 1 || samples[0].Valid == test.stale) { t.Fatalf("telemetry was not sampled independently of liveness: %+v", samples) } }) diff --git a/internal/logging/gin_logger.go b/internal/logging/gin_logger.go index 804d74870d6..dce94291900 100644 --- a/internal/logging/gin_logger.go +++ b/internal/logging/gin_logger.go @@ -22,6 +22,7 @@ var aiAPIPrefixes = []string{ "/v1beta", "/openai/v1", "/backend-api/codex", + "/muse-code", } const ( diff --git a/internal/logging/gin_logger_test.go b/internal/logging/gin_logger_test.go index ff1d44eeb69..feffc219af1 100644 --- a/internal/logging/gin_logger_test.go +++ b/internal/logging/gin_logger_test.go @@ -70,6 +70,7 @@ func TestIsAIAPIPathIncludesPublicAPIGroups(t *testing.T) { "/v1beta/interactions", "/openai/v1/videos", "/backend-api/codex/responses", + "/muse-code/models", } { if !isAIAPIPath(path) { t.Fatalf("expected %s to be treated as AI API path", path) @@ -80,6 +81,7 @@ func TestIsAIAPIPathIncludesPublicAPIGroups(t *testing.T) { "/v10/models", "/openai/v10/videos", "/backend-api/codex-status", + "/muse-code-status", } { if isAIAPIPath(path) { t.Fatalf("expected %s not to be treated as AI API path", path) diff --git a/internal/logging/request_capture.go b/internal/logging/request_capture.go index 6a97ea4ae8c..f922639af5f 100644 --- a/internal/logging/request_capture.go +++ b/internal/logging/request_capture.go @@ -1,10 +1,41 @@ package logging -import "context" +import ( + "bytes" + "context" + "fmt" + "net/http" + "sort" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/util" +) + +const ( + // MaxDeferredAPIRequestBodyBytes bounds total deferred upstream request bodies per HTTP request. + MaxDeferredAPIRequestBodyBytes = 32 << 20 // 32 MiB + // MaxDeferredAPIResponseBodyBytes bounds each upstream attempt's deferred response body. + MaxDeferredAPIResponseBodyBytes = 64 << 10 // 64 KiB + // MaxDeferredAPIResponseHeaderBytes bounds cloned response headers per upstream attempt. + MaxDeferredAPIResponseHeaderBytes = 16 << 10 // 16 KiB + // MaxDeferredAPIResponseErrorBytes bounds each recorded upstream error string. + MaxDeferredAPIResponseErrorBytes = 16 << 10 // 16 KiB + // MaxTotalDeferredAPIResponseBodyBytes bounds total deferred upstream response payload + // (body chunks, headers, and error strings) across retries for a single HTTP request. + MaxTotalDeferredAPIResponseBodyBytes = 512 << 10 // 512 KiB + // MaxDeferredAPIResponseAttempts bounds the number of upstream response attempt slots retained per HTTP request. + MaxDeferredAPIResponseAttempts = 16 + maxDeferredErrorsPerAttempt = 8 + maxDeferredHeaderEntries = 64 +) type deferredAPIRequestCaptureDisabledKey struct{} +type deferredAPICaptureKey struct{} -// WithDeferredAPIRequestCaptureDisabled skips error-only upstream request capture +// WithDeferredAPIRequestCaptureDisabled skips error-only upstream request and response capture // for this context and its descendants. Full request logging is unaffected. // Connection-scoped contexts keep this policy even when asynchronous callbacks // outlive the handler and its pooled Gin context is reused. @@ -12,6 +43,9 @@ func WithDeferredAPIRequestCaptureDisabled(ctx context.Context) context.Context if ctx == nil { ctx = context.Background() } + if capture := DeferredAPICaptureFromContext(ctx); capture != nil { + capture.Close() + } return context.WithValue(ctx, deferredAPIRequestCaptureDisabledKey{}, true) } @@ -23,3 +57,659 @@ func DeferredAPIRequestCaptureDisabled(ctx context.Context) bool { disabled, _ := ctx.Value(deferredAPIRequestCaptureDisabledKey{}).(bool) return disabled } + +// DeferredAPIResponse renders the upstream response attempt sections of an +// error log from details captured while full request logging is disabled. +type DeferredAPIResponse interface { + // HasPayload reports whether any upstream response metadata, body, or error was captured. + HasPayload() bool + // RenderAPIResponse returns the formatted "=== API RESPONSE n ===" attempt + // sections, or nil when no upstream response details were captured. + RenderAPIResponse() []byte +} + +// WithDeferredAPICapture attaches a request-scoped DeferredAPICapture to ctx so +// background stream producers record into the request's own synchronized holder +// without accessing a pooled Gin context. +func WithDeferredAPICapture(ctx context.Context, capture *DeferredAPICapture) context.Context { + if ctx == nil { + ctx = context.Background() + } + if capture == nil { + return ctx + } + return context.WithValue(ctx, deferredAPICaptureKey{}, capture) +} + +// DeferredAPICaptureFromContext returns the request-scoped DeferredAPICapture carried by ctx, if any. +func DeferredAPICaptureFromContext(ctx context.Context) *DeferredAPICapture { + if ctx == nil { + return nil + } + capture, _ := ctx.Value(deferredAPICaptureKey{}).(*DeferredAPICapture) + return capture +} + +// InheritDeferredCapture propagates error-only capture policy and any request-scoped +// DeferredAPICapture holder from src to dst. +func InheritDeferredCapture(dst, src context.Context) context.Context { + if dst == nil { + dst = context.Background() + } + if src == nil { + return dst + } + if DeferredAPIRequestCaptureDisabled(dst) || DeferredAPIRequestCaptureDisabled(src) { + return WithDeferredAPIRequestCaptureDisabled(dst) + } + if DeferredAPICaptureFromContext(dst) == nil { + if capture := DeferredAPICaptureFromContext(src); capture != nil { + dst = WithDeferredAPICapture(dst, capture) + } + } + return dst +} + +type deferredHeaderEntry struct { + key string + value string +} + +type deferredResponseAttempt struct { + index int + capturedAt time.Time + status int + headers []deferredHeaderEntry + headersRecorded bool + headersTruncated bool + body []byte + bodyHasContent bool + prevWasSSEEvent bool + bodyTruncated bool + errors []string + errorsTruncated bool + requestBodyBytes int +} + +func (a *deferredResponseAttempt) markCapturedAt() { + if a.capturedAt.IsZero() { + a.capturedAt = time.Now() + } +} + +func (a *deferredResponseAttempt) hasContent() bool { + return a.status > 0 || a.headersRecorded || a.headersTruncated || a.bodyHasContent || a.bodyTruncated || len(a.errors) > 0 || a.errorsTruncated +} + +// DeferredAPICapture retains bounded upstream request and response details for +// a single HTTP request while full request logging is disabled. All operations +// are synchronized and become no-ops after Close so asynchronous stream workers +// cannot race with Finalize or leak into a reused Gin context. +type DeferredAPICapture struct { + mu sync.Mutex + requests []DeferredAPIRequest + requestBytes int + attempts []*deferredResponseAttempt + omittedAttempts int + responseBytes int + closed bool +} + +// NewDeferredAPICapture constructs a fresh request-scoped DeferredAPICapture. +func NewDeferredAPICapture() *DeferredAPICapture { + return &DeferredAPICapture{} +} + +// Close marks the capture closed and releases buffered upstream payloads. +func (c *DeferredAPICapture) Close() { + if c == nil { + return + } + c.mu.Lock() + defer c.mu.Unlock() + c.closed = true + c.requests = nil + c.requestBytes = 0 + c.attempts = nil + c.omittedAttempts = 0 + c.responseBytes = 0 +} + +// IsClosed reports whether Close has been called. +func (c *DeferredAPICapture) IsClosed() bool { + if c == nil { + return true + } + c.mu.Lock() + defer c.mu.Unlock() + return c.closed +} + +// RecordRequest stores a deferred upstream request builder within MaxDeferredAPIRequestBodyBytes +// and opens the paired upstream response attempt slot. +func (c *DeferredAPICapture) RecordRequest(body []byte, build func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) DeferredAPIRequest) (DeferredAPIRequest, int, bool) { + return c.recordRequest(body, false, build) +} + +// RecordOrReplacePendingRequest replaces the trailing request builder when its paired +// response attempt has recorded no response details yet (for example when a websocket +// request is immediately rejected during its HTTP upgrade handshake), or appends a new +// request attempt otherwise. +func (c *DeferredAPICapture) RecordOrReplacePendingRequest(body []byte, build func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) DeferredAPIRequest) (DeferredAPIRequest, int, bool, bool) { + fn, bytesUsed, replaced, ok := c.recordRequestWithReplace(body, true, build) + return fn, bytesUsed, replaced, ok +} + +func (c *DeferredAPICapture) recordRequest(body []byte, replacePending bool, build func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) DeferredAPIRequest) (DeferredAPIRequest, int, bool) { + fn, bytesUsed, _, ok := c.recordRequestWithReplace(body, replacePending, build) + return fn, bytesUsed, ok +} + +func (c *DeferredAPICapture) recordRequestWithReplace(body []byte, replacePending bool, build func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) DeferredAPIRequest) (DeferredAPIRequest, int, bool, bool) { + if c == nil || build == nil { + return nil, 0, false, false + } + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return nil, 0, false, false + } + if replacePending && c.omittedAttempts == 0 && len(c.attempts) > 0 && len(c.requests) == len(c.attempts) { + lastAttempt := c.attempts[len(c.attempts)-1] + if lastAttempt != nil && !lastAttempt.hasContent() { + c.requestBytes -= lastAttempt.requestBodyBytes + if c.requestBytes < 0 { + c.requestBytes = 0 + } + capturedAt := time.Now() + remaining := MaxDeferredAPIRequestBodyBytes - c.requestBytes + if remaining < 0 { + remaining = 0 + } + captureLength := len(body) + if captureLength > remaining { + captureLength = remaining + } + capturedBody := bytes.Clone(body[:captureLength]) + bodyEmpty := len(body) == 0 + bodyTruncated := captureLength < len(body) + c.requestBytes += captureLength + lastAttempt.requestBodyBytes = captureLength + fn := build(lastAttempt.index, capturedAt, capturedBody, bodyEmpty, bodyTruncated) + c.requests[len(c.requests)-1] = fn + return fn, c.requestBytes, true, true + } + } + index := len(c.requests) + 1 + if len(c.requests) >= MaxDeferredAPIResponseAttempts { + c.startAttemptLocked(index, 0) + return nil, c.requestBytes, false, false + } + capturedAt := time.Now() + remaining := MaxDeferredAPIRequestBodyBytes - c.requestBytes + if remaining < 0 { + remaining = 0 + } + captureLength := len(body) + if captureLength > remaining { + captureLength = remaining + } + capturedBody := bytes.Clone(body[:captureLength]) + bodyEmpty := len(body) == 0 + bodyTruncated := captureLength < len(body) + c.requestBytes += captureLength + fn := build(index, capturedAt, capturedBody, bodyEmpty, bodyTruncated) + c.requests = append(c.requests, fn) + c.startAttemptLocked(index, captureLength) + return fn, c.requestBytes, false, true +} + +// HasRequests reports whether any deferred upstream requests were captured. +func (c *DeferredAPICapture) HasRequests() bool { + if c == nil { + return false + } + c.mu.Lock() + defer c.mu.Unlock() + return !c.closed && len(c.requests) > 0 +} + +// RenderAPIRequests renders all captured upstream request sections. +func (c *DeferredAPICapture) RenderAPIRequests() []byte { + if c == nil { + return nil + } + c.mu.Lock() + requests := append([]DeferredAPIRequest(nil), c.requests...) + omitted := c.omittedAttempts + closed := c.closed + c.mu.Unlock() + if closed || len(requests) == 0 { + return nil + } + var body bytes.Buffer + for _, buildRequest := range requests { + if buildRequest == nil { + continue + } + body.Write(buildRequest()) + } + if omitted > 0 { + body.WriteString(fmt.Sprintf("[API REQUEST ATTEMPTS TRUNCATED: omitted %d additional attempt(s)]\n\n", omitted)) + } + return body.Bytes() +} + +func (c *DeferredAPICapture) startAttemptLocked(index int, requestBodyBytes int) { + if len(c.attempts) >= MaxDeferredAPIResponseAttempts { + c.omittedAttempts++ + return + } + if next := len(c.attempts) + 1; next > index { + index = next + } + c.attempts = append(c.attempts, &deferredResponseAttempt{ + index: index, + requestBodyBytes: requestBodyBytes, + }) +} + +func (c *DeferredAPICapture) latestAttemptLocked() *deferredResponseAttempt { + if c.omittedAttempts > 0 { + return nil + } + if len(c.attempts) == 0 { + c.startAttemptLocked(1, 0) + } + if len(c.attempts) == 0 { + return nil + } + return c.attempts[len(c.attempts)-1] +} + +// RecordResponseMetadata records the HTTP status and bounded cloned headers for the latest attempt. +func (c *DeferredAPICapture) RecordResponseMetadata(status int, headers http.Header) { + if c == nil { + return + } + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return + } + attempt := c.latestAttemptLocked() + if attempt == nil { + return + } + attempt.markCapturedAt() + if status > 0 && attempt.status == 0 { + attempt.status = status + } + if !attempt.headersRecorded { + attempt.headersRecorded = true + if len(headers) > 0 { + budget := min(MaxDeferredAPIResponseHeaderBytes, MaxTotalDeferredAPIResponseBodyBytes-c.responseBytes) + cloned, used, truncated := cloneBoundedHeaders(headers, budget) + attempt.headers = cloned + attempt.headersTruncated = truncated + c.responseBytes += used + } + } +} + +// RecordResponseError appends a bounded transport or stream error to the latest attempt. +func (c *DeferredAPICapture) RecordResponseError(err error) { + if c == nil || err == nil { + return + } + raw := strings.TrimSpace(err.Error()) + if raw == "" { + return + } + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return + } + attempt := c.latestAttemptLocked() + if attempt == nil { + return + } + attempt.markCapturedAt() + if len(attempt.errors) >= maxDeferredErrorsPerAttempt { + attempt.errorsTruncated = true + return + } + budget := min(MaxDeferredAPIResponseErrorBytes, MaxTotalDeferredAPIResponseBodyBytes-c.responseBytes) + if budget <= 0 { + attempt.errorsTruncated = true + return + } + if len(raw) > budget { + cut := truncateUTF8Boundary(raw, budget) + cloned := strings.Clone(raw[:cut]) + c.responseBytes += cut + attempt.errors = append(attempt.errors, fmt.Sprintf("%s [API RESPONSE ERROR TRUNCATED: captured first %d bytes]", cloned, cut)) + return + } + cloned := strings.Clone(raw) + c.responseBytes += len(cloned) + attempt.errors = append(attempt.errors, cloned) +} + +// AppendResponseChunk appends a bounded response chunk to the latest attempt. +func (c *DeferredAPICapture) AppendResponseChunk(chunk []byte) { + if c == nil { + return + } + data := bytes.TrimSpace(chunk) + if len(data) == 0 { + return + } + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return + } + attempt := c.latestAttemptLocked() + if attempt == nil { + return + } + attempt.markCapturedAt() + + currentChunkIsSSEEvent := bytes.HasPrefix(data, []byte("event:")) + currentChunkIsSSEData := bytes.HasPrefix(data, []byte("data:")) + + attemptRemaining := MaxDeferredAPIResponseBodyBytes - len(attempt.body) + totalRemaining := MaxTotalDeferredAPIResponseBodyBytes - c.responseBytes + remaining := min(attemptRemaining, totalRemaining) + if remaining <= 0 { + attempt.bodyTruncated = true + return + } + + if attempt.bodyHasContent { + separator := "\n\n" + if attempt.prevWasSSEEvent && currentChunkIsSSEData { + separator = "\n" + } + if len(separator) >= remaining { + attempt.bodyTruncated = true + return + } + attempt.body = append(attempt.body, separator...) + c.responseBytes += len(separator) + remaining -= len(separator) + } + + writeLength := len(data) + if writeLength > remaining { + writeLength = remaining + attempt.bodyTruncated = true + } + if attempt.body == nil { + attempt.body = bytes.Clone(data[:writeLength]) + } else { + attempt.body = append(attempt.body, data[:writeLength]...) + } + c.responseBytes += writeLength + attempt.bodyHasContent = true + attempt.prevWasSSEEvent = currentChunkIsSSEEvent && !attempt.bodyTruncated +} + +// HasPayload reports whether any attempt recorded upstream response details. +func (c *DeferredAPICapture) HasPayload() bool { + if c == nil { + return false + } + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return false + } + return c.hasPayloadLocked() +} + +func (c *DeferredAPICapture) hasPayloadLocked() bool { + for _, attempt := range c.attempts { + if attempt != nil && attempt.hasContent() { + return true + } + } + return false +} + +// RenderAPIResponse formats captured upstream response attempts for error logs. +func (c *DeferredAPICapture) RenderAPIResponse() []byte { + if c == nil { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + if c.closed || !c.hasPayloadLocked() { + return nil + } + var builder strings.Builder + for _, attempt := range c.attempts { + if attempt == nil || !attempt.hasContent() { + continue + } + if builder.Len() > 0 { + builder.WriteByte('\n') + } + capturedAt := attempt.capturedAt + if capturedAt.IsZero() { + capturedAt = time.Now() + } + builder.WriteString(fmt.Sprintf("=== API RESPONSE %d ===\n", attempt.index)) + builder.WriteString(fmt.Sprintf("Timestamp: %s\n\n", capturedAt.Format(time.RFC3339Nano))) + if attempt.status > 0 { + builder.WriteString(fmt.Sprintf("Status: %d\n", attempt.status)) + } + if attempt.headersRecorded || attempt.headersTruncated || attempt.bodyHasContent || attempt.bodyTruncated { + builder.WriteString("Headers:\n") + writeMaskedHeaders(&builder, attempt.headers, attempt.headersTruncated) + builder.WriteByte('\n') + } + if attempt.bodyHasContent || attempt.bodyTruncated { + builder.WriteString("Body:\n") + builder.Write(attempt.body) + if attempt.bodyTruncated { + if len(attempt.body) > 0 && attempt.body[len(attempt.body)-1] != '\n' { + builder.WriteByte('\n') + } + builder.WriteString(fmt.Sprintf("[API RESPONSE BODY TRUNCATED: captured first %d bytes]", len(attempt.body))) + } + if len(attempt.body) == 0 || attempt.body[len(attempt.body)-1] != '\n' || attempt.bodyTruncated { + builder.WriteByte('\n') + } + if len(attempt.errors) > 0 || attempt.errorsTruncated { + builder.WriteByte('\n') + } + } + for i, errText := range attempt.errors { + if i > 0 { + builder.WriteByte('\n') + } + builder.WriteString(fmt.Sprintf("Error: %s\n", errText)) + } + if attempt.errorsTruncated { + if len(attempt.errors) > 0 { + builder.WriteByte('\n') + } + builder.WriteString("[API RESPONSE ERRORS TRUNCATED]\n") + } + } + if c.omittedAttempts > 0 && builder.Len() > 0 { + builder.WriteString(fmt.Sprintf("\n[API RESPONSE ATTEMPTS TRUNCATED: omitted %d additional attempt(s)]\n", c.omittedAttempts)) + } + if builder.Len() == 0 { + return nil + } + return []byte(builder.String()) +} + +// AttemptCount returns the number of recorded response attempt slots. +func (c *DeferredAPICapture) AttemptCount() int { + if c == nil { + return 0 + } + c.mu.Lock() + defer c.mu.Unlock() + return len(c.attempts) +} + +// AttemptCapturedAt returns the captured response timestamp for the given 0-based attempt slot. +func (c *DeferredAPICapture) AttemptCapturedAt(i int) time.Time { + if c == nil { + return time.Time{} + } + c.mu.Lock() + defer c.mu.Unlock() + if i < 0 || i >= len(c.attempts) || c.attempts[i] == nil { + return time.Time{} + } + return c.attempts[i].capturedAt +} + +// AttemptBodyStats returns the captured body length, slice capacity, and truncation flag for the given 0-based attempt slot. +func (c *DeferredAPICapture) AttemptBodyStats(i int) (length int, capacity int, truncated bool) { + if c == nil { + return 0, 0, false + } + c.mu.Lock() + defer c.mu.Unlock() + if i < 0 || i >= len(c.attempts) || c.attempts[i] == nil { + return 0, 0, false + } + attempt := c.attempts[i] + return len(attempt.body), cap(attempt.body), attempt.bodyTruncated +} + +// TotalResponseBodyBytes returns the total captured upstream response bytes across attempts. +func (c *DeferredAPICapture) TotalResponseBodyBytes() int { + if c == nil { + return 0 + } + c.mu.Lock() + defer c.mu.Unlock() + return c.responseBytes +} + +func cloneBoundedHeaders(headers http.Header, budget int) ([]deferredHeaderEntry, int, bool) { + if len(headers) == 0 { + return nil, 0, false + } + if budget <= 0 { + return nil, 0, true + } + truncated := len(headers) > maxDeferredHeaderEntries + limitKeys := min(len(headers), maxDeferredHeaderEntries) + keys := make([]string, 0, limitKeys) + for key := range headers { + pos := sort.SearchStrings(keys, key) + if len(keys) < limitKeys { + keys = append(keys, "") + for i := len(keys) - 1; i > pos; i-- { + keys[i] = keys[i-1] + } + keys[pos] = key + } else if pos < limitKeys { + for i := limitKeys - 1; i > pos; i-- { + keys[i] = keys[i-1] + } + keys[pos] = key + } + } + + entries := make([]deferredHeaderEntry, 0, len(keys)) + used := 0 + stop := false + for _, key := range keys { + if len(entries) >= maxDeferredHeaderEntries || len(key) > budget-used { + truncated = true + break + } + clonedKey := strings.Clone(key) + values := headers[key] + if len(values) == 0 { + entries = append(entries, deferredHeaderEntry{key: clonedKey}) + used += len(clonedKey) + continue + } + for _, value := range values { + if len(entries) >= maxDeferredHeaderEntries { + truncated = true + stop = true + break + } + masked := util.MaskSensitiveHeaderValue(clonedKey, value) + remaining := budget - used - len(clonedKey) + if remaining <= 0 { + truncated = true + stop = true + break + } + if len(masked) > remaining { + cut := truncateUTF8Boundary(masked, remaining) + entries = append(entries, deferredHeaderEntry{ + key: clonedKey, + value: strings.Clone(masked[:cut]), + }) + used += len(clonedKey) + cut + truncated = true + stop = true + break + } + entries = append(entries, deferredHeaderEntry{ + key: clonedKey, + value: strings.Clone(masked), + }) + used += len(clonedKey) + len(masked) + } + if stop { + break + } + } + return entries, used, truncated +} + +func truncateUTF8Boundary(s string, maxBytes int) int { + if maxBytes <= 0 { + return 0 + } + if len(s) <= maxBytes { + return len(s) + } + for maxBytes > 0 && !utf8.RuneStart(s[maxBytes]) { + maxBytes-- + } + if maxBytes == 0 { + return 1 + } + return maxBytes +} + +func writeMaskedHeaders(builder *strings.Builder, headers []deferredHeaderEntry, truncated bool) { + if builder == nil { + return + } + if len(headers) == 0 { + if truncated { + builder.WriteString("[API RESPONSE HEADERS TRUNCATED]\n") + return + } + builder.WriteString("\n") + return + } + for _, entry := range headers { + if entry.value == "" { + builder.WriteString(fmt.Sprintf("%s:\n", entry.key)) + continue + } + builder.WriteString(fmt.Sprintf("%s: %s\n", entry.key, entry.value)) + } + if truncated { + builder.WriteString("[API RESPONSE HEADERS TRUNCATED]\n") + } +} diff --git a/internal/logging/request_logger.go b/internal/logging/request_logger.go index 550a0ae26fc..cdc56790f03 100644 --- a/internal/logging/request_logger.go +++ b/internal/logging/request_logger.go @@ -15,6 +15,7 @@ const ( WebsocketTimelineSourceContextKey = "WEBSOCKET_TIMELINE_SOURCE" APIRequestSourceContextKey = "API_REQUEST_SOURCE" DeferredAPIRequestContextKey = "DEFERRED_API_REQUEST" + DeferredAPIResponseContextKey = "DEFERRED_API_RESPONSE" APIResponseSourceContextKey = "API_RESPONSE_SOURCE" APIResponseCapturedContextKey = "API_RESPONSE_CAPTURED" APIWebsocketTimelineSourceContextKey = "API_WEBSOCKET_TIMELINE_SOURCE" diff --git a/internal/logging/request_logger_home.go b/internal/logging/request_logger_home.go index 7aa6c0207ce..b283c44c5bc 100644 --- a/internal/logging/request_logger_home.go +++ b/internal/logging/request_logger_home.go @@ -257,3 +257,15 @@ func (w *homeStreamingLogWriter) Close() error { } return client.RPushRequestLog(context.Background(), raw) } + +func (w *homeStreamingLogWriter) Discard() error { + if w == nil { + return nil + } + if w.chunkChan != nil { + close(w.chunkChan) + <-w.doneChan + w.chunkChan = nil + } + return nil +} diff --git a/internal/logging/request_logger_streaming.go b/internal/logging/request_logger_streaming.go index 7c3505d4d60..15c67163848 100644 --- a/internal/logging/request_logger_streaming.go +++ b/internal/logging/request_logger_streaming.go @@ -258,6 +258,15 @@ func (w *FileStreamingLogWriter) Close() error { return writeErr } +// Discard stops the streaming writer and removes temporary files without creating a final log file. +func (w *FileStreamingLogWriter) Discard() error { + if w == nil { + return nil + } + w.logFilename = "" + return w.Close() +} + // asyncWriter runs in a goroutine to buffer chunks from the channel. // It continuously reads chunks from the channel and appends them to a temp file for later assembly. func (w *FileStreamingLogWriter) asyncWriter() { diff --git a/internal/pluginhost/adapters.go b/internal/pluginhost/adapters.go index eec740d2321..b449f297e1e 100644 --- a/internal/pluginhost/adapters.go +++ b/internal/pluginhost/adapters.go @@ -26,11 +26,13 @@ type modelProviderRegistry interface { } type pluginModelRegistration struct { - pluginID string - provider string - priority int - models []*registry.ModelInfo - hasExecutor bool + pluginID string + provider string + priority int + models []*registry.ModelInfo + hasExecutor bool + allowsStaticClient bool + hasModelProvider bool } func normalizedExecutorModelScope(caps pluginapi.Capabilities) pluginapi.ExecutorModelScope { @@ -41,6 +43,9 @@ func normalizedExecutorModelScope(caps pluginapi.Capabilities) pluginapi.Executo case pluginapi.ExecutorModelScopeStatic, pluginapi.ExecutorModelScopeOAuth, pluginapi.ExecutorModelScopeBoth: return caps.ExecutorModelScope default: + if hasAuthProviderCap(caps) { + return pluginapi.ExecutorModelScopeOAuth + } return pluginapi.ExecutorModelScopeBoth } } @@ -50,6 +55,9 @@ func executorScopeAllowsStaticModels(caps pluginapi.Capabilities) bool { return true } scope := normalizedExecutorModelScope(caps) + if hasAuthProviderCap(caps) { + return scope == pluginapi.ExecutorModelScopeStatic + } return scope == pluginapi.ExecutorModelScopeStatic || scope == pluginapi.ExecutorModelScopeBoth } @@ -256,9 +264,6 @@ func (h *Host) RegisterModels(ctx context.Context, modelRegistry modelRegistry) if modelProvider == nil && registrar == nil { continue } - if !executorScopeAllowsStaticModels(record.plugin.Capabilities) { - continue - } var resp pluginapi.ModelRegistrationResponse var errRegisterModels error if modelProvider != nil { @@ -313,11 +318,13 @@ func (h *Host) RegisterModels(ctx context.Context, modelRegistry modelRegistry) } regIndexByProvider[provider] = len(regsForPlugin) regsForPlugin = append(regsForPlugin, pluginModelRegistration{ - pluginID: record.id, - provider: provider, - priority: record.priority, - models: cloneRegistryModels(models), - hasExecutor: record.plugin.Capabilities.Executor != nil, + pluginID: record.id, + provider: provider, + priority: record.priority, + models: cloneRegistryModels(models), + hasExecutor: record.plugin.Capabilities.Executor != nil, + allowsStaticClient: record.plugin.Capabilities.Executor != nil && executorScopeAllowsStaticModels(record.plugin.Capabilities), + hasModelProvider: modelProvider != nil, }) } if len(regsForPlugin) == 0 { @@ -373,6 +380,17 @@ func (h *Host) authModelProviderMatches(record capabilityRecord, provider string return true } } + for _, prov := range recordAuthProviders(record) { + credIDs, okCredIDs := h.callAuthProviderCredentialProviders(record.id, prov) + if !okCredIDs { + return false + } + for _, credID := range credIDs { + if normalizeProviderID(credID) == provider { + return true + } + } + } } candidates := h.modelProvidersForPlugin(record.id) if len(candidates) > 0 { @@ -381,6 +399,11 @@ func (h *Host) authModelProviderMatches(record capabilityRecord, provider string return true } } + if caps.Executor != nil { + if candidate, okExec := h.executorProvider(record, caps.Executor); okExec && candidate == provider { + return true + } + } return false } if caps.Executor != nil { diff --git a/internal/pluginhost/adapters_executors.go b/internal/pluginhost/adapters_executors.go index 48771f958d6..6ad61910819 100644 --- a/internal/pluginhost/adapters_executors.go +++ b/internal/pluginhost/adapters_executors.go @@ -43,6 +43,7 @@ func (h *Host) RegisterExecutors(manager executorManager, modelRegistry modelPro registrations := h.snapshotModelRegistrations() selectedModels := make(map[string][]*registry.ModelInfo) providerModels := make(map[string][]*registry.ModelInfo) + staticAppendProviderModels := make(map[string][]*registry.ModelInfo) claimedModels := make(map[string]struct{}) claimedProviders := make(map[string]string) for _, registration := range registrations { @@ -50,6 +51,7 @@ func (h *Host) RegisterExecutors(manager executorManager, modelRegistry modelPro continue } appendModelsForProvider(providerModels, registration.provider, registration.models) + appendModelsForProvider(staticAppendProviderModels, registration.provider, registration.models) // Reserve native catalog models before plugin arbitration, independently of // credential publication or exclusions. This preserves native priority without // publishing availability, which remains credential-bound. @@ -72,9 +74,13 @@ func (h *Host) RegisterExecutors(manager executorManager, modelRegistry modelPro if !okProvider { continue } + if !executorScopeAllowsStaticModels(record.plugin.Capabilities) { + continue + } registration := h.modelRegistration(record.id) if h.providerHasNativeExecutor(manager, provider) { appendModelsForProvider(providerModels, provider, registration.models) + appendModelsForProvider(staticAppendProviderModels, provider, registration.models) continue } if len(registration.models) == 0 { @@ -101,6 +107,7 @@ func (h *Host) RegisterExecutors(manager executorManager, modelRegistry modelPro } seenProviders := make(map[string]struct{}) + seenCatalogProviders := make(map[string]struct{}) nextProviders := make(map[string]struct{}) nextModelClients := make(map[string]struct{}) executorRegistrations := make([]executorRegistration, 0) @@ -111,61 +118,105 @@ func (h *Host) RegisterExecutors(manager executorManager, modelRegistry modelPro continue } - provider, okProvider := h.executorProvider(record, executor) - if !okProvider { - continue - } + allowsStatic := executorScopeAllowsStaticModels(record.plugin.Capabilities) registration := h.modelRegistration(record.id) - if len(registration.models) > 0 && len(selectedModels[record.id]) == 0 { - continue - } - if _, seenProvider := seenProviders[provider]; seenProvider { + if allowsStatic && len(registration.models) > 0 && len(selectedModels[record.id]) == 0 { continue } - seenProviders[provider] = struct{}{} - if h.providerHasNativeExecutor(manager, provider) { + + provider, okProvider := h.executorProvider(record, executor) + if h.isPluginFused(record.id) { continue } - - nextProviders[provider] = struct{}{} - executorRegistrations = append(executorRegistrations, newExecutorAdapterRegistration(h, record, provider, executor)) - appendModelsForProvider(providerModels, provider, selectedModels[record.id]) - if len(selectedModels[record.id]) > 0 { - clientID := pluginExecutorModelClientID(record.id, provider) - modelClientRegistrations = append(modelClientRegistrations, modelClientRegistration{ - clientID: clientID, - provider: provider, - models: selectedModels[record.id], - }) - nextModelClients[clientID] = struct{}{} - } - if executorScopeAllowsOAuthModels(record.plugin.Capabilities) && hasRecordAuthProvider(record) { - if authIDs, okAuthIDs := h.callRecordAuthProviderIdentifiers(record); okAuthIDs { - for _, authID := range authIDs { - if authID == "" || authID == provider { - continue - } - if _, seenAuthProvider := seenProviders[authID]; seenAuthProvider { - continue - } - seenProviders[authID] = struct{}{} - if h.providerHasNativeExecutor(manager, authID) { - continue + if okProvider { + if _, seenProvider := seenProviders[provider]; !seenProvider { + seenProviders[provider] = struct{}{} + if !h.providerHasNativeExecutor(manager, provider) { + nextProviders[provider] = struct{}{} + executorRegistrations = append(executorRegistrations, newExecutorAdapterRegistration(h, record, provider, executor)) + if allowsStatic { + appendModelsForProvider(providerModels, provider, selectedModels[record.id]) + appendModelsForProvider(staticAppendProviderModels, provider, selectedModels[record.id]) + if len(selectedModels[record.id]) > 0 { + clientID := pluginExecutorModelClientID(record.id, provider) + modelClientRegistrations = append(modelClientRegistrations, modelClientRegistration{ + clientID: clientID, + provider: provider, + models: selectedModels[record.id], + }) + nextModelClients[clientID] = struct{}{} + } } - nextProviders[authID] = struct{}{} - executorRegistrations = append(executorRegistrations, newExecutorAdapterRegistration(h, record, authID, executor)) } } } + if !allowsStatic { + for _, reg := range h.pluginRegistrations(record.id) { + if _, seenCatalog := seenCatalogProviders[reg.provider]; seenCatalog { + continue + } + seenCatalogProviders[reg.provider] = struct{}{} + appendModelsForProvider(providerModels, reg.provider, reg.models) + if !reg.hasModelProvider { + appendModelsForProvider(staticAppendProviderModels, reg.provider, reg.models) + } + } + } + for _, authID := range h.recordOAuthExecutorProviders(record) { + if authID == "" || authID == provider { + continue + } + if _, seenAuthProvider := seenProviders[authID]; seenAuthProvider { + continue + } + seenProviders[authID] = struct{}{} + if h.providerHasNativeExecutor(manager, authID) { + continue + } + nextProviders[authID] = struct{}{} + executorRegistrations = append(executorRegistrations, newExecutorAdapterRegistration(h, record, authID, executor)) + } + } + h.commitExecutorState(snap, manager, modelRegistry, providerModels, staticAppendProviderModels, executorRegistrations, nextProviders, modelClientRegistrations, nextModelClients) +} + +func (h *Host) recordOAuthExecutorProviders(record capabilityRecord) []string { + if h == nil || !executorScopeAllowsOAuthModels(record.plugin.Capabilities) || !hasRecordAuthProvider(record) { + return nil + } + seen := make(map[string]struct{}) + var out []string + appendProvider := func(raw string) { + id := normalizeProviderID(raw) + if id == "" { + return + } + if _, exists := seen[id]; exists { + return + } + seen[id] = struct{}{} + out = append(out, id) + } + if authIDs, okAuthIDs := h.callRecordAuthProviderIdentifiers(record); okAuthIDs { + for _, authID := range authIDs { + appendProvider(authID) + } + } + for _, prov := range recordAuthProviders(record) { + if credIDs, okCredIDs := h.callAuthProviderCredentialProviders(record.id, prov); okCredIDs { + for _, credID := range credIDs { + appendProvider(credID) + } + } } - h.commitExecutorState(snap, manager, modelRegistry, providerModels, executorRegistrations, nextProviders, modelClientRegistrations, nextModelClients) + return out } func pluginExecutorModelClientID(pluginID, provider string) string { return "plugin:" + pluginID + ":" + provider + ":executor" } -func (h *Host) commitExecutorState(snap *Snapshot, manager executorManager, modelRegistry modelRegistry, providerModels map[string][]*registry.ModelInfo, registrations []executorRegistration, nextProviders map[string]struct{}, modelClientRegistrations []modelClientRegistration, nextModelClients map[string]struct{}) { +func (h *Host) commitExecutorState(snap *Snapshot, manager executorManager, modelRegistry modelRegistry, providerModels, staticAppendProviderModels map[string][]*registry.ModelInfo, registrations []executorRegistration, nextProviders map[string]struct{}, modelClientRegistrations []modelClientRegistration, nextModelClients map[string]struct{}) { if h == nil || manager == nil { return } @@ -180,6 +231,10 @@ func (h *Host) commitExecutorState(snap *Snapshot, manager executorManager, mode for provider, models := range providerModels { h.providerModels[provider] = cloneRegistryModels(models) } + h.staticAppendProviderModels = make(map[string][]*registryModelInfo, len(staticAppendProviderModels)) + for provider, models := range staticAppendProviderModels { + h.staticAppendProviderModels[provider] = cloneRegistryModels(models) + } staleProviders := make([]string, 0) for provider := range h.executorProviders { @@ -315,11 +370,23 @@ func (h *Host) modelRegistration(pluginID string) pluginModelRegistration { return registration } +func (h *Host) pluginRegistrations(pluginID string) []pluginModelRegistration { + if h == nil { + return nil + } + h.mu.Lock() + defer h.mu.Unlock() + return h.pluginRegistrationsLocked(pluginID) +} + func (h *Host) executorProvider(record capabilityRecord, executor pluginapi.ProviderExecutor) (string, bool) { if h == nil || !h.recordCurrent(record) { return "", false } - provider := h.modelProvider(record.id) + var provider string + if executorScopeAllowsStaticModels(record.plugin.Capabilities) { + provider = h.modelProvider(record.id) + } if provider == "" { identifier, okIdentifier := h.callExecutorIdentifier(record.id, executor) if !okIdentifier { @@ -327,6 +394,9 @@ func (h *Host) executorProvider(record capabilityRecord, executor pluginapi.Prov } provider = identifier } + if provider == "" { + provider = h.modelProvider(record.id) + } provider = strings.ToLower(strings.TrimSpace(provider)) return provider, provider != "" } @@ -405,6 +475,23 @@ func (h *Host) ModelsForProvider(provider string) []*registry.ModelInfo { return cloneRegistryModels(h.providerModels[provider]) } +// StaticAppendModelsForProvider returns static plugin models eligible to be +// appended to credential registrations when per-auth ModelProvider did not handle them. +// OAuth-scoped ModelProvider executors keep their StaticModels catalog-only so +// unfiltered or unaliased static models are never appended onto credentials. +func (h *Host) StaticAppendModelsForProvider(provider string) []*registry.ModelInfo { + if h == nil { + return nil + } + provider = strings.ToLower(strings.TrimSpace(provider)) + if provider == "" { + return nil + } + h.mu.Lock() + defer h.mu.Unlock() + return cloneRegistryModels(h.staticAppendProviderModels[provider]) +} + func (h *Host) HasExecutorCandidateProvider(provider string) bool { if h == nil { return false @@ -422,13 +509,9 @@ func (h *Host) HasExecutorCandidateProvider(provider string) bool { if okCandidate && candidate == provider { return true } - if executorScopeAllowsOAuthModels(record.plugin.Capabilities) && hasRecordAuthProvider(record) { - if authIDs, okAuthIDs := h.callRecordAuthProviderIdentifiers(record); okAuthIDs { - for _, authID := range authIDs { - if authID == provider { - return true - } - } + for _, authID := range h.recordOAuthExecutorProviders(record) { + if authID == provider { + return true } } } @@ -622,9 +705,11 @@ func (a *executorAdapter) lookupPluginModelInfo(baseModel string) *registry.Mode return model } } - for _, model := range a.host.modelRegistration(a.pluginID).models { - if model != nil && strings.EqualFold(strings.TrimSpace(model.ID), baseModel) { - return model + for _, reg := range a.host.pluginRegistrations(a.pluginID) { + for _, model := range reg.models { + if model != nil && strings.EqualFold(strings.TrimSpace(model.ID), baseModel) { + return model + } } } return nil diff --git a/internal/pluginhost/adapters_test.go b/internal/pluginhost/adapters_test.go index 90cbd557bfd..7ac57c63933 100644 --- a/internal/pluginhost/adapters_test.go +++ b/internal/pluginhost/adapters_test.go @@ -668,8 +668,8 @@ func TestRegisterExecutorsOAuthScopeSkipsStaticModelClientButRegistersExecutor(t host.RegisterModels(context.Background(), modelRegistry) host.RegisterExecutors(manager, modelRegistry) - if staticCalled { - t.Fatal("StaticModels was called for an OAuth-only executor") + if !staticCalled { + t.Fatal("StaticModels was not called to populate catalog metadata for OAuth executor") } if _, okExecutor := manager.executors["sample-provider"]; !okExecutor { t.Fatal("OAuth-only executor was not registered") @@ -677,8 +677,11 @@ func TestRegisterExecutorsOAuthScopeSkipsStaticModelClientButRegistersExecutor(t if _, okClient := modelRegistry.clients[pluginExecutorModelClientID("sample-provider", "sample-provider")]; okClient { t.Fatal("OAuth-only executor registered a static model client") } - if got := host.ModelsForProvider("sample-provider"); len(got) != 0 { - t.Fatalf("OAuth-only provider models = %#v, want none", got) + if got := host.ModelsForProvider("sample-provider"); len(got) != 1 || got[0].ID != "static-model" { + t.Fatalf("OAuth-only provider catalog models = %#v, want [static-model]", got) + } + if got := host.StaticAppendModelsForProvider("sample-provider"); len(got) != 0 { + t.Fatalf("OAuth-only StaticAppendModelsForProvider = %#v, want none", got) } result := host.ModelsForAuth(context.Background(), &coreauth.Auth{ @@ -766,45 +769,377 @@ func TestRegisterExecutorsStaticScopeSkipsModelsForAuth(t *testing.T) { } func TestRegisterExecutorsBothScopeKeepsStaticAndOAuthModels(t *testing.T) { + t.Run("without auth provider keeps static model client and oauth models", func(t *testing.T) { + modelRegistry := newFakeModelRegistry() + manager := newFakeExecutorManager() + host := newHostWithRecords(capabilityRecord{ + id: "alpha", + plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + ModelProvider: modelProviderFunc{ + staticModels: func(ctx context.Context, req pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "plugin-provider", + Models: []pluginapi.ModelInfo{{ID: "static-model"}}, + }, nil + }, + modelsForAuth: func(ctx context.Context, req pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "plugin-provider", + Models: []pluginapi.ModelInfo{{ID: "oauth-model"}}, + }, nil + }, + }, + Executor: &fakeExecutor{identifier: "plugin-provider"}, + ExecutorModelScope: pluginapi.ExecutorModelScopeBoth, + }}, + }) + + host.RegisterModels(context.Background(), modelRegistry) + host.RegisterExecutors(manager, modelRegistry) + + clientID := pluginExecutorModelClientID("alpha", "plugin-provider") + reg := modelRegistry.clients[clientID] + if reg == nil || reg.provider != "plugin-provider" || len(reg.models) != 1 || reg.models[0].ID != "static-model" { + t.Fatalf("both-scope static model client = %#v, want static-model", reg) + } + result := host.ModelsForAuth(context.Background(), &coreauth.Auth{ + ID: "plugin-auth", + Provider: "plugin-provider", + }) + if !result.Handled || result.Provider != "plugin-provider" || len(result.Models) != 1 || result.Models[0].ID != "oauth-model" { + t.Fatalf("both-scope OAuth model result = %#v, want oauth-model", result) + } + }) + + t.Run("with auth provider skips static model client and keeps catalog and oauth models", func(t *testing.T) { + modelRegistry := newFakeModelRegistry() + manager := newFakeExecutorManager() + host := newHostWithRecords(capabilityRecord{ + id: "alpha", + plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + AuthProvider: fakeAuthProvider{identifier: "plugin-provider"}, + ModelProvider: modelProviderFunc{ + staticModels: func(ctx context.Context, req pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "plugin-provider", + Models: []pluginapi.ModelInfo{{ID: "static-model"}}, + }, nil + }, + modelsForAuth: func(ctx context.Context, req pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "plugin-provider", + Models: []pluginapi.ModelInfo{{ID: "oauth-model"}}, + }, nil + }, + }, + Executor: &fakeExecutor{identifier: "plugin-provider"}, + ExecutorModelScope: pluginapi.ExecutorModelScopeBoth, + }}, + }) + + host.RegisterModels(context.Background(), modelRegistry) + host.RegisterExecutors(manager, modelRegistry) + + clientID := pluginExecutorModelClientID("alpha", "plugin-provider") + if _, okClient := modelRegistry.clients[clientID]; okClient { + t.Fatal("credential-bound both-scope executor registered a static model client") + } + if _, okExecutor := manager.executors["plugin-provider"]; !okExecutor { + t.Fatal("credential-bound both-scope executor was not registered") + } + if host.executorPluginReady("alpha", pluginapi.ModelRouteRequest{RequestedModel: "static-model", SourceFormat: "openai"}) { + t.Fatal("executorPluginReady returned true for credential-bound both-scope plugin") + } + if catalog := host.ModelsForProvider("plugin-provider"); len(catalog) != 1 || catalog[0].ID != "static-model" { + t.Fatalf("ModelsForProvider = %#v, want [static-model]", catalog) + } + result := host.ModelsForAuth(context.Background(), &coreauth.Auth{ + ID: "plugin-auth", + Provider: "plugin-provider", + }) + if !result.Handled || result.Provider != "plugin-provider" || len(result.Models) != 1 || result.Models[0].ID != "oauth-model" { + t.Fatalf("both-scope OAuth model result = %#v, want oauth-model", result) + } + }) +} + +func TestRegisterExecutorsAuthProviderUnsetScopeSkipsStaticModelClientAndPreservesCatalog(t *testing.T) { modelRegistry := newFakeModelRegistry() + modelRegistry.RegisterClient("native-client", "claude", []*registry.ModelInfo{{ID: "native-overlap-model"}}) manager := newFakeExecutorManager() + manager.RegisterExecutor(&fakeProviderExecutor{provider: "claude"}) + + plugin := pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + AuthProvider: fakeAuthProvider{identifier: "demo"}, + ModelProvider: modelProviderFunc{ + staticModels: func(ctx context.Context, req pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "demo", + Models: []pluginapi.ModelInfo{ + {ID: "demo-a"}, + {ID: "demo-blocked"}, + {ID: "native-overlap-model"}, + }, + }, nil + }, + modelsForAuth: func(ctx context.Context, req pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "demo", + Models: []pluginapi.ModelInfo{ + {ID: "demo-a"}, + {ID: "demo-blocked"}, + }, + }, nil + }, + }, + Executor: &fakeExecutor{identifier: "demo"}, + }} + host := newHostWithRecords(capabilityRecord{id: "demo-oauth-plugin", plugin: plugin}) + + if rpcCaps := rpcCapabilitiesFromPlugin(plugin); rpcCaps.ExecutorModelScope != pluginapi.ExecutorModelScopeOAuth { + t.Fatalf("rpcCapabilitiesFromPlugin ExecutorModelScope = %q, want %q", rpcCaps.ExecutorModelScope, pluginapi.ExecutorModelScopeOAuth) + } + + host.RegisterModels(context.Background(), modelRegistry) + host.RegisterExecutors(manager, modelRegistry) + + if _, okClient := modelRegistry.clients[pluginExecutorModelClientID("demo-oauth-plugin", "demo")]; okClient { + t.Fatal("credential-bound plugin with unset ExecutorModelScope leaked synthetic static model client into ModelRegistry") + } + if _, okExecutor := manager.executors["demo"]; !okExecutor { + t.Fatal("credential-bound plugin executor was not registered") + } + if got := host.ModelsForProvider("demo"); len(got) != 3 { + t.Fatalf("ModelsForProvider(demo) = %#v, want 3 static catalog models", got) + } + if got := host.StaticAppendModelsForProvider("demo"); len(got) != 0 { + t.Fatalf("StaticAppendModelsForProvider(demo) = %#v, want none", got) + } + if host.executorPluginReady("demo-oauth-plugin", pluginapi.ModelRouteRequest{RequestedModel: "demo-a", SourceFormat: "openai"}) { + t.Fatal("executorPluginReady returned true for credential-bound plugin with unset ExecutorModelScope") + } + result := host.ModelsForAuth(context.Background(), &coreauth.Auth{ID: "demo-auth", Provider: "demo"}) + if !result.Handled || len(result.Models) != 2 { + t.Fatalf("ModelsForAuth(demo) = %#v, want 2 models", result) + } +} + +func TestRegisterExecutorsAuthProviderCredentialProviderMatchesModelsForAuthWithStaticCatalog(t *testing.T) { + modelRegistry := newFakeModelRegistry() + manager := newFakeExecutorManager() + host := newHostWithRecords(capabilityRecord{ - id: "alpha", + id: "multi-portal-oauth", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ - AuthProvider: fakeAuthProvider{identifier: "plugin-provider"}, + AuthProvider: fakeAuthProvider{ + identifier: "portal-a", + credentialProviders: []string{"cred-a"}, + }, ModelProvider: modelProviderFunc{ staticModels: func(ctx context.Context, req pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { return pluginapi.ModelResponse{ - Provider: "plugin-provider", - Models: []pluginapi.ModelInfo{{ID: "static-model"}}, + Provider: "portal-a", + Models: []pluginapi.ModelInfo{{ID: "portal-model"}}, }, nil }, modelsForAuth: func(ctx context.Context, req pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { return pluginapi.ModelResponse{ - Provider: "plugin-provider", - Models: []pluginapi.ModelInfo{{ID: "oauth-model"}}, + Provider: "cred-a", + Models: []pluginapi.ModelInfo{{ID: "cred-model"}}, }, nil }, }, - Executor: &fakeExecutor{identifier: "plugin-provider"}, - ExecutorModelScope: pluginapi.ExecutorModelScopeBoth, + Executor: &fakeExecutor{identifier: "cred-a"}, + ExecutorModelScope: pluginapi.ExecutorModelScopeOAuth, }}, }) host.RegisterModels(context.Background(), modelRegistry) host.RegisterExecutors(manager, modelRegistry) - clientID := pluginExecutorModelClientID("alpha", "plugin-provider") - reg := modelRegistry.clients[clientID] - if reg == nil || reg.provider != "plugin-provider" || len(reg.models) != 1 || reg.models[0].ID != "static-model" { - t.Fatalf("both-scope static model client = %#v, want static-model", reg) + if _, okExec := manager.executors["cred-a"]; !okExec { + t.Fatal("executor for credential provider cred-a was not registered") } - result := host.ModelsForAuth(context.Background(), &coreauth.Auth{ - ID: "plugin-auth", - Provider: "plugin-provider", + if _, okPortalExec := manager.executors["portal-a"]; !okPortalExec { + t.Fatal("executor for auth portal portal-a was not registered") + } + if !host.HasExecutorCandidateProvider("cred-a") || !host.HasExecutorCandidateProvider("portal-a") { + t.Fatal("HasExecutorCandidateProvider failed for cred-a or portal-a") + } + if !host.HasAuthModelProvider("cred-a") { + t.Fatal("HasAuthModelProvider(cred-a) = false, want true") + } + result := host.ModelsForAuth(context.Background(), &coreauth.Auth{ID: "cred-auth", Provider: "cred-a"}) + if !result.Handled || result.Provider != "cred-a" || len(result.Models) != 1 || result.Models[0].ID != "cred-model" { + t.Fatalf("ModelsForAuth(cred-a) = %#v, want cred-model", result) + } +} + +func TestShutdownAllContextClearsStaticAppendProviderModels(t *testing.T) { + modelRegistry := newFakeModelRegistry() + manager := newFakeExecutorManager() + host := newHostWithRecords(capabilityRecord{ + id: "catalog-only", + plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + ModelRegistrar: staticModelRegistrar("kimi", "catalog-model"), + }}, }) - if !result.Handled || result.Provider != "plugin-provider" || len(result.Models) != 1 || result.Models[0].ID != "oauth-model" { - t.Fatalf("both-scope OAuth model result = %#v, want oauth-model", result) + + host.RegisterModels(context.Background(), modelRegistry) + host.RegisterExecutors(manager, modelRegistry) + + if got := host.ModelsForProvider("kimi"); len(got) != 1 || got[0].ID != "catalog-model" { + t.Fatalf("ModelsForProvider(kimi) = %#v, want [catalog-model]", got) + } + if got := host.StaticAppendModelsForProvider("kimi"); len(got) != 1 || got[0].ID != "catalog-model" { + t.Fatalf("StaticAppendModelsForProvider(kimi) = %#v, want [catalog-model]", got) + } + + host.ShutdownAllContext(context.Background()) + + if got := host.ModelsForProvider("kimi"); len(got) != 0 { + t.Fatalf("ModelsForProvider(kimi) after shutdown = %#v, want empty", got) + } + if got := host.StaticAppendModelsForProvider("kimi"); len(got) != 0 { + t.Fatalf("StaticAppendModelsForProvider(kimi) after shutdown = %#v, want empty", got) + } +} + +func TestModelsForAuthOAuthScopeWithoutAuthProviderMatchesExecutorIdentifierWithStaticCatalog(t *testing.T) { + modelRegistry := newFakeModelRegistry() + manager := newFakeExecutorManager() + + host := newHostWithRecords(capabilityRecord{ + id: "oauth-no-auth-provider", + plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + ModelProvider: modelProviderFunc{ + staticModels: func(ctx context.Context, req pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "catalog-a", + Models: []pluginapi.ModelInfo{{ID: "catalog-model"}}, + }, nil + }, + modelsForAuth: func(ctx context.Context, req pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "cred-a", + Models: []pluginapi.ModelInfo{{ID: "cred-model"}}, + }, nil + }, + }, + Executor: &fakeExecutor{identifier: "cred-a"}, + ExecutorModelScope: pluginapi.ExecutorModelScopeOAuth, + }}, + }) + + host.RegisterModels(context.Background(), modelRegistry) + host.RegisterExecutors(manager, modelRegistry) + + if _, okExec := manager.executors["cred-a"]; !okExec { + t.Fatal("OAuth-only executor cred-a was not registered") + } + if !host.HasAuthModelProvider("cred-a") { + t.Fatal("HasAuthModelProvider(cred-a) = false, want true") + } + result := host.ModelsForAuth(context.Background(), &coreauth.Auth{ID: "cred-auth", Provider: "cred-a"}) + if !result.Handled || result.Provider != "cred-a" || len(result.Models) != 1 || result.Models[0].ID != "cred-model" { + t.Fatalf("ModelsForAuth(cred-a) = %#v, want cred-model", result) + } + if catalog := host.ModelsForProvider("catalog-a"); len(catalog) != 1 || catalog[0].ID != "catalog-model" { + t.Fatalf("ModelsForProvider(catalog-a) = %#v, want [catalog-model]", catalog) + } +} + +func TestRegisterExecutorsNativePrimaryProviderStillRegistersOAuthAuthProviders(t *testing.T) { + modelRegistry := newFakeModelRegistry() + manager := newFakeExecutorManager() + nativeClaude := &fakeProviderExecutor{provider: "claude"} + manager.RegisterExecutor(nativeClaude) + + host := newHostWithRecords(capabilityRecord{ + id: "oauth-native-primary-conflict", + plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + AuthProvider: fakeAuthProvider{ + identifier: "portal-a", + credentialProviders: []string{"cred-a"}, + }, + ModelProvider: modelProviderFunc{ + staticModels: func(ctx context.Context, req pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "catalog-a", + Models: []pluginapi.ModelInfo{{ID: "catalog-model"}}, + }, nil + }, + modelsForAuth: func(ctx context.Context, req pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "cred-a", + Models: []pluginapi.ModelInfo{{ID: "cred-model"}}, + }, nil + }, + }, + Executor: &fakeExecutor{identifier: "claude"}, + }}, + }) + + host.RegisterModels(context.Background(), modelRegistry) + host.RegisterExecutors(manager, modelRegistry) + + if manager.executors["claude"] != nativeClaude { + t.Fatalf("native claude executor was overwritten: %#v", manager.executors["claude"]) + } + if _, okPortal := manager.executors["portal-a"]; !okPortal { + t.Fatal("auth portal executor portal-a was skipped when primary provider conflicted with native claude") + } + if _, okCred := manager.executors["cred-a"]; !okCred { + t.Fatal("credential provider executor cred-a was skipped when primary provider conflicted with native claude") + } + if catalog := host.ModelsForProvider("catalog-a"); len(catalog) != 1 || catalog[0].ID != "catalog-model" { + t.Fatalf("ModelsForProvider(catalog-a) = %#v, want [catalog-model]", catalog) + } +} + +func TestRegisterExecutorsOAuthScopePreservesStaticCatalogAndRegistersExecutorWithNativeOverlap(t *testing.T) { + modelRegistry := newFakeModelRegistry() + modelRegistry.RegisterClient("native-client", "claude", []*registry.ModelInfo{{ID: "native-overlap-model"}}) + manager := newFakeExecutorManager() + manager.RegisterExecutor(&fakeProviderExecutor{provider: "claude"}) + + host := newHostWithRecords(capabilityRecord{ + id: "oauth-catalog-plugin", + plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + AuthProvider: fakeAuthProvider{identifier: "demo-oauth"}, + ModelProvider: modelProviderFunc{ + staticModels: func(ctx context.Context, req pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "demo-oauth", + Models: []pluginapi.ModelInfo{ + {ID: "native-overlap-model"}, + }, + }, nil + }, + modelsForAuth: func(ctx context.Context, req pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{ + Provider: "demo-oauth", + Models: []pluginapi.ModelInfo{{ID: "demo-oauth-model"}}, + }, nil + }, + }, + Executor: &fakeExecutor{identifier: "demo-oauth"}, + ExecutorModelScope: pluginapi.ExecutorModelScopeOAuth, + }}, + }) + + host.RegisterModels(context.Background(), modelRegistry) + host.RegisterExecutors(manager, modelRegistry) + + if _, okClient := modelRegistry.clients[pluginExecutorModelClientID("oauth-catalog-plugin", "demo-oauth")]; okClient { + t.Fatal("OAuth-scoped executor leaked synthetic static model client into ModelRegistry") + } + if _, okExecutor := manager.executors["demo-oauth"]; !okExecutor { + t.Fatal("OAuth-scoped executor was suppressed due to native catalog overlap") + } + got := host.ModelsForProvider("demo-oauth") + if len(got) != 1 || got[0].ID != "native-overlap-model" { + t.Fatalf("ModelsForProvider(demo-oauth) = %#v, want [native-overlap-model]", got) } } @@ -2793,6 +3128,130 @@ func TestUsageAdapterPropagatesRequestIDAndTraceID(t *testing.T) { } } +func TestUsageAdapterPropagatesModalityTokenDetails(t *testing.T) { + var gotRecord pluginapi.UsageRecord + plugin := usagePluginFunc(func(ctx context.Context, record pluginapi.UsageRecord) { + gotRecord = record + }) + host := newHostWithRecords(capabilityRecord{ + id: "usage-modality-details", + plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + UsagePlugin: plugin, + }}, + }) + adapter := &usageAdapter{ + host: host, + pluginID: "usage-modality-details", + plugin: plugin, + } + + textIn := int64(30) + imageIn := int64(50) + audioIn := int64(0) + videoIn := int64(18) + fileIn := int64(12) + cachedText := int64(25) + cachedImage := int64(15) + cachedAudio := int64(0) + textOut := int64(0) + imageOut := int64(1056) + audioOut := int64(42) + + adapter.HandleUsage(context.Background(), coreusage.Record{ + Provider: "openai", + Model: "gpt-image-2.5-flare", + Detail: coreusage.Detail{ + InputTokens: 110, + OutputTokens: 1098, + ReasoningTokens: 10, + CachedTokens: 40, + CacheReadTokens: 40, + CacheCreationTokens: 5, + TotalTokens: 1208, + TextInputTokens: &textIn, + ImageInputTokens: &imageIn, + AudioInputTokens: &audioIn, + VideoInputTokens: &videoIn, + FileInputTokens: &fileIn, + CachedTextTokens: &cachedText, + CachedImageTokens: &cachedImage, + CachedAudioTokens: &cachedAudio, + TextOutputTokens: &textOut, + ImageOutputTokens: &imageOut, + AudioOutputTokens: &audioOut, + }, + }) + + // Mutate caller-owned source values after HandleUsage to verify independent pointer copies. + textIn = 999 + imageIn = 999 + audioIn = 999 + videoIn = 999 + fileIn = 999 + cachedText = 999 + cachedImage = 999 + cachedAudio = 999 + textOut = 999 + imageOut = 999 + audioOut = 999 + + got := gotRecord.Detail + if got.InputTokens != 110 || got.OutputTokens != 1098 || got.ReasoningTokens != 10 || + got.CachedTokens != 40 || got.CacheReadTokens != 40 || got.CacheCreationTokens != 5 || got.TotalTokens != 1208 { + t.Fatalf("aggregate Detail = %+v", got) + } + assertInt64Ptr := func(name string, ptr *int64, src *int64, want int64) { + t.Helper() + if ptr == nil { + t.Fatalf("%s = nil, want %d", name, want) + } + if ptr == src { + t.Fatalf("%s shares pointer %p with source record", name, ptr) + } + if *ptr != want { + t.Fatalf("%s = %d, want %d", name, *ptr, want) + } + } + assertInt64Ptr("TextInputTokens", got.TextInputTokens, &textIn, 30) + assertInt64Ptr("ImageInputTokens", got.ImageInputTokens, &imageIn, 50) + assertInt64Ptr("AudioInputTokens", got.AudioInputTokens, &audioIn, 0) + assertInt64Ptr("VideoInputTokens", got.VideoInputTokens, &videoIn, 18) + assertInt64Ptr("FileInputTokens", got.FileInputTokens, &fileIn, 12) + assertInt64Ptr("CachedTextTokens", got.CachedTextTokens, &cachedText, 25) + assertInt64Ptr("CachedImageTokens", got.CachedImageTokens, &cachedImage, 15) + assertInt64Ptr("CachedAudioTokens", got.CachedAudioTokens, &cachedAudio, 0) + assertInt64Ptr("TextOutputTokens", got.TextOutputTokens, &textOut, 0) + assertInt64Ptr("ImageOutputTokens", got.ImageOutputTokens, &imageOut, 1056) + assertInt64Ptr("AudioOutputTokens", got.AudioOutputTokens, &audioOut, 42) + + // Verify absent counters remain nil and distinct from explicit zero. + adapter.HandleUsage(context.Background(), coreusage.Record{ + Provider: "openai", + Model: "gpt-image-2.5-flare", + Detail: coreusage.Detail{ + InputTokens: 80, + TextInputTokens: coreusage.Int64Ptr(30), + ImageInputTokens: coreusage.Int64Ptr(50), + TextOutputTokens: coreusage.Int64Ptr(0), + }, + }) + got = gotRecord.Detail + if got.TextInputTokens == nil || *got.TextInputTokens != 30 { + t.Fatalf("TextInputTokens = %v, want 30", got.TextInputTokens) + } + if got.ImageInputTokens == nil || *got.ImageInputTokens != 50 { + t.Fatalf("ImageInputTokens = %v, want 50", got.ImageInputTokens) + } + if got.TextOutputTokens == nil || *got.TextOutputTokens != 0 { + t.Fatalf("TextOutputTokens = %v, want explicit 0", got.TextOutputTokens) + } + if got.AudioInputTokens != nil || got.VideoInputTokens != nil || got.FileInputTokens != nil || + got.CachedTextTokens != nil || got.CachedImageTokens != nil || got.CachedAudioTokens != nil || + got.ImageOutputTokens != nil || got.AudioOutputTokens != nil { + t.Fatalf("expected absent modality counters to remain nil, got %+v", got) + } +} + func TestUsageAdapterPreservesExplicitGenerateFalse(t *testing.T) { var gotGenerate bool plugin := usagePluginFunc(func(ctx context.Context, record pluginapi.UsageRecord) { diff --git a/internal/pluginhost/adapters_usage_translation.go b/internal/pluginhost/adapters_usage_translation.go index 2dcab50abb0..e064fd82cbb 100644 --- a/internal/pluginhost/adapters_usage_translation.go +++ b/internal/pluginhost/adapters_usage_translation.go @@ -640,6 +640,17 @@ func (a *usageAdapter) HandleUsage(ctx context.Context, record coreusage.Record) CacheReadTokens: record.Detail.CacheReadTokens, CacheCreationTokens: record.Detail.CacheCreationTokens, TotalTokens: record.Detail.TotalTokens, + TextInputTokens: coreusage.CloneInt64Ptr(record.Detail.TextInputTokens), + ImageInputTokens: coreusage.CloneInt64Ptr(record.Detail.ImageInputTokens), + AudioInputTokens: coreusage.CloneInt64Ptr(record.Detail.AudioInputTokens), + VideoInputTokens: coreusage.CloneInt64Ptr(record.Detail.VideoInputTokens), + FileInputTokens: coreusage.CloneInt64Ptr(record.Detail.FileInputTokens), + CachedTextTokens: coreusage.CloneInt64Ptr(record.Detail.CachedTextTokens), + CachedImageTokens: coreusage.CloneInt64Ptr(record.Detail.CachedImageTokens), + CachedAudioTokens: coreusage.CloneInt64Ptr(record.Detail.CachedAudioTokens), + TextOutputTokens: coreusage.CloneInt64Ptr(record.Detail.TextOutputTokens), + ImageOutputTokens: coreusage.CloneInt64Ptr(record.Detail.ImageOutputTokens), + AudioOutputTokens: coreusage.CloneInt64Ptr(record.Detail.AudioOutputTokens), }, ResponseHeaders: cloneHeader(record.ResponseHeaders), }) diff --git a/internal/pluginhost/host.go b/internal/pluginhost/host.go index f95b69b5e60..87b332f396f 100644 --- a/internal/pluginhost/host.go +++ b/internal/pluginhost/host.go @@ -62,42 +62,43 @@ type pluginLoadResult struct { } type Host struct { - applyMu chan struct{} - mu sync.Mutex - loader pluginLoader - loaded map[string]*loadedPlugin - retired map[string][]*loadedPlugin - loading map[string]*pluginLoadRequest - fused map[string]string - pluginFileVersions map[string]string - activePluginVersions map[string]string - activePluginPaths map[string]string - cleanupFilesPending bool - runtimeConfig *config.Config - authManager *coreauth.Manager - modelExecutor modelExecutor - modelClientIDs map[string]struct{} // Reserved for future use; catalog-only plugins do not populate it. - executorModelClientIDs map[string]struct{} - modelProviders map[string]string - modelProviderSets map[string][]string - authCredentialProviders map[string]map[string]string - modelRegistrations map[string]pluginModelRegistration - pluginModelRegistrations map[string][]pluginModelRegistration - providerModels map[string][]*registryModelInfo - executorProviders map[string]struct{} - accessProviderKeys map[string]struct{} - commandLineFlags map[string]commandLineFlagRecord - commandLineHits map[string]struct{} - managementRoutes map[string]managementRouteRecord - resourceRoutes map[string]resourceRouteRecord - streams *streamBridge - httpStreams *hostHTTPStreamBridge - httpOperations *hostHTTPOperationBridge - modelStreams *modelStreamBridge - callbackContexts *callbackContextRegistry - usageStates map[string]*pluginUsageState - maxPendingUsageRecords int - snapshot atomic.Value + applyMu chan struct{} + mu sync.Mutex + loader pluginLoader + loaded map[string]*loadedPlugin + retired map[string][]*loadedPlugin + loading map[string]*pluginLoadRequest + fused map[string]string + pluginFileVersions map[string]string + activePluginVersions map[string]string + activePluginPaths map[string]string + cleanupFilesPending bool + runtimeConfig *config.Config + authManager *coreauth.Manager + modelExecutor modelExecutor + modelClientIDs map[string]struct{} // Reserved for future use; catalog-only plugins do not populate it. + executorModelClientIDs map[string]struct{} + modelProviders map[string]string + modelProviderSets map[string][]string + authCredentialProviders map[string]map[string]string + modelRegistrations map[string]pluginModelRegistration + pluginModelRegistrations map[string][]pluginModelRegistration + providerModels map[string][]*registryModelInfo + staticAppendProviderModels map[string][]*registryModelInfo + executorProviders map[string]struct{} + accessProviderKeys map[string]struct{} + commandLineFlags map[string]commandLineFlagRecord + commandLineHits map[string]struct{} + managementRoutes map[string]managementRouteRecord + resourceRoutes map[string]resourceRouteRecord + streams *streamBridge + httpStreams *hostHTTPStreamBridge + httpOperations *hostHTTPOperationBridge + modelStreams *modelStreamBridge + callbackContexts *callbackContextRegistry + usageStates map[string]*pluginUsageState + maxPendingUsageRecords int + snapshot atomic.Value // loadCleanupDoneHook, set by tests, runs after a late load cleanup dropped its load token. loadCleanupDoneHook func() // usageDrainWaitHook, set by tests, runs when beginUsageReplacement waits for admitted usage calls to drain. @@ -108,36 +109,37 @@ type Host struct { func New() *Host { h := &Host{ - applyMu: make(chan struct{}, 1), - loader: defaultPluginLoader(), - loaded: make(map[string]*loadedPlugin), - retired: make(map[string][]*loadedPlugin), - loading: make(map[string]*pluginLoadRequest), - fused: make(map[string]string), - pluginFileVersions: make(map[string]string), - activePluginVersions: make(map[string]string), - activePluginPaths: make(map[string]string), - cleanupFilesPending: true, - modelClientIDs: make(map[string]struct{}), - executorModelClientIDs: make(map[string]struct{}), - modelProviders: make(map[string]string), - modelProviderSets: make(map[string][]string), - authCredentialProviders: make(map[string]map[string]string), - modelRegistrations: make(map[string]pluginModelRegistration), - pluginModelRegistrations: make(map[string][]pluginModelRegistration), - providerModels: make(map[string][]*registryModelInfo), - executorProviders: make(map[string]struct{}), - accessProviderKeys: make(map[string]struct{}), - commandLineFlags: make(map[string]commandLineFlagRecord), - commandLineHits: make(map[string]struct{}), - managementRoutes: make(map[string]managementRouteRecord), - resourceRoutes: make(map[string]resourceRouteRecord), - streams: newStreamBridge(), - httpStreams: newHostHTTPStreamBridge(), - httpOperations: newHostHTTPOperationBridge(), - modelStreams: newModelStreamBridge(), - callbackContexts: newCallbackContextRegistry(), - usageStates: make(map[string]*pluginUsageState), + applyMu: make(chan struct{}, 1), + loader: defaultPluginLoader(), + loaded: make(map[string]*loadedPlugin), + retired: make(map[string][]*loadedPlugin), + loading: make(map[string]*pluginLoadRequest), + fused: make(map[string]string), + pluginFileVersions: make(map[string]string), + activePluginVersions: make(map[string]string), + activePluginPaths: make(map[string]string), + cleanupFilesPending: true, + modelClientIDs: make(map[string]struct{}), + executorModelClientIDs: make(map[string]struct{}), + modelProviders: make(map[string]string), + modelProviderSets: make(map[string][]string), + authCredentialProviders: make(map[string]map[string]string), + modelRegistrations: make(map[string]pluginModelRegistration), + pluginModelRegistrations: make(map[string][]pluginModelRegistration), + providerModels: make(map[string][]*registryModelInfo), + staticAppendProviderModels: make(map[string][]*registryModelInfo), + executorProviders: make(map[string]struct{}), + accessProviderKeys: make(map[string]struct{}), + commandLineFlags: make(map[string]commandLineFlagRecord), + commandLineHits: make(map[string]struct{}), + managementRoutes: make(map[string]managementRouteRecord), + resourceRoutes: make(map[string]resourceRouteRecord), + streams: newStreamBridge(), + httpStreams: newHostHTTPStreamBridge(), + httpOperations: newHostHTTPOperationBridge(), + modelStreams: newModelStreamBridge(), + callbackContexts: newCallbackContextRegistry(), + usageStates: make(map[string]*pluginUsageState), } h.snapshot.Store(emptySnapshot()) return h @@ -901,6 +903,7 @@ func (h *Host) ShutdownAllContext(ctx context.Context) { h.modelRegistrations = make(map[string]pluginModelRegistration) h.pluginModelRegistrations = make(map[string][]pluginModelRegistration) h.providerModels = make(map[string][]*registryModelInfo) + h.staticAppendProviderModels = make(map[string][]*registryModelInfo) h.executorProviders = make(map[string]struct{}) h.commandLineFlags = make(map[string]commandLineFlagRecord) h.commandLineHits = make(map[string]struct{}) @@ -1081,14 +1084,24 @@ func (h *Host) removePluginRuntimeStateLocked(id string) { delete(h.pluginModelRegistrations, id) for provider := range affectedProviders { delete(h.providerModels, provider) + delete(h.staticAppendProviderModels, provider) } if len(affectedProviders) > 0 { for _, registration := range h.snapshotModelRegistrationsLocked() { - if registration.hasExecutor { + if registration.hasExecutor && registration.allowsStaticClient { continue } if _, ok := affectedProviders[registration.provider]; ok { + if h.providerModels == nil { + h.providerModels = make(map[string][]*registryModelInfo) + } appendModelsForProvider(h.providerModels, registration.provider, registration.models) + if !registration.hasExecutor || !registration.hasModelProvider { + if h.staticAppendProviderModels == nil { + h.staticAppendProviderModels = make(map[string][]*registryModelInfo) + } + appendModelsForProvider(h.staticAppendProviderModels, registration.provider, registration.models) + } } } } diff --git a/internal/pluginhost/quota_provider.go b/internal/pluginhost/quota_provider.go index 93f214f41dd..4e3a0e4a51a 100644 --- a/internal/pluginhost/quota_provider.go +++ b/internal/pluginhost/quota_provider.go @@ -11,6 +11,11 @@ import ( // RegisterPluginForTest registers a plugin directly on the host for testing. func (h *Host) RegisterPluginForTest(id string, plugin pluginapi.Plugin) { + h.RegisterPluginWithPriorityForTest(id, 1, plugin) +} + +// RegisterPluginWithPriorityForTest registers a plugin with an explicit runtime priority on the host for testing. +func (h *Host) RegisterPluginWithPriorityForTest(id string, priority int, plugin pluginapi.Plugin) { if h == nil { return } @@ -20,7 +25,7 @@ func (h *Host) RegisterPluginForTest(id string, plugin pluginapi.Plugin) { version: "1.0.0", meta: plugin.Metadata, plugin: plugin, - priority: 1, + priority: priority, } records := append(h.activeRecords(), record) h.mu.Lock() diff --git a/internal/pluginhost/rpc_client.go b/internal/pluginhost/rpc_client.go index 332674bfdf5..ed96ba2e300 100644 --- a/internal/pluginhost/rpc_client.go +++ b/internal/pluginhost/rpc_client.go @@ -53,6 +53,7 @@ type rpcError struct { message string statusCode int retryAfterSeconds int + credentialScoped bool } func (e rpcError) Error() string { @@ -67,6 +68,22 @@ func (e rpcError) StatusCode() int { return e.statusCode } +func (e rpcError) IsCredentialScoped() bool { + return e.credentialScoped || strings.EqualFold(strings.TrimSpace(e.Code), pluginabi.ErrorCodeCredentialQuota) +} + +func (e rpcError) IsRequestScoped() bool { + return !e.IsCredentialScoped() && strings.EqualFold(strings.TrimSpace(e.Code), pluginabi.ErrorCodeRequestScoped) +} + +func (e rpcError) IsTransientRateLimit() bool { + return !e.IsCredentialScoped() && strings.EqualFold(strings.TrimSpace(e.Code), pluginabi.ErrorCodeTransientRateLimit) +} + +func (e rpcError) IsStreamTruncated() bool { + return !e.IsCredentialScoped() && strings.EqualFold(strings.TrimSpace(e.Code), pluginabi.ErrorCodeStreamTruncated) +} + func (e rpcError) RetryAfter() *time.Duration { if e.retryAfterSeconds <= 0 { return nil @@ -440,6 +457,7 @@ func decodeEnvelopeResult[T any](envelope pluginabi.Envelope) (T, error) { message: message, statusCode: envelope.Error.HTTPStatus, retryAfterSeconds: envelope.Error.RetryAfterSeconds, + credentialScoped: envelope.Error.CredentialScoped, } } return zero, fmt.Errorf("plugin call failed") diff --git a/internal/pluginhost/rpc_client_error_test.go b/internal/pluginhost/rpc_client_error_test.go index 8baefe6f9ff..8bf430e0653 100644 --- a/internal/pluginhost/rpc_client_error_test.go +++ b/internal/pluginhost/rpc_client_error_test.go @@ -9,6 +9,8 @@ import ( "testing" "time" + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/redisqueue" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" @@ -89,16 +91,19 @@ func TestPluginErrorCarriesRetryAfterIntoCooldownAndHTTPHeader(t *testing.T) { if errExec == nil { t.Fatal("authMgr.Execute returned nil error") } - if got := coreauth.SafeResponseHeaders(errExec).Get("Retry-After"); got != "7" { - t.Fatalf("SafeResponseHeaders(errExec) Retry-After = %q, want 7", got) + // The raw plugin hint remains 7s, but the exhausted single-credential pool + // applies the 10s quota cooldown floor. Report the actual recovery deadline + // to the caller rather than the shorter upstream hint (upstream issue #7521). + if got := coreauth.SafeResponseHeaders(errExec).Get("Retry-After"); got != "10" { + t.Fatalf("SafeResponseHeaders(errExec) Retry-After = %q, want 10 (pool cooldown floor)", got) } updated, okAuth := authMgr.GetByID(authID) if !okAuth || updated == nil { t.Fatalf("GetByID(%q) missing", authID) } state := updated.ModelStates[model] - if state == nil || !state.NextRetryAfter.After(before.Add(5*time.Second)) { - t.Fatalf("model NextRetryAfter = %v, want at least %v (7s cooldown)", state, before.Add(7*time.Second)) + if state == nil || state.NextRetryAfter.Before(before.Add(10*time.Second)) { + t.Fatalf("model NextRetryAfter = %v, want at least %v (10s cooldown floor)", state, before.Add(10*time.Second)) } } @@ -492,3 +497,335 @@ func TestPluginCountTokensNotImplementedDoesNotTriggerCooldown(t *testing.T) { t.Fatal("Execute returned empty payload") } } + +type resultCapturingHook struct { + results []coreauth.Result +} + +func (h *resultCapturingHook) OnAuthRegistered(context.Context, *coreauth.Auth) {} +func (h *resultCapturingHook) OnAuthUpdated(context.Context, *coreauth.Auth) {} +func (h *resultCapturingHook) OnResult(_ context.Context, result coreauth.Result) { + h.results = append(h.results, result) +} + +func TestPluginExecutor429CredentialScopedCoolsEntireCredentialAndSiblingModels(t *testing.T) { + coreauth.SetQuotaCooldownDisabled(false) + + prevQueueEnabled := redisqueue.Enabled() + redisqueue.SetEnabled(false) + redisqueue.SetEnabled(true) + t.Cleanup(func() { + redisqueue.SetEnabled(false) + redisqueue.SetEnabled(prevQueueEnabled) + }) + + for _, tc := range []struct { + name string + envelopeJSON string + wantCode string + }{ + { + name: "credential_scoped flag", + envelopeJSON: `{"ok":false,"error":{"code":"rate_limited","message":"account limited, resets at 2026-01-01T00:00:00Z","http_status":429,"retry_after_seconds":120,"credential_scoped":true}}`, + wantCode: "rate_limited", + }, + { + name: "credential_quota error code", + envelopeJSON: `{"ok":false,"error":{"code":"credential_quota","message":"account limited, resets at 2026-01-01T00:00:00Z","http_status":429,"retry_after_seconds":120}}`, + wantCode: "credential_quota", + }, + { + name: "credential_scoped overrides transient_rate_limit code", + envelopeJSON: `{"ok":false,"error":{"code":"transient_rate_limit","message":"account limited, resets at 2026-01-01T00:00:00Z","http_status":429,"retry_after_seconds":120,"credential_scoped":true}}`, + wantCode: "credential_quota", + }, + { + name: "credential_scoped overrides request_scoped code", + envelopeJSON: `{"ok":false,"error":{"code":"request_scoped","message":"account limited, resets at 2026-01-01T00:00:00Z","http_status":429,"retry_after_seconds":120,"credential_scoped":true}}`, + wantCode: "credential_quota", + }, + } { + t.Run(tc.name, func(t *testing.T) { + subscriber, unsubscribe := redisqueue.SubscribeErrors() + defer unsubscribe() + + _, errDecode := decodeRPCEnvelope[pluginapi.ExecutorResponse]([]byte(tc.envelopeJSON)) + if errDecode == nil { + t.Fatal("decodeRPCEnvelope returned nil error") + } + var scoped interface{ IsCredentialScoped() bool } + if !errors.As(errDecode, &scoped) || !scoped.IsCredentialScoped() { + t.Fatalf("decoded plugin error %T does not report IsCredentialScoped() = true", errDecode) + } + + var ( + provider = "plugin-provider-cred-scope-" + tc.name + modelA = "plugin-model-a-" + tc.name + modelB = "plugin-model-b-" + tc.name + modelC = "plugin-model-c-" + tc.name + authID = "auth-cred-scope-" + tc.name + execCalled int + ) + executorRecord := normalizeTestCapabilityRecord(capabilityRecord{id: "executor-cred-scope-" + tc.name}) + host := newHostWithRecords(executorRecord) + exec := &fakeExecutor{ + identifier: provider, + execute: func(context.Context, pluginapi.ExecutorRequest) (pluginapi.ExecutorResponse, error) { + execCalled++ + return pluginapi.ExecutorResponse{}, errDecode + }, + } + adapter := newExecutorAdapterForRecordForTest(host, executorRecord, exec, + []sdktranslator.Format{sdktranslator.FormatOpenAI}, + []sdktranslator.Format{sdktranslator.FormatOpenAI}, + ) + adapter.provider = provider + + hook := &resultCapturingHook{} + authMgr := coreauth.NewManager(nil, nil, hook) + authMgr.SetRetryConfig(0, 0, 0) + authMgr.RegisterExecutor(adapter) + auth := &coreauth.Auth{ + ID: authID, + Provider: provider, + Status: coreauth.StatusActive, + FileName: authID + ".json", + Attributes: map[string]string{"type": "oauth"}, + ModelStates: map[string]*coreauth.ModelState{ + modelB: {Status: coreauth.StatusActive}, + }, + } + if _, errReg := authMgr.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{ + {ID: modelA}, + {ID: modelB}, + {ID: modelC}, + }) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(auth.ID) + }) + + opts := coreexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + } + + before := time.Now() + _, errExecA := authMgr.Execute(context.Background(), []string{provider}, coreexecutor.Request{ + Model: modelA, + Payload: []byte(`{"model":"` + modelA + `"}`), + }, opts) + if errExecA == nil { + t.Fatal("Execute(modelA) returned nil error, want 429") + } + if execCalled != 1 { + t.Fatalf("execCalled after modelA = %d, want 1", execCalled) + } + if len(hook.results) != 1 || !hook.results[0].CredentialScope { + t.Fatalf("recorded result = %+v, want CredentialScope=true", hook.results) + } + + var eventPayload []byte + select { + case eventPayload = <-subscriber: + case <-time.After(time.Second): + t.Fatal("timeout waiting for published error event") + } + statusCode := int(ojson.GetBytes(eventPayload, "status_code").Int()) + eventCode := ojson.GetBytes(eventPayload, "code").String() + if statusCode != http.StatusTooManyRequests || eventCode != tc.wantCode { + t.Fatalf("error event status=%d code=%q, want 429 %q", statusCode, eventCode, tc.wantCode) + } + unavailable := ojson.GetBytes(eventPayload, "auth_status.unavailable").Bool() + quotaExceeded := ojson.GetBytes(eventPayload, "auth_status.quota.exceeded").Bool() + quotaReason := ojson.GetBytes(eventPayload, "auth_status.quota.reason").String() + if !unavailable || !quotaExceeded || quotaReason != "credential_quota" { + t.Fatalf("error event auth_status = %s, want unavailable with quota.reason=credential_quota", string(eventPayload)) + } + + updated, okAuth := authMgr.GetByID(authID) + if !okAuth || updated == nil { + t.Fatalf("GetByID(%q) missing", authID) + } + if !updated.Unavailable || !updated.Quota.Exceeded || updated.Quota.Reason != "credential_quota" { + t.Fatalf("updated auth quota = %+v (unavailable=%v), want unavailable with reason=credential_quota", updated.Quota, updated.Unavailable) + } + if !updated.Quota.NextRecoverAt.After(before.Add(110 * time.Second)) { + t.Fatalf("updated auth NextRecoverAt = %v, want > %v", updated.Quota.NextRecoverAt, before.Add(110*time.Second)) + } + stateB := updated.ModelStates[modelB] + if stateB == nil || !stateB.Unavailable || !stateB.Quota.Exceeded || stateB.Quota.Reason != "credential_quota" { + t.Fatalf("sibling modelB state = %+v, want unavailable with reason=credential_quota", stateB) + } + + // Sending requests for sibling modelB (pre-existing ModelState) and modelC (unvisited model) + // must NOT select the cooled credential again. + for _, siblingModel := range []string{modelB, modelC} { + _, errSibling := authMgr.Execute(context.Background(), []string{provider}, coreexecutor.Request{ + Model: siblingModel, + Payload: []byte(`{"model":"` + siblingModel + `"}`), + }, opts) + if errSibling == nil { + t.Fatalf("Execute(%s) returned nil error, want cooldown rejection", siblingModel) + } + if execCalled != 1 { + t.Fatalf("execCalled after %s = %d, want 1 (credential must not be selected again for sibling model)", siblingModel, execCalled) + } + } + }) + } +} + +func TestStreamCallbacksPreserveCredentialScopedPluginErrors(t *testing.T) { + detail := `{"code":"rate_limited","message":"account limited","http_status":429,"retry_after_seconds":60,"credential_scoped":true}` + for _, tc := range []struct { + name string + send func(host *Host, streamID string) error + }{ + {"emit", func(host *Host, streamID string) error { + _, err := host.callHostStreamEmit(context.Background(), []byte(`{"stream_id":"`+streamID+`","error_detail":`+detail+`}`)) + return err + }}, + {"close", func(host *Host, streamID string) error { + _, err := host.callHostStreamClose([]byte(`{"stream_id":"` + streamID + `","error_detail":` + detail + `}`)) + return err + }}, + } { + t.Run(tc.name, func(t *testing.T) { + host := New() + streamID, chunks, cleanup := host.streams.open(context.Background()) + t.Cleanup(cleanup) + if err := tc.send(host, streamID); err != nil { + t.Fatalf("stream %s callback error = %v", tc.name, err) + } + chunk := <-chunks + if chunk.Err == nil { + t.Fatal("stream error was dropped") + } + var scoped interface{ IsCredentialScoped() bool } + if !errors.As(chunk.Err, &scoped) || !scoped.IsCredentialScoped() { + t.Fatalf("stream error %T does not report IsCredentialScoped() = true", chunk.Err) + } + }) + } +} + +func TestPluginExecutorStream429CredentialScopedCoolsEntireCredential(t *testing.T) { + coreauth.SetQuotaCooldownDisabled(false) + + for _, tc := range []struct { + name string + detail string + }{ + { + name: "rate_limited with credential_scoped", + detail: `{"code":"rate_limited","message":"account limited","http_status":429,"retry_after_seconds":90,"credential_scoped":true}`, + }, + { + name: "transient_rate_limit overridden by credential_scoped", + detail: `{"code":"transient_rate_limit","message":"account limited","http_status":429,"retry_after_seconds":90,"credential_scoped":true}`, + }, + { + name: "request_scoped overridden by credential_scoped", + detail: `{"code":"request_scoped","message":"account limited","http_status":429,"retry_after_seconds":90,"credential_scoped":true}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + var ( + provider = "plugin-provider-stream-cred-scope-" + tc.name + modelA = "plugin-stream-model-a-" + tc.name + modelB = "plugin-stream-model-b-" + tc.name + authID = "auth-stream-cred-scope-" + tc.name + ) + executorRecord := normalizeTestCapabilityRecord(capabilityRecord{id: "executor-stream-cred-scope-" + tc.name}) + host := newHostWithRecords(executorRecord) + + var streamCalls int + exec := &fakeExecutor{ + identifier: provider, + executeStream: func(ctx context.Context, _ pluginapi.ExecutorRequest) (pluginapi.ExecutorStreamResponse, error) { + streamCalls++ + streamID, chunks, cleanup := host.streams.open(ctx) + if _, errClose := host.callHostStreamClose([]byte(`{"stream_id":"` + streamID + `","error_detail":` + tc.detail + `}`)); errClose != nil { + cleanup() + return pluginapi.ExecutorStreamResponse{}, errClose + } + return pluginapi.ExecutorStreamResponse{ + Chunks: cleanupWhenStreamDone(ctx, chunks, cleanup), + }, nil + }, + } + adapter := newExecutorAdapterForRecordForTest(host, executorRecord, exec, + []sdktranslator.Format{sdktranslator.FormatOpenAI}, + []sdktranslator.Format{sdktranslator.FormatOpenAI}, + ) + adapter.provider = provider + + authMgr := coreauth.NewManager(nil, nil, nil) + authMgr.SetRetryConfig(0, 0, 0) + authMgr.RegisterExecutor(adapter) + auth := &coreauth.Auth{ + ID: authID, + Provider: provider, + Status: coreauth.StatusActive, + FileName: authID + ".json", + Attributes: map[string]string{"type": "oauth"}, + } + if _, errReg := authMgr.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{ + {ID: modelA}, + {ID: modelB}, + }) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(auth.ID) + }) + + opts := coreexecutor.Options{ + Stream: true, + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + } + + resStreamA, errStreamA := authMgr.ExecuteStream(context.Background(), []string{provider}, coreexecutor.Request{ + Model: modelA, + Payload: []byte(`{"model":"` + modelA + `","stream":true}`), + }, opts) + if errStreamA == nil { + if resStreamA == nil || resStreamA.Chunks == nil { + t.Fatal("ExecuteStream(modelA) returned nil error and nil chunks") + } + chunk := <-resStreamA.Chunks + errStreamA = chunk.Err + } + if errStreamA == nil { + t.Fatal("ExecuteStream(modelA) returned nil stream error, want 429") + } + if streamCalls != 1 { + t.Fatalf("streamCalls after modelA = %d, want 1", streamCalls) + } + + updated, okAuth := authMgr.GetByID(authID) + if !okAuth || updated == nil { + t.Fatalf("GetByID(%q) missing", authID) + } + if !updated.Unavailable || !updated.Quota.Exceeded || updated.Quota.Reason != "credential_quota" { + t.Fatalf("updated auth quota = %+v (unavailable=%v), want unavailable with reason=credential_quota", updated.Quota, updated.Unavailable) + } + + _, errStreamB := authMgr.ExecuteStream(context.Background(), []string{provider}, coreexecutor.Request{ + Model: modelB, + Payload: []byte(`{"model":"` + modelB + `","stream":true}`), + }, opts) + if errStreamB == nil { + t.Fatal("ExecuteStream(modelB) returned nil error, want cooldown rejection") + } + if streamCalls != 1 { + t.Fatalf("streamCalls after modelB = %d, want 1 (credential must not be selected again for sibling model)", streamCalls) + } + }) + } +} diff --git a/internal/pluginhost/rpc_schema_test.go b/internal/pluginhost/rpc_schema_test.go index bf5a1e83b8e..7d5b7e4b47b 100644 --- a/internal/pluginhost/rpc_schema_test.go +++ b/internal/pluginhost/rpc_schema_test.go @@ -11,6 +11,7 @@ import ( "testing" sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginabi" "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" ) @@ -906,6 +907,105 @@ func TestRPCSchedulerAndUsageSelectionIDCompatibility(t *testing.T) { } } +func TestUsageRecordRPCModalityTokenCounters(t *testing.T) { + var deliveredRaw []byte + var deliveredRecord pluginapi.UsageRecord + rpcAdapter := &rpcPluginAdapter{ + id: "rpc-usage-modality", + client: &lifecycleTestClient{call: func(_ context.Context, method string, request []byte) ([]byte, error) { + if method != pluginabi.MethodUsageHandle { + return nil, io.ErrUnexpectedEOF + } + deliveredRaw = bytes.Clone(request) + if errUnmarshal := json.Unmarshal(request, &deliveredRecord); errUnmarshal != nil { + return nil, errUnmarshal + } + return marshalRPCResult(rpcEmptyResponse{}) + }}, + } + + host := newHostWithRecords(capabilityRecord{ + id: "rpc-usage-modality", + plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{ + UsagePlugin: rpcAdapter, + }}, + }) + rpcAdapter.host = host + adapter := &usageAdapter{ + host: host, + pluginID: "rpc-usage-modality", + plugin: rpcAdapter, + } + + adapter.HandleUsage(context.Background(), coreusage.Record{ + Provider: "openai", + Model: "gpt-image-2.5-flare", + Detail: coreusage.Detail{ + InputTokens: 80, + OutputTokens: 1056, + CachedTokens: 40, + CacheReadTokens: 40, + TotalTokens: 1136, + TextInputTokens: coreusage.Int64Ptr(30), + ImageInputTokens: coreusage.Int64Ptr(50), + CachedTextTokens: coreusage.Int64Ptr(25), + CachedImageTokens: coreusage.Int64Ptr(15), + TextOutputTokens: coreusage.Int64Ptr(0), + ImageOutputTokens: coreusage.Int64Ptr(1056), + }, + }) + + got := deliveredRecord.Detail + if got.InputTokens != 80 || got.OutputTokens != 1056 || got.CachedTokens != 40 || got.CacheReadTokens != 40 || got.TotalTokens != 1136 { + t.Fatalf("delivered aggregate Detail = %+v", got) + } + if got.TextInputTokens == nil || *got.TextInputTokens != 30 { + t.Fatalf("delivered TextInputTokens = %v, want 30", got.TextInputTokens) + } + if got.ImageInputTokens == nil || *got.ImageInputTokens != 50 { + t.Fatalf("delivered ImageInputTokens = %v, want 50", got.ImageInputTokens) + } + if got.CachedTextTokens == nil || *got.CachedTextTokens != 25 { + t.Fatalf("delivered CachedTextTokens = %v, want 25", got.CachedTextTokens) + } + if got.CachedImageTokens == nil || *got.CachedImageTokens != 15 { + t.Fatalf("delivered CachedImageTokens = %v, want 15", got.CachedImageTokens) + } + if got.TextOutputTokens == nil || *got.TextOutputTokens != 0 { + t.Fatalf("delivered TextOutputTokens = %v, want explicit 0", got.TextOutputTokens) + } + if got.ImageOutputTokens == nil || *got.ImageOutputTokens != 1056 { + t.Fatalf("delivered ImageOutputTokens = %v, want 1056", got.ImageOutputTokens) + } + if got.AudioInputTokens != nil || got.VideoInputTokens != nil || got.FileInputTokens != nil || + got.CachedAudioTokens != nil || got.AudioOutputTokens != nil { + t.Fatalf("expected absent modality counters to remain nil over RPC, got %+v", got) + } + + // Legacy plugins compiled against the 7-field UsageDetail must still unmarshal cleanly. + type legacyUsageDetail struct { + InputTokens int64 + OutputTokens int64 + ReasoningTokens int64 + CachedTokens int64 + CacheReadTokens int64 + CacheCreationTokens int64 + TotalTokens int64 + } + type legacyUsageRecordWithDetail struct { + Provider string + Model string + Detail legacyUsageDetail + } + var legacyRec legacyUsageRecordWithDetail + if errLegacy := json.Unmarshal(deliveredRaw, &legacyRec); errLegacy != nil { + t.Fatalf("Unmarshal(legacyUsageRecordWithDetail) error = %v", errLegacy) + } + if legacyRec.Detail.InputTokens != 80 || legacyRec.Detail.OutputTokens != 1056 || legacyRec.Detail.TotalTokens != 1136 { + t.Fatalf("legacyUsageRecordWithDetail.Detail = %+v", legacyRec.Detail) + } +} + type recordingRawPatchClient struct { schemaVersion uint32 methods []string diff --git a/internal/pluginhost/stream_bridge.go b/internal/pluginhost/stream_bridge.go index 6cd5b1639b1..943cc628633 100644 --- a/internal/pluginhost/stream_bridge.go +++ b/internal/pluginhost/stream_bridge.go @@ -79,6 +79,7 @@ func rpcStreamError(message string, detail *pluginabi.Error) error { message: text, statusCode: detail.HTTPStatus, retryAfterSeconds: detail.RetryAfterSeconds, + credentialScoped: detail.CredentialScoped, } } if message != "" { diff --git a/internal/redisqueue/home_usage_test.go b/internal/redisqueue/home_usage_test.go new file mode 100644 index 00000000000..5821fee3cd9 --- /dev/null +++ b/internal/redisqueue/home_usage_test.go @@ -0,0 +1,41 @@ +package redisqueue + +import ( + "testing" + + "github.com/MoeForge/moego/ojson" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" +) + +func TestUsageQueueCarriesHomeSelection(t *testing.T) { + withEnabledQueue(t, func() { + for _, selection := range []*coreusage.HomeSelection{ + nil, + {Model: "route-model"}, + {Additional: true, Model: "route-model"}, + {Reused: true, Additional: true, Model: "route-model"}, + {Reused: true, Model: "route-model", CredentialPolicy: "codex-alpha-search-v1"}, + } { + (&usageQueuePlugin{}).HandleUsage(t.Context(), coreusage.Record{ + RequestID: "response-unique-id", Provider: "codex", Model: "upstream-model", HomeSelection: selection, + }) + items := PopOldest(1) + if len(items) != 1 { + t.Fatalf("queued=%d", len(items)) + } + got := ojson.GetBytes(items[0], "home_selection") + if selection == nil { + if got.Exists() { + t.Fatal("legacy usage acquired a Home marker") + } + continue + } + if got.Get("reused").Bool() != selection.Reused || got.Get("additional").Bool() != selection.Additional || got.Get("model").String() != selection.Model || got.Get("credential_policy").String() != selection.CredentialPolicy { + t.Fatalf("lost selection metadata: %s", got.Raw) + } + if ojson.GetBytes(items[0], "execution_id").String() != "response-unique-id" { + t.Fatal("usage lost the per-response replay identity") + } + } + }) +} diff --git a/internal/redisqueue/plugin.go b/internal/redisqueue/plugin.go index a479a4778b2..acbdf4f8a85 100644 --- a/internal/redisqueue/plugin.go +++ b/internal/redisqueue/plugin.go @@ -177,6 +177,7 @@ func (p *usageQueuePlugin) HandleUsage(ctx context.Context, record coreusage.Rec AccessProvider: accessProvider, RequestID: requestID, ExecutionID: executionID, + HomeSelection: record.HomeSelection, TraceID: traceID, SessionID: sessionID, ParentSessionID: parentSessionID, @@ -222,6 +223,7 @@ type queuedUsageDetail struct { AccessProvider string `json:"access_provider,omitempty"` RequestID string `json:"request_id"` ExecutionID string `json:"execution_id,omitempty"` + HomeSelection *coreusage.HomeSelection `json:"home_selection,omitempty"` TraceID string `json:"trace_id,omitempty"` SessionID string `json:"session_id,omitempty"` ParentSessionID string `json:"parent_session_id,omitempty"` diff --git a/internal/registry/model_registry.go b/internal/registry/model_registry.go index 7f82e7dcf39..f02e53f828a 100644 --- a/internal/registry/model_registry.go +++ b/internal/registry/model_registry.go @@ -174,6 +174,9 @@ type ModelRegistration struct { Providers map[string]int // SuspendedClients tracks temporarily disabled clients keyed by client ID SuspendedClients map[string]string + // SuspendedClientDeadlines records optional expiry deadlines for suspended clients. + // Clients without an entry (or with a zero deadline) stay suspended until resumed. + SuspendedClientDeadlines map[string]time.Time } // ModelRegistryHook provides optional callbacks for external integrations to track model list changes. @@ -216,6 +219,8 @@ type ModelRegistry struct { registrationEpoch atomic.Uint64 // hook is an optional callback sink for model registration changes hook ModelRegistryHook + // nowFunc overrides time.Now when set (used by deterministic tests). + nowFunc func() time.Time } // Global model registry instance @@ -239,6 +244,13 @@ func GetGlobalRegistry() *ModelRegistry { }) return globalRegistry } +func (r *ModelRegistry) now() time.Time { + if r != nil && r.nowFunc != nil { + return r.nowFunc() + } + return time.Now() +} + func (r *ModelRegistry) ensureAvailableModelsCacheLocked() { if r.availableModelsCache == nil { r.availableModelsCache = make(map[string]availableModelsCacheEntry) @@ -553,7 +565,7 @@ func (r *ModelRegistry) registerClientLocked(clientID, clientProvider string, mo } r.registrationEpoch.Add(1) - now := time.Now() + now := r.now() if !hadExisting { // Pure addition normally has no prior metadata. Clear orphaned metadata // and refresh its models before publishing the new catalog. @@ -693,6 +705,9 @@ func (r *ModelRegistry) registerClientLocked(clientID, clientProvider string, mo if !preserveState || providerChanged || oldCounts[id] == 0 { delete(reg.QuotaExceededClients, clientID) delete(reg.SuspendedClients, clientID) + if reg.SuspendedClientDeadlines != nil { + delete(reg.SuspendedClientDeadlines, clientID) + } } if providerChanged && provider != "" { if _, newlyAdded := addedSet[id]; newlyAdded { @@ -757,6 +772,9 @@ func (r *ModelRegistry) addModelRegistration(modelID, provider string, model *Mo if existing.SuspendedClients == nil { existing.SuspendedClients = make(map[string]string) } + if existing.SuspendedClientDeadlines == nil { + existing.SuspendedClientDeadlines = make(map[string]time.Time) + } if existing.InfoByProvider == nil { existing.InfoByProvider = make(map[string]*ModelInfo) } @@ -774,12 +792,13 @@ func (r *ModelRegistry) addModelRegistration(modelID, provider string, model *Mo } registration := &ModelRegistration{ - Info: cloneModelInfo(model), - InfoByProvider: make(map[string]*ModelInfo), - Count: 1, - LastUpdated: now, - QuotaExceededClients: make(map[string]*time.Time), - SuspendedClients: make(map[string]string), + Info: cloneModelInfo(model), + InfoByProvider: make(map[string]*ModelInfo), + Count: 1, + LastUpdated: now, + QuotaExceededClients: make(map[string]*time.Time), + SuspendedClients: make(map[string]string), + SuspendedClientDeadlines: make(map[string]time.Time), } if provider != "" { registration.Providers = map[string]int{provider: 1} @@ -800,6 +819,9 @@ func (r *ModelRegistry) removeModelRegistration(clientID, modelID, provider stri if !preserveState { delete(registration.QuotaExceededClients, clientID) delete(registration.SuspendedClients, clientID) + if registration.SuspendedClientDeadlines != nil { + delete(registration.SuspendedClientDeadlines, clientID) + } } if registration.Count < 0 { registration.Count = 0 @@ -926,7 +948,7 @@ func (r *ModelRegistry) unregisterClientInternal(clientID string) { return } - now := time.Now() + now := r.now() for _, modelID := range models { if registration, isExists := r.models[modelID]; isExists { registration.Count-- @@ -937,6 +959,9 @@ func (r *ModelRegistry) unregisterClientInternal(clientID string) { if registration.SuspendedClients != nil { delete(registration.SuspendedClients, clientID) } + if registration.SuspendedClientDeadlines != nil { + delete(registration.SuspendedClientDeadlines, clientID) + } if hasProvider && registration.Providers != nil { if count, ok := registration.Providers[provider]; ok { @@ -994,7 +1019,7 @@ func (r *ModelRegistry) SetModelQuotaExceeded(clientID, modelID string) { r.ensureAvailableModelsCacheLocked() if registration, exists := r.models[modelID]; exists { - now := time.Now() + now := r.now() registration.QuotaExceededClients[clientID] = &now r.invalidateAvailableModelsCacheLocked() log.Debugf("Marked model %s as quota exceeded for client %s", modelID, clientID) @@ -1022,6 +1047,9 @@ type ClientModelProjection struct { ModelID string Suspended bool SuspendReason string + // SuspendUntil optionally bounds the suspension in time. Once it passes, + // the client counts as available again without requiring re-projection. + SuspendUntil time.Time QuotaExceeded bool } @@ -1089,7 +1117,7 @@ func (r *ModelRegistry) ApplyClientModelProjections(clientID string, epoch uint6 r.clientGenerations[clientID] = generation r.ensureAvailableModelsCacheLocked() - now := time.Now() + now := r.now() changed := false for _, proj := range projections { modelID := strings.TrimSpace(proj.ModelID) @@ -1109,8 +1137,22 @@ func (r *ModelRegistry) ApplyClientModelProjections(clientID string, epoch uint6 if registration.SuspendedClients == nil { registration.SuspendedClients = make(map[string]string) } - if currentReason, ok := registration.SuspendedClients[clientID]; !ok || currentReason != proj.SuspendReason { + if registration.SuspendedClientDeadlines == nil { + registration.SuspendedClientDeadlines = make(map[string]time.Time) + } + deadlineChanged := false + if currentDeadline, ok := registration.SuspendedClientDeadlines[clientID]; ok { + deadlineChanged = !proj.SuspendUntil.Equal(currentDeadline) + } else { + deadlineChanged = !proj.SuspendUntil.IsZero() + } + if currentReason, ok := registration.SuspendedClients[clientID]; !ok || currentReason != proj.SuspendReason || deadlineChanged { registration.SuspendedClients[clientID] = proj.SuspendReason + if proj.SuspendUntil.IsZero() { + delete(registration.SuspendedClientDeadlines, clientID) + } else { + registration.SuspendedClientDeadlines[clientID] = proj.SuspendUntil + } registration.LastUpdated = now changed = true } @@ -1118,6 +1160,9 @@ func (r *ModelRegistry) ApplyClientModelProjections(clientID string, epoch uint6 if registration.SuspendedClients != nil { if _, ok := registration.SuspendedClients[clientID]; ok { delete(registration.SuspendedClients, clientID) + if registration.SuspendedClientDeadlines != nil { + delete(registration.SuspendedClientDeadlines, clientID) + } registration.LastUpdated = now changed = true } @@ -1348,11 +1393,20 @@ func (r *ModelRegistry) SuspendClientModel(clientID, modelID, reason string) { if registration.SuspendedClients == nil { registration.SuspendedClients = make(map[string]string) } - if _, already := registration.SuspendedClients[clientID]; already { + now := r.now() + _, _, active := clientSuspensionActive(registration, clientID, now) + hadDeadline := false + if registration.SuspendedClientDeadlines != nil { + _, hadDeadline = registration.SuspendedClientDeadlines[clientID] + } + if active && !hadDeadline { return } registration.SuspendedClients[clientID] = reason - registration.LastUpdated = time.Now() + if registration.SuspendedClientDeadlines != nil { + delete(registration.SuspendedClientDeadlines, clientID) + } + registration.LastUpdated = now r.invalidateAvailableModelsCacheLocked() if reason != "" { log.Debugf("Suspended client %s for model %s: %s", clientID, modelID, reason) @@ -1381,7 +1435,10 @@ func (r *ModelRegistry) ResumeClientModel(clientID, modelID string) { return } delete(registration.SuspendedClients, clientID) - registration.LastUpdated = time.Now() + if registration.SuspendedClientDeadlines != nil { + delete(registration.SuspendedClientDeadlines, clientID) + } + registration.LastUpdated = r.now() r.invalidateAvailableModelsCacheLocked() log.Debugf("Resumed client %s for model %s", clientID, modelID) } @@ -1419,15 +1476,16 @@ func (r *ModelRegistry) IsModelSuspendedForClient(clientID, modelID string) bool return false } + now := r.now() r.mutex.RLock() defer r.mutex.RUnlock() registration, exists := r.models[modelID] - if !exists || registration == nil || registration.SuspendedClients == nil { + if !exists || registration == nil { return false } - _, suspended := registration.SuspendedClients[clientID] - return suspended + _, _, active := clientSuspensionActive(registration, clientID, now) + return active } // IsModelQuotaExceededForClient reports whether a model is currently marked quota exceeded for a specific client. @@ -1456,7 +1514,7 @@ func (r *ModelRegistry) IsModelQuotaExceededForClient(clientID, modelID string) // Returns: // - []map[string]any: List of available models in the requested format func (r *ModelRegistry) GetAvailableModels(handlerType string) []map[string]any { - now := time.Now() + now := r.now() r.mutex.RLock() if cache, ok := r.availableModelsCache[handlerType]; ok && (cache.expiresAt.IsZero() || now.Before(cache.expiresAt)) { @@ -1493,6 +1551,34 @@ func isQuotaSuspension(reason string) bool { return strings.EqualFold(reason, "quota") || strings.EqualFold(reason, "credential_quota") } +func clientSuspensionActive(registration *ModelRegistration, clientID string, now time.Time) (string, time.Time, bool) { + if registration == nil || len(registration.SuspendedClients) == 0 { + return "", time.Time{}, false + } + reason, ok := registration.SuspendedClients[clientID] + if !ok { + return "", time.Time{}, false + } + if deadline, hasDeadline := registration.SuspendedClientDeadlines[clientID]; hasDeadline && !deadline.IsZero() { + if !now.Before(deadline) { + return "", time.Time{}, false + } + return reason, deadline, true + } + return reason, time.Time{}, true +} + +func clientQuotaRecoveryAt(registration *ModelRegistration, clientID string, quotaTime *time.Time) (time.Time, bool) { + if registration == nil || quotaTime == nil { + return time.Time{}, false + } + recoveryAt := quotaTime.Add(modelQuotaExceededWindow) + if deadline, hasDeadline := registration.SuspendedClientDeadlines[clientID]; hasDeadline && !deadline.IsZero() && deadline.Before(recoveryAt) { + recoveryAt = deadline + } + return recoveryAt, true +} + func modelRegistrationAvailability(registration *ModelRegistration, now time.Time) (bool, time.Time) { if registration == nil { return false, time.Time{} @@ -1501,11 +1587,11 @@ func modelRegistrationAvailability(registration *ModelRegistration, now time.Tim availableClients := registration.Count expiredClients := 0 var expiresAt time.Time - for _, quotaTime := range registration.QuotaExceededClients { - if quotaTime == nil { + for clientID, quotaTime := range registration.QuotaExceededClients { + recoveryAt, ok := clientQuotaRecoveryAt(registration, clientID, quotaTime) + if !ok { continue } - recoveryAt := quotaTime.Add(modelQuotaExceededWindow) if now.Before(recoveryAt) { expiredClients++ if expiresAt.IsZero() || recoveryAt.Before(expiresAt) { @@ -1518,8 +1604,15 @@ func modelRegistrationAvailability(registration *ModelRegistration, now time.Tim otherSuspended := 0 quotaAndSuspended := 0 if registration.SuspendedClients != nil { - for clientID, reason := range registration.SuspendedClients { - if quotaTime := registration.QuotaExceededClients[clientID]; quotaTime != nil && now.Before(quotaTime.Add(modelQuotaExceededWindow)) { + for clientID := range registration.SuspendedClients { + reason, deadline, active := clientSuspensionActive(registration, clientID, now) + if !active { + continue + } + if !deadline.IsZero() && (expiresAt.IsZero() || deadline.Before(expiresAt)) { + expiresAt = deadline + } + if recoveryAt, ok := clientQuotaRecoveryAt(registration, clientID, registration.QuotaExceededClients[clientID]); ok && now.Before(recoveryAt) { quotaAndSuspended++ } if isQuotaSuspension(reason) { @@ -1543,7 +1636,7 @@ func modelRegistrationAvailability(registration *ModelRegistration, now time.Tim // GetAvailableModelInfos returns cloned metadata for all currently available models. func (r *ModelRegistry) GetAvailableModelInfos() []*ModelInfo { - now := time.Now() + now := r.now() r.mutex.RLock() defer r.mutex.RUnlock() @@ -1681,7 +1774,7 @@ func (r *ModelRegistry) GetAvailableModelsByProvider(provider string) []*ModelIn return nil } - now := time.Now() + now := r.now() result := make([]*ModelInfo, 0, len(providerModels)) for modelID, entry := range providerModels { @@ -1703,20 +1796,24 @@ func (r *ModelRegistry) GetAvailableModelsByProvider(provider string) []*ModelIn if p, okProvider := r.clientProviders[clientID]; !okProvider || p != provider { continue } - if quotaTime != nil && now.Sub(*quotaTime) < modelQuotaExceededWindow { + if recoveryAt, okRecovery := clientQuotaRecoveryAt(registration, clientID, quotaTime); okRecovery && now.Before(recoveryAt) { expiredClients++ } } } if registration.SuspendedClients != nil { - for clientID, reason := range registration.SuspendedClients { + for clientID := range registration.SuspendedClients { if clientID == "" { continue } if p, okProvider := r.clientProviders[clientID]; !okProvider || p != provider { continue } - if quotaTime := registration.QuotaExceededClients[clientID]; quotaTime != nil && now.Before(quotaTime.Add(modelQuotaExceededWindow)) { + reason, _, active := clientSuspensionActive(registration, clientID, now) + if !active { + continue + } + if recoveryAt, okRecovery := clientQuotaRecoveryAt(registration, clientID, registration.QuotaExceededClients[clientID]); okRecovery && now.Before(recoveryAt) { quotaAndSuspended++ } if isQuotaSuspension(reason) { @@ -1759,18 +1856,21 @@ func (r *ModelRegistry) GetModelCount(modelID string) int { defer r.mutex.RUnlock() if registration, exists := r.models[modelID]; exists { - now := time.Now() + now := r.now() // Count clients that have exceeded quota but haven't recovered yet expiredClients := 0 - for _, quotaTime := range registration.QuotaExceededClients { - if quotaTime != nil && now.Sub(*quotaTime) < modelQuotaExceededWindow { + for clientID, quotaTime := range registration.QuotaExceededClients { + if recoveryAt, ok := clientQuotaRecoveryAt(registration, clientID, quotaTime); ok && now.Before(recoveryAt) { expiredClients++ } } suspendedClients := 0 for clientID := range registration.SuspendedClients { - if quotaTime := registration.QuotaExceededClients[clientID]; quotaTime != nil && now.Before(quotaTime.Add(modelQuotaExceededWindow)) { + if _, _, active := clientSuspensionActive(registration, clientID, now); !active { + continue + } + if recoveryAt, ok := clientQuotaRecoveryAt(registration, clientID, registration.QuotaExceededClients[clientID]); ok && now.Before(recoveryAt) { continue } suspendedClients++ @@ -1991,22 +2091,33 @@ func (r *ModelRegistry) convertModelToMap(model *ModelInfo, handlerType string) } } -// CleanupExpiredQuotas removes expired quota tracking entries +// CleanupExpiredQuotas removes expired quota and bounded suspension entries func (r *ModelRegistry) CleanupExpiredQuotas() { r.mutex.Lock() defer r.mutex.Unlock() - now := time.Now() + now := r.now() invalidated := false for modelID, registration := range r.models { + if registration == nil { + continue + } for clientID, quotaTime := range registration.QuotaExceededClients { - if quotaTime != nil && now.Sub(*quotaTime) >= modelQuotaExceededWindow { + if recoveryAt, ok := clientQuotaRecoveryAt(registration, clientID, quotaTime); ok && !now.Before(recoveryAt) { delete(registration.QuotaExceededClients, clientID) invalidated = true log.Debugf("Cleaned up expired quota tracking for model %s, client %s", modelID, clientID) } } + for clientID, deadline := range registration.SuspendedClientDeadlines { + if !deadline.IsZero() && !now.Before(deadline) { + delete(registration.SuspendedClientDeadlines, clientID) + delete(registration.SuspendedClients, clientID) + invalidated = true + log.Debugf("Cleaned up expired suspension for model %s, client %s", modelID, clientID) + } + } } if invalidated { r.invalidateAvailableModelsCacheLocked() diff --git a/internal/registry/model_registry_transient_suspend_deadline_test.go b/internal/registry/model_registry_transient_suspend_deadline_test.go new file mode 100644 index 00000000000..c22398e5a76 --- /dev/null +++ b/internal/registry/model_registry_transient_suspend_deadline_test.go @@ -0,0 +1,194 @@ +package registry + +import ( + "testing" + "time" +) + +func listedIDs(models []map[string]any) map[string]bool { + out := make(map[string]bool, len(models)) + for _, m := range models { + if id, _ := m["id"].(string); id != "" { + out[id] = true + } + } + return out +} + +func infoIDs(infos []*ModelInfo) map[string]bool { + out := make(map[string]bool, len(infos)) + for _, info := range infos { + if info != nil && info.ID != "" { + out[info.ID] = true + } + } + return out +} + +func TestModelRegistry_TransientSuspendDeadline_AutoExpiresCacheAndAllViews(t *testing.T) { + baseNow := time.Date(2026, 11, 11, 1, 5, 0, 0, time.UTC) + mockNow := baseNow + + r := newTestModelRegistry() + r.nowFunc = func() time.Time { return mockNow } + + r.RegisterClient("xai-auth", "xai", []*ModelInfo{ + {ID: "grok-4.7", OwnedBy: "xai", Created: baseNow.Unix()}, + {ID: "grok-4.7-cp", OwnedBy: "xai", Created: baseNow.Unix()}, + {ID: "grok-4.6", OwnedBy: "xai", Created: baseNow.Unix()}, + }) + epoch := r.ClientRegistrationEpoch("xai-auth") + deadline := baseNow.Add(time.Minute) + + if !r.ApplyClientModelProjections("xai-auth", epoch, 1, []ClientModelProjection{ + {ModelID: "grok-4.7", Suspended: true, SuspendReason: "xai stream error: stream disconnected", SuspendUntil: deadline}, + {ModelID: "grok-4.7-cp", Suspended: true, SuspendReason: "xai stream error: stream disconnected", SuspendUntil: deadline}, + {ModelID: "grok-4.6"}, + }) { + t.Fatal("expected initial projection to apply") + } + + // During cooldown: grok-4.7 and grok-4.7-cp are hidden, grok-4.6 remains listed. + duringOpenAI := listedIDs(r.GetAvailableModels("openai")) + if duringOpenAI["grok-4.7"] || duringOpenAI["grok-4.7-cp"] || !duringOpenAI["grok-4.6"] { + t.Fatalf("unexpected /v1/models set during transient cooldown: %v", duringOpenAI) + } + if cached := r.availableModelsCache["openai"]; !cached.expiresAt.Equal(deadline) { + t.Fatalf("availableModelsCache expiresAt = %v, want %v", cached.expiresAt, deadline) + } + if infos := infoIDs(r.GetAvailableModelInfos()); infos["grok-4.7"] || infos["grok-4.7-cp"] || !infos["grok-4.6"] { + t.Fatalf("unexpected GetAvailableModelInfos during transient cooldown: %v", infos) + } + if provInfos := infoIDs(r.GetAvailableModelsByProvider("xai")); provInfos["grok-4.7"] || provInfos["grok-4.7-cp"] || !provInfos["grok-4.6"] { + t.Fatalf("unexpected GetAvailableModelsByProvider during transient cooldown: %v", provInfos) + } + if got := r.GetModelCount("grok-4.7"); got != 0 { + t.Fatalf("GetModelCount(grok-4.7) during cooldown = %d, want 0", got) + } + if !r.IsModelSuspendedForClient("xai-auth", "grok-4.7") { + t.Fatal("expected IsModelSuspendedForClient to report true during active transient cooldown") + } + + // Still active 1ns before deadline. + mockNow = deadline.Add(-time.Nanosecond) + stillCooling := listedIDs(r.GetAvailableModels("openai")) + if stillCooling["grok-4.7"] || stillCooling["grok-4.7-cp"] { + t.Fatalf("models listed before deadline elapsed: %v", stillCooling) + } + + // Exact deadline instant with NO re-projection, NO request, and NO refresh. + mockNow = deadline + afterOpenAI := listedIDs(r.GetAvailableModels("openai")) + if !afterOpenAI["grok-4.7"] || !afterOpenAI["grok-4.7-cp"] || !afterOpenAI["grok-4.6"] { + t.Fatalf("expected all models listed once transient cooldown expired without re-projection, got %v", afterOpenAI) + } + if infos := infoIDs(r.GetAvailableModelInfos()); !infos["grok-4.7"] || !infos["grok-4.7-cp"] { + t.Fatalf("expected GetAvailableModelInfos to list models after deadline, got %v", infos) + } + if provInfos := infoIDs(r.GetAvailableModelsByProvider("xai")); !provInfos["grok-4.7"] || !provInfos["grok-4.7-cp"] { + t.Fatalf("expected GetAvailableModelsByProvider to list models after deadline, got %v", provInfos) + } + if got := r.GetModelCount("grok-4.7"); got != 1 { + t.Fatalf("GetModelCount(grok-4.7) after cooldown = %d, want 1", got) + } + if got := r.GetModelCount("grok-4.7-cp"); got != 1 { + t.Fatalf("GetModelCount(grok-4.7-cp) after cooldown = %d, want 1", got) + } + if r.IsModelSuspendedForClient("xai-auth", "grok-4.7") { + t.Fatal("expected IsModelSuspendedForClient to report false once transient cooldown expired") + } + + r.CleanupExpiredQuotas() + if _, exists := r.models["grok-4.7"].SuspendedClients["xai-auth"]; exists { + t.Fatal("expected CleanupExpiredQuotas to prune expired transient suspension entry") + } + if _, exists := r.models["grok-4.7"].SuspendedClientDeadlines["xai-auth"]; exists { + t.Fatal("expected CleanupExpiredQuotas to prune expired transient suspension deadline") + } +} + +func TestModelRegistry_OpenEndedSuspensionAndManualOverridePersist(t *testing.T) { + baseNow := time.Date(2026, 11, 11, 2, 0, 0, 0, time.UTC) + mockNow := baseNow + + r := newTestModelRegistry() + r.nowFunc = func() time.Time { return mockNow } + + r.RegisterClient("xai-auth", "xai", []*ModelInfo{{ID: "grok-4.7", OwnedBy: "xai"}}) + epoch := r.ClientRegistrationEpoch("xai-auth") + deadline := baseNow.Add(time.Minute) + + // Start with a bounded transient suspension. + if !r.ApplyClientModelProjections("xai-auth", epoch, 1, []ClientModelProjection{ + {ModelID: "grok-4.7", Suspended: true, SuspendReason: "transient 408", SuspendUntil: deadline}, + }) { + t.Fatal("initial transient projection rejected") + } + + // Override with manual open-ended SuspendClientModel while already in SuspendedClients. + r.SuspendClientModel("xai-auth", "grok-4.7", "manual") + + mockNow = baseNow.Add(24 * time.Hour) + if listed := listedIDs(r.GetAvailableModels("openai")); listed["grok-4.7"] { + t.Fatalf("manual SuspendClientModel leaked model after earlier transient deadline: %v", listed) + } + if !r.IsModelSuspendedForClient("xai-auth", "grok-4.7") { + t.Fatal("expected manual open-ended suspension to stay active") + } + + // Resume, then apply an open-ended projection (zero SuspendUntil). + r.ResumeClientModel("xai-auth", "grok-4.7") + if !listedIDs(r.GetAvailableModels("openai"))["grok-4.7"] { + t.Fatal("expected ResumeClientModel to restore listing") + } + + if !r.ApplyClientModelProjections("xai-auth", epoch, 2, []ClientModelProjection{ + {ModelID: "grok-4.7", Suspended: true, SuspendReason: "disabled"}, + }) { + t.Fatal("open-ended projection rejected") + } + mockNow = baseNow.Add(48 * time.Hour) + if listed := listedIDs(r.GetAvailableModels("openai")); listed["grok-4.7"] { + t.Fatalf("open-ended projection leaked model: %v", listed) + } +} + +func TestModelRegistry_ShortQuotaDeadlineRecoversWithDisabledBackup(t *testing.T) { + baseNow := time.Date(2026, 11, 11, 3, 0, 0, 0, time.UTC) + mockNow := baseNow + + r := newTestModelRegistry() + r.nowFunc = func() time.Time { return mockNow } + + model := []*ModelInfo{{ID: "grok-4.7", OwnedBy: "xai"}} + r.RegisterClient("c1-quota", "xai", model) + r.RegisterClient("c2-disabled", "xai", model) + + epoch1 := r.ClientRegistrationEpoch("c1-quota") + epoch2 := r.ClientRegistrationEpoch("c2-disabled") + + shortQuotaDeadline := baseNow.Add(time.Minute) + if !r.ApplyClientModelProjections("c1-quota", epoch1, 1, []ClientModelProjection{ + {ModelID: "grok-4.7", Suspended: true, SuspendReason: "quota", SuspendUntil: shortQuotaDeadline, QuotaExceeded: true}, + }) { + t.Fatal("quota projection rejected") + } + if !r.ApplyClientModelProjections("c2-disabled", epoch2, 1, []ClientModelProjection{ + {ModelID: "grok-4.7", Suspended: true, SuspendReason: "disabled"}, + }) { + t.Fatal("disabled projection rejected") + } + + if listedIDs(r.GetAvailableModels("openai"))["grok-4.7"] { + t.Fatal("expected model hidden while c1 is in 1m quota cooldown and c2 is disabled") + } + + // Advance past the 1m quota deadline (still within the default 5m modelQuotaExceededWindow). + mockNow = shortQuotaDeadline.Add(time.Second) + if !listedIDs(r.GetAvailableModels("openai"))["grok-4.7"] { + t.Fatal("expected model listed once c1's 1m quota deadline passed") + } + if got := r.GetModelCount("grok-4.7"); got != 1 { + t.Fatalf("GetModelCount(grok-4.7) after c1 quota recovery = %d, want 1", got) + } +} diff --git a/internal/registry/models/devin_models.json b/internal/registry/models/devin_models.json index 63e2de3d1fa..c47f8d04101 100644 --- a/internal/registry/models/devin_models.json +++ b/internal/registry/models/devin_models.json @@ -46,11 +46,11 @@ } }, { - "id": "claude-fable-5-1", + "id": "claude-fable-5-2", "object": "model", "type": "devin", "owned_by": "anthropic", - "display_name": "Claude Fable 5.1", + "display_name": "Claude Fable 5.2", "context_length": 1000000, "max_completion_tokens": 64000, "supportedInputModalities": [ @@ -173,11 +173,11 @@ } }, { - "id": "gemini-4-argon", + "id": "gemini-4-carbon", "object": "model", "type": "devin", "owned_by": "google", - "display_name": "Gemini 4 Argon", + "display_name": "Gemini 4 Carbon", "context_length": 1048576, "max_completion_tokens": 64000, "supportedInputModalities": [ @@ -196,11 +196,11 @@ } }, { - "id": "kimi-k3", + "id": "kimi-k3-1-pro", "object": "model", "type": "devin", "owned_by": "moonshot", - "display_name": "Kimi K3", + "display_name": "Kimi K3.1 Pro", "context_length": 1048576, "max_completion_tokens": 64000, "supportedInputModalities": [ @@ -213,32 +213,12 @@ "thinking": { "levels": [ "low", + "medium", "high", "max" ] } }, - { - "id": "glm-5-2", - "object": "model", - "type": "devin", - "owned_by": "zhipu", - "display_name": "GLM-5.2", - "context_length": 200000, - "max_completion_tokens": 64000, - "supportedInputModalities": [ - "text" - ], - "supportedOutputModalities": [ - "text" - ], - "thinking": { - "levels": [ - "none", - "max" - ] - } - }, { "id": "glm-5-3", "object": "model", @@ -409,6 +389,31 @@ ] } }, + { + "id": "claude-fable-5-1", + "object": "model", + "type": "devin", + "owned_by": "anthropic", + "display_name": "Claude Fable 5.1", + "context_length": 1000000, + "max_completion_tokens": 64000, + "supportedInputModalities": [ + "text", + "image" + ], + "supportedOutputModalities": [ + "text" + ], + "thinking": { + "levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ] + } + }, { "id": "claude-sonnet-5", "object": "model", @@ -530,6 +535,29 @@ ] } }, + { + "id": "gemini-4-argon", + "object": "model", + "type": "devin", + "owned_by": "google", + "display_name": "Gemini 4 Argon", + "context_length": 1048576, + "max_completion_tokens": 64000, + "supportedInputModalities": [ + "text", + "image" + ], + "supportedOutputModalities": [ + "text" + ], + "thinking": { + "levels": [ + "low", + "medium", + "high" + ] + } + }, { "id": "gpt-5-6-sol", "object": "model", @@ -658,6 +686,27 @@ ] } }, + { + "id": "glm-5-2", + "object": "model", + "type": "devin", + "owned_by": "zhipu", + "display_name": "GLM-5.2", + "context_length": 200000, + "max_completion_tokens": 64000, + "supportedInputModalities": [ + "text" + ], + "supportedOutputModalities": [ + "text" + ], + "thinking": { + "levels": [ + "none", + "max" + ] + } + }, { "id": "glm-5-2-1m", "object": "model", @@ -776,6 +825,29 @@ ] } }, + { + "id": "kimi-k3", + "object": "model", + "type": "devin", + "owned_by": "moonshot", + "display_name": "Kimi K3", + "context_length": 1048576, + "max_completion_tokens": 64000, + "supportedInputModalities": [ + "text", + "image" + ], + "supportedOutputModalities": [ + "text" + ], + "thinking": { + "levels": [ + "low", + "high", + "max" + ] + } + }, { "id": "glm-5-3-flash", "object": "model", diff --git a/internal/registry/models/models.json b/internal/registry/models/models.json index d8e576221be..bd53efb40c8 100644 --- a/internal/registry/models/models.json +++ b/internal/registry/models/models.json @@ -278,6 +278,35 @@ "text" ] }, + { + "id": "claude-fable-5-2", + "object": "model", + "created": 1794250800, + "owned_by": "anthropic", + "type": "claude", + "display_name": "Claude Fable 5.2", + "description": "Claude Fable 5.2 extends Claude Fable 5 at the same input and output prices, with cache reads at a quarter of the cost, and brings stronger long-running agentic coding, multistep research, and document, spreadsheet, and slide work.", + "context_length": 1000000, + "max_completion_tokens": 128000, + "thinking": { + "zero_allowed": false, + "dynamic_allowed": true, + "levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ] + }, + "supportedInputModalities": [ + "text", + "image" + ], + "supportedOutputModalities": [ + "text" + ] + }, { "id": "claude-opus-5-5", "native_capabilities": { @@ -1035,6 +1064,36 @@ "native_capabilities": { "web_search": true } + }, + { + "id": "gemini-omni-1.2-flash", + "object": "model", + "owned_by": "google", + "type": "gemini", + "display_name": "Gemini Omni 1.2 Flash", + "name": "models/gemini-omni-1.2-flash", + "version": "1.2", + "description": "Gemini Omni 1.2 Flash", + "context_length": 131072, + "max_completion_tokens": 65536, + "thinking": { + "min": 128, + "max": 32768, + "dynamic_allowed": true, + "levels": [ + "low", + "high" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "video" + ], + "supportedOutputModalities": [ + "text", + "video" + ] } ], "vertex": [ @@ -1756,6 +1815,98 @@ "native_capabilities": { "web_search": true } + }, + { + "id": "gemini-4-carbon", + "object": "model", + "owned_by": "google", + "type": "gemini", + "display_name": "Gemini 4 Carbon", + "name": "gemini-4-carbon", + "description": "Gemini 4 Carbon", + "context_length": 1048576, + "max_completion_tokens": 1048576, + "thinking": { + "min": 128, + "max": 65535, + "dynamic_allowed": true, + "levels": [ + "low", + "medium", + "high" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "audio", + "video" + ], + "supportedOutputModalities": [ + "text" + ], + "native_capabilities": { + "web_search": true + } + }, + { + "id": "gemini-4-hydrogen", + "object": "model", + "owned_by": "google", + "type": "gemini", + "display_name": "Gemini 4 Hydrogen", + "name": "gemini-4-hydrogen", + "description": "Gemini 4 Hydrogen", + "context_length": 1048576, + "max_completion_tokens": 1048576, + "thinking": { + "levels": [ + "low", + "medium", + "high" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "audio", + "video" + ], + "supportedOutputModalities": [ + "text" + ], + "native_capabilities": { + "web_search": true + } + }, + { + "id": "gemini-omni-1.2-flash", + "object": "model", + "owned_by": "google", + "type": "gemini", + "display_name": "Gemini Omni 1.2 Flash", + "name": "gemini-omni-1.2-flash", + "description": "Gemini Omni 1.2 Flash", + "context_length": 131072, + "max_completion_tokens": 260640, + "thinking": { + "min": 128, + "max": 32768, + "dynamic_allowed": true, + "levels": [ + "low", + "high" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "video" + ], + "supportedOutputModalities": [ + "text", + "video" + ] } ], "gemini-cli": [ @@ -2590,6 +2741,36 @@ "native_capabilities": { "web_search": true } + }, + { + "id": "gemini-omni-1.2-flash", + "object": "model", + "owned_by": "google", + "type": "gemini", + "display_name": "Gemini Omni 1.2 Flash", + "name": "models/gemini-omni-1.2-flash", + "version": "1.2", + "description": "Gemini Omni 1.2 Flash", + "context_length": 131072, + "max_completion_tokens": 65536, + "thinking": { + "min": 128, + "max": 32768, + "dynamic_allowed": true, + "levels": [ + "low", + "high" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "video" + ], + "supportedOutputModalities": [ + "text", + "video" + ] } ], "codex-free": [ @@ -4314,6 +4495,75 @@ "web_search": true } }, + { + "id": "gemini-4-carbon-high", + "object": "model", + "owned_by": "antigravity", + "type": "antigravity", + "supports_web_search": true, + "display_name": "Gemini 4 Carbon", + "name": "gemini-4-carbon-high", + "description": "Gemini 4 Carbon (High)", + "context_length": 1048576, + "max_completion_tokens": 1048576, + "thinking": { + "min": 1, + "max": 65535, + "dynamic_allowed": true, + "levels": [ + "low", + "medium", + "high" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "audio", + "video" + ], + "supportedOutputModalities": [ + "text" + ], + "native_capabilities": { + "web_search": true + } + }, + { + "id": "gemini-4-hydrogen-xhigh", + "object": "model", + "owned_by": "antigravity", + "type": "antigravity", + "supports_web_search": true, + "display_name": "Gemini 4 Hydrogen", + "name": "gemini-4-hydrogen-xhigh", + "description": "Gemini 4 Hydrogen (XHigh)", + "context_length": 1048576, + "max_completion_tokens": 1048576, + "thinking": { + "min": 1, + "max": 65535, + "dynamic_allowed": true, + "levels": [ + "low", + "medium", + "high", + "xhigh" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "audio", + "video" + ], + "supportedOutputModalities": [ + "text" + ], + "native_capabilities": { + "web_search": true + } + }, { "id": "gemini-3.8-flash-high", "object": "model", @@ -4348,6 +4598,40 @@ "web_search": true } }, + { + "id": "gemini-3.8-flash-tiered", + "object": "model", + "owned_by": "antigravity", + "type": "antigravity", + "supports_web_search": true, + "display_name": "Gemini 3.8 Flash (Tiered)", + "name": "gemini-3.8-flash-tiered", + "description": "Gemini 3.8 Flash (Tiered)", + "context_length": 1048576, + "max_completion_tokens": 65536, + "thinking": { + "min": 1, + "max": 65535, + "dynamic_allowed": true, + "levels": [ + "low", + "medium", + "high" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "audio", + "video" + ], + "supportedOutputModalities": [ + "text" + ], + "native_capabilities": { + "web_search": true + } + }, { "id": "gemini-3-flash", "object": "model", @@ -4895,6 +5179,40 @@ } ], "meta": [ + { + "id": "muse-ember-1.0", + "object": "model", + "created": 1794182400, + "owned_by": "meta", + "type": "meta", + "display_name": "Muse Ember 1.0", + "name": "muse-ember-1.0", + "description": "Meta's smallest and most efficient model designed for complex reasoning execution, tool calls, coding subtasks, routing, extraction, and long document parsing.", + "context_length": 1048576, + "max_completion_tokens": 524288, + "thinking": { + "levels": [ + "minimal", + "low", + "medium", + "high", + "xhigh", + "max" + ] + }, + "supportedInputModalities": [ + "text", + "image", + "video", + "audio" + ], + "supportedOutputModalities": [ + "text" + ], + "native_capabilities": { + "web_search": true + } + }, { "id": "muse-wonder-1.0", "object": "model", @@ -5160,4 +5478,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/internal/runtime/executor/aistudio_executor.go b/internal/runtime/executor/aistudio_executor.go index a827a4e911d..48ab3d0a6ae 100644 --- a/internal/runtime/executor/aistudio_executor.go +++ b/internal/runtime/executor/aistudio_executor.go @@ -186,10 +186,24 @@ func (e *AIStudioExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, helps.AppendAPIResponseChunk(ctx, e.cfg, wsResp.Body) } if wsResp.Status < 200 || wsResp.Status >= 300 { + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, body.replayScope, wsResp.Status, wsResp.Body); errClear != nil { + logAntigravityReasoningReplayDegraded(body.replayScope, "invalidate", errClear) + } return resp, statusErr{code: wsResp.Status, msg: string(wsResp.Body)} } - reporter.ObserveResponseModel(wsResp.Body) responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) + reporter.ObserveResponseModel(wsResp.Body) + if body.action != "countTokens" { + if _, zeroErrMsg, zeroOutput := helps.CheckGeminiZeroOutputNonStream(responseFormat, wsResp.Body, false); zeroOutput { + gemDetail := helps.ParseGeminiUsage(wsResp.Body) + helps.ApplyGeminiRequestImageConfig(&gemDetail, body.payload) + err = statusErr{code: http.StatusBadGateway, msg: zeroErrMsg} + helps.RecordAPIResponseError(ctx, e.cfg, err) + reporter.PublishFailureWithDetail(ctx, gemDetail, err) + return cliproxyexecutor.Response{}, err + } + cacheAntigravityReasoningReplayFromResponse(ctx, body.replayScope, body.replayRequestPayload, wsResp.Body) + } var param any out := sdktranslator.TranslateNonStream(ctx, body.toFormat, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translatedReq, wsResp.Body, ¶m) if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { @@ -284,20 +298,23 @@ func (e *AIStudioExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth reporter.StartResponseTTFT() metadataLogged = true } - var body bytes.Buffer + var errBody bytes.Buffer if len(firstEvent.Payload) > 0 { reporter.MarkFirstResponseByte() helps.AppendAPIResponseChunk(ctx, e.cfg, firstEvent.Payload) - body.Write(firstEvent.Payload) + errBody.Write(firstEvent.Payload) } if firstEvent.Type == wsrelay.MessageTypeStreamEnd { - return nil, statusErr{code: firstEvent.Status, msg: body.String()} + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, body.replayScope, firstEvent.Status, errBody.Bytes()); errClear != nil { + logAntigravityReasoningReplayDegraded(body.replayScope, "invalidate", errClear) + } + return nil, statusErr{code: firstEvent.Status, msg: errBody.String()} } for event := range wsStream { if event.Err != nil { helps.RecordAPIResponseError(ctx, e.cfg, event.Err) - if body.Len() == 0 { - body.WriteString(event.Err.Error()) + if errBody.Len() == 0 { + errBody.WriteString(event.Err.Error()) } break } @@ -309,14 +326,18 @@ func (e *AIStudioExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth if len(event.Payload) > 0 { reporter.MarkFirstResponseByte() helps.AppendAPIResponseChunk(ctx, e.cfg, event.Payload) - body.Write(event.Payload) + errBody.Write(event.Payload) } if event.Type == wsrelay.MessageTypeStreamEnd { break } } - return nil, statusErr{code: firstEvent.Status, msg: body.String()} + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, body.replayScope, firstEvent.Status, errBody.Bytes()); errClear != nil { + logAntigravityReasoningReplayDegraded(body.replayScope, "invalidate", errClear) + } + return nil, statusErr{code: firstEvent.Status, msg: errBody.String()} } + replayAccumulator := newAntigravityReasoningReplayAccumulator(body.replayScope, body.replayRequestPayload) out := make(chan cliproxyexecutor.StreamChunk, 1) go func(first wsrelay.StreamEvent) { defer close(out) @@ -336,29 +357,81 @@ func (e *AIStudioExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth _ = helps.StopTranslatedClaudeStream(ctx, &streamErr, reporter, &streamUsage, out) }() var param any + var replayCommitted bool + commitReplay := func() { + if !replayCommitted && replayAccumulator != nil && replayAccumulator.terminal && streamErr == nil && helps.ApplyPatchTranslationError(param) == nil { + replayAccumulator.Commit(ctx) + replayCommitted = true + } + } helps.InitializeApplyPatchStream(ctx, body.toFormat, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translatedReq, ¶m) metadataLogged := false var relayFrames helps.RelaySSEBuffer + zeroOutputGuard := helps.NewGeminiZeroOutputStreamGuard(false, responseFormat) + failZeroOutput := func(finishReason string) bool { + streamErr = statusErr{code: http.StatusBadGateway, msg: helps.GeminiZeroOutputErrorMessage(responseFormat, finishReason)} + helps.RecordAPIResponseError(ctx, e.cfg, streamErr) + _ = helps.StopTranslatedClaudeStream(ctx, &streamErr, reporter, &streamUsage, out) + return false + } + emitRelayFrame := func(frame []byte) bool { + filtered := helps.FilterSSEUsageMetadata(frame) + lines := helps.TranslateStreamWithClaudeInputTokens(ctx, body.toFormat, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translatedReq, filtered, ¶m, claudeInputTokens) + helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { + return statusErr{code: http.StatusBadGateway, msg: msg} + }) + if replayAccumulator != nil && replayAccumulator.terminal && !replayCommitted && antigravityStreamChunksHaveTerminalCommitEvent(lines) { + commitReplay() + } + for i := range lines { + spaced := ensureColonSpacedJSON(lines[i]) + select { + case out <- cliproxyexecutor.StreamChunk{Payload: spaced}: + if len(spaced) > 0 { + zeroOutputGuard.MarkEmitted() + } + case <-ctx.Done(): + return false + } + } + return !helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + } processRelayFrames := func(payloads [][]byte) bool { for _, payload := range payloads { for _, frame := range splitRelayFrames(payload) { + if replayAccumulator != nil { + replayAccumulator.ObserveSSELine(frame) + } reporter.ObserveResponseModel(frame) streamUsage.ObserveGeminiStream(frame) - filtered := helps.FilterSSEUsageMetadata(frame) - lines := helps.TranslateStreamWithClaudeInputTokens(ctx, body.toFormat, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translatedReq, filtered, ¶m, claudeInputTokens) - helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) - helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { - return statusErr{code: http.StatusBadGateway, msg: msg} - }) - for i := range lines { - select { - case out <- cliproxyexecutor.StreamChunk{Payload: ensureColonSpacedJSON(lines[i])}: - case <-ctx.Done(): + if len(helps.JSONPayload(frame)) == 0 { + continue + } + shells, action, finishReason := zeroOutputGuard.Observe(frame) + switch action { + case helps.GeminiZeroOutputContinue: + continue + case helps.GeminiZeroOutputFailNow: + return failZeroOutput(finishReason) + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = frame + } + if !emitRelayFrame(errFrame) { + return false + } + return failZeroOutput(finishReason) + default: + for _, shell := range shells { + if !emitRelayFrame(shell) { + return false + } + } + if !emitRelayFrame(frame) { return false } - } - if helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { - return false } } } @@ -368,6 +441,28 @@ func (e *AIStudioExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth if !processRelayFrames(relayFrames.Finish()) { return } + shells, action, finishReason := zeroOutputGuard.Finalize() + switch action { + case helps.GeminiZeroOutputFailNow: + failZeroOutput(finishReason) + return + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + if !emitRelayFrame(errFrame) { + return + } + failZeroOutput(finishReason) + return + default: + for _, shell := range shells { + if !emitRelayFrame(shell) { + return + } + } + } if helps.EndApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return } @@ -382,6 +477,7 @@ func (e *AIStudioExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { return statusErr{code: http.StatusBadGateway, msg: msg} }) + commitReplay() for _, line := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: ensureColonSpacedJSON(line)}: @@ -435,6 +531,9 @@ func (e *AIStudioExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth helps.AppendAPIResponseChunk(ctx, e.cfg, event.Payload) } if event.Status < http.StatusOK || event.Status >= http.StatusMultipleChoices { + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, body.replayScope, event.Status, event.Payload); errClear != nil { + logAntigravityReasoningReplayDegraded(body.replayScope, "invalidate", errClear) + } errResponse := statusErr{code: event.Status, msg: string(event.Payload)} helps.RecordAPIResponseError(ctx, e.cfg, errResponse) reporter.PublishFailure(ctx, errResponse) @@ -444,13 +543,50 @@ func (e *AIStudioExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth } return false } + if !processRelayFrames(relayFrames.Finish()) { + return false + } reporter.ObserveResponseModel(event.Payload) streamUsage.Observe(helps.ParseGeminiUsage(event.Payload), true) + shells, action, finishReason := zeroOutputGuard.Observe(event.Payload) + if action == helps.GeminiZeroOutputContinue { + var finShells [][]byte + finShells, action, finishReason = zeroOutputGuard.Finalize() + if len(finShells) > 0 { + shells = append(shells, finShells...) + } + } + switch action { + case helps.GeminiZeroOutputFailNow: + return failZeroOutput(finishReason) + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = event.Payload + } + if !emitRelayFrame(errFrame) { + return false + } + return failZeroOutput(finishReason) + default: + for _, shell := range shells { + if !emitRelayFrame(shell) { + return false + } + } + } + if replayAccumulator != nil { + replayAccumulator.observeResponsePayload(event.Payload) + if !replayAccumulator.terminal && (ojson.GetBytesNoCopy(event.Payload, "response.candidates.0").Exists() || ojson.GetBytesNoCopy(event.Payload, "candidates.0").Exists()) { + replayAccumulator.terminal = true + } + } lines := helps.TranslateStreamWithClaudeInputTokens(ctx, body.toFormat, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translatedReq, event.Payload, ¶m, claudeInputTokens) helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { return statusErr{code: http.StatusBadGateway, msg: msg} }) + commitReplay() for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: ensureColonSpacedJSON(lines[i])}: @@ -485,6 +621,18 @@ func (e *AIStudioExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth return } } + if ctx.Err() == nil && zeroOutputGuard.HasAbnormalFinish() { + _, action, finishReason := zeroOutputGuard.Finalize() + if action == helps.GeminiZeroOutputEmitErrorThenFail { + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + _ = emitRelayFrame(errFrame) + } + failZeroOutput(finishReason) + return + } _ = helps.EndApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) _ = helps.StopTranslatedClaudeStream(ctx, &streamErr, reporter, &streamUsage, out) }(firstEvent) @@ -561,9 +709,11 @@ func (e *AIStudioExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) } type translatedPayload struct { - payload []byte - action string - toFormat sdktranslator.Format + payload []byte + action string + toFormat sdktranslator.Format + replayScope antigravityReasoningReplayScope + replayRequestPayload []byte } func (e *AIStudioExecutor) translateRequest(ctx context.Context, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, stream bool) ([]byte, translatedPayload, error) { @@ -608,6 +758,19 @@ func (e *AIStudioExecutor) translateRequest(ctx context.Context, req cliproxyexe } normalizeAIStudioThinkingLevelDoc(doc) internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents") + replayScope := antigravityReasoningReplayScope{} + var replayRequestPayload []byte + if antigravityUsesReasoningReplayCache(baseModel) { + var changedReplay bool + var errReplay error + replayScope, replayRequestPayload, changedReplay, errReplay = prepareGeminiTopLevelReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc) + if errReplay != nil { + return nil, translatedPayload{}, errReplay + } + if changedReplay { + internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents") + } + } if action == "countTokens" { _ = doc.Delete("generationConfig") _ = doc.Delete("tools") @@ -615,7 +778,13 @@ func (e *AIStudioExecutor) translateRequest(ctx context.Context, req cliproxyexe } helps.ApplyPayloadConfigWithRequestDoc(e.cfg, baseModel, to.String(), from.String(), "", doc, originalTranslated, requestedModel, requestPath, opts.Headers) payload = doc.Bytes() - return payload, translatedPayload{payload: payload, action: action, toFormat: to}, nil + return payload, translatedPayload{ + payload: payload, + action: action, + toFormat: to, + replayScope: replayScope, + replayRequestPayload: replayRequestPayload, + }, nil } // normalizeAIStudioThinkingLevel normalizes thinking levels to Google's canonical uppercase enum values. diff --git a/internal/runtime/executor/aistudio_executor_test.go b/internal/runtime/executor/aistudio_executor_test.go index a0657dab488..1473e55e118 100644 --- a/internal/runtime/executor/aistudio_executor_test.go +++ b/internal/runtime/executor/aistudio_executor_test.go @@ -668,11 +668,15 @@ func TestAIStudioExecutorClaudeMalformedFunctionCallReturnsRetryableError(t *tes t.Fatalf("%s ExecuteStream() chunk.Err = nil, want 502 error propagated", mode) } streamText := combined.String() - if strings.Contains(streamText, `"stop_reason":"refusal"`) { - t.Fatalf("%s stream unexpectedly emitted stop_reason refusal:\n%s", mode, streamText) + if strings.TrimSpace(streamText) != "" { + t.Fatalf("%s stream unexpectedly emitted payload before bootstrap retryable error:\n%s", mode, streamText) } - if !strings.Contains(streamText, "event: error\n") || !strings.Contains(streamText, `"type": "api_error"`) && !strings.Contains(streamText, `"type":"api_error"`) { - t.Fatalf("%s stream missing retryable api_error event:\n%s", mode, streamText) + streamStatus, okStreamStatus := streamErr.(interface{ StatusCode() int }) + if !okStreamStatus || streamStatus.StatusCode() != http.StatusBadGateway { + t.Fatalf("%s ExecuteStream() chunk.Err = %T %v, want status 502", mode, streamErr, streamErr) + } + if got := ojson.Get(streamErr.Error(), "error.type").String(); got != "api_error" { + t.Fatalf("%s ExecuteStream() chunk.Err error.type = %q, want api_error; err=%s", mode, got, streamErr.Error()) } assertMalformedFunctionCallFailedUsage(t, capture.records) } diff --git a/internal/runtime/executor/antigravity_executor.go b/internal/runtime/executor/antigravity_executor.go index bd0c33ecd63..2b89a12804f 100644 --- a/internal/runtime/executor/antigravity_executor.go +++ b/internal/runtime/executor/antigravity_executor.go @@ -13,6 +13,7 @@ import ( "fmt" "net/http" "strings" + "sync" "time" "github.com/MoeForge/moego/ojson" @@ -50,7 +51,10 @@ const ( // AntigravityExecutor proxies requests to the antigravity upstream. type AntigravityExecutor struct { - cfg *config.Config + cfg *config.Config + matcherMu sync.RWMutex + lastWordsKey string + cachedMatcher *helps.SensitiveWordMatcher } // NewAntigravityExecutor creates a new Antigravity executor instance. @@ -64,19 +68,51 @@ func NewAntigravityExecutor(cfg *config.Config) *AntigravityExecutor { return &AntigravityExecutor{cfg: cfg} } +func (e *AntigravityExecutor) getSensitiveWordMatcher() *helps.SensitiveWordMatcher { + if e == nil || e.cfg == nil { + return nil + } + words := e.cfg.Antigravity.SensitiveWords + replacements := e.cfg.Antigravity.SensitiveWordsReplace + patterns := e.cfg.Antigravity.SensitivePatternsReplace + if len(words) == 0 && len(replacements) == 0 && len(patterns) == 0 { + return nil + } + key := helps.SensitiveWordConfigCacheKeyWithPatterns(words, replacements, patterns) + e.matcherMu.RLock() + if e.lastWordsKey == key { + m := e.cachedMatcher + e.matcherMu.RUnlock() + return m + } + e.matcherMu.RUnlock() + + e.matcherMu.Lock() + defer e.matcherMu.Unlock() + if e.lastWordsKey == key { + return e.cachedMatcher + } + e.lastWordsKey = key + e.cachedMatcher = helps.BuildAntigravitySensitiveWordMatcherWithPatterns(words, replacements, patterns) + return e.cachedMatcher +} + func (e *AntigravityExecutor) obfuscateSensitiveWords(payload []byte) []byte { - if e == nil || e.cfg == nil || len(e.cfg.Antigravity.SensitiveWords) == 0 { + matcher := e.getSensitiveWordMatcher() + if matcher == nil { return payload } - matcher := helps.BuildSensitiveWordMatcher(e.cfg.Antigravity.SensitiveWords) return helps.ObfuscateSensitiveWordsInSystemInstruction(payload, matcher) } func (e *AntigravityExecutor) obfuscateSensitiveWordsDoc(doc *ojson.Doc) bool { - if doc == nil || e == nil || e.cfg == nil || len(e.cfg.Antigravity.SensitiveWords) == 0 { + if doc == nil { + return false + } + matcher := e.getSensitiveWordMatcher() + if matcher == nil { return false } - matcher := helps.BuildSensitiveWordMatcher(e.cfg.Antigravity.SensitiveWords) return helps.ObfuscateSensitiveWordsInSystemInstructionDoc(doc, matcher) } diff --git a/internal/runtime/executor/antigravity_executor_credits.go b/internal/runtime/executor/antigravity_executor_credits.go index 2e4e6230f6f..a995703a38c 100644 --- a/internal/runtime/executor/antigravity_executor_credits.go +++ b/internal/runtime/executor/antigravity_executor_credits.go @@ -355,15 +355,88 @@ func antigravityHasExplicitCreditsBalanceExhaustedReason(body []byte) bool { return false } +// antigravityTOSViolation captures the parsed state of a 403 PERMISSION_DENIED +// carrying an ErrorInfo reason=TOS_VIOLATION (issue #7515). This is a +// terminal, service-scoped credential suspension — the OAuth token and model +// catalog keep working while inference is refused — so the credential must be +// deactivated rather than cooled, and sibling credentials in the same pool +// should not be hammered during an automated sweep. +type antigravityTOSViolation struct { + AppealURL string + AppealURLText string +} + +// parseAntigravityTOSViolation extracts the TOS_VIOLATION signature from a +// Google RPC error body. It returns nil for any other shape, including +// transient 429 quota errors and non-TOS 403s. +func parseAntigravityTOSViolation(body []byte) *antigravityTOSViolation { + if len(body) == 0 { + return nil + } + code := int(ojson.GetBytesNoCopy(body, "error.code").Int()) + if code != http.StatusForbidden { + return nil + } + status := strings.TrimSpace(ojson.GetBytesNoCopy(body, "error.status").String()) + if !strings.EqualFold(status, "PERMISSION_DENIED") { + return nil + } + details := ojson.GetBytesNoCopy(body, "error.details") + if !details.Exists() || !details.IsArray() { + return nil + } + for _, detail := range details.Array() { + if detail.Get("@type").String() != "type.googleapis.com/google.rpc.ErrorInfo" { + continue + } + reason := strings.TrimSpace(detail.Get("reason").String()) + if !strings.EqualFold(reason, "TOS_VIOLATION") { + continue + } + meta := detail.Get("metadata") + return &antigravityTOSViolation{ + AppealURL: strings.Clone(strings.TrimSpace(meta.Get("appeal_url").String())), + AppealURLText: strings.Clone(strings.TrimSpace(meta.Get("appeal_url_link_text").String())), + } + } + return nil +} + func newAntigravityStatusErr(statusCode int, body []byte) statusErr { err := statusErr{code: statusCode, msg: string(body)} if statusCode == http.StatusTooManyRequests { if retryAfter, parseErr := helps.ParseRetryDelay(body); parseErr == nil && retryAfter != nil { err.retryAfter = retryAfter } + } else if statusCode == http.StatusForbidden { + if violation := parseAntigravityTOSViolation(body); violation != nil { + err.tosViolation = true + err.credentialScoped = true + err.tosAppealURL = violation.AppealURL + err.tosAppealURLText = violation.AppealURLText + } } return err } + +// applyAntigravityTOSState performs the executor-side bookkeeping for a terminal +// TOS_VIOLATION: it arms the optional pool-wide protective pause and logs the +// appeal URL for the operator. The durable credential deactivation and the +// appeal metadata on the auth record are carried by the returned statusErr +// (tos_violation code + Error.Metadata) through the conductor, since the +// executor only sees a cloned auth. It is a no-op for non-TOS errors. +func (e *AntigravityExecutor) applyAntigravityTOSState(cfg *config.Config, auth *cliproxyauth.Auth, body []byte) { + violation := parseAntigravityTOSViolation(body) + if violation == nil || auth == nil { + return + } + markAntigravityTOSPause(cfg, auth) + if violation.AppealURL != "" { + log.Warnf("antigravity executor: credential %s suspended for TOS_VIOLATION; submit appeal: %s (%s)", auth.ID, redactTOSAppealURL(violation.AppealURL), violation.AppealURLText) + } else { + log.Warnf("antigravity executor: credential %s suspended for TOS_VIOLATION", auth.ID) + } +} func (e *AntigravityExecutor) maybeRefreshAntigravityCreditsHint(ctx context.Context, auth *cliproxyauth.Auth, accessToken string) { if e == nil || auth == nil || !antigravityCreditsRetryEnabled(e.cfg) || antigravityCoolingDisabled(auth, e.cfg) { return @@ -798,3 +871,118 @@ func homeKVUnavailableStatusErr(cause error) statusErr { } return statusErr{code: http.StatusServiceUnavailable, msg: fmt.Sprintf("home kv store unavailable: %v", cause)} } + +// antigravityTOSPauseUntil stores the pool-wide protective pause deadline. +// It mirrors the credits/cooldown dual-track pattern: an in-process map for +// standalone mode and the home KV store (prefix cpa:antigravity:*) so the pause +// is shared when the control plane is active. +var antigravityTOSPauseUntil sync.Map + +const antigravityTOSPauseKVKey = "cpa:antigravity:tos-pause:until" + +// antigravityTOSPauseWindow resolves the configured protective pause window. +// Defaults to 6h (community convention from issue #7515); "0", "off", "false", +// or "none" disable the pause entirely. +func antigravityTOSPauseWindow(cfg *config.Config) (time.Duration, bool) { + raw := "6h" + if cfg != nil { + if trimmed := strings.TrimSpace(cfg.Antigravity.TOSPauseWindow); trimmed != "" { + raw = trimmed + } + } + switch strings.ToLower(raw) { + case "0", "off", "false", "none", "disabled": + return 0, false + } + window, err := time.ParseDuration(raw) + if err != nil || window <= 0 { + return 6 * time.Hour, true + } + return window, true +} + +func antigravityTOSPauseKey(auth *cliproxyauth.Auth) string { + if auth == nil { + return "" + } + _ = auth + return "pool" +} + +// markAntigravityTOSPause records a pool-wide protective pause after the first +// TOS_VIOLATION. Only the TOS path calls this; transient 429 quota errors must +// never write or extend the pause. +func markAntigravityTOSPause(cfg *config.Config, auth *cliproxyauth.Auth) { + window, enabled := antigravityTOSPauseWindow(cfg) + if !enabled || window <= 0 { + return + } + until := time.Now().Add(window) + key := antigravityTOSPauseKey(auth) + antigravityTOSPauseUntil.Store(key, until) + if client, homeMode, errClient := currentAntigravityKVClient(); homeMode { + if errClient != nil { + log.Errorf("antigravity executor: home kv tos pause write error: %v", errClient) + return + } + payload := []byte(strconv.FormatInt(until.UnixNano(), 10)) + if _, errSet := client.KVSet(context.Background(), antigravityTOSPauseKVKey, payload, homekv.KVSetOptions{EX: window + 5*time.Second}); errSet != nil { + log.Errorf("antigravity executor: home kv tos pause write error: %v", errSet) + } + } + log.Warnf("antigravity executor: TOS_VIOLATION pause armed for %s (pool-wide until %s)", window, until.Format(time.RFC3339)) +} + +// antigravityInTOSPause reports whether the Antigravity pool is currently under +// a protective TOS pause. The check is provider-scoped (any Antigravity +// credential) and ignores per-credential identity. +func antigravityInTOSPause(cfg *config.Config, auth *cliproxyauth.Auth) bool { + _, enabled := antigravityTOSPauseWindow(cfg) + if !enabled { + return false + } + key := antigravityTOSPauseKey(auth) + if key == "" { + return false + } + now := time.Now() + if value, ok := antigravityTOSPauseUntil.Load(key); ok { + if until, ok := value.(time.Time); ok && until.After(now) { + return true + } + // Delete only if it is still the same expired value; a concurrent + // markAntigravityTOSPause may have already installed a newer deadline. + antigravityTOSPauseUntil.CompareAndDelete(key, value) + } + if client, homeMode, errClient := currentAntigravityKVClient(); homeMode { + if errClient != nil { + log.Errorf("antigravity executor: home kv tos pause read error: %v", errClient) + return false + } + raw, found, errGet := client.KVGet(context.Background(), antigravityTOSPauseKVKey) + if errGet != nil || !found { + return false + } + untilNano, errParse := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64) + if errParse != nil { + return false + } + remaining := time.Unix(0, untilNano).Sub(now) + // An expired deadline is treated as absent; the KV EX ttl reclaims the + // key, so no explicit delete is needed (which could race a concurrent + // markAntigravityTOSPause writing a newer deadline). + return remaining > 0 + } + return false +} + +// redactTOSAppealURL strips query parameters and fragments from an appeal URL +// before logging, so a signed or tracking URL cannot leak through log output. +// The full URL remains available on the auth record for operator use. +func redactTOSAppealURL(raw string) string { + trimmed := strings.TrimSpace(raw) + if idx := strings.IndexAny(trimmed, "?#"); idx >= 0 { + trimmed = trimmed[:idx] + } + return trimmed +} diff --git a/internal/runtime/executor/antigravity_executor_credits_test.go b/internal/runtime/executor/antigravity_executor_credits_test.go index 98c45a1ca62..c19c0ad79ef 100644 --- a/internal/runtime/executor/antigravity_executor_credits_test.go +++ b/internal/runtime/executor/antigravity_executor_credits_test.go @@ -29,6 +29,7 @@ import ( // may still be writing these maps when a test's cleanup runs. Replacing the // variable is an unsynchronized write and races with them; Clear is not. func resetAntigravityCreditsRetryState() { + antigravityTOSPauseUntil.Clear() antigravityCreditsFailureByAuth.Clear() antigravityShortCooldownByAuth.Clear() antigravityCreditsBalanceByAuth.Clear() diff --git a/internal/runtime/executor/antigravity_executor_execute.go b/internal/runtime/executor/antigravity_executor_execute.go index bb7ab2fcce4..114d6e363df 100644 --- a/internal/runtime/executor/antigravity_executor_execute.go +++ b/internal/runtime/executor/antigravity_executor_execute.go @@ -44,6 +44,9 @@ func (e *AntigravityExecutor) Execute(ctx context.Context, auth *cliproxyauth.Au return e.executeCompaction(ctx, auth, req, opts) } baseModel := thinking.ParseSuffix(req.Model).ModelName + if antigravityInTOSPause(e.cfg, auth) { + return resp, statusErr{code: http.StatusServiceUnavailable, msg: "antigravity pool paused after TOS_VIOLATION"} + } if !antigravityCoolingDisabled(auth, e.cfg) { if inCooldown, remaining, errCooldown := antigravityIsInShortCooldownRequired(ctx, auth, baseModel, time.Now()); errCooldown != nil { return resp, homeKVUnavailableStatusErr(errCooldown) @@ -152,12 +155,12 @@ func (e *AntigravityExecutor) Execute(ctx context.Context, auth *cliproxyauth.Au if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("antigravity executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) err = errRead return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes) if httpResp.StatusCode == http.StatusTooManyRequests { decision := decideAntigravity429(bodyBytes) @@ -186,6 +189,9 @@ func (e *AntigravityExecutor) Execute(ctx context.Context, auth *cliproxyauth.Au // Report the upstream failure rather than the cleanup failure. logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) } + if httpResp.StatusCode == http.StatusForbidden { + e.applyAntigravityTOSState(e.cfg, auth, bodyBytes) + } err = newAntigravityStatusErr(httpResp.StatusCode, bodyBytes) return resp, err } @@ -194,17 +200,32 @@ func (e *AntigravityExecutor) Execute(ctx context.Context, auth *cliproxyauth.Au if useCredits { clearAntigravityCreditsFailureState(auth) } + reporter.ObserveResponseModel(bodyBytes) + if _, zeroErrMsg, zeroOutput := helps.CheckGeminiZeroOutputNonStream(responseFormat, bodyBytes, true); zeroOutput { + antiDetail := helps.ParseAntigravityUsage(bodyBytes) + helps.ApplyGeminiRequestImageConfig(&antiDetail, requestPayload) + err = statusErr{code: http.StatusBadGateway, msg: zeroErrMsg} + helps.RecordAPIResponseError(ctx, e.cfg, err) + reporter.PublishFailureWithDetail(ctx, antiDetail, err) + return cliproxyexecutor.Response{}, err + } if len(replayRequestPayload) == 0 { replayRequestPayload = requestPayload } cacheAntigravityReasoningReplayFromResponse(ctx, replayScope, replayRequestPayload, bodyBytes) bodyBytes = e.resolveWebSearchGroundingURLs(ctx, auth, from, originalPayload, translated, bodyBytes) - reporter.ObserveResponseModel(bodyBytes) var param any converted := sdktranslator.TranslateNonStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, bodyBytes, ¶m) if helps.ApplyPatchTranslationError(param) != nil || len(converted) == 0 { return cliproxyexecutor.Response{}, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} } + if errPayload, okErr := helps.TranslatedClaudeErrorPayload(responseFormat, converted); okErr { + err = statusErr{code: http.StatusBadGateway, msg: errPayload} + antiDetail := helps.ParseAntigravityUsage(bodyBytes) + helps.ApplyGeminiRequestImageConfig(&antiDetail, requestPayload) + reporter.PublishFailureWithDetail(ctx, antiDetail, err) + return cliproxyexecutor.Response{}, err + } antiDetail := helps.ParseAntigravityUsage(bodyBytes) helps.ApplyGeminiRequestImageConfig(&antiDetail, requestPayload) reporter.Publish(ctx, antiDetail) @@ -270,6 +291,9 @@ func (e *AntigravityExecutor) executeCompaction(ctx context.Context, auth *clipr // executeClaudeNonStream performs a claude non-streaming request to the Antigravity API. func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { baseModel := thinking.ParseSuffix(req.Model).ModelName + if antigravityInTOSPause(e.cfg, auth) { + return resp, statusErr{code: http.StatusServiceUnavailable, msg: "antigravity pool paused after TOS_VIOLATION"} + } if !antigravityCoolingDisabled(auth, e.cfg) { if inCooldown, remaining, errCooldown := antigravityIsInShortCooldownRequired(ctx, auth, baseModel, time.Now()); errCooldown != nil { return resp, homeKVUnavailableStatusErr(errCooldown) @@ -373,6 +397,7 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("antigravity executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) if errors.Is(errRead, context.Canceled) || errors.Is(errRead, context.DeadlineExceeded) { @@ -386,7 +411,6 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * err = errRead return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes) if httpResp.StatusCode == http.StatusTooManyRequests { decision := decideAntigravity429(bodyBytes) @@ -413,6 +437,9 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * // Report the upstream failure rather than the cleanup failure. logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) } + if httpResp.StatusCode == http.StatusForbidden { + e.applyAntigravityTOSState(e.cfg, auth, bodyBytes) + } err = newAntigravityStatusErr(httpResp.StatusCode, bodyBytes) return resp, err } @@ -428,6 +455,7 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * var rawPayloads [][]byte var pendingFilterPayload []byte var pendingFilterMsg string + var pendingJSON []byte scanner := bufio.NewScanner(httpResp.Body) scanner.Buffer(nil, streamScannerBuffer) for scanner.Scan() { @@ -437,9 +465,47 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * replayAccumulator.ObserveSSELine(line) } payload := helps.JSONPayload(line) + if len(pendingJSON) > 0 { + // Reassemble a logical SSE event whose JSON is split across multiple + // data: lines before classification; a TOS error object may span + // lines and must not be swallowed line-by-line. + trimmedLine := bytes.TrimSpace(line) + if bytes.HasPrefix(trimmedLine, []byte("data:")) { + trimmedLine = bytes.TrimSpace(trimmedLine[len("data:"):]) + } + if len(trimmedLine) > 0 { + pendingJSON = append(pendingJSON, 10) + pendingJSON = append(pendingJSON, trimmedLine...) + } + if !ojson.ValidBytes(pendingJSON) { + continue + } + payload = pendingJSON + pendingJSON = nil + } else if payload != nil && !ojson.ValidBytes(payload) { + pendingJSON = append([]byte(nil), payload...) + continue + } if payload == nil { continue } + // A mid-stream error frame can still carry the TOS_VIOLATION signature on + // HTTP 200; surface it as a terminal credential error before it degrades + // into a generic empty-output failure so the credential is deactivated + // and the pool pause armed. + if errorResult := ojson.GetBytesNoCopy(payload, "error"); errorResult.Exists() { + tosCode := int(errorResult.Get("code").Int()) + if tosCode == http.StatusForbidden { + e.applyAntigravityTOSState(e.cfg, auth, payload) + if errClose := httpResp.Body.Close(); errClose != nil { + log.Errorf("antigravity executor: close response body error: %v", errClose) + } + err = newAntigravityStatusErr(tosCode, payload) + helps.RecordAPIResponseError(ctx, e.cfg, err) + reporter.PublishFailure(ctx, err) + return resp, err + } + } if len(pendingFilterPayload) > 0 { reporter.ObserveResponseModel(pendingFilterPayload) rawPayloads = append(rawPayloads, pendingFilterPayload) @@ -469,10 +535,20 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * reporter.PublishFailure(ctx, filterErr) return resp, filterErr } + aggregatedPayload := e.convertStreamChunksToNonStream(rawPayloads) + reporter.ObserveResponseModel(aggregatedPayload) + if _, zeroErrMsg, zeroOutput := helps.CheckGeminiZeroOutputNonStream(responseFormat, aggregatedPayload, true); zeroOutput { + antiDetail := helps.ParseAntigravityUsage(aggregatedPayload) + helps.ApplyGeminiRequestImageConfig(&antiDetail, requestPayload) + err = statusErr{code: http.StatusBadGateway, msg: zeroErrMsg} + helps.RecordAPIResponseError(ctx, e.cfg, err) + reporter.PublishFailureWithDetail(ctx, antiDetail, err) + return cliproxyexecutor.Response{}, err + } if replayAccumulator != nil { replayAccumulator.Commit(ctx) } - resp = cliproxyexecutor.Response{Payload: e.convertStreamChunksToNonStream(rawPayloads)} + resp = cliproxyexecutor.Response{Payload: aggregatedPayload} resp.Payload = e.resolveWebSearchGroundingURLs(ctx, auth, from, originalPayload, translated, resp.Payload) reporter.ObserveResponseModel(resp.Payload) @@ -481,6 +557,13 @@ func (e *AntigravityExecutor) executeClaudeNonStream(ctx context.Context, auth * if helps.ApplyPatchTranslationError(param) != nil || len(converted) == 0 { return cliproxyexecutor.Response{}, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} } + if errPayload, okErr := helps.TranslatedClaudeErrorPayload(responseFormat, converted); okErr { + err = statusErr{code: http.StatusBadGateway, msg: errPayload} + antiDetail := helps.ParseAntigravityUsage(resp.Payload) + helps.ApplyGeminiRequestImageConfig(&antiDetail, requestPayload) + reporter.PublishFailureWithDetail(ctx, antiDetail, err) + return cliproxyexecutor.Response{}, err + } antiDetail := helps.ParseAntigravityUsage(resp.Payload) helps.ApplyGeminiRequestImageConfig(&antiDetail, requestPayload) reporter.Publish(ctx, antiDetail) @@ -597,6 +680,9 @@ func (e *AntigravityExecutor) convertStreamChunksToNonStream(chunks [][]byte) [] if root.Get("candidates").Exists() { responseNode = root } else { + if usageMetadataResult := root.Get("usageMetadata"); usageMetadataResult.Exists() { + usageRaw = usageMetadataResult.Raw + } continue } } diff --git a/internal/runtime/executor/antigravity_executor_request.go b/internal/runtime/executor/antigravity_executor_request.go index 2a7df38a20f..0516d09fc27 100644 --- a/internal/runtime/executor/antigravity_executor_request.go +++ b/internal/runtime/executor/antigravity_executor_request.go @@ -782,14 +782,22 @@ func generateSessionID() string { } func generateStableSessionID(payload []byte) string { - return generateStableSessionIDFromContents(util.GetGJSONBytesNoCopy(payload, "request.contents")) + contents := util.GetGJSONBytesNoCopy(payload, "request.contents") + if !contents.IsArray() { + contents = util.GetGJSONBytesNoCopy(payload, "contents") + } + return generateStableSessionIDFromContents(contents) } func generateStableSessionIDDoc(doc *ojson.Doc) string { if doc == nil { return generateSessionID() } - return generateStableSessionIDFromContents(doc.Get("request.contents")) + contents := doc.Get("request.contents") + if !contents.IsArray() { + contents = doc.Get("contents") + } + return generateStableSessionIDFromContents(contents) } func generateStableSessionIDFromContents(contents ojson.Result) string { diff --git a/internal/runtime/executor/antigravity_executor_signature_test.go b/internal/runtime/executor/antigravity_executor_signature_test.go index bca7bc24bfe..9de06e68eca 100644 --- a/internal/runtime/executor/antigravity_executor_signature_test.go +++ b/internal/runtime/executor/antigravity_executor_signature_test.go @@ -236,8 +236,8 @@ func TestAntigravitySensitiveWordsObfuscatesSystemInstructionOnly(t *testing.T) payload := []byte(`{"request":{"systemInstruction":{"parts":[{"text":"Use proxy safely"}]},"contents":[{"role":"user","parts":[{"text":"proxy remains unchanged"}]}]}}`) got := executor.obfuscateSensitiveWords(payload) - if systemText := ojson.GetBytes(got, "request.systemInstruction.parts.0.text").String(); systemText != "Use p\u200Broxy safely" { - t.Fatalf("system instruction = %q, want zero-width obfuscation", systemText) + if systemText := ojson.GetBytes(got, "request.systemInstruction.parts.0.text").String(); systemText != "Use p\u034Froxy safely" { + t.Fatalf("system instruction = %q, want CGJ obfuscation", systemText) } if contentText := ojson.GetBytes(got, "request.contents.0.parts.0.text").String(); contentText != "proxy remains unchanged" { t.Fatalf("content text = %q, want unchanged", contentText) @@ -288,12 +288,211 @@ func TestAntigravityStreamObfuscatesSensitiveSystemInstruction(t *testing.T) { body := <-captured got := ojson.GetBytes(body, "request.systemInstruction.parts.0.text").String() - want := "You are H\u200Bermes Agent, an intelligent AI assistant created by N\u200Bous Research." + want := "You are H\u034Fermes Agent, an intelligent AI assistant created by N\u034Fous R\u034Fesearch." if got != want { t.Fatalf("system instruction = %q, want %q; body=%s", got, want, body) } } +func TestAntigravityExecuteObfuscatesCodexIdentityWithCGJ(t *testing.T) { + captured := make(chan []byte, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read request body: %v", errRead) + return + } + captured <- body + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"OK"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":1,"totalTokenCount":11}}}`)) + })) + defer server.Close() + + executor := NewAntigravityExecutor(&config.Config{ + Antigravity: config.AntigravityConfig{SensitiveWords: []string{"codex", "GPT-5"}}, + RequestRetry: 1, + }) + auth := &cliproxyauth.Auth{ + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: false, + } + + cases := []struct { + name string + payload string + }{ + { + name: "instructions_field", + payload: `{"model":"gemini-4-carbon-high","instructions":"You are Codex, an agent based on GPT-5.","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Reply only OK."}]}],"max_output_tokens":128,"stream":false}`, + }, + { + name: "initial_developer_message", + payload: `{"model":"gemini-4-carbon-high","input":[{"type":"message","role":"developer","content":[{"type":"input_text","text":"You are Codex, an agent based on GPT-5."}]},{"type":"message","role":"user","content":[{"type":"input_text","text":"Reply only OK."}]}],"max_output_tokens":128,"stream":false}`, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, errExec := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-carbon-high", + Payload: []byte(tc.payload), + }, opts) + if errExec != nil { + t.Fatalf("Execute() error = %v", errExec) + } + body := <-captured + got := ojson.GetBytes(body, "request.systemInstruction.parts.0.text").String() + want := "You are C\u034Fodex, an agent based on G\u034FPT-5." + if got != want { + t.Fatalf("systemInstruction = %q, want %q", got, want) + } + if strings.Contains(got, "\u200B") { + t.Fatalf("systemInstruction = %q, must not use U+200B", got) + } + }) + } +} + +func TestAntigravitySensitiveWordsReplaceFromYAML(t *testing.T) { + cfg, errParse := config.ParseConfigBytes([]byte(`antigravity: + sensitive-words: + - "Codex" + - "GPT-5" + sensitive-words-replace: + "You are Codex, an agent based on GPT-5.": "You are a helpful coding assistant." +`)) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + executor := NewAntigravityExecutor(cfg) + payload := []byte(`{"request":{"systemInstruction":{"parts":[{"text":"You are Codex, an agent based on GPT-5. Avoid mentioning Codex."}]},"contents":[{"role":"user","parts":[{"text":"You are Codex, an agent based on GPT-5."}]}]}}`) + + got := executor.obfuscateSensitiveWords(payload) + systemText := ojson.GetBytes(got, "request.systemInstruction.parts.0.text").String() + wantSystem := "You are a helpful coding assistant. Avoid mentioning C\u034Fodex." + if systemText != wantSystem { + t.Fatalf("systemInstruction = %q, want %q", systemText, wantSystem) + } + contentText := ojson.GetBytes(got, "request.contents.0.parts.0.text").String() + if contentText != "You are Codex, an agent based on GPT-5." { + t.Fatalf("contents = %q, want unchanged", contentText) + } +} + +func TestAntigravitySensitivePatternsReplaceFromYAML(t *testing.T) { + cfg, errParse := config.ParseConfigBytes([]byte(`antigravity: + sensitive-words: + - "omp" + - "RFC 2119" + sensitive-patterns-replace: + - pattern: '(?m)^RFC 2119[^\n]*\n?' + replacement: "" + - pattern: '(?s).*?\n?' + replacement: "" + - pattern: '(?m)^You are omp[^\n]*\n?' + replacement: "" +`)) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + executor := NewAntigravityExecutor(cfg) + payload := []byte(`{"request":{"systemInstruction":{"parts":[{"text":"You are omp's trusted coding assistant.\nRFC 2119 keywords: MUST, REQUIRED.\n\nRFC 2119 applies.\n\nKeep this instruction for omp."}]},"contents":[{"role":"user","parts":[{"text":"You are omp's trusted coding assistant."}]}]}}`) + + got := executor.obfuscateSensitiveWords(payload) + systemText := ojson.GetBytes(got, "request.systemInstruction.parts.0.text").String() + wantSystem := "Keep this instruction for o\u034Fmp." + if systemText != wantSystem { + t.Fatalf("systemInstruction = %q, want %q", systemText, wantSystem) + } + contentText := ojson.GetBytes(got, "request.contents.0.parts.0.text").String() + if contentText != "You are omp's trusted coding assistant." { + t.Fatalf("contents = %q, want unchanged", contentText) + } +} + +func TestAntigravitySensitiveWordsReplaceOnlyPreservesToolsAndCountTokens(t *testing.T) { + captured := make(chan []byte, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read request body: %v", errRead) + return + } + captured <- body + w.Header().Set("Content-Type", "application/json") + if strings.Contains(r.URL.Path, "countTokens") { + _, _ = w.Write([]byte(`{"totalTokens":42}`)) + return + } + _, _ = w.Write([]byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"OK"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":1,"totalTokenCount":11}}}`)) + })) + defer server.Close() + + cfg := &config.Config{ + Antigravity: config.AntigravityConfig{ + SensitiveWordsReplace: map[string]string{ + "You are Codex, an agent based on GPT-5.": "You are a helpful coding assistant.", + }, + }, + RequestRetry: 1, + } + executor := NewAntigravityExecutor(cfg) + m1 := executor.getSensitiveWordMatcher() + m2 := executor.getSensitiveWordMatcher() + if m1 == nil || m1 != m2 { + t.Fatal("expected cached matcher reuse when replacements are unchanged") + } + + auth := &cliproxyauth.Auth{ + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + req := cliproxyexecutor.Request{ + Model: "gemini-4-carbon-high", + Payload: []byte(`{"model":"gemini-4-carbon-high","instructions":"You are Codex, an agent based on GPT-5. Keep extra instructions intact.","tools":[{"type":"function","name":"run_codex_check","description":"Codex diagnostic tool","parameters":{"type":"object","properties":{"q":{"type":"string"}}}}],"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"You are Codex, an agent based on GPT-5."}]}],"max_output_tokens":128,"stream":false}`), + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + } + + if _, errExec := executor.Execute(context.Background(), auth, req, opts); errExec != nil { + t.Fatalf("Execute() error = %v", errExec) + } + execBody := <-captured + wantInstruction := "You are a helpful coding assistant. Keep extra instructions intact." + if got := ojson.GetBytes(execBody, "request.systemInstruction.parts.0.text").String(); got != wantInstruction { + t.Fatalf("Execute systemInstruction = %q, want %q", got, wantInstruction) + } + if gotToolDesc := ojson.GetBytes(execBody, "request.tools.0.functionDeclarations.0.description").String(); gotToolDesc != "Codex diagnostic tool" { + t.Fatalf("tool description = %q, want unchanged", gotToolDesc) + } + if gotUser := ojson.GetBytes(execBody, "request.contents.0.parts.0.text").String(); gotUser != "You are Codex, an agent based on GPT-5." { + t.Fatalf("user content = %q, want unchanged", gotUser) + } + + if _, errCount := executor.CountTokens(context.Background(), auth, req, opts); errCount != nil { + t.Fatalf("CountTokens() error = %v", errCount) + } + countBody := <-captured + if got := ojson.GetBytes(countBody, "request.systemInstruction.parts.0.text").String(); got != wantInstruction { + t.Fatalf("CountTokens systemInstruction = %q, want %q", got, wantInstruction) + } +} + func TestAntigravityStreamDoesNotEmitSyntheticTerminalOnReadError(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/event-stream") diff --git a/internal/runtime/executor/antigravity_executor_stream.go b/internal/runtime/executor/antigravity_executor_stream.go index 9be7ccf93ce..9b0fb5b4606 100644 --- a/internal/runtime/executor/antigravity_executor_stream.go +++ b/internal/runtime/executor/antigravity_executor_stream.go @@ -47,6 +47,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya } baseModel := thinking.ParseSuffix(req.Model).ModelName + if antigravityInTOSPause(e.cfg, auth) { + return nil, statusErr{code: http.StatusServiceUnavailable, msg: "antigravity pool paused after TOS_VIOLATION"} + } ctx = context.WithValue(ctx, "alt", "") if !antigravityCoolingDisabled(auth, e.cfg) { if inCooldown, remaining, errCooldown := antigravityIsInShortCooldownRequired(ctx, auth, baseModel, time.Now()); errCooldown != nil { @@ -151,6 +154,7 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("antigravity executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) if errors.Is(errRead, context.Canceled) || errors.Is(errRead, context.DeadlineExceeded) { @@ -164,7 +168,6 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya err = errRead return nil, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes) if httpResp.StatusCode == http.StatusTooManyRequests { decision := decideAntigravity429(bodyBytes) @@ -191,6 +194,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya // Report the upstream failure rather than the cleanup failure. logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) } + if httpResp.StatusCode == http.StatusForbidden { + e.applyAntigravityTOSState(e.cfg, auth, bodyBytes) + } err = newAntigravityStatusErr(httpResp.StatusCode, bodyBytes) return nil, err } @@ -217,12 +223,14 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya var streamUsage helps.StreamUsageBuffer streamUsage.SetRequestPayload(requestPayload) var streamErr error + var translatedClaudeErr error + var translatedErrorStopped bool var pendingJSON []byte var replayCommitted bool var terminalDelivered bool var param any commitReplay := func() { - if !replayCommitted && replayAccumulator != nil && replayAccumulator.terminal && helps.ApplyPatchTranslationError(param) == nil { + if !replayCommitted && replayAccumulator != nil && replayAccumulator.terminal && streamErr == nil && translatedClaudeErr == nil && helps.ApplyPatchTranslationError(param) == nil { replayAccumulator.Commit(ctx) replayCommitted = true } @@ -239,6 +247,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya commitReplay() } close(out) + if translatedErrorStopped { + return + } if streamErr == nil { streamErr = ctx.Err() } @@ -264,6 +275,21 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya }() var pendingFilterPayload []byte var pendingFilterMsg string + zeroOutputGuard := helps.NewGeminiZeroOutputStreamGuard(true, responseFormat) + failZeroOutput := func(finishReason string) bool { + translatedClaudeErr = nil + streamErr = statusErr{code: http.StatusBadGateway, msg: helps.GeminiZeroOutputErrorMessage(responseFormat, finishReason)} + stopDeliverySupport() + helps.RecordAPIResponseError(ctx, e.cfg, streamErr) + if !streamUsage.PublishFailure(ctx, reporter, streamErr) { + reporter.PublishFailure(ctx, streamErr) + } + select { + case out <- cliproxyexecutor.StreamChunk{Err: streamErr}: + case <-ctx.Done(): + } + return false + } helps.InitializeApplyPatchStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, ¶m) for scanner.Scan() { line := scanner.Bytes() @@ -302,6 +328,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya if statusCode < http.StatusBadRequest || statusCode > 599 { statusCode = http.StatusBadGateway } + if statusCode == http.StatusForbidden { + e.applyAntigravityTOSState(e.cfg, auth, payload) + } streamErr = newAntigravityStatusErr(statusCode, payload) stopDeliverySupport() helps.RecordAPIResponseError(ctx, e.cfg, streamErr) @@ -311,7 +340,7 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya } return } - processPayload := func(p []byte) bool { + emitTranslatedPayload := func(p []byte) bool { // Filter usage metadata for all models after block classification // so only the terminal chunk retains client-visible usage statistics. p = helps.JSONPayload(helps.FilterSSEUsageMetadata(append([]byte("data: "), p...))) @@ -323,6 +352,9 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya p = e.resolveWebSearchGroundingURLs(ctx, auth, from, originalPayload, translated, p) chunks := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, bytes.Clone(p), ¶m, claudeInputTokens) helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + helps.CaptureTranslatedClaudeStreamError(responseFormat, chunks, &translatedClaudeErr, func(msg string) error { + return statusErr{code: http.StatusBadGateway, msg: msg} + }) var isTerminalChunk bool if finishReason := ojson.GetBytesNoCopy(p, "candidates.0.finishReason"); finishReason.Exists() && strings.TrimSpace(finishReason.String()) != "" { isTerminalChunk = true @@ -358,27 +390,49 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya } } } - if replayAccumulator != nil && replayAccumulator.terminal && !replayCommitted && responseFormat == sdktranslator.FormatOpenAIResponse { - for _, chunk := range chunks { - for _, line := range bytes.Split(chunk, []byte("\n")) { - if ojson.GetBytesNoCopy(helps.JSONPayload(line), "type").String() == "response.completed" { - commitReplay() - } - } - } + if replayAccumulator != nil && replayAccumulator.terminal && !replayCommitted && translatedClaudeErr == nil && antigravityStreamChunksHaveTerminalCommitEvent(chunks) { + commitReplay() } for i := range chunks { select { case out <- cliproxyexecutor.StreamChunk{Payload: chunks[i]}: + if len(chunks[i]) > 0 { + zeroOutputGuard.MarkEmitted() + } case <-ctx.Done(): return false } } - if isTerminalChunk { + if isTerminalChunk && translatedClaudeErr == nil { terminalDelivered = true } return !helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) } + processPayload := func(p []byte) bool { + shells, action, finishReason := zeroOutputGuard.Observe(p) + switch action { + case helps.GeminiZeroOutputContinue: + return true + case helps.GeminiZeroOutputFailNow: + return failZeroOutput(finishReason) + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = p + } + if !emitTranslatedPayload(errFrame) { + return false + } + return failZeroOutput(finishReason) + default: + for _, shell := range shells { + if !emitTranslatedPayload(shell) { + return false + } + } + return emitTranslatedPayload(p) + } + } if len(pendingFilterPayload) > 0 { flushed := pendingFilterPayload pendingFilterPayload = nil @@ -406,9 +460,33 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya } return } + if scanner.Err() == nil && ctx.Err() == nil && zeroOutputGuard.HasAbnormalFinish() { + _, action, finishReason := zeroOutputGuard.Finalize() + if action == helps.GeminiZeroOutputEmitErrorThenFail { + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + tailErr := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, errFrame, ¶m, claudeInputTokens) + for i := range tailErr { + select { + case out <- cliproxyexecutor.StreamChunk{Payload: tailErr[i]}: + case <-ctx.Done(): + return + } + } + } + failZeroOutput(finishReason) + return + } if helps.EndApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return } + if helps.StopTranslatedClaudeStream(ctx, &translatedClaudeErr, reporter, &streamUsage, out) { + stopDeliverySupport() + translatedErrorStopped = true + return + } if errScan := scanner.Err(); errScan != nil { streamErr = errScan if errors.Is(errScan, context.Canceled) && ctx.Err() != nil { @@ -426,6 +504,44 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya case <-ctx.Done(): } } else if ctx.Err() == nil { + shells, action, finishReason := zeroOutputGuard.Finalize() + switch action { + case helps.GeminiZeroOutputFailNow: + failZeroOutput(finishReason) + return + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + tailErr := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, errFrame, ¶m, claudeInputTokens) + for i := range tailErr { + select { + case out <- cliproxyexecutor.StreamChunk{Payload: tailErr[i]}: + case <-ctx.Done(): + return + } + } + failZeroOutput(finishReason) + return + default: + for _, shell := range shells { + shellFiltered := helps.JSONPayload(helps.FilterSSEUsageMetadata(append([]byte("data: "), shell...))) + if len(shellFiltered) == 0 { + continue + } + reporter.ObserveResponseModel(shellFiltered) + shellFiltered = e.resolveWebSearchGroundingURLs(ctx, auth, from, originalPayload, translated, shellFiltered) + shellChunks := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, bytes.Clone(shellFiltered), ¶m, claudeInputTokens) + for i := range shellChunks { + select { + case out <- cliproxyexecutor.StreamChunk{Payload: shellChunks[i]}: + case <-ctx.Done(): + return + } + } + } + } // Only a clean end of stream may produce a synthetic terminal event. // Translating [DONE] after a read error would report a truncated // stream as a successful completion. A clean EOF is a normal end @@ -433,9 +549,14 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya // end that way (see antigravityNoFinishReasonSSE). tail := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), translated, []byte("[DONE]"), ¶m, claudeInputTokens) helps.RecordApplyPatchStreamFailure(ctx, param, reporter, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) + helps.CaptureTranslatedClaudeStreamError(responseFormat, tail, &translatedClaudeErr, func(msg string) error { + return statusErr{code: http.StatusBadGateway, msg: msg} + }) // Commit upstream output before EOF-generated completion reaches interceptors. // Commit itself rejects partial streams without an upstream terminal. - commitReplay() + if translatedClaudeErr == nil { + commitReplay() + } for i := range tail { select { case out <- cliproxyexecutor.StreamChunk{Payload: tail[i]}: @@ -443,6 +564,11 @@ func (e *AntigravityExecutor) ExecuteStream(ctx context.Context, auth *cliproxya return } } + if helps.StopTranslatedClaudeStream(ctx, &translatedClaudeErr, reporter, &streamUsage, out) { + stopDeliverySupport() + translatedErrorStopped = true + return + } terminalDelivered = true } }(httpResp) diff --git a/internal/runtime/executor/antigravity_executor_tokens.go b/internal/runtime/executor/antigravity_executor_tokens.go index a076b45537a..e696c644e52 100644 --- a/internal/runtime/executor/antigravity_executor_tokens.go +++ b/internal/runtime/executor/antigravity_executor_tokens.go @@ -21,6 +21,9 @@ import ( // CountTokens counts tokens for the given request using the Antigravity API. func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { baseModel := thinking.ParseSuffix(req.Model).ModelName + if antigravityInTOSPause(e.cfg, auth) { + return cliproxyexecutor.Response{}, statusErr{code: http.StatusServiceUnavailable, msg: "antigravity pool paused after TOS_VIOLATION"} + } from := opts.SourceFormat responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) @@ -66,7 +69,7 @@ func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyaut e.obfuscateSensitiveWordsDoc(doc) helps.PrepareAntigravityClaudeStructuredOutputDoc(baseModel, doc) sanitizeAntigravityGeminiRequestSignaturesDoc(baseModel, doc) - if _, _, errReplay := prepareAntigravityGeminiReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc); errReplay != nil { + if _, errReplay := prepareAntigravityGeminiCountTokensReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc); errReplay != nil { return cliproxyexecutor.Response{}, errReplay } ensureAntigravityGeminiLeadingUserContentDoc(baseModel, doc) @@ -140,11 +143,11 @@ func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyaut if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("antigravity executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return cliproxyexecutor.Response{}, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, bodyBytes) if httpResp.StatusCode >= http.StatusOK && httpResp.StatusCode < http.StatusMultipleChoices { count := ojson.GetBytesNoCopy(bodyBytes, "totalTokens").Int() @@ -152,7 +155,10 @@ func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyaut return cliproxyexecutor.Response{Payload: translated, Headers: httpResp.Header.Clone()}, nil } - sErr := statusErr{code: httpResp.StatusCode, msg: string(bodyBytes)} + if httpResp.StatusCode == http.StatusForbidden { + e.applyAntigravityTOSState(e.cfg, auth, bodyBytes) + } + sErr := newAntigravityStatusErr(httpResp.StatusCode, bodyBytes) if httpResp.StatusCode == http.StatusTooManyRequests { closeAntigravityAuthIdleTransports(auth) if retryAfter, parseErr := helps.ParseRetryDelay(bodyBytes); parseErr == nil && retryAfter != nil { diff --git a/internal/runtime/executor/antigravity_executor_tos_test.go b/internal/runtime/executor/antigravity_executor_tos_test.go new file mode 100644 index 00000000000..800066b046d --- /dev/null +++ b/internal/runtime/executor/antigravity_executor_tos_test.go @@ -0,0 +1,241 @@ +package executor + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +// antigravityTOSBody reproduces the verbatim 403 PERMISSION_DENIED signature from +// issue #7296/#7515: a service-scoped Terms-of-Service suspension carrying an +// ErrorInfo reason=TOS_VIOLATION plus appeal metadata. +const antigravityTOSBody = `{ + "error": { + "code": 403, + "message": "This service has been disabled in this account for violation of Terms of Service. Please submit an appeal to continue using this product.", + "status": "PERMISSION_DENIED", + "details": [ + { + "@type": "type.googleapis.com/google.rpc.ErrorInfo", + "reason": "TOS_VIOLATION", + "domain": "cloudcode-pa.googleapis.com", + "metadata": { + "uiMessage": "true", + "appeal_url": "https://forms.gle/hGzM9MEUv2azZsrb9", + "appeal_url_link_text": "Submit Appeal" + } + } + ] + } +}` + +func TestAntigravityTOSViolationParsing(t *testing.T) { + t.Run("matches verbatim tos signature and extracts appeal url", func(t *testing.T) { + violation := parseAntigravityTOSViolation([]byte(antigravityTOSBody)) + if violation == nil { + t.Fatal("parseAntigravityTOSViolation() = nil, want TOS violation match") + } + if violation.AppealURL != "https://forms.gle/hGzM9MEUv2azZsrb9" { + t.Fatalf("AppealURL = %q, want %q", violation.AppealURL, "https://forms.gle/hGzM9MEUv2azZsrb9") + } + if violation.AppealURLText != "Submit Appeal" { + t.Fatalf("AppealURLText = %q, want %q", violation.AppealURLText, "Submit Appeal") + } + }) + + t.Run("does not match plain 403 permission denied without tos reason", func(t *testing.T) { + body := `{"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"SOME_OTHER_REASON"}]}}` + if violation := parseAntigravityTOSViolation([]byte(body)); violation != nil { + t.Fatalf("parseAntigravityTOSViolation() = %+v, want nil for non-TOS 403", violation) + } + }) + + t.Run("does not match 429 resource exhausted", func(t *testing.T) { + body := `{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"RATE_LIMIT_EXCEEDED"}]}}` + if violation := parseAntigravityTOSViolation([]byte(body)); violation != nil { + t.Fatalf("parseAntigravityTOSViolation() = %+v, want nil for 429", violation) + } + }) + + t.Run("does not match empty or invalid body", func(t *testing.T) { + if violation := parseAntigravityTOSViolation(nil); violation != nil { + t.Fatalf("parseAntigravityTOSViolation(nil) = %+v, want nil", violation) + } + if violation := parseAntigravityTOSViolation([]byte("not json")); violation != nil { + t.Fatalf("parseAntigravityTOSViolation(invalid) = %+v, want nil", violation) + } + }) +} + +func TestAntigravityTOSStatusErrTerminal(t *testing.T) { + err := newAntigravityStatusErr(403, []byte(antigravityTOSBody)) + if !err.credentialScoped { + t.Fatal("newAntigravityStatusErr(TOS).credentialScoped = false, want true (terminal credential state)") + } +} + +func TestAntigravityTOSPoolPause(t *testing.T) { + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + cfg := &config.Config{} + // default 6h window + auth := &cliproxyauth.Auth{ID: "tos-auth", Provider: "antigravity"} + + if antigravityInTOSPause(cfg, auth) { + t.Fatal("antigravityInTOSPause() = true before any TOS violation") + } + markAntigravityTOSPause(cfg, auth) + if !antigravityInTOSPause(cfg, auth) { + t.Fatal("antigravityInTOSPause() = false after TOS violation, want pool-wide pause") + } + // A different auth in the same pool must also be paused. + other := &cliproxyauth.Auth{ID: "sibling-auth", Provider: "antigravity"} + if !antigravityInTOSPause(cfg, other) { + t.Fatal("antigravityInTOSPause() = false for sibling credential, want pool-wide pause") + } + + // A 429 quota result must never create or extend the pause. + antigravityTOSPauseUntil.Clear() + decision := decideAntigravity429([]byte(`{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"RATE_LIMIT_EXCEEDED"},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"0.5s"}]}}`)) + if decision.kind == antigravity429DecisionFullQuotaExhausted { + t.Fatalf("decideAntigravity429() = %q, want transient rate-limit decision", decision.kind) + } + if antigravityInTOSPause(cfg, auth) { + t.Fatal("antigravityInTOSPause() = true after 429-only handling, want no pause") + } +} + +func TestAntigravityTOSPauseWindowConfigurable(t *testing.T) { + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + // A disabled (zero) window must not pause the pool. + disabled := &config.Config{} + disabled.Antigravity.TOSPauseWindow = "0" + auth := &cliproxyauth.Auth{ID: "tos-auth", Provider: "antigravity"} + markAntigravityTOSPause(disabled, auth) + if antigravityInTOSPause(disabled, auth) { + t.Fatal("antigravityInTOSPause() = true with window disabled, want no pause") + } + + // A custom window must be honored. + custom := &config.Config{} + custom.Antigravity.TOSPauseWindow = "2h" + markAntigravityTOSPause(custom, auth) + if !antigravityInTOSPause(custom, auth) { + t.Fatal("antigravityInTOSPause() = false with custom 2h window, want pause") + } +} + +func TestAntigravityTOSErrorCarriesTerminalMarker(t *testing.T) { + err := newAntigravityStatusErr(403, []byte(antigravityTOSBody)) + if !err.IsTerminalTOSViolation() { + t.Fatal("newAntigravityStatusErr(TOS).IsTerminalTOSViolation() = false, want true") + } + // Non-TOS 403 must not be marked terminal. + plain := newAntigravityStatusErr(403, []byte(`{"error":{"code":403,"status":"PERMISSION_DENIED"}}`)) + if plain.IsTerminalTOSViolation() { + t.Fatal("newAntigravityStatusErr(plain 403).IsTerminalTOSViolation() = true, want false") + } +} + +// TestAntigravityClaudeNonStream_SSEErrorFrameIsTerminal verifies that a TOS +// error frame arriving inside an HTTP 200 SSE stream is surfaced as the +// terminal tos_violation error (so the credential is deactivated), not +// swallowed by the aggregation loop into a generic empty-output failure. +func TestAntigravityClaudeNonStream_SSEErrorFrameIsTerminal(t *testing.T) { + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + // One normal data frame followed by the TOS error frame. + _, _ = w.Write([]byte("data: " + `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"partial"}]}}]}}` + "\n\n")) + tosLine := strings.Join(strings.Fields(antigravityTOSBody), " ") + _, _ = w.Write([]byte("data: " + tosLine + "\n\n")) + })) + defer server.Close() + + exec := NewAntigravityExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + ID: "tos-sse", + Attributes: map[string]string{"base_url": server.URL}, + Metadata: map[string]any{ + "access_token": "token", + "project_id": "project-1", + "expired": time.Now().Add(time.Hour).Format(time.RFC3339), + }, + } + + _, err := exec.executeClaudeNonStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-sonnet-4-6", + Payload: []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatAntigravity}) + if err == nil { + t.Fatal("executeClaudeNonStream() = nil, want terminal TOS error") + } + sErr, ok := err.(statusErr) + if !ok { + t.Fatalf("error type = %T, want statusErr", err) + } + if !sErr.IsTerminalTOSViolation() { + t.Fatalf("IsTerminalTOSViolation() = false; error was swallowed by aggregation: %v", err) + } + if sErr.ErrorCode() != "tos_violation" { + t.Fatalf("ErrorCode() = %q, want tos_violation", sErr.ErrorCode()) + } +} + +// TestAntigravityClaudeNonStream_MultiLineSSEErrorIsTerminal verifies that a +// TOS error event split across multiple SSE data: lines is reassembled and +// surfaced as a terminal error rather than being dropped by line-by-line +// classification. +func TestAntigravityClaudeNonStream_MultiLineSSEErrorIsTerminal(t *testing.T) { + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("data: " + `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"partial"}]}}]}}` + "\n\n")) + // Split the TOS error object across two data: lines at a field boundary + // (real SSE framers break between JSON tokens, not inside a string). + tosLine := strings.Join(strings.Fields(antigravityTOSBody), " ") + mid := strings.Index(tosLine, `"details"`) - 1 + _, _ = w.Write([]byte("data: " + tosLine[:mid] + "\n")) + _, _ = w.Write([]byte("data: " + tosLine[mid:] + "\n\n")) + })) + defer server.Close() + + exec := NewAntigravityExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + ID: "tos-sse-multiline", + Attributes: map[string]string{"base_url": server.URL}, + Metadata: map[string]any{ + "access_token": "token", + "project_id": "project-1", + "expired": time.Now().Add(time.Hour).Format(time.RFC3339), + }, + } + _, err := exec.executeClaudeNonStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "claude-sonnet-4-6", + Payload: []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatAntigravity}) + if err == nil { + t.Fatal("executeClaudeNonStream() = nil, want terminal TOS error for multi-line event") + } + sErr, ok := err.(statusErr) + if !ok || !sErr.IsTerminalTOSViolation() { + t.Fatalf("err = %v (%T), want terminal tos_violation statusErr", err, err) + } +} diff --git a/internal/runtime/executor/antigravity_issue7000_boundary_test.go b/internal/runtime/executor/antigravity_issue7000_boundary_test.go index 538e96625de..f4c9c88974b 100644 --- a/internal/runtime/executor/antigravity_issue7000_boundary_test.go +++ b/internal/runtime/executor/antigravity_issue7000_boundary_test.go @@ -241,7 +241,7 @@ func TestIssue7000AntigravityExecutionAndFinalPayloadRules(t *testing.T) { switch rules { case "none": assertIssue7000PromptSchema(t, request.Get("systemInstruction"), issue7000LiteralSchema) - if !strings.Contains(request.Get("systemInstruction.parts.0.text").String(), "a\u200bnthropic") { + if !strings.Contains(request.Get("systemInstruction.parts.0.text").String(), "a\u034fnthropic") { t.Errorf("original system instruction was lost or not obfuscated: %s", body) } for _, key := range []string{"responseSchema", "responseMimeType"} { diff --git a/internal/runtime/executor/antigravity_reasoning_replay.go b/internal/runtime/executor/antigravity_reasoning_replay.go index 24f5c55da88..de83bb24415 100644 --- a/internal/runtime/executor/antigravity_reasoning_replay.go +++ b/internal/runtime/executor/antigravity_reasoning_replay.go @@ -19,9 +19,11 @@ import ( homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" internalsignature "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" log "github.com/sirupsen/logrus" ) @@ -39,14 +41,22 @@ func antigravityReplayLogKey(value string) string { // antigravityCountClaudeToolProvenanceIDs reports how many reserved // Claude-facing provenance IDs are still present in a Gemini-shaped payload. func antigravityCountClaudeToolProvenanceIDs(payload []byte) int { - return antigravityCountClaudeToolProvenanceIDsResult(util.GetGJSONBytesNoCopy(payload, "request.contents")) + contents := util.GetGJSONBytesNoCopy(payload, "request.contents") + if !contents.IsArray() { + contents = util.GetGJSONBytesNoCopy(payload, "contents") + } + return antigravityCountClaudeToolProvenanceIDsResult(contents) } func antigravityCountClaudeToolProvenanceIDsDoc(doc *ojson.Doc) int { if doc == nil { return 0 } - return antigravityCountClaudeToolProvenanceIDsResult(doc.Get("request.contents")) + contents := doc.Get("request.contents") + if !contents.IsArray() { + contents = doc.Get("contents") + } + return antigravityCountClaudeToolProvenanceIDsResult(contents) } func antigravityCountClaudeToolProvenanceIDsResult(contents ojson.Result) int { @@ -88,6 +98,27 @@ func (s antigravityReasoningReplayScope) valid() bool { return strings.TrimSpace(s.modelName) != "" && strings.TrimSpace(s.sessionKey) != "" } +func antigravityFormatCarriesNativeThoughtSignatures(format sdktranslator.Format) bool { + switch strings.ToLower(strings.TrimSpace(format.String())) { + case sdktranslator.FormatGemini.String(), + sdktranslator.FormatInteractions.String(): + return true + default: + return false + } +} + +func antigravityRequestIsSymmetricForReasoningReplay(opts cliproxyexecutor.Options) bool { + source := strings.TrimSpace(opts.SourceFormat.String()) + if source == "" { + return false + } + if !antigravityFormatCarriesNativeThoughtSignatures(opts.SourceFormat) { + return false + } + return antigravityFormatCarriesNativeThoughtSignatures(cliproxyexecutor.ResponseFormatOrSource(opts)) +} + func antigravityReasoningReplayScopeFromPayload(modelName string, payload []byte) antigravityReasoningReplayScope { sessionID := antigravityReplaySessionIDFromPayload(payload) if sessionID == "" { @@ -127,6 +158,9 @@ func antigravityReasoningReplayScopeFromDoc(modelName string, doc *ojson.Doc) an } func antigravityReasoningReplayScopeFromRequest(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, payload []byte) antigravityReasoningReplayScope { + if antigravityRequestIsSymmetricForReasoningReplay(opts) && !antigravityPayloadHasClaudeToolProvenanceID(payload) { + return antigravityReasoningReplayScope{} + } // Prefer an explicit downstream session over a provider sessionId synthesized // from request text. This keeps identical prompts in separate client sessions // from sharing an opaque Gemini reasoning chain. @@ -157,6 +191,9 @@ func antigravityReasoningReplayScopeFromRequest(ctx context.Context, modelName s } func antigravityReasoningReplayScopeFromRequestDoc(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc) antigravityReasoningReplayScope { + if antigravityRequestIsSymmetricForReasoningReplay(opts) && !antigravityDocHasClaudeToolProvenanceID(doc) { + return antigravityReasoningReplayScope{} + } scope := antigravityReasoningReplayScope{modelName: modelName} if sessionKey := antigravityReasoningReplayClientSessionKey(ctx, req, opts); sessionKey != "" { scope.sessionKey = sessionKey @@ -351,12 +388,117 @@ func prepareAntigravityGeminiReasoningReplayPayload(ctx context.Context, modelNa return doc.Bytes(), scope, nil } +// antigravityStreamChunksHaveTerminalCommitEvent reports whether translated SSE +// chunks carry a client-visible terminal completion/truncation event before +// which accumulated reasoning replay items must be committed to KV. +func antigravityStreamChunksHaveTerminalCommitEvent(chunks [][]byte) bool { + for _, chunk := range chunks { + for _, line := range bytes.Split(chunk, []byte("\n")) { + payload := helps.JSONPayload(line) + if len(payload) == 0 { + continue + } + switch ojson.GetBytesNoCopy(payload, "type").String() { + case "response.completed", "response.incomplete", "response.done", "message_stop": + return true + } + if ojson.GetBytesNoCopy(payload, "event_type").String() == "interaction.completed" { + return true + } + for _, path := range []string{ + "choices.0.finish_reason", + "response.choices.0.finish_reason", + "candidates.0.finishReason", + "response.candidates.0.finishReason", + } { + if finishReason := ojson.GetBytesNoCopy(payload, path); finishReason.Exists() && strings.TrimSpace(finishReason.String()) != "" { + return true + } + } + } + } + return false +} + +func isGeminiCountTokensAction(req cliproxyexecutor.Request, opts cliproxyexecutor.Options) bool { + if req.Metadata != nil { + if action, _ := req.Metadata["action"].(string); strings.EqualFold(strings.TrimSpace(action), "countTokens") { + return true + } + } + if opts.Metadata != nil { + if action, _ := opts.Metadata["action"].(string); strings.EqualFold(strings.TrimSpace(action), "countTokens") { + return true + } + } + return false +} + +func prepareGeminiTopLevelReasoningReplayPayloadDoc(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc) (antigravityReasoningReplayScope, []byte, bool, error) { + return prepareGeminiTopLevelReasoningReplayPayloadDocWithMode(ctx, modelName, req, opts, doc, !isGeminiCountTokensAction(req, opts)) +} + +func prepareGeminiTopLevelCountTokensReasoningReplayPayloadDoc(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc) (bool, error) { + _, _, changed, err := prepareGeminiTopLevelReasoningReplayPayloadDocWithMode(ctx, modelName, req, opts, doc, false) + return changed, err +} + +func prepareGeminiTopLevelReasoningReplayPayloadDocWithMode(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc, reserveOnMiss bool) (antigravityReasoningReplayScope, []byte, bool, error) { + if doc == nil || !antigravityUsesReasoningReplayCache(modelName) { + return antigravityReasoningReplayScope{}, nil, false, nil + } + if doc.Get("request.contents").Exists() { + scope, changed, err := prepareAntigravityGeminiReasoningReplayPayloadDocWithOptions(ctx, modelName, req, opts, doc, true, reserveOnMiss) + var replayRequestPayload []byte + if reserveOnMiss && scope.valid() { + replayRequestPayload, _ = antigravityReplayRequestEnvelopeFromDoc(doc) + } + return scope, replayRequestPayload, changed, err + } + if !doc.Get("contents").Exists() { + return antigravityReasoningReplayScope{}, nil, false, nil + } + wrappedBytes, ok := antigravityReplayRequestEnvelopeFromDoc(doc) + if !ok { + return antigravityReasoningReplayScope{}, nil, false, nil + } + wrappedDoc := ojson.NewDoc(wrappedBytes) + for _, key := range []string{"sessionId", "session_id"} { + if val := doc.Get(key); val.Exists() { + _ = wrappedDoc.SetRawBytes(key, []byte(val.Raw)) + } + } + scope, changed, err := prepareAntigravityGeminiReasoningReplayPayloadDocWithOptions(ctx, modelName, req, opts, wrappedDoc, false, reserveOnMiss) + if err != nil { + return scope, nil, false, err + } + if changed { + if updatedContents := wrappedDoc.Get("request.contents"); updatedContents.Exists() { + _ = doc.SetRawBytes("contents", []byte(updatedContents.Raw)) + } + } + var replayRequestPayload []byte + if reserveOnMiss && scope.valid() { + replayRequestPayload, _ = antigravityReplayRequestEnvelopeFromDoc(doc) + } + return scope, replayRequestPayload, changed, nil +} + func prepareAntigravityGeminiReasoningReplayPayloadDoc(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc) (antigravityReasoningReplayScope, bool, error) { + return prepareAntigravityGeminiReasoningReplayPayloadDocWithOptions(ctx, modelName, req, opts, doc, true, !isGeminiCountTokensAction(req, opts)) +} + +func prepareAntigravityGeminiCountTokensReasoningReplayPayloadDoc(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc) (bool, error) { + _, changed, err := prepareAntigravityGeminiReasoningReplayPayloadDocWithOptions(ctx, modelName, req, opts, doc, true, false) + return changed, err +} + +func prepareAntigravityGeminiReasoningReplayPayloadDocWithOptions(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc, normalizeFunctionResponseRoles, reserveOnMiss bool) (antigravityReasoningReplayScope, bool, error) { if doc == nil || !antigravityUsesReasoningReplayCache(modelName) { return antigravityReasoningReplayScope{}, false, nil } originalContentsRaw := doc.Get("request.contents").Raw - scope, replayApplied, errReplay := applyAntigravityReasoningReplayCacheDoc(ctx, modelName, req, opts, doc) + scope, replayApplied, errReplay := applyAntigravityReasoningReplayCacheDocWithMode(ctx, modelName, req, opts, doc, reserveOnMiss) changed := replayApplied if errReplay != nil { logAntigravityReasoningReplayDegraded(scope, "read", errReplay) @@ -366,7 +508,7 @@ func prepareAntigravityGeminiReasoningReplayPayloadDoc(ctx context.Context, mode changed = false replayApplied = false } - if normalizeAntigravityGeminiFunctionResponseRolesDoc(doc) { + if normalizeFunctionResponseRoles && normalizeAntigravityGeminiFunctionResponseRolesDoc(doc) { changed = true } if antigravityDocHasClaudeToolProvenanceID(doc) { @@ -381,7 +523,7 @@ func prepareAntigravityGeminiReasoningReplayPayloadDoc(ctx context.Context, mode changed = true } } - if normalizeAntigravityGeminiFunctionResponseRolesDoc(doc) { + if normalizeFunctionResponseRoles && normalizeAntigravityGeminiFunctionResponseRolesDoc(doc) { changed = true } } @@ -400,7 +542,7 @@ func prepareAntigravityGeminiReasoningReplayPayloadDoc(ctx context.Context, mode origWrapped = []byte(`{"request":{"contents":` + originalContentsRaw + `}}`) } originalPairingValid := internalsignature.ValidateGeminiFunctionCallPairing(origWrapped) == nil - if replayApplied && originalPairingValid && scope.valid() { + if replayApplied && originalPairingValid && scope.valid() && reserveOnMiss { if _, errDelete := internalcache.DeleteAntigravityReasoningReplayItemsIfUnchanged(ctx, scope.modelName, scope.sessionKey, scope.cacheSnapshot); errDelete != nil { logAntigravityReasoningReplayDegraded(scope, "invalidate", errDelete) } @@ -443,6 +585,10 @@ func applyAntigravityReasoningReplayCache(ctx context.Context, modelName string, } func applyAntigravityReasoningReplayCacheDoc(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc) (antigravityReasoningReplayScope, bool, error) { + return applyAntigravityReasoningReplayCacheDocWithMode(ctx, modelName, req, opts, doc, true) +} + +func applyAntigravityReasoningReplayCacheDocWithMode(ctx context.Context, modelName string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, doc *ojson.Doc, reserveOnMiss bool) (antigravityReasoningReplayScope, bool, error) { if doc == nil { return antigravityReasoningReplayScope{}, false, nil } @@ -450,7 +596,17 @@ func applyAntigravityReasoningReplayCacheDoc(ctx context.Context, modelName stri if !scope.valid() { return scope, false, nil } - items, snapshot, ok, err := internalcache.GetAntigravityReasoningReplayItemsWithSnapshotRequired(ctx, scope.modelName, scope.sessionKey) + var ( + items [][]byte + snapshot internalcache.AntigravityReasoningReplaySnapshot + ok bool + err error + ) + if reserveOnMiss { + items, snapshot, ok, err = internalcache.GetAntigravityReasoningReplayItemsWithSnapshotRequired(ctx, scope.modelName, scope.sessionKey) + } else { + items, snapshot, ok, err = internalcache.PeekAntigravityReasoningReplayItemsWithSnapshotRequired(ctx, scope.modelName, scope.sessionKey) + } scope.cacheSnapshot = snapshot reservedBefore := antigravityCountClaudeToolProvenanceIDsDoc(doc) if err != nil || !ok || len(items) == 0 { @@ -490,9 +646,14 @@ func antigravityReplayRequestEnvelopeFromDoc(doc *ojson.Doc) ([]byte, bool) { if requestNode := doc.Get("request"); requestNode.IsObject() { return []byte(`{"request":` + requestNode.Raw + `}`), true } + prefix := "request." contents := doc.Get("request.contents") if !contents.Exists() { - return nil, false + prefix = "" + contents = doc.Get("contents") + if !contents.Exists() { + return nil, false + } } var buf bytes.Buffer buf.WriteString(`{"request":{`) @@ -501,10 +662,10 @@ func antigravityReplayRequestEnvelopeFromDoc(doc *ojson.Doc) ([]byte, bool) { key string path string }{ - {key: "systemInstruction", path: "request.systemInstruction"}, - {key: "tools", path: "request.tools"}, - {key: "toolConfig", path: "request.toolConfig"}, - {key: "contents", path: "request.contents"}, + {key: "systemInstruction", path: prefix + "systemInstruction"}, + {key: "tools", path: prefix + "tools"}, + {key: "toolConfig", path: prefix + "toolConfig"}, + {key: "contents", path: prefix + "contents"}, } { val := doc.Get(field.path) if !val.Exists() { @@ -1972,14 +2133,22 @@ func antigravityFunctionCallMatchesReplayItem(functionCall, itemResult ojson.Res } func antigravityPayloadHasClaudeToolProvenanceID(payload []byte) bool { - return antigravityContentsHasClaudeToolProvenanceID(util.GetGJSONBytesNoCopy(payload, "request.contents")) + contents := util.GetGJSONBytesNoCopy(payload, "request.contents") + if !contents.IsArray() { + contents = util.GetGJSONBytesNoCopy(payload, "contents") + } + return antigravityContentsHasClaudeToolProvenanceID(contents) } func antigravityDocHasClaudeToolProvenanceID(doc *ojson.Doc) bool { if doc == nil { return false } - return antigravityContentsHasClaudeToolProvenanceID(doc.Get("request.contents")) + contents := doc.Get("request.contents") + if !contents.IsArray() { + contents = doc.Get("contents") + } + return antigravityContentsHasClaudeToolProvenanceID(contents) } func antigravityContentsHasClaudeToolProvenanceID(contents ojson.Result) bool { @@ -2528,6 +2697,12 @@ type antigravityPendingThoughtSignature struct { targetKind string } +type antigravityStreamingReplayToolCall struct { + call *translatorcommon.VertexStreamingToolCall + partIndex int + signature string +} + type antigravityReasoningReplayAccumulator struct { scope antigravityReasoningReplayScope responseContextHash string @@ -2544,6 +2719,8 @@ type antigravityReasoningReplayAccumulator struct { thoughtPartIndex int lastResponseKind string pendingSignatures []antigravityPendingThoughtSignature + activeStreamingFC *antigravityStreamingReplayToolCall + hasIncompleteFC bool itemBytes int overflow bool terminal bool @@ -2674,9 +2851,20 @@ func (a *antigravityReasoningReplayAccumulator) appendItem(item []byte) { a.itemBytes += len(item) } -func (a *antigravityReasoningReplayAccumulator) attachDetachedSignatureToLastFunctionCall(signature string) { +func (a *antigravityReasoningReplayAccumulator) attachDetachedSignatureToLastFunctionCall(signature string) bool { if a == nil || signature == "" { - return + return false + } + if a.activeStreamingFC != nil { + if a.activeStreamingFC.signature != "" { + return false + } + if a.itemBytes+len(signature) > internalcache.AntigravityReasoningReplayCacheMaxBytesPerEntry { + a.overflow = true + return false + } + a.activeStreamingFC.signature = signature + return true } for itemIndex := len(a.items) - 1; itemIndex >= 0; itemIndex-- { item := util.ParseGJSONBytesNoCopy(a.items[itemIndex]) @@ -2684,21 +2872,22 @@ func (a *antigravityReasoningReplayAccumulator) attachDetachedSignatureToLastFun continue } if strings.TrimSpace(item.Get("thoughtSignature").String()) != "" { - return + return false } updated, errSet := ojson.SetBytes(a.items[itemIndex], "thoughtSignature", signature) if errSet != nil { - return + return false } delta := len(updated) - len(a.items[itemIndex]) if a.itemBytes+delta > internalcache.AntigravityReasoningReplayCacheMaxBytesPerEntry { a.overflow = true - return + return false } a.items[itemIndex] = updated a.itemBytes += delta - return + return true } + return false } func (a *antigravityReasoningReplayAccumulator) ObserveSSELine(line []byte) { @@ -2759,56 +2948,17 @@ func (a *antigravityReasoningReplayAccumulator) observeResponsePayload(payload [ signature = "" } if fc := part.Get("functionCall"); fc.Exists() { - if a.lastResponseKind == "text" || a.lastResponseKind == "thought" { - a.flushPendingThoughtSignaturesForKind(a.lastResponseKind) - } - if signature != "" { - remainingPending := a.pendingSignatures[:0] - for _, pending := range a.pendingSignatures { - if pending.targetKind != "" { - remainingPending = append(remainingPending, pending) - } - } - a.pendingSignatures = remainingPending - } - if signature == "" { - for pendingIndex := len(a.pendingSignatures) - 1; pendingIndex >= 0; pendingIndex-- { - if a.pendingSignatures[pendingIndex].targetKind == "" { - signature = a.pendingSignatures[pendingIndex].signature - a.pendingSignatures = append(a.pendingSignatures[:pendingIndex], a.pendingSignatures[pendingIndex+1:]...) - break - } - } - } - if signature == "" { - signature = a.claimPrecedingTurnThoughtSignature() - } - keys := antigravityReplayToolCallKeysFromPart(fc) - for _, key := range keys { - dedupeKey := key + "\x00" + signature - if signature == "" { - dedupeKey = fmt.Sprintf("%s\x00part:%d", key, pi) - } - if a.seenFC[dedupeKey] { - return true - } - a.seenFC[dedupeKey] = true - } - occurrenceKey := antigravityFunctionCallKey(fc.Get("name").String(), fc.Get("args").Raw, "") - occurrence := a.functionCallOccurrences[occurrenceKey] - if occurrenceKey != "" { - a.functionCallOccurrences[occurrenceKey] = occurrence + 1 - } - item := buildAntigravityFunctionCallPartItem(a.contentIndex, pi, occurrence, fc, signature) - if len(item) > 0 { - a.appendItem(antigravitySetReplayItemContextHashValue(item, a.responseContextHash)) - if signature != "" { - a.seenSignatures[signature] = true - } - } - a.lastResponseKind = "function_call" + a.observeFunctionCallPart(pi, fc, signature) return true } + if a.activeStreamingFC != nil { + text := part.Get("text") + hasSemanticText := text.Exists() && text.String() != "" + if hasSemanticText { + a.hasIncompleteFC = true + a.activeStreamingFC = nil + } + } targetKind := "" if part.Get("thought").Bool() { @@ -2818,8 +2968,7 @@ func (a *antigravityReasoningReplayAccumulator) observeResponsePayload(payload [ hasSemanticText := text.Exists() && text.String() != "" signatureOnly := signature != "" && !hasSemanticText if signatureOnly && a.lastResponseKind == "function_call" { - if !a.seenSignatures[signature] { - a.attachDetachedSignatureToLastFunctionCall(signature) + if !a.seenSignatures[signature] && a.attachDetachedSignatureToLastFunctionCall(signature) { a.seenSignatures[signature] = true } return true @@ -3007,15 +3156,163 @@ func (a *antigravityReasoningReplayAccumulator) appendPendingThoughtSignatures() a.pendingSignatures = nil } +func (a *antigravityReasoningReplayAccumulator) resolveFunctionCallSignature(signature string) string { + if a.lastResponseKind == "text" || a.lastResponseKind == "thought" { + a.flushPendingThoughtSignaturesForKind(a.lastResponseKind) + } + if signature != "" { + remainingPending := a.pendingSignatures[:0] + for _, pending := range a.pendingSignatures { + if pending.targetKind != "" { + remainingPending = append(remainingPending, pending) + } + } + a.pendingSignatures = remainingPending + } + if signature == "" { + for pendingIndex := len(a.pendingSignatures) - 1; pendingIndex >= 0; pendingIndex-- { + if a.pendingSignatures[pendingIndex].targetKind == "" { + signature = a.pendingSignatures[pendingIndex].signature + a.pendingSignatures = append(a.pendingSignatures[:pendingIndex], a.pendingSignatures[pendingIndex+1:]...) + break + } + } + } + if signature == "" { + signature = a.claimPrecedingTurnThoughtSignature() + } + return signature +} + +func (a *antigravityReasoningReplayAccumulator) recordCompletedFunctionCall(pi int, fc ojson.Result, signature string) { + keys := antigravityReplayToolCallKeysFromPart(fc) + for _, key := range keys { + dedupeKey := key + "\x00" + signature + if signature == "" { + dedupeKey = fmt.Sprintf("%s\x00part:%d", key, pi) + } + if a.seenFC[dedupeKey] { + return + } + a.seenFC[dedupeKey] = true + } + occurrenceKey := antigravityFunctionCallKey(fc.Get("name").String(), fc.Get("args").Raw, "") + occurrence := a.functionCallOccurrences[occurrenceKey] + if occurrenceKey != "" { + a.functionCallOccurrences[occurrenceKey] = occurrence + 1 + } + item := buildAntigravityFunctionCallPartItem(a.contentIndex, pi, occurrence, fc, signature) + if len(item) > 0 { + a.appendItem(antigravitySetReplayItemContextHashValue(item, a.responseContextHash)) + if signature != "" { + a.seenSignatures[signature] = true + } + } + a.lastResponseKind = "function_call" +} + +func (a *antigravityReasoningReplayAccumulator) flushCompletedStreamingFunctionCall(active *antigravityStreamingReplayToolCall) { + if a == nil || active == nil || active.call == nil || active.call.Assembler == nil { + return + } + if active.call.Assembler.Err() != nil { + a.hasIncompleteFC = true + return + } + argsRaw := strings.TrimSpace(active.call.Assembler.FullArguments()) + if argsRaw == "" { + argsRaw = "{}" + } + if !ojson.Valid(argsRaw) { + a.hasIncompleteFC = true + return + } + fcDoc := ojson.NewDocString(`{"name":""}`) + _ = fcDoc.Set("name", active.call.RawName) + if active.call.UpstreamID != "" { + _ = fcDoc.Set("id", active.call.UpstreamID) + } + _ = fcDoc.SetRaw("args", argsRaw) + a.recordCompletedFunctionCall(active.partIndex, ojson.ParseBytes(fcDoc.Bytes()), active.signature) +} + +func (a *antigravityReasoningReplayAccumulator) observeFunctionCallPart(pi int, fc ojson.Result, signature string) { + if a == nil { + return + } + if active := a.activeStreamingFC; active != nil && active.call != nil && active.call.CanContinueWith(fc) { + if signature != "" && active.signature == "" { + active.signature = signature + } + if upstreamID := strings.TrimSpace(fc.Get("id").String()); upstreamID != "" && active.call.UpstreamID == "" { + active.call.UpstreamID = strings.Clone(upstreamID) + } + _, done := active.call.Assembler.PushFunctionCall(fc) + if active.call.Assembler.Err() != nil { + a.hasIncompleteFC = true + a.activeStreamingFC = nil + return + } + if done { + a.activeStreamingFC = nil + a.flushCompletedStreamingFunctionCall(active) + } + a.lastResponseKind = "function_call" + return + } + if translatorcommon.IsVertexStreamingFunctionCall(fc) { + if a.activeStreamingFC != nil { + a.hasIncompleteFC = true + a.activeStreamingFC = nil + } + rawName := strings.Clone(strings.TrimSpace(fc.Get("name").String())) + if rawName == "" { + a.hasIncompleteFC = true + return + } + upstreamID := strings.Clone(strings.TrimSpace(fc.Get("id").String())) + resolvedSig := a.resolveFunctionCallSignature(signature) + call := translatorcommon.NewVertexStreamingToolCall(rawName, rawName, upstreamID, upstreamID, 0) + _, done := call.Assembler.PushFunctionCall(fc) + if call.Assembler.Err() != nil { + a.hasIncompleteFC = true + return + } + active := &antigravityStreamingReplayToolCall{ + call: call, + partIndex: pi, + signature: resolvedSig, + } + if done { + a.flushCompletedStreamingFunctionCall(active) + } else { + a.activeStreamingFC = active + } + a.lastResponseKind = "function_call" + return + } + if a.activeStreamingFC != nil { + a.hasIncompleteFC = true + a.activeStreamingFC = nil + } + rawName := strings.TrimSpace(fc.Get("name").String()) + if rawName == "" && !fc.Get("args").Exists() { + return + } + resolvedSig := a.resolveFunctionCallSignature(signature) + a.recordCompletedFunctionCall(pi, fc, resolvedSig) +} + func (a *antigravityReasoningReplayAccumulator) Commit(ctx context.Context) { if a == nil || !a.scope.valid() { return } log.Debugf("antigravity replay: accumulator commit terminal=%t overflow=%t items=%d (session=%s)", a.terminal, a.overflow, len(a.items), antigravityReplayLogKey(a.scope.sessionKey)) - if !a.terminal { - // No terminal finishReason means the stream never completed, so this turn - // contributes nothing to the ledger and its tool IDs become unresolvable. + if !a.terminal || a.activeStreamingFC != nil || a.hasIncompleteFC { + // No terminal finishReason (or an unclosed/corrupted streaming tool call) + // means the stream never completed cleanly, so this turn contributes + // nothing to the ledger and its tool IDs become unresolvable. return } if a.overflow { diff --git a/internal/runtime/executor/antigravity_reasoning_replay_test.go b/internal/runtime/executor/antigravity_reasoning_replay_test.go index fc3b7545870..16036897074 100644 --- a/internal/runtime/executor/antigravity_reasoning_replay_test.go +++ b/internal/runtime/executor/antigravity_reasoning_replay_test.go @@ -12,6 +12,7 @@ import ( internalcache "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" internalsignature "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" @@ -1955,6 +1956,155 @@ func TestPrepareAntigravityGeminiReasoningReplayStillRejectsBrokenPairing(t *tes } } +func TestAntigravityReasoningReplaySkipsSymmetricGeminiAndInteractionsButKeepsAsymmetricAlias(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + t.Cleanup(internalcache.ClearAntigravityReasoningReplayCache) + + const model = "gemini-3-flash" + payload := []byte(`{"sessionId":"sess-symmetry","request":{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Beijing"}]}]}}`) + responseSSE := []byte(`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":""},{"thoughtSignature":"EmcKZQFpFH0THU+YNRY5uVwt/0bo2hFo1RmXsMhlX9FCg2n6GssBe5sMV37KB6OrgeKKEP9fxN261QX","functionCall":{"name":"get_weather","args":{"city":"Beijing"},"id":"call_1"}}]},"finishReason":"STOP"}]}}`) + + for _, format := range []sdktranslator.Format{sdktranslator.FormatGemini, sdktranslator.FormatInteractions} { + t.Run("symmetric_"+format.String(), func(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + req := cliproxyexecutor.Request{Model: model, Payload: payload} + opts := cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + } + _, scope, errPrepare := prepareAntigravityGeminiReasoningReplayPayload(context.Background(), model, req, opts, payload) + if errPrepare != nil { + t.Fatalf("prepare error: %v", errPrepare) + } + if scope.valid() { + t.Fatalf("symmetric format %q must not allocate reasoning replay KV scope, got %+v", format, scope) + } + if acc := newAntigravityReasoningReplayAccumulator(scope, payload); acc != nil { + t.Fatalf("symmetric format %q must not create replay accumulator", format) + } + }) + } + + t.Run("asymmetric_claude_haiku_alias_to_gemini_3_flash", func(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + // Downstream client sends Claude /v1/messages with model="claude-haiku-4-5-20251001", + // which model-alias resolves to baseModel="gemini-3-flash" inside AntigravityExecutor. + req := cliproxyexecutor.Request{Model: model, Payload: payload} + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + ResponseFormat: sdktranslator.FormatClaude, + Metadata: map[string]any{ + cliproxyexecutor.RequestedModelMetadataKey: "claude-haiku-4-5-20251001", + }, + } + _, scope, errPrepare := prepareAntigravityGeminiReasoningReplayPayload(context.Background(), model, req, opts, payload) + if errPrepare != nil { + t.Fatalf("prepare error: %v", errPrepare) + } + if !scope.valid() { + t.Fatal("asymmetric Claude -> Gemini alias request must allocate reasoning replay KV scope") + } + acc := newAntigravityReasoningReplayAccumulator(scope, payload) + if acc == nil { + t.Fatal("expected non-nil accumulator for asymmetric Claude -> Gemini request") + } + acc.ObserveSSELine(responseSSE) + acc.Commit(context.Background()) + + items, ok := internalcache.GetAntigravityReasoningReplayItems(scope.modelName, scope.sessionKey) + if !ok || len(items) == 0 { + t.Fatalf("expected asymmetric replay items to be persisted in KV, ok=%v len=%d", ok, len(items)) + } + }) + + t.Run("top_level_gemini_doc_replays_asymmetric_and_skips_symmetric", func(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + topLevelTurn1 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Beijing"}]}]}`) + topLevelTurn2 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Beijing"}]},{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"get_weather","args":{"city":"Beijing"},"id":"call_1"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_1","response":{"result":"sunny"}}}]}]}`) + topLevelResponse := []byte(`{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":""},{"thoughtSignature":"EmcKZQFpFH0THU+YNRY5uVwt/0bo2hFo1RmXsMhlX9FCg2n6GssBe5sMV37KB6OrgeKKEP9fxN261QX","functionCall":{"name":"get_weather","args":{"city":"Beijing"},"id":"call_1"}}]},"finishReason":"STOP"}]}`) + + symDoc := ojson.NewDoc(topLevelTurn1) + symScope, _, _, errSym := prepareGeminiTopLevelReasoningReplayPayloadDoc( + context.Background(), + model, + cliproxyexecutor.Request{Model: model, Payload: topLevelTurn1}, + cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatGemini, ResponseFormat: sdktranslator.FormatGemini}, + symDoc, + ) + if errSym != nil { + t.Fatalf("symmetric top-level prepare error: %v", errSym) + } + if symScope.valid() { + t.Fatalf("symmetric top-level Gemini must not allocate replay scope, got %+v", symScope) + } + + headers := make(http.Header) + headers.Set("Session-Id", "sess-non-ag-gemini") + asymOpts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Headers: headers, + } + doc1 := ojson.NewDoc(topLevelTurn1) + scope1, replayReq1, _, err1 := prepareGeminiTopLevelReasoningReplayPayloadDoc( + context.Background(), + model, + cliproxyexecutor.Request{Model: model, Payload: topLevelTurn1}, + asymOpts, + doc1, + ) + if err1 != nil || !scope1.valid() { + t.Fatalf("asymmetric top-level prepare turn 1: scope=%+v err=%v", scope1, err1) + } + cacheAntigravityReasoningReplayFromResponse(context.Background(), scope1, replayReq1, topLevelResponse) + + doc2 := ojson.NewDoc(topLevelTurn2) + scope2, replayReq2, changed2, err2 := prepareGeminiTopLevelReasoningReplayPayloadDoc( + context.Background(), + model, + cliproxyexecutor.Request{Model: model, Payload: topLevelTurn2}, + asymOpts, + doc2, + ) + if err2 != nil || !changed2 { + t.Fatalf("asymmetric top-level prepare turn 2: changed=%v err=%v", changed2, err2) + } + if gotSig := doc2.Get("contents.1.parts.0.thoughtSignature").String(); gotSig != "EmcKZQFpFH0THU+YNRY5uVwt/0bo2hFo1RmXsMhlX9FCg2n6GssBe5sMV37KB6OrgeKKEP9fxN261QX" { + t.Fatalf("replayed signature = %q, want native thoughtSignature", gotSig) + } + if gotRole := doc2.Get("contents.2.role").String(); gotRole != "user" { + t.Fatalf("non-Antigravity functionResponse role = %q, want user", gotRole) + } + + // Turn 2 simulates Vertex stripping wire-only functionCall.id/functionResponse.id + // after prepareGeminiTopLevelReasoningReplayPayloadDoc; the captured replayRequestPayload + // from prepareGeminiTopLevelReasoningReplayPayloadDoc must still keep canonical call_id + // context so Turn 3 matches both call_1 and call_2 signatures. + helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc2, asymOpts.SourceFormat.String()) + topLevelResponse2 := []byte(`{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":""},{"thoughtSignature":"EsMTCsATARFNMg/XNVix5lDpkKaHR7Xg","functionCall":{"name":"get_weather","args":{"city":"Shanghai"},"id":"call_2"}}]},"finishReason":"STOP"}]}`) + cacheAntigravityReasoningReplayFromResponse(context.Background(), scope2, replayReq2, topLevelResponse2) + + topLevelTurn3 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather for Beijing"}]},{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"get_weather","args":{"city":"Beijing"},"id":"call_1"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_1","response":{"result":"sunny"}}}]},{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"get_weather","args":{"city":"Shanghai"},"id":"call_2"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_2","response":{"result":"cloudy"}}}]}]}`) + doc3 := ojson.NewDoc(topLevelTurn3) + _, _, changed3, err3 := prepareGeminiTopLevelReasoningReplayPayloadDoc( + context.Background(), + model, + cliproxyexecutor.Request{Model: model, Payload: topLevelTurn3}, + asymOpts, + doc3, + ) + if err3 != nil || !changed3 { + t.Fatalf("asymmetric top-level prepare turn 3: changed=%v err=%v", changed3, err3) + } + if gotSig1 := doc3.Get("contents.1.parts.0.thoughtSignature").String(); gotSig1 != "EmcKZQFpFH0THU+YNRY5uVwt/0bo2hFo1RmXsMhlX9FCg2n6GssBe5sMV37KB6OrgeKKEP9fxN261QX" { + t.Fatalf("turn 3 call_1 signature = %q, want preserved signature", gotSig1) + } + if gotSig2 := doc3.Get("contents.3.parts.0.thoughtSignature").String(); gotSig2 != "EsMTCsATARFNMg/XNVix5lDpkKaHR7Xg" { + t.Fatalf("turn 3 call_2 signature = %q, want second signature", gotSig2) + } + }) +} + func TestPrepareAntigravityGeminiReasoningReplayDegradesWhenReplayBreaksPairing(t *testing.T) { internalcache.ClearAntigravityReasoningReplayCache() t.Cleanup(internalcache.ClearAntigravityReasoningReplayCache) @@ -1982,3 +2132,174 @@ func TestPrepareAntigravityGeminiReasoningReplayDegradesWhenReplayBreaksPairing( t.Fatalf("out = %s, want original payload %s", out, payload) } } + +func TestAntigravityStreamChunksHaveTerminalCommitEvent(t *testing.T) { + cases := []struct { + name string + chunks [][]byte + want bool + }{ + { + name: "openai responses completed", + chunks: [][]byte{[]byte("event: response.completed\ndata: {\"type\":\"response.completed\"}\n\n")}, + want: true, + }, + { + name: "openai responses incomplete", + chunks: [][]byte{[]byte("event: response.incomplete\ndata: {\"type\":\"response.incomplete\",\"response\":{\"incomplete_details\":{\"reason\":\"max_output_tokens\"}}}\n\n")}, + want: true, + }, + { + name: "openai chat finish_reason stop", + chunks: [][]byte{[]byte("data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n")}, + want: true, + }, + { + name: "openai chat null finish_reason", + chunks: [][]byte{[]byte("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hi\"},\"finish_reason\":null}]}\n\n")}, + want: false, + }, + { + name: "claude message_stop", + chunks: [][]byte{[]byte("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")}, + want: true, + }, + { + name: "bare done frame only", + chunks: [][]byte{[]byte("data: [DONE]\n\n")}, + want: false, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := antigravityStreamChunksHaveTerminalCommitEvent(tc.chunks); got != tc.want { + t.Fatalf("antigravityStreamChunksHaveTerminalCommitEvent() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestAntigravityReasoningReplayAccumulatorAssemblesVertexStreamingPartialArgs(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + t.Cleanup(internalcache.ClearAntigravityReasoningReplayCache) + + const model = "gemini-3.8-flash" + asymOpts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Headers: http.Header{"X-Session-Id": []string{"sess-vertex-partial-args"}}, + } + + turn1 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Weather in New York?"}]}]}`) + doc1 := ojson.NewDoc(turn1) + scope1, replayReq1, _, err1 := prepareGeminiTopLevelReasoningReplayPayloadDoc( + context.Background(), + model, + cliproxyexecutor.Request{Model: model, Payload: turn1}, + asymOpts, + doc1, + ) + if err1 != nil || !scope1.valid() { + t.Fatalf("prepare turn 1: scope=%+v err=%v", scope1, err1) + } + + acc := newAntigravityReasoningReplayAccumulator(scope1, replayReq1) + acc.ObserveSSELine([]byte(`data: {"candidates":[{"index":0,"content":{"role":"model","parts":[{"functionCall":{"id":"call_ny","name":"get_weather","partialArgs":[{"jsonPath":"$.city","stringValue":"New ","willContinue":true}],"willContinue":true}}]}}]}`)) + acc.ObserveSSELine([]byte(`data: {"candidates":[{"index":0,"content":{"role":"model","parts":[{"text":"","thoughtSignature":"EmcKZQFpFH0THU+YNRY5uVwt/0bo2hFo1RmXsMhlX9FCg2n6GssBe5sMV37KB6OrgeKKEP9fxN261QX"}]}}]}`)) + acc.ObserveSSELine([]byte(`data: {"candidates":[{"index":0,"content":{"role":"model","parts":[{"functionCall":{"partialArgs":[{"jsonPath":"$.city","stringValue":"York"}],"willContinue":false}}]},"finishReason":"STOP"}]}`)) + acc.Commit(context.Background()) + + turn2 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Weather in New York?"}]},{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"get_weather","args":{"city":"New York"},"id":"call_ny"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_ny","response":{"result":"sunny"}}}]}]}`) + doc2 := ojson.NewDoc(turn2) + _, _, changed2, err2 := prepareGeminiTopLevelReasoningReplayPayloadDoc( + context.Background(), + model, + cliproxyexecutor.Request{Model: model, Payload: turn2}, + asymOpts, + doc2, + ) + if err2 != nil || !changed2 { + t.Fatalf("prepare turn 2 after partialArgs stream: changed=%v err=%v", changed2, err2) + } + if gotSig := doc2.Get("contents.1.parts.0.thoughtSignature").String(); gotSig != "EmcKZQFpFH0THU+YNRY5uVwt/0bo2hFo1RmXsMhlX9FCg2n6GssBe5sMV37KB6OrgeKKEP9fxN261QX" { + t.Fatalf("replayed signature = %q, want native signature from partialArgs stream", gotSig) + } +} + +func TestNonVertexSanitizesReplayedVertexBareTinkSignature(t *testing.T) { + // Verify that a Vertex bare-Tink thoughtSignature replayed from shared KV is + // downgraded to skip_thought_signature_validator when post-replay non-Vertex + // sanitization runs (as in GeminiExecutor and AIStudioExecutor). + const vertexBareTinkSig = "AY89a18f0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + internalcache.ClearAntigravityReasoningReplayCache() + const model = "gemini-3.8-flash" + asymOpts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Headers: http.Header{"X-Session-Id": []string{"sess-vertex-to-gemini"}}, + } + turn1 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather"}]}]}`) + doc1 := ojson.NewDoc(turn1) + scope1, replayReq1, _, err1 := prepareGeminiTopLevelReasoningReplayPayloadDoc( + context.Background(), + model, + cliproxyexecutor.Request{Model: model, Payload: turn1}, + asymOpts, + doc1, + ) + if err1 != nil || !scope1.valid() { + t.Fatalf("prepare turn 1: scope=%+v err=%v", scope1, err1) + } + vertexResp := []byte(`{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"` + vertexBareTinkSig + `","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_tink"}}]},"finishReason":"STOP"}]}`) + cacheAntigravityReasoningReplayFromResponse(context.Background(), scope1, replayReq1, vertexResp) + + turn2 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather"}]},{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_tink"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_tink","response":{"result":"clear"}}}]}]}`) + nonVertexDoc := ojson.NewDoc(turn2) + _, _, changed2, err2 := prepareGeminiTopLevelReasoningReplayPayloadDoc( + context.Background(), + model, + cliproxyexecutor.Request{Model: model, Payload: turn2}, + asymOpts, + nonVertexDoc, + ) + if err2 != nil || !changed2 { + t.Fatalf("prepare turn 2: changed=%v err=%v", changed2, err2) + } + internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(nonVertexDoc, "contents") + if got := nonVertexDoc.Get("contents.1.parts.0.thoughtSignature").String(); got != "skip_thought_signature_validator" { + t.Fatalf("non-Vertex post-replay sanitized signature = %q, want skip_thought_signature_validator", got) + } +} + +func TestCountTokensReasoningReplayPeeksWithoutReservingTombstone(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + t.Cleanup(internalcache.ClearAntigravityReasoningReplayCache) + + const model = "gemini-3.8-flash" + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Headers: http.Header{"X-Session-Id": []string{"sess-count-tokens-no-tombstone"}}, + } + payload := []byte(`{"contents":[{"role":"user","parts":[{"text":"Count tokens only"}]}]}`) + doc := ojson.NewDoc(payload) + req := cliproxyexecutor.Request{ + Model: model, + Payload: payload, + Metadata: map[string]any{"action": "countTokens"}, + } + scope, replayReq, changed, err := prepareGeminiTopLevelReasoningReplayPayloadDoc(context.Background(), model, req, opts, doc) + if err != nil || changed || len(replayReq) != 0 { + t.Fatalf("countTokens prepare = scope:%+v len(replayReq):%d changed:%v err:%v", scope, len(replayReq), changed, err) + } + // A subsequent real generation turn must still be able to cache best-effort + // without being blocked by an unclosed countTokens reservation. + item := []byte(`{"type":"thought_signature","contentIndex":0,"partIndex":0,"targetOccurrence":0,"thoughtSignature":"EmcKZQFpFH0THU+YNRY5uVwt/0bo2hFo1RmXsMhlX9FCg2n6GssBe5sMV37KB6OrgeKKEP9fxN261QX"}`) + if !internalcache.CacheAntigravityReasoningReplayItems(model, scope.sessionKey, [][]byte{item}) { + t.Fatal("failed to cache replay item after countTokens peek") + } + got, ok := internalcache.GetAntigravityReasoningReplayItems(model, scope.sessionKey) + if !ok || len(got) != 1 { + t.Fatalf("GetAntigravityReasoningReplayItems after countTokens peek = %v, ok=%v", got, ok) + } +} diff --git a/internal/runtime/executor/apply_patch_repair_test.go b/internal/runtime/executor/apply_patch_repair_test.go index d1403004a4d..6ec34b9b78b 100644 --- a/internal/runtime/executor/apply_patch_repair_test.go +++ b/internal/runtime/executor/apply_patch_repair_test.go @@ -470,12 +470,20 @@ func TestApplyPatchRepairResponsesSourceTerminalNonStream(t *testing.T) { if len(response.Payload) != 0 { t.Errorf("failed source returned payload: %s", response.Payload) } - assertTask6PatchError(t, errExecute) + wantGatewayMsg := "Invalid apply_patch tool arguments received from upstream." + if provider == "xai" && mode == "empty" { + wantGatewayMsg = xaiEmptyStreamMessage + if status, okStatus := errExecute.(interface{ StatusCode() int }); !okStatus || status.StatusCode() != http.StatusBadGateway || errExecute.Error() != xaiEmptyStreamMessage { + t.Fatalf("expected xai empty stream 502, got %T %v", errExecute, errExecute) + } + } else { + assertTask6PatchError(t, errExecute) + } checkUsage() auth.ID += "-gateway" checkGatewayUsage := task6CaptureFailureUsage(t, auth.ID) result := task6Gateway(t, exec, auth, false) - if result.Code != http.StatusBadGateway || !strings.Contains(result.Body.String(), "Invalid apply_patch tool arguments received from upstream.") { + if result.Code != http.StatusBadGateway || !strings.Contains(result.Body.String(), wantGatewayMsg) { t.Errorf("non-stream gateway did not return clean 502: %d %s", result.Code, result.Body) } checkGatewayUsage() @@ -615,6 +623,10 @@ func TestApplyPatchRepairOrdinaryEmptyHTTPPassthrough(t *testing.T) { if errExecute != nil || len(response.Payload) != 0 { t.Fatalf("ordinary Kimi response changed: %s %v", response.Payload, errExecute) } + } else if provider == "xai" { + if status, okStatus := errExecute.(interface{ StatusCode() int }); !okStatus || status.StatusCode() != http.StatusBadGateway || errExecute.Error() != xaiEmptyStreamMessage { + t.Fatalf("ordinary xAI empty stream changed: %v", errExecute) + } } else if status, okStatus := errExecute.(interface{ StatusCode() int }); !okStatus || status.StatusCode() != http.StatusRequestTimeout { t.Fatalf("ordinary disconnect changed: %v", errExecute) } diff --git a/internal/runtime/executor/claude_cloaked_cache_repro_test.go b/internal/runtime/executor/claude_cloaked_cache_repro_test.go index d5bd0502e6c..6bdd3cad8af 100644 --- a/internal/runtime/executor/claude_cloaked_cache_repro_test.go +++ b/internal/runtime/executor/claude_cloaked_cache_repro_test.go @@ -726,3 +726,232 @@ func TestClaudeCloakedColdStartToolContinuationUsesDeterministicPromptID(t *test t.Fatalf("cold start tool continuation prompt IDs differ between failure and retry: %q != %q", p1, p2) } } + +func TestClaudeCloakedTopLevelCacheControl_Issue7366(t *testing.T) { + newCloakedOAuthEnv := func(t *testing.T) (context.Context, *cliproxyauth.Auth, *ClaudeExecutor, *[][]byte) { + t.Helper() + var capturedBodies [][]byte + call := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, errRead := io.ReadAll(req.Body) + if errRead != nil { + t.Fatal(errRead) + } + capturedBodies = append(capturedBodies, body) + call++ + response := fmt.Sprintf(`{"id":"msg_%d","type":"message","model":"claude-opus-5-5","role":"assistant","content":[{"type":"text","text":"OK"}],"usage":{"input_tokens":10,"output_tokens":2}}`, call) + header := make(http.Header) + header.Set("Content-Type", "application/json") + header.Set("request-id", fmt.Sprintf("req_issue7366_%d", call)) + return &http.Response{ + StatusCode: http.StatusOK, + Header: header, + Body: io.NopCloser(strings.NewReader(response)), + Request: req, + }, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + auth := &cliproxyauth.Auth{ + ID: "test-issue7366-oauth", + Attributes: map[string]string{"api_key": "sk-ant-oat-test-issue7366-key"}, + Metadata: map[string]any{ + "account_uuid": "11111111-2222-4333-8444-555555555555", + claudeauth.ClaudeDeviceIDsMetadataKey: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + return ctx, auth, NewClaudeExecutor(&config.Config{}), &capturedBodies + } + + t.Run("Error1_SingleTurnBareTopLevelCacheControlNoTTLMismatch", func(t *testing.T) { + ctx, auth, exec, captured := newCloakedOAuthEnv(t) + payload := []byte(`{"model":"claude-opus-5-5","max_tokens":64,"cache_control":{"type":"ephemeral"},"system":[{"type":"text","text":"You are a helpful assistant.","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"What time is it?"}]}]}`) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + Headers: http.Header{"Anthropic-Version": []string{"2023-06-01"}}, + } + if _, err := exec.Execute(ctx, auth, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, opts); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if len(*captured) != 1 { + t.Fatalf("captured %d bodies, want 1", len(*captured)) + } + seenBody := (*captured)[0] + if ojson.GetBytes(seenBody, "cache_control").Exists() { + t.Fatalf("expected top-level cache_control to be materialized and removed on cloaked request, got body: %s", seenBody) + } + if got := ojson.GetBytes(seenBody, "system.1.cache_control.ttl").String(); got != "1h" { + t.Fatalf("system.1.cache_control.ttl = %q, want 1h: %s", got, seenBody) + } + if got := ojson.GetBytes(seenBody, "messages.0.content.1.cache_control.ttl").String(); got != "1h" { + t.Fatalf("messages.0.content.1.cache_control.ttl = %q, want 1h: %s", got, seenBody) + } + if got := ojson.GetBytes(seenBody, "messages.1.content.0.cache_control.ttl").String(); got != "1h" { + t.Fatalf("messages.1.content.0.cache_control.ttl = %q, want 1h: %s", got, seenBody) + } + }) + + t.Run("Error2_ToolResultTurnWith1hTopLevelCacheControlStaysWithin4Breakpoints", func(t *testing.T) { + ctx, auth, exec, captured := newCloakedOAuthEnv(t) + payload := []byte(`{"model":"claude-opus-5-5","max_tokens":64,"cache_control":{"type":"ephemeral","ttl":"1h"},"system":[{"type":"text","text":"You are a helpful assistant.","cache_control":{"type":"ephemeral","ttl":"1h"}}],"tools":[{"name":"get_time","description":"Returns the current time.","input_schema":{"type":"object","properties":{}}}],"messages":[{"role":"user","content":[{"type":"text","text":"What time is it?"}]},{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"get_time","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":"12:00"}]}]}`) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + Headers: http.Header{"Anthropic-Version": []string{"2023-06-01"}}, + } + if _, err := exec.Execute(ctx, auth, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, opts); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if len(*captured) != 1 { + t.Fatalf("captured %d bodies, want 1", len(*captured)) + } + seenBody := (*captured)[0] + if ojson.GetBytes(seenBody, "cache_control").Exists() { + t.Fatalf("expected top-level cache_control to be materialized onto last cacheable block and removed, got body: %s", seenBody) + } + if total := countCacheControls(seenBody); total != 4 { + t.Fatalf("total cache_control count = %d, want 4: %s", total, seenBody) + } + for _, path := range []string{ + "system.1.cache_control.ttl", + "messages.0.content.1.cache_control.ttl", + "messages.1.content.0.cache_control.ttl", + "messages.3.content.0.cache_control.ttl", + } { + if got := ojson.GetBytes(seenBody, path).String(); got != "1h" { + t.Fatalf("%s = %q, want 1h: %s", path, got, seenBody) + } + } + }) + + t.Run("StreamPath_MaterializesTopLevelCacheControlAndStaysWithin4Breakpoints", func(t *testing.T) { + var seenBody []byte + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + var errRead error + seenBody, errRead = io.ReadAll(req.Body) + if errRead != nil { + t.Fatal(errRead) + } + header := make(http.Header) + header.Set("Content-Type", "text/event-stream") + sse := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_s1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-5-5\"}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + return &http.Response{ + StatusCode: http.StatusOK, + Header: header, + Body: io.NopCloser(strings.NewReader(sse)), + Request: req, + }, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + auth := &cliproxyauth.Auth{ + ID: "test-issue7366-stream-oauth", + Attributes: map[string]string{"api_key": "sk-ant-oat-test-issue7366-stream-key"}, + Metadata: map[string]any{ + "account_uuid": "11111111-2222-4333-8444-555555555555", + claudeauth.ClaudeDeviceIDsMetadataKey: []string{ + "0000000000000000000000000000000000000000000000000000000000000001", + }, + }, + } + exec := NewClaudeExecutor(&config.Config{}) + payload := []byte(`{"model":"claude-opus-5-5","max_tokens":64,"stream":true,"cache_control":{"type":"ephemeral","ttl":"1h"},"system":[{"type":"text","text":"You are a helpful assistant.","cache_control":{"type":"ephemeral","ttl":"1h"}}],"tools":[{"name":"get_time","description":"Returns the current time.","input_schema":{"type":"object","properties":{}}}],"messages":[{"role":"user","content":[{"type":"text","text":"What time is it?"}]},{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"get_time","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":"12:00"}]}]}`) + res, err := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + Headers: http.Header{"Anthropic-Version": []string{"2023-06-01"}}, + }) + if err != nil { + t.Fatalf("ExecuteStream() error = %v", err) + } + if res != nil && res.Chunks != nil { + for range res.Chunks { + } + } + if ojson.GetBytes(seenBody, "cache_control").Exists() { + t.Fatalf("expected top-level cache_control to be removed in stream path, got: %s", seenBody) + } + if total := countCacheControls(seenBody); total != 4 { + t.Fatalf("total cache_control count = %d, want 4: %s", total, seenBody) + } + }) + + t.Run("DirectAPIKeyPassthroughPreservesTopLevelCacheControlWithoutSyntheticBlocks", func(t *testing.T) { + var seenBody []byte + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + seenBody, _ = io.ReadAll(req.Body) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"msg_direct","type":"message","model":"claude-opus-5-5","role":"assistant","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":1,"output_tokens":1}}`)), + Request: req, + }, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + auth := &cliproxyauth.Auth{ + Attributes: map[string]string{ + "api_key": "sk-ant-api03-direct-top-cc-test", + "base_url": "https://api.anthropic.com", + }, + } + payload := []byte(`{"model":"claude-opus-5-5","max_tokens":32,"cache_control":{"type":"ephemeral"},"system":[{"type":"text","text":"caller system"}],"messages":[{"role":"user","content":"hello"}]}`) + if _, err := NewClaudeExecutor(&config.Config{}).Execute(ctx, auth, cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: payload}, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + Headers: http.Header{"User-Agent": {"custom-sdk/1.0"}}, + }); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if got := ojson.GetBytes(seenBody, "cache_control.type").String(); got != "ephemeral" { + t.Fatalf("direct API key top-level cache_control.type = %q, want ephemeral: %s", got, seenBody) + } + if ojson.GetBytes(seenBody, "system.0.cache_control").Exists() || ojson.GetBytes(seenBody, "messages.0.content.0.cache_control").Exists() { + t.Fatalf("direct API key request with top-level cache_control must not gain synthetic block breakpoints: %s", seenBody) + } + }) + + t.Run("HelpersRespectAndMaterializeTopLevelCacheControl", func(t *testing.T) { + withScope := []byte(`{"cache_control":{"type":"ephemeral","scope":"global"},"system":"Sys","messages":[{"role":"user","content":"Hello"}]}`) + ensured := ensureCacheControl(withScope) + if ojson.GetBytes(ensured, "cache_control").Exists() { + t.Fatalf("ensureCacheControl should remove materialized top-level cache_control: %s", ensured) + } + if got := ojson.GetBytes(ensured, "messages.0.content.0.cache_control.scope").String(); got != "global" { + t.Fatalf("messages.0.content.0.cache_control.scope = %q, want global: %s", got, ensured) + } + + // When top-level cache_control remains (e.g. direct call to enforceCacheControlLimit / upgrade / normalize / strip), + // helpers still account for it. + fiveMarkers := []byte(`{ + "cache_control":{"type":"ephemeral"}, + "system":[ + {"type":"text","text":"s0","cache_control":{"type":"ephemeral"}}, + {"type":"text","text":"s1","cache_control":{"type":"ephemeral"}} + ], + "messages":[{ + "role":"user", + "content":[ + {"type":"text","text":"m0","cache_control":{"type":"ephemeral"}}, + {"type":"text","text":"m1","cache_control":{"type":"ephemeral"}} + ] + }] + }`) + limited := enforceCacheControlLimit(fiveMarkers, 4) + if total := countCacheControls(limited); total != 4 { + t.Fatalf("countCacheControls(limited) = %d, want 4: %s", total, limited) + } + upgraded := upgradeClaudeCacheControlTTL(limited, claudeCacheControlTTL1h) + if got := ojson.GetBytes(upgraded, "cache_control.ttl").String(); got != "1h" { + t.Fatalf("top-level cache_control.ttl after upgrade = %q, want 1h: %s", got, upgraded) + } + stripped := stripClaudeCacheControlTTL(upgraded) + if ojson.GetBytes(stripped, "cache_control.ttl").Exists() { + t.Fatalf("top-level cache_control.ttl should be stripped: %s", stripped) + } + mixedOrder := []byte(`{ + "cache_control":{"type":"ephemeral","ttl":"1h"}, + "messages":[{"role":"user","content":[{"type":"text","text":"m0","cache_control":{"type":"ephemeral"}}]}] + }`) + normalized := normalizeCacheControlTTL(mixedOrder) + if ojson.GetBytes(normalized, "cache_control.ttl").Exists() { + t.Fatalf("normalizeCacheControlTTL must downgrade top-level 1h TTL after a 5m block: %s", normalized) + } + }) +} diff --git a/internal/runtime/executor/claude_cloaked_date_pin_test.go b/internal/runtime/executor/claude_cloaked_date_pin_test.go index 26357d2c358..86608119f52 100644 --- a/internal/runtime/executor/claude_cloaked_date_pin_test.go +++ b/internal/runtime/executor/claude_cloaked_date_pin_test.go @@ -346,15 +346,21 @@ func TestClaudeCloakedDateReminderProbeOverrideDoesNotReinitializeSessionDate(t func TestClaudeCloakedDateReminderPersistsAcrossRestartWithLocalBBoltKV(t *testing.T) { homekv.ClearCurrent() - _ = kvstore.ShutdownLocal() + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatalf("kvstore.ShutdownLocal() setup error = %v", errShutdown) + } helps.ResetClaudeDiagnosticsForTest() + + // Cleanups run in LIFO order: close bbolt before TempDir removes its files. + dbPath := filepath.Join(t.TempDir(), "kv.db") t.Cleanup(func() { homekv.ClearCurrent() - _ = kvstore.ShutdownLocal() + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Errorf("kvstore.ShutdownLocal() cleanup error = %v", errShutdown) + } helps.ResetClaudeDiagnosticsForTest() }) - dbPath := filepath.Join(t.TempDir(), "kv.db") if errCfg := kvstore.ConfigureLocal(true, dbPath); errCfg != nil { t.Fatalf("kvstore.ConfigureLocal(true, %q) error = %v", dbPath, errCfg) } diff --git a/internal/runtime/executor/claude_executor.go b/internal/runtime/executor/claude_executor.go index a90251d9025..7af56cde8ea 100644 --- a/internal/runtime/executor/claude_executor.go +++ b/internal/runtime/executor/claude_executor.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "net/http" + "sort" "strings" "time" @@ -19,6 +20,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/util" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + cliproxysession "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" log "github.com/sirupsen/logrus" ) @@ -34,6 +36,7 @@ type ClaudeExecutor struct { // oauthToolAliases is shared by every ForAPIKey copy of this executor; // constructors allocate it so copies made per request reuse one store. oauthToolAliases *claudeOAuthToolAliasStore + threadBetas *helps.ClaudeThreadBetaStore } type claudeOAuthCancellationError struct { @@ -342,7 +345,104 @@ func stripTranslatedDefaultMaxTokens(from sdktranslator.Format, originalPayload, } func NewClaudeExecutor(cfg *config.Config) *ClaudeExecutor { - return &ClaudeExecutor{cfg: cfg, oauthToolAliases: &claudeOAuthToolAliasStore{}} + return &ClaudeExecutor{cfg: cfg, oauthToolAliases: &claudeOAuthToolAliasStore{}, threadBetas: &helps.ClaudeThreadBetaStore{}} +} + +func (e *ClaudeExecutor) prepareClaudeThreadBetas(ctx context.Context, request *http.Request, auth *cliproxyauth.Auth, body []byte, extraBetas []string, payloadBetasConfigured bool, incomingHeaders http.Header, uncloak bool, metadataSets ...map[string]any) (*helps.ClaudeThreadBetaRequest, error) { + if !ojson.GetBytesNoCopy(body, "thread").IsObject() { + return nil, nil + } + apiKey, _ := claudeCreds(auth) + fp := resolveClaudeFingerprintPolicy(e.cfg, auth, apiKey) + identity := claudeDiagnosticsCredentialIdentity(auth) + if identity == "" { + identity = apiKey + } + caller := resolveClaudeMCPAliasOptions(ctx, metadataSets...).secret + scope := sha256.Sum256([]byte(e.upstreamRequestLogProvider() + "\x00" + request.URL.Scheme + "://" + request.URL.Host + request.URL.Path + "\x00" + identity + "\x00" + caller)) + var hd config.ClaudeHeaderDefaults + if e.cfg != nil { + hd = e.cfg.ClaudeHeaderDefaults + } + var customBetas []string + betaAttrs := make(map[string]string) + if auth != nil && !isAnthropicUpstreamURL(request.URL) { + for name, value := range auth.Attributes { + if strings.EqualFold(name, "header:Anthropic-Beta") { + customBetas = append(customBetas, value) + betaAttrs[name] = value + } + } + } + sort.Strings(customBetas) + customBetaApplied := false + if len(customBetas) > 0 { + probe := (&http.Request{Header: make(http.Header)}).WithContext(request.Context()) + util.ApplyCustomHeadersFromAttrs(probe, betaAttrs, incomingHeaders) + resolved := helps.HeaderValuesCaseInsensitive(probe.Header, "Anthropic-Beta") + customBetaApplied = len(resolved) > 0 + customBetas = append(customBetas, strings.Join(resolved, ",")) + } + policy := sha256.Sum256([]byte(fmt.Sprintf("%q\x00%q\x00%q\x00%t\x00%t", hd.AnthropicBetaStrip, hd.AnthropicBetaAppend, customBetas, uncloak, fp.UseOAuthBetas))) + // Literal executors need the same lazy-allocation protection as alias state. + claudeOAuthToolAliasStoreInitMu.Lock() + if e.threadBetas == nil { + e.threadBetas = &helps.ClaudeThreadBetaStore{} + } + store := e.threadBetas + claudeOAuthToolAliasStoreInitMu.Unlock() + // Track only body declarations that actually contribute independent flags. + independent := claudeRequestedBetas(strings.Join(helps.HeaderValuesCaseInsensitive(incomingHeaders, "Anthropic-Beta"), ","), hd.AnthropicBetaAppend) + actual := claudeRequestedBetas(strings.Join(helps.HeaderValuesCaseInsensitive(request.Header, "Anthropic-Beta"), ","), nil) + var bodyBetas []string + for _, beta := range extraBetas { + beta = strings.TrimSpace(beta) + credentialBeta := fp.UseOAuthBetas && (beta == claudeOAuthBeta || beta == claudeExtendedCacheTTLBeta) + if !customBetaApplied && actual[beta] && !independent[beta] && !credentialBeta { + bodyBetas = append(bodyBetas, beta) + independent[beta] = true + } + } + state, found, errBind := store.Bind(string(scope[:]), ojson.GetBytesNoCopy(body, "thread.previous_message_id").String(), request.Header, helps.ClaudeThreadBetaPolicy{Fingerprint: hex.EncodeToString(policy[:]), BodyBetas: strings.Join(bodyBetas, ","), PayloadConfigured: payloadBetasConfigured}) + if errBind != nil { + return nil, errBind + } + if !found { + return nil, helps.ClaudeThreadBetaConflictError{} + } + // The restored profile must satisfy this final business payload on every path. + declared := claudeRequestedBetas(strings.Join(helps.HeaderValuesCaseInsensitive(request.Header, "Anthropic-Beta"), ","), nil) + for beta, needed := range map[string]bool{ + claudeFastModeBeta: strings.EqualFold(ojson.GetBytesNoCopy(body, "speed").String(), "fast"), + claudeAdvisorToolBeta: claudeBodyHasAdvisorTool(body), + claudeThinkingBindingBeta: ojson.GetBytesNoCopy(body, "thinking.block_binding").Exists(), + claudeExtendedCacheTTLBeta: helps.ClaudePayloadHas1hTTL(body), + } { + if needed && !declared[beta] { + return nil, helps.ClaudeThreadBetaConflictError{} + } + } + selectedAuthID := "" + for _, metadata := range metadataSets { + if selectedAuthID = metadataString(metadata, cliproxyexecutor.SelectedAuthMetadataKey); selectedAuthID != "" { + break + } + } + if auth != nil && auth.ID != "" && selectedAuthID == auth.ID && e.upstreamRequestLogProvider() == "claude" { + ownerScope := cliproxysession.ClaudeThreadCallerScope(helps.APIKeyFromContext(ctx), metadataSets...) + authID := strings.Clone(auth.ID) + state.OnCommit(func(messageID string) { + cliproxysession.RememberClaudeThreadAuth(ownerScope, messageID, authID) + }) + } + return state, nil +} + +// WithConfig rebinds configuration without discarding successful Thread state. +// Like ForAPIKey, the copy shares pointer-owned stores and copies no mutexes. +func (e ClaudeExecutor) WithConfig(cfg *config.Config) *ClaudeExecutor { + e.cfg = cfg + return &e } func (e *ClaudeExecutor) Identifier() string { return "claude" } diff --git a/internal/runtime/executor/claude_executor_beta_passthrough_test.go b/internal/runtime/executor/claude_executor_beta_passthrough_test.go index 5c37b17c1de..7c351ee5160 100644 --- a/internal/runtime/executor/claude_executor_beta_passthrough_test.go +++ b/internal/runtime/executor/claude_executor_beta_passthrough_test.go @@ -21,7 +21,7 @@ func fixtureAuth() *cliproxyauth.Auth { // A caller the cloak does not recognize (a Claude Code newer than the pinned // profile) keeps betas the proxy does not manage: dropping them fails whole // turns whose features need the missing authorization (#5738). per-turn-control -// is now assembled for fable-5-1, so this uses a beta that is still unmanaged. +// and message-threads are now assembled, so this uses a beta that is still unmanaged. func TestApplyClaudeHeaders_ForwardsUnmanagedCallerBetas(t *testing.T) { t.Parallel() @@ -31,16 +31,16 @@ func TestApplyClaudeHeaders_ForwardsUnmanagedCallerBetas(t *testing.T) { t.Fatalf("NewRequest() error = %v", errReq) } incoming := http.Header{} - incoming.Set("Anthropic-Beta", "message-threads-2026-08-12") + incoming.Set("Anthropic-Beta", "future-feature-2030-01-01") if errHeaders := applyClaudeHeaders(req, auth, auth.Attributes[cliproxyauth.AttributeAPIKey], false, nil, []byte(`{"model":"claude-fable-5-1"}`), &config.Config{}, incoming, false); errHeaders != nil { t.Fatalf("applyClaudeHeaders() error = %v", errHeaders) } betas := req.Header.Get("Anthropic-Beta") - if !strings.Contains(betas, "message-threads-2026-08-12") { + if !strings.Contains(betas, "future-feature-2030-01-01") { t.Fatalf("Anthropic-Beta = %q, want unmanaged caller beta forwarded", betas) } - if !strings.Contains(betas, "mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24") { - t.Fatalf("Anthropic-Beta = %q, want fable-5-1 per-turn-control between mid-conversation-system and tool-changes", betas) + if !strings.Contains(betas, "prompt-caching-scope-2026-01-05,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24") { + t.Fatalf("Anthropic-Beta = %q, want fable-5-1 per-turn-control right after prompt-caching-scope", betas) } } diff --git a/internal/runtime/executor/claude_executor_cli_2321_test.go b/internal/runtime/executor/claude_executor_cli_2321_test.go new file mode 100644 index 00000000000..84c1bd5cadc --- /dev/null +++ b/internal/runtime/executor/claude_executor_cli_2321_test.go @@ -0,0 +1,109 @@ +package executor + +import ( + "strings" + "testing" +) + +// claudeCode2321MainBetas is the Anthropic-Beta value native Claude Code 2.1.321 +// sent for an interactive cli main-thread turn on Fable 5.2, Fable 5.1, Opus 5.5 +// and Sonnet 5.5 (captured against api.anthropic.com on 2026-11-09 with OAuth, +// in an auto-mode session, hence afk-mode). +const claudeCode2321MainBetas = "claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14," + + "context-management-2025-06-27,prompt-caching-scope-2026-01-05,per-turn-control-2026-07-01," + + "mid-conversation-tool-changes-2026-07-01,inline-tools-2026-09-15,advisor-tool-2026-03-01," + + "thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,mid-conversation-system-clear-at-2026-08-21," + + "effort-2025-11-24,dangerous-tool-use-2026-09-03,thinking-binding-controls-2026-08-01," + + "thinking-display-updates-2026-08-18,afk-mode-2026-01-31,extended-cache-ttl-2025-04-11," + + "cache-diagnosis-2026-04-07,message-threads-2026-08-12" + +// claudeCode2321MainBody keeps only the fields of the captured main-thread body +// that gate betas: a role=system turn with an inline tool_addition, a deferred +// tool, the advisor tool, safeguards, thread, diagnostics, and a 1h cache TTL. +func claudeCode2321MainBody(model, display string) []byte { + return []byte(`{"model":"` + model + `","max_tokens":128000,` + + `"messages":[{"role":"user","content":[{"type":"text","text":"say ok"}]},` + + `{"role":"system","content":[{"type":"text","text":"tools changed"},` + + `{"type":"tool_addition","tool":{"type":"tool_definition","definition":{"name":"mcp__docs__guide","input_schema":{"type":"object"}}}}]}],` + + `"system":[{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."},` + + `{"type":"text","text":"prompt","cache_control":{"type":"ephemeral","ttl":"1h","scope":"global"}}],` + + `"tools":[{"name":"Read","input_schema":{"type":"object"}},` + + `{"name":"DeferredToolPlaceholder","input_schema":{"type":"object"},"defer_loading":true},` + + `{"type":"advisor_20260301","name":"advisor","model":"claude-opus-5-5","defer_loading":true}],` + + `"thinking":{"type":"adaptive","display":"` + display + `"},` + + `"context_management":{"edits":[{"type":"clear_thinking_20251015","keep":"all"}]},` + + `"safeguards":{"type":"dangerous_tool_use"},"output_config":{"effort":"medium"},` + + `"thread":{"type":"create"},"diagnostics":{"previous_message_id":null},` + + `"metadata":{"user_id":"user"},"stream":true}`) +} + +func TestClaudeCodeCLIBetas_MatchesClaudeCode2321Captures(t *testing.T) { + // Haiku 5.5 moves claude-code-20250219 behind prompt-caching-scope. + haiku55 := strings.Replace(claudeCode2321MainBetas, + "claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,context-management-2025-06-27,prompt-caching-scope-2026-01-05,", + "oauth-2025-04-20,interleaved-thinking-2025-05-14,context-management-2025-06-27,prompt-caching-scope-2026-01-05,claude-code-20250219,", 1) + // The sdk-cli entrypoint sends thinking.display=omitted. + sdkCLI := withoutClaudeBeta(claudeCode2321MainBetas, claudeThinkingDisplayUpdatesBeta) + + tests := []struct { + name string + body []byte + native string + }{ + {name: "fable-5-2 cli", body: claudeCode2321MainBody("claude-fable-5-2", "updates"), native: claudeCode2321MainBetas}, + {name: "fable-5-1 cli", body: claudeCode2321MainBody("claude-fable-5-1", "updates"), native: claudeCode2321MainBetas}, + {name: "opus-5-5 cli", body: claudeCode2321MainBody("claude-opus-5-5", "updates"), native: claudeCode2321MainBetas}, + {name: "sonnet-5-5 cli", body: claudeCode2321MainBody("claude-sonnet-5-5", "updates"), native: claudeCode2321MainBetas}, + {name: "haiku-5-5 cli", body: claudeCode2321MainBody("claude-haiku-5-5", "updates"), native: haiku55}, + {name: "fable-5-2 sdk-cli", body: claudeCode2321MainBody("claude-fable-5-2", "omitted"), native: sdkCLI}, + { + name: "haiku-4-5 quota probe", + body: []byte(`{"model":"claude-haiku-4-5-20251001","max_tokens":1,"messages":[{"role":"user","content":"quota"}],"metadata":{"user_id":"user"}}`), + native: "oauth-2025-04-20,interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,context-management-2025-06-27,prompt-caching-scope-2026-01-05", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + requested := claudeRequestedBetas(tt.native, nil) + if got := claudeCodeCLIBetas(tt.body, requested, true); got != tt.native { + t.Fatalf("with native betas requested:\n got: %s\nwant: %s", got, tt.native) + } + // A caller that sends no betas gets the same list minus afk-mode, + // which Claude Code only sends from auto-mode sessions. + want := withoutClaudeBeta(tt.native, claudeAFKModeBeta) + if got := claudeCodeCLIBetas(tt.body, nil, true); got != want { + t.Fatalf("with no betas requested:\n got: %s\nwant: %s", got, want) + } + }) + } +} + +// The 2.1.321 capture of the prompt "say ok" carried cc_version=2.1.321.20d. +func TestComputeFingerprintMatchesClaudeCode2321Capture(t *testing.T) { + if got := computeFingerprint("say ok", "2.1.321"); got != "20d" { + t.Fatalf("computeFingerprint() = %q, want 20d", got) + } +} + +func TestClaudeIncludePerTurnTiming_2321CatalogModels(t *testing.T) { + for _, tc := range []struct { + model string + want bool + }{ + {model: "claude-fable-5-2", want: true}, + {model: "claude-fable-5-2[1m]", want: true}, + {model: "claude-fable-5-1", want: true}, + {model: "claude-opus-5-5", want: true}, + {model: "claude-sonnet-5-5", want: true}, + {model: "claude-mythos-5-2", want: true}, + {model: "claude-haiku-5-5", want: false}, + {model: "claude-fable-5", want: false}, + } { + t.Run(tc.model, func(t *testing.T) { + body := []byte(`{"model":"` + tc.model + `","output_config":{"timing":{"type":"enabled"}}}`) + if got := claudeIncludePerTurnTiming(body, nil); got != tc.want { + t.Fatalf("claudeIncludePerTurnTiming(%s) = %v, want %v", tc.model, got, tc.want) + } + }) + } +} diff --git a/internal/runtime/executor/claude_executor_cloaking.go b/internal/runtime/executor/claude_executor_cloaking.go index 8db1f64c3f9..d7f373db78f 100644 --- a/internal/runtime/executor/claude_executor_cloaking.go +++ b/internal/runtime/executor/claude_executor_cloaking.go @@ -11,6 +11,7 @@ import ( "net/http" "strconv" "strings" + "sync" "time" "unicode" "unicode/utf16" @@ -82,7 +83,9 @@ func getCloakConfigFromAuth(auth *cliproxyauth.Auth) (cloakMode string, strictMo strictMode = strings.EqualFold(lookupCloakAttr("cloak_strict_mode"), "true") - if wordsStr := lookupCloakAttr("cloak_sensitive_words"); wordsStr != "" { + if metaWords := claudeauth.ReadMetadataStringSlice(&auth.Metadata, "cloak_sensitive_words"); len(metaWords) > 0 { + sensitiveWords = metaWords + } else if wordsStr := lookupCloakAttr("cloak_sensitive_words"); wordsStr != "" { sensitiveWords = strings.Split(wordsStr, ",") for i := range sensitiveWords { sensitiveWords[i] = strings.TrimSpace(sensitiveWords[i]) @@ -94,6 +97,117 @@ func getCloakConfigFromAuth(auth *cliproxyauth.Auth) (cloakMode string, strictMo return cloakMode, strictMode, sensitiveWords, cacheUserID } +func getCloakReplacementsFromAuth(auth *cliproxyauth.Auth) map[string]string { + if auth == nil { + return nil + } + parseJSONStringMap := func(raw string) map[string]string { + trimmed := strings.TrimSpace(raw) + if trimmed == "" || !strings.HasPrefix(trimmed, "{") || !ojson.Valid(trimmed) { + return nil + } + parsed := ojson.Parse(trimmed) + if !parsed.IsObject() { + return nil + } + out := make(map[string]string) + parsed.ForEach(func(k, v ojson.Result) bool { + if v.Type == ojson.String { + out[k.String()] = v.String() + } + return true + }) + return config.NormalizeSensitiveWordsReplace(out) + } + if auth.Attributes != nil { + if raw := auth.Attributes["cloak_sensitive_words_replace"]; strings.TrimSpace(raw) != "" { + if parsed := parseJSONStringMap(raw); len(parsed) > 0 { + return parsed + } + } + } + if fromMap := claudeauth.ReadMetadataStringMap(&auth.Metadata, "cloak_sensitive_words_replace"); len(fromMap) > 0 { + return config.NormalizeSensitiveWordsReplace(fromMap) + } + if raw := claudeauth.ReadMetadataString(&auth.Metadata, "cloak_sensitive_words_replace"); strings.TrimSpace(raw) != "" { + return parseJSONStringMap(raw) + } + return nil +} + +func sanitizeBlankPatternRules(in []config.SensitivePatternRule) []config.SensitivePatternRule { + if len(in) == 0 { + return nil + } + out := make([]config.SensitivePatternRule, 0, len(in)) + for _, rule := range in { + if strings.TrimSpace(rule.Pattern) == "" { + continue + } + out = append(out, config.SensitivePatternRule{ + Pattern: rule.Pattern, + Replacement: rule.Replacement, + }) + } + if len(out) == 0 { + return nil + } + return out +} + +func getCloakPatternReplacementsFromAuth(auth *cliproxyauth.Auth) []config.SensitivePatternRule { + if auth == nil { + return nil + } + parseJSONPatternList := func(raw string) []config.SensitivePatternRule { + trimmed := strings.TrimSpace(raw) + if trimmed == "" || !strings.HasPrefix(trimmed, "[") || !ojson.Valid(trimmed) { + return nil + } + parsed := ojson.Parse(trimmed) + if !parsed.IsArray() { + return nil + } + var out []config.SensitivePatternRule + parsed.ForEach(func(_, item ojson.Result) bool { + if !item.IsObject() { + return true + } + patternNode := item.Get("pattern") + if patternNode.Type != ojson.String { + return true + } + out = append(out, config.SensitivePatternRule{ + Pattern: patternNode.String(), + Replacement: item.Get("replacement").String(), + }) + return true + }) + return sanitizeBlankPatternRules(out) + } + if auth.Attributes != nil { + if raw := auth.Attributes["cloak_sensitive_patterns_replace"]; strings.TrimSpace(raw) != "" { + if parsed := parseJSONPatternList(raw); len(parsed) > 0 { + return parsed + } + } + } + if pairs := claudeauth.ReadMetadataPatternPairs(&auth.Metadata, "cloak_sensitive_patterns_replace"); len(pairs) > 0 { + out := make([]config.SensitivePatternRule, 0, len(pairs)) + for _, pair := range pairs { + out = append(out, config.SensitivePatternRule{ + Pattern: pair[0], + Replacement: pair[1], + }) + } + return sanitizeBlankPatternRules(out) + } + if raw := claudeauth.ReadMetadataString(&auth.Metadata, "cloak_sensitive_patterns_replace"); strings.TrimSpace(raw) != "" { + return parseJSONPatternList(raw) + } + return nil +} + // injectFakeUserID generates and injects a fake user ID into the request metadata. // When useCache is false, a new user ID is generated for every call. func injectFakeUserID(ctx context.Context, payload []byte, apiKey string, useCache bool) ([]byte, error) { @@ -696,12 +810,12 @@ Report what actually happened, not what you intended. When you say something is func checkSystemInstructionsWithMode(payload []byte, strictMode bool, keepCallerSystemTopLevel ...bool) []byte { keepAtTopLevel := len(keepCallerSystemTopLevel) > 0 && keepCallerSystemTopLevel[0] - return checkSystemInstructionsWithSigningMode(payload, strictMode, false, "2.1.280", "cli", "", keepAtTopLevel) + return checkSystemInstructionsWithSigningMode(payload, strictMode, false, "2.1.321", "cli", "", keepAtTopLevel) } func checkSystemInstructionsWithModeDoc(doc *ojson.Doc, strictMode bool, keepCallerSystemTopLevel ...bool) bool { keepAtTopLevel := len(keepCallerSystemTopLevel) > 0 && keepCallerSystemTopLevel[0] - return checkSystemInstructionsWithSigningModeDoc(doc, strictMode, false, "2.1.280", "cli", "", keepAtTopLevel) + return checkSystemInstructionsWithSigningModeDoc(doc, strictMode, false, "2.1.321", "cli", "", keepAtTopLevel) } // checkSystemInstructionsWithSigningMode keeps the top-level system in Claude @@ -2300,9 +2414,48 @@ type claudeWirePolicy struct { } type claudeCloakSettings struct { - strictMode bool - sensitiveWords []string - cacheUserID bool + strictMode bool + sensitiveWords []string + sensitiveWordsReplace map[string]string + sensitivePatternsReplace []config.SensitivePatternRule + cacheUserID bool + serverSideFallback bool +} + +const claudeMatcherCacheCapacity = 1024 + +var ( + claudeMatcherCacheMu sync.RWMutex + claudeMatcherCache = make(map[string]*helps.SensitiveWordMatcher) + claudeMatcherCacheOrder []string +) + +func (s claudeCloakSettings) buildSensitiveWordMatcher() *helps.SensitiveWordMatcher { + if len(s.sensitiveWords) == 0 && len(s.sensitiveWordsReplace) == 0 && len(s.sensitivePatternsReplace) == 0 { + return nil + } + key := helps.SensitiveWordConfigCacheKeyWithPatterns(s.sensitiveWords, s.sensitiveWordsReplace, s.sensitivePatternsReplace) + claudeMatcherCacheMu.RLock() + if cached, ok := claudeMatcherCache[key]; ok { + claudeMatcherCacheMu.RUnlock() + return cached + } + claudeMatcherCacheMu.RUnlock() + + claudeMatcherCacheMu.Lock() + defer claudeMatcherCacheMu.Unlock() + if cached, ok := claudeMatcherCache[key]; ok { + return cached + } + if len(claudeMatcherCacheOrder) >= claudeMatcherCacheCapacity { + oldest := claudeMatcherCacheOrder[0] + claudeMatcherCacheOrder = claudeMatcherCacheOrder[1:] + delete(claudeMatcherCache, oldest) + } + built := helps.BuildSensitiveWordMatcherWithPatterns(s.sensitiveWords, s.sensitiveWordsReplace, s.sensitivePatternsReplace) + claudeMatcherCache[key] = built + claudeMatcherCacheOrder = append(claudeMatcherCacheOrder, key) + return built } func isClaudeCodeIdentitySystemText(text string) bool { @@ -2415,15 +2568,20 @@ func resolveClaudeWirePolicy(cfg *config.Config, auth *cliproxyauth.Auth, apiKey } cloakCfg := resolveClaudeKeyCloakConfig(cfg, auth) attrMode, attrStrict, attrWords, attrCache := getCloakConfigFromAuth(auth) + attrWordsReplace := getCloakReplacementsFromAuth(auth) + attrPatternsReplace := getCloakPatternReplacementsFromAuth(auth) cloakMode := "auto" if cfg != nil && cfg.DisableClaudeCloakMode { cloakMode = "never" } settings := claudeCloakSettings{ - strictMode: attrStrict, - sensitiveWords: attrWords, - cacheUserID: attrCache, + strictMode: attrStrict, + sensitiveWords: attrWords, + sensitiveWordsReplace: attrWordsReplace, + sensitivePatternsReplace: attrPatternsReplace, + cacheUserID: attrCache, + serverSideFallback: cfg != nil && cfg.Claude.ServerSideFallback, } explicitMode := strings.ToLower(strings.TrimSpace(attrMode)) if attrMode != "" { @@ -2440,13 +2598,19 @@ func resolveClaudeWirePolicy(cfg *config.Config, auth *cliproxyauth.Auth, apiKey if len(cloakCfg.SensitiveWords) > 0 { settings.sensitiveWords = cloakCfg.SensitiveWords } + if len(cloakCfg.SensitiveWordsReplace) > 0 { + settings.sensitiveWordsReplace = cloakCfg.SensitiveWordsReplace + } + if len(cloakCfg.SensitivePatternsReplace) > 0 { + settings.sensitivePatternsReplace = cloakCfg.SensitivePatternsReplace + } if cloakCfg.CacheUserID != nil { settings.cacheUserID = *cloakCfg.CacheUserID } } fp := resolveClaudeFingerprintPolicy(cfg, auth, apiKey) - cloakConfigured := cloakCfg != nil || attrMode != "" || attrStrict || len(attrWords) > 0 || attrCache + cloakConfigured := cloakCfg != nil || attrMode != "" || attrStrict || len(attrWords) > 0 || len(attrWordsReplace) > 0 || len(attrPatternsReplace) > 0 || attrCache trimmedMode := strings.ToLower(strings.TrimSpace(cloakMode)) uncloak := !fp.ProfileClaudeCodeCLI && (explicitMode == "never" || explicitMode == "uncloak") explicitNever := trimmedMode == "never" && !uncloak @@ -2602,14 +2766,13 @@ func applyCloakingInternalDoc( turnOriginArgs..., ) - // In native Claude Code 2.1.258, claude-fable-5-1 requests carry: - // "fallbacks": [{"model": "claude-opus-5"}] - model := strings.ToLower(strings.TrimSpace(doc.Get("model").String())) - if isClaudeOpus55Model(model) && !isProbeOrHelper && !doc.Get("fallbacks").Exists() { - _ = doc.SetRawBytes("fallbacks", []byte(`[{"model":"claude-opus-4-8"}]`)) - } - if isClaudeFable51Model(model) && !isProbeOrHelper { - if !doc.Get("fallbacks").Exists() { + // Inject cross-model server-side refusal fallbacks only when explicitly + // enabled via upstream.claude.server-side-fallback. + if settings.serverSideFallback && !isProbeOrHelper && !doc.Get("fallbacks").Exists() { + model := strings.ToLower(strings.TrimSpace(doc.Get("model").String())) + if isClaudeOpus55Model(model) { + _ = doc.SetRawBytes("fallbacks", []byte(`[{"model":"claude-opus-4-8"}]`)) + } else if isClaudeFable51Model(model) { _ = doc.SetRawBytes("fallbacks", []byte(`[{"model":"claude-opus-5"}]`)) } } @@ -2633,10 +2796,11 @@ func applyCloakingInternalDoc( } } - // Apply sensitive word obfuscation - if obfuscateSensitiveWords && len(settings.sensitiveWords) > 0 { - matcher := helps.BuildSensitiveWordMatcher(settings.sensitiveWords) - helps.ObfuscateSensitiveWordsDoc(doc, matcher) + // Apply sensitive word obfuscation and replacements + if obfuscateSensitiveWords { + if matcher := settings.buildSensitiveWordMatcher(); matcher != nil { + helps.ObfuscateSensitiveWordsDoc(doc, matcher) + } } return true, true, nil @@ -2697,7 +2861,7 @@ func ensureCacheControlDoc(doc *ojson.Doc) bool { if doc == nil { return false } - changed := false + changed, materializedInMessages := materializeTopLevelCacheControlDoc(doc) if !claudeDocHasCacheableSystem(doc) { if injectToolsCacheControlDoc(doc) { changed = true @@ -2706,12 +2870,114 @@ func ensureCacheControlDoc(doc *ojson.Doc) bool { if injectSystemCacheControlDoc(doc) { changed = true } - if injectMessagesCacheControlDoc(doc) { + if !materializedInMessages && injectMessagesCacheControlDoc(doc) { changed = true } return changed } +func isBareEphemeralClaudeCacheControl(cc ojson.Result) bool { + if !isValidClaudeCacheControl(cc) { + return false + } + return len(cc.Map()) == 1 +} + +func buildTextBlockWithRawCacheControl(text, rawCC string) string { + if rawCC != "" { + return `{"type":"text","text":` + marshalJSONStringWithoutHTMLEscape(text) + `,"cache_control":` + rawCC + `}` + } + return buildTextBlock(text, nil) +} + +func applyTopLevelCacheControlToBlockDoc(doc *ojson.Doc, blockPath string, topCC ojson.Result) bool { + ccPath := blockPath + ".cache_control" + existingCC := doc.Get(ccPath) + if !isValidClaudeCacheControl(existingCC) || (isBareEphemeralClaudeCacheControl(existingCC) && !isBareEphemeralClaudeCacheControl(topCC)) { + if errSet := doc.SetRawBytes(ccPath, []byte(topCC.Raw)); errSet != nil { + return false + } + } + return doc.Delete("cache_control") == nil +} + +// materializeTopLevelCacheControlDoc moves a top-level cache_control (Anthropic +// automatic prompt caching) onto the last cacheable block in the request and +// removes the top-level field so it participates in the 4-breakpoint limit and +// TTL normalization/upgrades without duplicating the final breakpoint. +func materializeTopLevelCacheControlDoc(doc *ojson.Doc) (bool, bool) { + if doc == nil || doc.Len() == 0 { + return false, false + } + topCC := doc.Get("cache_control") + if !isValidClaudeCacheControl(topCC) { + return false, false + } + + var scanner claudeStreamDocScanner + scanner.scan(doc, false, false) + if scanner.messagesIsArray && scanner.lastMessageIndex >= 0 { + if scanner.lastEligibleIndex >= 0 && scanner.lastMsgRole == "system" && scanner.lastMsgContentIsNonEmptyString { + contentPath := fmt.Sprintf("messages.%d.content", scanner.lastMessageIndex) + finalContent := doc.Get(contentPath) + if finalContent.Type == ojson.String && strings.TrimSpace(finalContent.String()) != "" { + newContent := "[" + buildTextBlockWithRawCacheControl(finalContent.String(), topCC.Raw) + "]" + if doc.SetRawBytes(contentPath, []byte(newContent)) == nil && doc.Delete("cache_control") == nil { + return true, true + } + } + } + if scanner.lastEligibleIndex >= 0 { + if scanner.lastEligibleContentIsArray && scanner.lastEligibleTargetBlockIndex >= 0 { + blockPath := fmt.Sprintf("messages.%d.content.%d", scanner.lastEligibleIndex, scanner.lastEligibleTargetBlockIndex) + if applyTopLevelCacheControlToBlockDoc(doc, blockPath, topCC) { + return true, true + } + } + if scanner.lastEligibleContentIsNonEmptyStr { + contentPath := fmt.Sprintf("messages.%d.content", scanner.lastEligibleIndex) + contentRes := doc.Get(contentPath) + if contentRes.Type == ojson.String && strings.TrimSpace(contentRes.String()) != "" { + newContent := "[" + buildTextBlockWithRawCacheControl(contentRes.String(), topCC.Raw) + "]" + if doc.SetRawBytes(contentPath, []byte(newContent)) == nil && doc.Delete("cache_control") == nil { + return true, true + } + } + } + } + } + + system := doc.Get("system") + if system.IsArray() { + if lastSysIdx := lastCacheableClaudeSystemIndex(system); lastSysIdx >= 0 { + return applyTopLevelCacheControlToBlockDoc(doc, fmt.Sprintf("system.%d", lastSysIdx), topCC), false + } + } else if system.Type == ojson.String && strings.TrimSpace(system.String()) != "" { + newSystem := "[" + buildTextBlockWithRawCacheControl(system.String(), topCC.Raw) + "]" + if doc.SetRawBytes("system", []byte(newSystem)) == nil { + return doc.Delete("cache_control") == nil, false + } + } + + tools := doc.Get("tools") + if tools.IsArray() { + lastEligibleToolIndex := -1 + idx := 0 + tools.ForEach(func(_, tool ojson.Result) bool { + if !tool.Get("defer_loading").Bool() { + lastEligibleToolIndex = idx + } + idx++ + return true + }) + if lastEligibleToolIndex >= 0 { + return applyTopLevelCacheControlToBlockDoc(doc, fmt.Sprintf("tools.%d", lastEligibleToolIndex), topCC), false + } + } + + return false, false +} + // claudePayloadHasCacheableSystem reports whether the payload has a system prompt // that injectSystemCacheControl can actually host a breakpoint on. An absent key, an // empty array, an array of only empty/whitespace text blocks, and an empty string @@ -2792,6 +3058,20 @@ func upgradeClaudeCacheControlTTL(payload []byte, ttl string) []byte { return doc.Bytes() } +func claudeCacheControlPath(path string) string { + if path == "" { + return "cache_control" + } + return path + ".cache_control" +} + +func claudeCacheControlTTLPath(path string) string { + if path == "" { + return "cache_control.ttl" + } + return path + ".cache_control.ttl" +} + func upgradeClaudeCacheControlTTLDoc(doc *ojson.Doc, ttl string) bool { if ttl == "" || doc == nil || doc.Len() == 0 { return false @@ -2813,7 +3093,7 @@ func upgradeClaudeCacheControlTTLDoc(doc *ojson.Doc, ttl string) bool { upgraded += `,"scope":` + scope.Raw } upgraded += "}" - if errSet := doc.SetRawBytes(path+".cache_control", []byte(upgraded)); errSet == nil { + if errSet := doc.SetRawBytes(claudeCacheControlPath(path), []byte(upgraded)); errSet == nil { changed = true } return true @@ -2846,7 +3126,7 @@ func stripClaudeCacheControlTTLDoc(doc *ojson.Doc) bool { if !cacheControl.IsObject() || !cacheControl.Get("ttl").Exists() { return true } - if errDel := doc.Delete(path + ".cache_control.ttl"); errDel == nil { + if errDel := doc.Delete(claudeCacheControlTTLPath(path)); errDel == nil { changed = true } return true @@ -2861,6 +3141,7 @@ const ( claudeSecTools claudeSecSystem claudeSecMessages + claudeSecTopCacheControl ) const ( @@ -2936,6 +3217,7 @@ type claudeStreamDocScanner struct { sysCCBuf [8]claudeScannedCC msgCC []claudeScannedCC msgCCBuf [16]claudeScannedCC + topCC []byte messagesIsArray bool messagesLen int @@ -2974,6 +3256,7 @@ func (s *claudeStreamDocScanner) scan(doc *ojson.Doc, collectCC, stopOnFirstUser s.toolCC = s.toolCCBuf[:0] s.sysCC = s.sysCCBuf[:0] s.msgCC = s.msgCCBuf[:0] + s.topCC = nil _, _ = doc.WriteTo(s) } @@ -3041,6 +3324,8 @@ func (s *claudeStreamDocScanner) finishCapture(p []byte, endIdx int) { s.sysCC = append(s.sysCC, claudeScannedCC{idx1: s.elemIdx, raw: stored}) case claudeSecMessages: s.msgCC = append(s.msgCC, claudeScannedCC{idx1: s.elemIdx, idx2: s.blockIdx, raw: stored}) + case claudeSecTopCacheControl: + s.topCC = stored } } @@ -3168,6 +3453,8 @@ func (s *claudeStreamDocScanner) finishKey() { s.topSection = claudeSecSystem case "messages": s.topSection = claudeSecMessages + case "cache_control": + s.topSection = claudeSecTopCacheControl default: s.topSection = claudeSecNone } @@ -3212,6 +3499,10 @@ func (s *claudeStreamDocScanner) finishKey() { func (s *claudeStreamDocScanner) startValue(c byte, idx int) { switch s.depth { + case 1: + if s.topSection == claudeSecTopCacheControl && s.collectCC && s.isObj[1] { + s.startCapture(1, idx) + } case 2: if s.topSection != claudeSecNone && !s.isObj[2] { if s.topSection == claudeSecMessages { @@ -3618,6 +3909,14 @@ func forEachClaudeCacheControlPathDoc(doc *ojson.Doc, visit func(path string, ca return } } + if len(scanner.topCC) > 0 { + ccRes := util.ParseGJSONBytesNoCopy(scanner.topCC) + if ccRes.Exists() { + if !visit("", ccRes) { + return + } + } + } } // forEachClaudeCacheControlBlock walks every block that can carry cache_control @@ -3728,11 +4027,15 @@ func shouldEnsureCacheControlDoc(doc *ojson.Doc, cloaked, confirmedClaudeCode bo } func countCacheControls(payload []byte) int { - return countCacheControlsResult( + count := countCacheControlsResult( ojson.GetBytesNoCopy(payload, "system"), ojson.GetBytesNoCopy(payload, "tools"), ojson.GetBytesNoCopy(payload, "messages"), ) + if isValidClaudeCacheControl(ojson.GetBytesNoCopy(payload, "cache_control")) { + count++ + } + return count } func countCacheControlsDoc(doc *ojson.Doc) int { @@ -3829,7 +4132,7 @@ func normalizeCacheControlTTLDoc(doc *ojson.Doc) bool { if !seen5m { return true } - if errDel := doc.Delete(path + ".cache_control.ttl"); errDel == nil { + if errDel := doc.Delete(claudeCacheControlTTLPath(path)); errDel == nil { modified = true } return true @@ -3875,13 +4178,15 @@ func enforceCacheControlLimitDoc(doc *ojson.Doc, maxBlocks int) bool { maxBlocks-- } - var toolPaths, systemPaths, messagePaths []string + var toolPaths, systemPaths, messagePaths, topPaths []string forEachClaudeCacheControlPathDoc(doc, func(path string, cc ojson.Result) bool { if !isValidClaudeCacheControl(cc) { return true } - ccPath := path + ".cache_control" + ccPath := claudeCacheControlPath(path) switch { + case path == "": + topPaths = append(topPaths, ccPath) case strings.HasPrefix(path, "tools."): toolPaths = append(toolPaths, ccPath) case strings.HasPrefix(path, "system."): @@ -3892,7 +4197,7 @@ func enforceCacheControlLimitDoc(doc *ojson.Doc, maxBlocks int) bool { return true }) - total := len(toolPaths) + len(systemPaths) + len(messagePaths) + total := len(toolPaths) + len(systemPaths) + len(messagePaths) + len(topPaths) if total <= maxBlocks { return false } @@ -3936,6 +4241,10 @@ func enforceCacheControlLimitDoc(doc *ojson.Doc, maxBlocks int) bool { if len(toolPaths) > 0 { deleteList(toolPaths[len(toolPaths)-1:]) } + if excess <= 0 { + return changed + } + deleteList(topPaths) return changed } diff --git a/internal/runtime/executor/claude_executor_diagnostics_test.go b/internal/runtime/executor/claude_executor_diagnostics_test.go index 5f3e7cdbfd0..b8c96baa4ad 100644 --- a/internal/runtime/executor/claude_executor_diagnostics_test.go +++ b/internal/runtime/executor/claude_executor_diagnostics_test.go @@ -193,7 +193,7 @@ func TestClaudeExecutorContinuityAdvancesRequestIDAndPromptIDInBillingHeader(t * // Verify Turn 1: h1 := capturedBillingHeaders[0] - if !strings.Contains(h1, "cc_version=2.1.280.") || !strings.Contains(h1, "cc_entrypoint=cli;") || !strings.Contains(h1, "cch=") { + if !strings.Contains(h1, "cc_version=2.1.321.") || !strings.Contains(h1, "cc_entrypoint=cli;") || !strings.Contains(h1, "cch=") { t.Fatalf("h1 invalid: %s", h1) } if strings.Contains(h1, "cc_prev_req=") { diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index ed58582cee2..f0eb97c91e2 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -220,6 +220,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r return resp, err } } + helps.NormalizeClaudeToolPropertyNamesDoc(doc) sanitizeClaudeMessagesForClaudeUpstreamWithDebugDoc(ctx, doc, baseModel, helps.APIKeyModelIsCompat(req)) if fp.ApplyCLIIdentity { err = applyClaudeCLIIdentityDoc(doc, auth, apiKey, url, claudeSessionID, fp.SynthesizeIdentity) @@ -227,9 +228,10 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r return resp, err } } - if cloaked && len(wireSettings.sensitiveWords) > 0 { - matcher := helps.BuildSensitiveWordMatcher(wireSettings.sensitiveWords) - helps.ObfuscateSensitiveWordsDoc(doc, matcher) + if cloaked { + if matcher := wireSettings.buildSensitiveWordMatcher(); matcher != nil { + helps.ObfuscateSensitiveWordsDoc(doc, matcher) + } } cchBilling := "" if cchSigning { @@ -250,7 +252,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r touchedPayloadPaths := helps.ApplyPayloadConfigWithTrackedPathsDoc( e.cfg, baseModel, to.String(), from.String(), "", doc, stripTranslatedDefaultMaxTokens(from, originalPayload, originalTranslated), helps.PayloadRequestedModel(opts, req.Model), helps.PayloadRequestPath(opts), opts.Headers, - "diagnostics", + "diagnostics", "betas", ) if touchedPayloadPaths["diagnostics"] { diagnosticsState = claudeDiagnosticsRequestState{} @@ -290,6 +292,10 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r ); errHeaders != nil { return resp, errHeaders } + threadBetas, errThread := e.prepareClaudeThreadBetas(ctx, httpReq, auth, bodyForUpstream, extraBetas, touchedPayloadPaths["betas"], incomingHeaders, wirePolicy.Uncloak, opts.Metadata, req.Metadata) + if errThread != nil { + return resp, errThread + } fastRequest := isAnthropicUpstreamBase(baseURL) && claudeRequestIsFast(httpReq, bodyForUpstream) authID, authLabel, authType, authValue := claudeAuthLogIdentity(auth) helps.RecordAPIRequest(ctx, e.cfg, helps.UpstreamRequestLog{ @@ -328,13 +334,15 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r return resp, errClassified } b, readErr := io.ReadAll(errBody) + helps.AppendAPIResponseChunk(ctx, e.cfg, b) if readErr != nil { helps.RecordAPIResponseError(ctx, e.cfg, readErr) msg := fmt.Sprintf("failed to read error response body: %v", readErr) helps.LogWithRequestID(ctx).Warn(msg) - b = []byte(msg) + if len(b) == 0 { + b = []byte(msg) + } } - helps.AppendAPIResponseChunk(ctx, e.cfg, b) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) if errClose := errBody.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) @@ -358,18 +366,20 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r } }() data, err := io.ReadAll(decodedBody) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, err) } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) var streamUsage helps.StreamUsageBuffer + threadMessageID := "" if upstreamStream { if errValidate := validateClaudeStreamingResponse(data); errValidate != nil { helps.RecordAPIResponseError(ctx, e.cfg, errValidate) return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, errValidate) } - if msgID := claudeMessageIDFromSSE(data); msgID != "" { + threadMessageID = claudeMessageIDFromSSE(data) + if msgID := threadMessageID; msgID != "" { commitClaudeContinuity(diagnosticsState, msgID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) e.rememberClaudeOAuthToolAliases(body, oauthToolNamesReverseMap, msgID) } @@ -411,6 +421,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r data = bytes.Join(lines, []byte("\n")) } else { messageID := claudeMessageIDFromResponse(data) + threadMessageID = messageID commitClaudeContinuity(diagnosticsState, messageID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) e.rememberClaudeOAuthToolAliases(body, oauthToolNamesReverseMap, messageID) reporter.ObserveResponseModel(data) @@ -453,6 +464,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r if responseFormat == sdktranslator.FormatOpenAIResponse { out = helps.EnsureResponsesUsageDetails(out) } + threadBetas.Commit(threadMessageID) resp = cliproxyexecutor.Response{Payload: out, Headers: httpResp.Header.Clone()} return resp, nil } diff --git a/internal/runtime/executor/claude_executor_native_helper_test.go b/internal/runtime/executor/claude_executor_native_helper_test.go index da7893617c1..e453efb4519 100644 --- a/internal/runtime/executor/claude_executor_native_helper_test.go +++ b/internal/runtime/executor/claude_executor_native_helper_test.go @@ -30,7 +30,7 @@ func claudeNativeHelperHeaders(betas, compression string) http.Header { "Accept": {"application/json"}, "Accept-Encoding": {compression}, "Content-Type": {"application/json"}, - "User-Agent": {"claude-cli/2.1.280 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {betas}, "Anthropic-Version": {"2023-06-01"}, @@ -39,8 +39,8 @@ func claudeNativeHelperHeaders(betas, compression string) http.Header { "X-Client-Request-Id": {"66666666-7777-4888-8999-aaaaaaaaaaaa"}, "X-Stainless-Lang": {"js"}, "X-Stainless-Runtime": {"node"}, - "X-Stainless-Package-Version": {"0.112.1"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Package-Version": {"0.128.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, "X-Stainless-OS": {"MacOS"}, "X-Stainless-Arch": {"arm64"}, "X-Stainless-Retry-Count": {"0"}, diff --git a/internal/runtime/executor/claude_executor_request.go b/internal/runtime/executor/claude_executor_request.go index 425010e677b..5a11869a7da 100644 --- a/internal/runtime/executor/claude_executor_request.go +++ b/internal/runtime/executor/claude_executor_request.go @@ -54,6 +54,8 @@ const ( claudeCacheDiagnosisBeta = "cache-diagnosis-2026-04-07" claudeRedactThinkingBeta = "redact-thinking-2026-02-12" claudeAFKModeBeta = "afk-mode-2026-01-31" + claudeThinkingTokenCountBeta = "thinking-token-count-2026-05-13" + claudeMessageThreadsBeta = "message-threads-2026-08-12" ) // claudeCodeCLIConstantBetas are the betas Claude Code sends on every @@ -66,7 +68,6 @@ const ( var claudeCodeCLIConstantBetas = []string{ "interleaved-thinking-2025-05-14", claudeRedactThinkingBeta, - "thinking-token-count-2026-05-13", "context-management-2025-06-27", "prompt-caching-scope-2026-01-05", } @@ -112,6 +113,8 @@ var claudeManagedBetaSet = func() map[string]bool { claudeCacheDiagnosisBeta, claudeRedactThinkingBeta, claudeAFKModeBeta, + claudeThinkingTokenCountBeta, + claudeMessageThreadsBeta, } managed = append(managed, claudeCodeCLIConstantBetas...) managed = append(managed, claudeCodeTrailingBetas...) @@ -127,52 +130,61 @@ func isManagedClaudeBeta(beta string) bool { } // claudeCodeCLIBetas assembles the Anthropic-Beta baseline the way Claude Code -// 2.1.280 does: the list is per-request, not a fixed string. requested holds the +// 2.1.321 does: the list is per-request, not a fixed string. requested holds the // betas the caller asked for, which decide the capability flags below. // // Verified against api.anthropic.com with native 2.1.258 captures on interactive, // non-interactive, subagent, and multi-model paths (Sonnet, Opus, Fable, Haiku). -// Claude Code 2.1.280 (measured 2026-09-23, binary 80abbfe) inserts -// mid-conversation-tool-changes immediately after mid-conversation-system on the -// same non-legacy models. The betas named in issue #6054 are feature-gated in -// that binary, so they are emitted only for the model capability or body shape +// Claude Code 2.1.321 (measured 2026-11-09 on cli and sdk-cli entrypoints for +// Fable 5.2, Fable 5.1, Opus 5.5, Sonnet 5.5, Haiku 5.5 and the Haiku 4.5 quota +// probe) no longer sends mid-conversation-system even with role=system turns, +// moves thinking-token-count behind advisor-tool, sends effort ahead of +// dangerous-tool-use, and adds message-threads for bodies carrying thread. +// Feature-gated betas are emitted only for the model capability or body shape // that actually sends them, in the same relative order: // -// 1 claude-code-20250219 +// 1 claude-code-20250219 after prompt-caching-scope on Haiku 5.5; never on quota probes // 2 oauth-2025-04-20 OAuth credentials only // 3 context-1m-2025-08-07 [1m] model variants only // 4 interleaved-thinking-2025-05-14 // 5 redact-thinking-2026-02-12 cli entrypoint, no thinking.display -// 6 thinking-token-count-2026-05-13 -// 7 context-management-2025-06-27 -// 8 prompt-caching-scope-2026-01-05 -// 9 mid-conversation-system-2026-04-07 models accepting a role=system turn -// 10 per-turn-control-2026-07-01 opus-5-5 and fable-5-1, or requested -// 11 timing-2026-09-09 per-turn timing body, or requested -// 12 mid-conversation-tool-changes-2026-07-01 same models as mid-conversation-system -// 13 inline-tools-2026-09-15 inline tool_addition blocks, or requested -// 14 advisor-tool-2026-03-01 requests declaring advisor tools or requesting advisor beta +// 6 context-management-2025-06-27 +// 7 prompt-caching-scope-2026-01-05 +// 8 mid-conversation-system-2026-04-07 requested only, on models accepting a role=system turn +// 9 per-turn-control-2026-07-01 per-turn-control models, or requested +// 10 timing-2026-09-09 per-turn timing body, or requested +// 11 mid-conversation-tool-changes-2026-07-01 models accepting a role=system turn, except Sonnet 5 +// 12 inline-tools-2026-09-15 inline tool_addition blocks, or requested +// 13 advisor-tool-2026-03-01 requests declaring advisor tools or requesting advisor beta +// 14 thinking-token-count-2026-05-13 every request except quota probes // 15 advanced-tool-use-2025-11-20 requests using tool search or another advanced tool-use feature -// 16 mid-conversation-system-clear-at-2026-08-21 messages with clear_at, or requested -// 17 dangerous-tool-use-2026-09-03 safeguards body, or requested -// 18 effort-2025-11-24 effort-supporting models with active thinking +// 16 mid-conversation-system-clear-at-2026-08-21 progress-display models, messages with clear_at, or requested +// 17 effort-2025-11-24 effort-supporting models with active thinking +// 18 dangerous-tool-use-2026-09-03 safeguards body, or requested // 19 server-side-fallback-2026-06-01 requests with fallbacks or requested // 20 fallback-credit-2026-06-01 requests with fallback tokens, fallbacks, or requested // 21 structured-outputs-2025-12-15 structured output requests -// 22 thinking-binding-controls-2026-08-01 thinking.block_binding, or requested +// 22 thinking-binding-controls-2026-08-01 thinking.block_binding, adaptive progress-display models, or requested // 23 thinking-display-updates-2026-08-18 requests with thinking.display=updates -// 24 thinking-resumption-2026-07-17 requested only; the 2.1.280 flag defaults off +// 24 thinking-resumption-2026-07-17 requested only; the flag defaults off // 25 fast-mode-2026-02-01 speed:fast requests only // 26 afk-mode-2026-01-31 auto-mode sessions, forwarded when the caller sends it // 27 extended-cache-ttl-2025-04-11 OAuth credentials (omitted on subagent & probe) // 28 prompt-caching-evict-2026-05-12 evict_on_complete, or requested // 29 cache-diagnosis-2026-04-07 requests with diagnostics only +// 30 message-threads-2026-08-12 requests with a thread object, or requested // // An empty body keeps the optimistic role=system default, matching the cloaking // policy for unknown and future model IDs. func claudeCodeCLIBetas(body []byte, requested map[string]bool, oauthToken bool) string { - betas := make([]string, 0, len(claudeCodeCLIConstantBetas)+len(claudeCodeTrailingBetas)+10) - betas = append(betas, claudeCodeBeta) + betas := make([]string, 0, len(claudeCodeCLIConstantBetas)+len(claudeCodeTrailingBetas)+12) + isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) + isQuotaProbe := helps.IsClaudeQuotaProbeRequest(body) + model := ojson.GetBytesNoCopy(body, "model").String() + claudeCodeAfterScope := isClaudeHaiku55Model(model) + if !isQuotaProbe && !claudeCodeAfterScope { + betas = append(betas, claudeCodeBeta) + } if oauthToken { betas = append(betas, claudeOAuthBeta) } @@ -186,15 +198,20 @@ func claudeCodeCLIBetas(body []byte, requested map[string]bool, oauthToken bool) } betas = append(betas, beta) } + if !isQuotaProbe && claudeCodeAfterScope { + betas = append(betas, claudeCodeBeta) + } if !claudeUsesLegacySystemReminder(body) { - betas = append(betas, claudeMidConvSystemBeta) + if requested[claudeMidConvSystemBeta] { + betas = append(betas, claudeMidConvSystemBeta) + } if claudeIncludePerTurnControl(body, requested) { betas = append(betas, claudePerTurnControlBeta) } if claudeIncludePerTurnTiming(body, requested) { betas = append(betas, claudePerTurnTimingBeta) } - if !isClaudeSonnet5Model(ojson.GetBytesNoCopy(body, "model").String()) { + if !isClaudeSonnet5Model(model) { betas = append(betas, claudeMidConvToolChangesBeta) } if claudeIncludeInlineTools(body, requested) { @@ -213,19 +230,21 @@ func claudeCodeCLIBetas(body []byte, requested map[string]bool, oauthToken bool) if requested[claudeAdvisorToolBeta] || claudeBodyHasAdvisorTool(body) { betas = append(betas, claudeAdvisorToolBeta) } + if !isQuotaProbe || requested[claudeThinkingTokenCountBeta] { + betas = append(betas, claudeThinkingTokenCountBeta) + } if requested[claudeAdvancedToolUseBeta] || claudeBodyUsesAdvancedToolUse(body) { betas = append(betas, claudeAdvancedToolUseBeta) } if !claudeUsesLegacySystemReminder(body) && claudeIncludeMidConvClearAt(body, requested) { betas = append(betas, claudeMidConvSystemClearAtBeta) } - if requested[claudeDangerousToolUseBeta] || ojson.GetBytesNoCopy(body, "safeguards").Exists() { - betas = append(betas, claudeDangerousToolUseBeta) - } if claudeRequestSupportsEffort(body, requested) { betas = append(betas, claudeEffortBeta) } - isProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) + if requested[claudeDangerousToolUseBeta] || ojson.GetBytesNoCopy(body, "safeguards").Exists() { + betas = append(betas, claudeDangerousToolUseBeta) + } if !isProbeOrHelper && (requested[claudeServerSideFallbackBeta] || ojson.GetBytesNoCopy(body, "fallbacks").Exists()) { betas = append(betas, claudeServerSideFallbackBeta) } @@ -274,6 +293,9 @@ func claudeCodeCLIBetas(body []byte, requested map[string]bool, oauthToken bool) if diagnostics := ojson.GetBytesNoCopy(body, "diagnostics"); diagnostics.IsObject() { betas = append(betas, claudeCacheDiagnosisBeta) } + if requested[claudeMessageThreadsBeta] || ojson.GetBytesNoCopy(body, "thread").IsObject() { + betas = append(betas, claudeMessageThreadsBeta) + } return strings.Join(betas, ",") } @@ -289,7 +311,7 @@ func claudeCanonicalModel(model string) string { return model } -// claudeModelHasPerTurnEffort reports models whose 2.1.280 catalog capability +// claudeModelHasPerTurnEffort reports models whose 2.1.321 catalog capability // per_turn_effort puts per-turn-control-2026-07-01 on every first-party request. func isClaudeOpus55Model(model string) bool { model = claudeCanonicalModel(model) @@ -337,7 +359,7 @@ func isClaudeFable51OnlyModel(model string) bool { // prefix fails binding validation unless the request opts into dropping them. // See https://platform.claude.com/docs/en/build-with-claude/preserved-thinking func isClaudePreservedThinkingModel(model string) bool { - return isClaudeOpus55Model(model) || isClaudeSonnet55Model(model) || isClaudeHaiku55Model(model) || isClaudeFable51OnlyModel(model) + return isClaudeOpus55Model(model) || isClaudeSonnet55Model(model) || isClaudeHaiku55Model(model) || isClaudeFable51OnlyModel(model) || isClaudeFable52Model(model) } // claudeThinkingTypeAcceptsBlockBinding reports whether the body's thinking @@ -432,10 +454,22 @@ func applyClaudePreservedThinkingBindingDoc(doc *ojson.Doc) bool { return doc.Set("thinking.block_binding.prefix_mismatch_behavior", "drop_block") == nil } -// claudeModelUsesProgressDisplay reports the 2.1.280 interactive CLI models that -// send thinking.display=updates unless the caller already chose a display mode. +// claudeModelUsesProgressDisplay reports the interactive CLI models that send +// thinking.display=updates unless the caller already chose a display mode. +// Claude Code 2.1.321 added Fable 5.2 and Haiku 5.5. func claudeModelUsesProgressDisplay(model string) bool { - return isClaudeOpus55Model(model) || isClaudeFable51Model(model) || isClaudeSonnet5Model(model) || isClaudeSonnet55Model(model) + return isClaudeOpus55Model(model) || isClaudeFable51Model(model) || isClaudeFable52Model(model) || + isClaudeSonnet5Model(model) || isClaudeSonnet55Model(model) || isClaudeHaiku55Model(model) +} + +func isClaudeFable52Model(model string) bool { + model = claudeCanonicalModel(model) + for _, prefix := range []string{"claude-fable-5-2", "claude-fable-5.2"} { + if model == prefix || strings.HasPrefix(model, prefix+"-") || strings.HasPrefix(model, prefix+"[") { + return true + } + } + return false } // applyClaudeCloakThinkingDisplay fills the latest CLI display only when the @@ -468,7 +502,11 @@ func applyClaudeCloakThinkingDisplayDoc(doc *ojson.Doc, callerOwned bool) bool { } func claudeModelHasPerTurnEffort(model string) bool { - return isClaudeOpus55Model(model) || strings.HasPrefix(claudeCanonicalModel(model), "claude-fable-5-1") + return isClaudeOpus55Model(model) || + strings.HasPrefix(claudeCanonicalModel(model), "claude-fable-5-1") || + isClaudeFable52Model(model) || + isClaudeSonnet55Model(model) || + isClaudeHaiku55Model(model) } // claudeModelHasPerTurnTiming reports models whose catalog lists per_turn_timing. @@ -476,9 +514,17 @@ func claudeModelHasPerTurnEffort(model string) bool { // is set, so the beta follows the body or an explicit caller request. func claudeModelHasPerTurnTiming(model string) bool { model = claudeCanonicalModel(model) - return claudeModelHasPerTurnEffort(model) || strings.HasPrefix(model, "claude-mythos-5-1") + if isClaudeHaiku55Model(model) { + return false + } + return claudeModelHasPerTurnEffort(model) || + strings.HasPrefix(model, "claude-mythos-5-1") || + strings.HasPrefix(model, "claude-mythos-5-2") || + strings.HasPrefix(model, "claude-mythos-5.2") } +// claudeIncludePerTurnControl also covers the models Claude Code 2.1.321 sends +// per-turn-control-2026-07-01 for on every main-thread request. func claudeIncludePerTurnControl(body []byte, requested map[string]bool) bool { if requested[claudePerTurnControlBeta] { return true @@ -546,7 +592,8 @@ func claudeRequestSupportsEffort(body []byte, requested map[string]bool) bool { return false } model := strings.ToLower(strings.TrimSpace(ojson.GetBytesNoCopy(body, "model").String())) - if isClaudeHaikuModel(model) { + // Haiku 5.5 is the first Haiku that Claude Code 2.1.321 sends effort for. + if isClaudeHaikuModel(model) && !isClaudeHaiku55Model(model) { return false } thinkingType := strings.ToLower(strings.TrimSpace(ojson.GetBytesNoCopy(body, "thinking.type").String())) @@ -1208,6 +1255,7 @@ func applyClaudeHeadersWithNativeProfile( incomingBetas := strings.TrimSpace(strings.Join(helps.HeaderValuesCaseInsensitive(incomingHeaders, "Anthropic-Beta"), ",")) countTokens := r.URL != nil && strings.HasSuffix(r.URL.Path, "/count_tokens") + preserveThreadCapabilities := !countTokens && (incomingBetas != "" || len(extraBetas) > 0) && ojson.GetBytesNoCopy(body, "thread").IsObject() if !confirmedClaudeCode && !wirePolicy.Cloak && wirePolicy.ExplicitNever && !wirePolicy.Uncloak { det := helps.DetectClaudeCodeRequest(incomingHeaders, body, countTokens, cfg) if det.ConfirmedShape { @@ -1234,7 +1282,7 @@ func applyClaudeHeadersWithNativeProfile( baseBetas = withClaudeAdvisorToolBeta(baseBetas) } // Measured Haiku helper requests already carry their own cache-ttl beta - // choice (omitting extended-cache-ttl on 2.1.220/2.1.280 probes/title + // choice (omitting extended-cache-ttl on 2.1.220/2.1.280/2.1.321 probes/title // helpers), while helpers arriving via ANTHROPIC_BASE_URL still need // oauth-2025-04-20 when CPA authenticates upstream with OAuth. // Native Claude Code subagents and probes also omit extended-cache-ttl. @@ -1316,6 +1364,25 @@ func applyClaudeHeadersWithNativeProfile( } } } + // A Thread declares capabilities for all turns, not just its first body. + // Preserve them before binding the final emitted profile to its response ID. + if preserveThreadCapabilities { + threadCapabilities := incomingBetas + if useOAuthBetas { + threadCapabilities = withClaudeOAuthCredentialBetas(threadCapabilities, !wirePolicy.Uncloak) + } + for _, beta := range extraBetas { + threadCapabilities = withClaudeBetaAppended(threadCapabilities, beta) + } + // Keep required protocol additions after the client-declared capabilities. + for _, beta := range strings.Split(baseBetas, ",") { + threadCapabilities = withClaudeBetaAppended(threadCapabilities, beta) + } + if advisorNeeded { + threadCapabilities = withClaudeAdvisorToolBeta(threadCapabilities) + } + baseBetas = threadCapabilities + } applyBetaHeader := func() { if wirePolicy.Uncloak { baseBetas = withoutClaudeBeta(baseBetas, claudeCodeBeta) @@ -1332,30 +1399,31 @@ func applyClaudeHeadersWithNativeProfile( baseBetas = withoutClaudeBeta(baseBetas, claudeExtendedCacheTTLBeta) } } - // Enforce strict native Claude Code 2.1.280 model & turn beta gating: - if !claudeRequestSupportsEffort(body, nil) { - baseBetas = withoutClaudeBeta(baseBetas, claudeEffortBeta) - } reqProbeOrHelper := helps.IsClaudeProbeOrHelperRequest(body) - if reqProbeOrHelper && !helperProfile { - baseBetas = withoutClaudeBeta(baseBetas, claudeServerSideFallbackBeta) - baseBetas = withoutClaudeBeta(baseBetas, claudeThinkingDisplayUpdatesBeta) - baseBetas = withoutClaudeBeta(baseBetas, claudeExtendedCacheTTLBeta) - } - reqThinkingType := ojson.GetBytesNoCopy(body, "thinking.type").String() - if reqThinkingType == "disabled" { - baseBetas = withoutClaudeBeta(baseBetas, claudeThinkingDisplayUpdatesBeta) - } - if helps.IsClaudeSubagentRequest(incomingHeaders, body) && !helps.ClaudeSubagentRequests1h(incomingHeaders, body) { - baseBetas = withoutClaudeBeta(baseBetas, claudeExtendedCacheTTLBeta) + if !preserveThreadCapabilities { + // Per-turn gating remains unchanged outside caller-declared Threads. + if !claudeRequestSupportsEffort(body, nil) { + baseBetas = withoutClaudeBeta(baseBetas, claudeEffortBeta) + } + if reqProbeOrHelper && !helperProfile { + baseBetas = withoutClaudeBeta(baseBetas, claudeServerSideFallbackBeta) + baseBetas = withoutClaudeBeta(baseBetas, claudeThinkingDisplayUpdatesBeta) + baseBetas = withoutClaudeBeta(baseBetas, claudeExtendedCacheTTLBeta) + } + if ojson.GetBytesNoCopy(body, "thinking.type").String() == "disabled" { + baseBetas = withoutClaudeBeta(baseBetas, claudeThinkingDisplayUpdatesBeta) + } + if helps.IsClaudeSubagentRequest(incomingHeaders, body) && !helps.ClaudeSubagentRequests1h(incomingHeaders, body) { + baseBetas = withoutClaudeBeta(baseBetas, claudeExtendedCacheTTLBeta) + } + reqModel := strings.ToLower(strings.TrimSpace(ojson.GetBytesNoCopy(body, "model").String())) + if isClaudeHaikuModel(reqModel) && !ojson.GetBytesNoCopy(body, "fallbacks").Exists() && !helperProfile { + baseBetas = withoutClaudeBeta(baseBetas, claudeServerSideFallbackBeta) + } } if !reqProbeOrHelper && !countTokens && helps.ClaudePayloadHas1hTTL(body) { baseBetas = withClaudeExtendedCacheTTLBeta(baseBetas) } - reqModel := strings.ToLower(strings.TrimSpace(ojson.GetBytesNoCopy(body, "model").String())) - if isClaudeHaikuModel(reqModel) && !ojson.GetBytesNoCopy(body, "fallbacks").Exists() && !helperProfile { - baseBetas = withoutClaudeBeta(baseBetas, claudeServerSideFallbackBeta) - } // A body carrying thinking.block_binding is rejected upstream unless // the binding-controls beta travels with it, in every fingerprint // mode (cloaked, caller-owned, and confirmed passthrough alike). @@ -1456,7 +1524,7 @@ func applyClaudeHeadersWithNativeProfile( identityHeader("Anthropic-Version", "2023-06-01") identityHeader("Anthropic-Dangerous-Direct-Browser-Access", "true") identityHeader("X-App", "cli") - // Values below match Claude Code 2.1.280 / @anthropic-ai/sdk 0.112.1. + // Values below match Claude Code 2.1.321 / @anthropic-ai/sdk 0.128.0. identityHeader("X-Stainless-Retry-Count", "0") identityHeader("X-Stainless-Runtime", "node") identityHeader("X-Stainless-Lang", "js") @@ -1574,7 +1642,7 @@ func applyClaudeHeadersWithNativeProfile( if errDeviceProfile != nil { return errDeviceProfile } - helps.ApplyClaudeDeviceProfileHeaders(r, deviceProfile) + helps.ApplyClaudeDeviceProfileHeaders(r, deviceProfile, helps.HeaderValueCaseInsensitive(incomingHeaders, "User-Agent")) } else { helps.ApplyClaudeDefaultDeviceProfileHeaders(r, cfg) } diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index 382f755e3de..d8c24179457 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -217,6 +217,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return nil, err } } + helps.NormalizeClaudeToolPropertyNamesDoc(doc) sanitizeClaudeMessagesForClaudeUpstreamWithDebugDoc(ctx, doc, baseModel, helps.APIKeyModelIsCompat(req)) if fp.ApplyCLIIdentity { err = applyClaudeCLIIdentityDoc(doc, auth, apiKey, url, claudeSessionID, fp.SynthesizeIdentity) @@ -224,9 +225,10 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return nil, err } } - if cloaked && len(wireSettings.sensitiveWords) > 0 { - matcher := helps.BuildSensitiveWordMatcher(wireSettings.sensitiveWords) - helps.ObfuscateSensitiveWordsDoc(doc, matcher) + if cloaked { + if matcher := wireSettings.buildSensitiveWordMatcher(); matcher != nil { + helps.ObfuscateSensitiveWordsDoc(doc, matcher) + } } cchBilling := "" if cchSigning { @@ -244,7 +246,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A touchedPayloadPaths := helps.ApplyPayloadConfigWithTrackedPathsDoc( e.cfg, baseModel, to.String(), from.String(), "", doc, stripTranslatedDefaultMaxTokens(from, originalPayload, originalTranslated), helps.PayloadRequestedModel(opts, req.Model), helps.PayloadRequestPath(opts), opts.Headers, - "diagnostics", + "diagnostics", "betas", ) if touchedPayloadPaths["diagnostics"] { diagnosticsState = claudeDiagnosticsRequestState{} @@ -265,18 +267,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return nil, errMidSystem } reporter.SetTranslatedReasoningEffort(bodyForUpstream, to.String()) - // The upstream request follows downstream cancellation only until - // message_stop has been observed. After that it is detached, so the - // remaining body can be drained (and the connection pooled) even though - // the downstream handler cancels ctx as soon as Chunks closes. - upstreamCtx, detachUpstream, releaseUpstream := helps.NewDetachableContext(ctx) - streamStarted := false - defer func() { - if !streamStarted { - releaseUpstream() - } - }() - httpReq, err := http.NewRequestWithContext(upstreamCtx, http.MethodPost, url, bytes.NewReader(bodyForUpstream)) + httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(bodyForUpstream)) if err != nil { return nil, err } @@ -295,6 +286,10 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A ); errHeaders != nil { return nil, errHeaders } + threadBetas, errThread := e.prepareClaudeThreadBetas(ctx, httpReq, auth, bodyForUpstream, extraBetas, touchedPayloadPaths["betas"], incomingHeaders, wirePolicy.Uncloak, opts.Metadata, req.Metadata) + if errThread != nil { + return nil, errThread + } fastRequest := isAnthropicUpstreamBase(baseURL) && claudeRequestIsFast(httpReq, bodyForUpstream) authID, authLabel, authType, authValue := claudeAuthLogIdentity(auth) helps.RecordAPIRequest(ctx, e.cfg, helps.UpstreamRequestLog{ @@ -333,13 +328,15 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return nil, errClassified } b, readErr := io.ReadAll(errBody) + helps.AppendAPIResponseChunk(ctx, e.cfg, b) if readErr != nil { helps.RecordAPIResponseError(ctx, e.cfg, readErr) msg := fmt.Sprintf("failed to read error response body: %v", readErr) helps.LogWithRequestID(ctx).Warn(msg) - b = []byte(msg) + if len(b) == 0 { + b = []byte(msg) + } } - helps.AppendAPIResponseChunk(ctx, e.cfg, b) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) if errClose := errBody.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) @@ -358,34 +355,13 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return nil, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, err) } out := make(chan cliproxyexecutor.StreamChunk, 1) - streamStarted = true go func() { - // detached is set once message_stop has been observed and the upstream - // request was detached from downstream cancellation in time. - detached := false - markUpstreamCompleted := func() { - // detach reports false on repeated calls, so a failed first - // attempt is never turned into a success later. - if !detached { - detached = detachUpstream() - } - } + defer close(out) defer func() { - // Runs after out is closed, so the drain never delays stream - // completion. Drain what is left of the upstream body (chunked - // terminator, gzip trailer) so net/http can return the connection to - // the pool instead of closing it. The drain is bounded to 64 KiB and - // ends when the upstream finishes the response or drops the - // connection; it is skipped unless the response completed. - if detached { - _, _ = io.Copy(io.Discard, io.LimitReader(httpResp.Body, 64<<10)) - } if errClose := decodedBody.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } - releaseUpstream() }() - defer close(out) var streamUsage helps.StreamUsageBuffer defer streamUsage.Publish(ctx, reporter) emitCancellation := func(cause error) bool { @@ -420,9 +396,13 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } } + streamBody := threadBetas.StreamReader(decodedBody, func(messageID string) { + commitClaudeContinuity(diagnosticsState, messageID, helps.HeaderValueCaseInsensitive(httpResp.Header, "request-id")) + e.rememberClaudeOAuthToolAliases(body, oauthToolNamesReverseMap, messageID) + }) // If the response target is Claude, directly forward complete SSE events without translation. if responseFormat == to { - scanner := bufio.NewScanner(decodedBody) + scanner := bufio.NewScanner(streamBody) scanner.Buffer(nil, 52_428_800) // 50MB var event bytes.Buffer var upstreamMessageID string @@ -433,9 +413,6 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return true } observeClaudeSSEEvent(event.Bytes(), &upstreamMessageID, &upstreamCompleted, &upstreamStreamErr) - if upstreamCompleted { - markUpstreamCompleted() - } streamUsage.ObserveClaudeSSEEvent(event.Bytes()) cloned := bytes.Clone(event.Bytes()) event.Reset() @@ -503,7 +480,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } // For other formats, use translation - scanner := bufio.NewScanner(decodedBody) + scanner := bufio.NewScanner(streamBody) scanner.Buffer(nil, 52_428_800) // 50MB var param any helps.InitializeApplyPatchStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), bodyForTranslation, ¶m) @@ -517,23 +494,9 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A eventBuf.WriteByte('\n') if len(bytes.TrimSpace(line)) == 0 { observeClaudeSSEEvent(eventBuf.Bytes(), &upstreamMessageID, &upstreamCompleted, &upstreamStreamErr) - if upstreamCompleted { - markUpstreamCompleted() - } streamUsage.ObserveClaudeSSEEvent(eventBuf.Bytes()) eventBuf.Reset() } - // Translation runs per line, so the message_stop data line can already - // yield the terminal event (e.g. response.completed) and the client may - // cancel before the event's blank separator is read. Treat that line as - // completion and detach before it is translated, so the loop exits after - // delivering it instead of waiting for the separator; translators ignore - // non-data lines, and the buffered event is observed after the loop. Like - // the event observer, only valid JSON counts. - if payload := helps.JSONPayload(line); !upstreamCompleted && payload != nil && ojson.ValidBytes(payload) && ojson.GetBytesNoCopy(payload, "type").String() == "message_stop" { - upstreamCompleted = true - markUpstreamCompleted() - } helps.AppendAPIResponseChunk(ctx, e.cfg, line) reporter.ObserveResponseModel(line) streamUsage.ObserveClaudeStream(line) diff --git a/internal/runtime/executor/claude_executor_stream_keepalive_test.go b/internal/runtime/executor/claude_executor_stream_keepalive_test.go deleted file mode 100644 index 426aea21f50..00000000000 --- a/internal/runtime/executor/claude_executor_stream_keepalive_test.go +++ /dev/null @@ -1,579 +0,0 @@ -package executor - -import ( - "bytes" - "compress/gzip" - "context" - "io" - "net" - "net/http" - "net/http/httptest" - "net/http/httptrace" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/router-for-me/CLIProxyAPI/v8/internal/config" - cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" - cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" - "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" - sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" -) - -const keepaliveStreamStart = "event: message_start\n" + - `data: {"type":"message_start","message":{"id":"msg_keepalive","type":"message","role":"assistant","content":[],"model":"claude-opus-5","stop_reason":null,"usage":{"input_tokens":1,"output_tokens":1}}}` + "\n\n" - -const keepaliveStreamData = keepaliveStreamStart + - "event: content_block_start\n" + - `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" + - "event: content_block_delta\n" + - `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}` + "\n\n" + - "event: content_block_stop\n" + - `data: {"type":"content_block_stop","index":0}` + "\n\n" + - "event: message_delta\n" + - `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}` + "\n\n" + - "event: message_stop\n" + - `data: {"type":"message_stop"}` + "\n\n" - -// keepaliveFailSafe only bounds how long a broken implementation may hang; it -// never orders events in a passing run. -const keepaliveFailSafe = 10 * time.Second - -// keepaliveHarness runs streamed requests through the Claude executor against -// a local chunked SSE server and counts upstream connections. -type keepaliveHarness struct { - t *testing.T - server *httptest.Server - transport http.RoundTripper - exec *ClaudeExecutor - auth *cliproxyauth.Auth - format sdktranslator.Format - // gzipBody makes the server gzip the stream, holding the gzip trailer - // back together with the terminating chunk (see keepaliveGzipParts). - gzipBody bool - newConns atomic.Int32 - settled chan struct{} - trace *httptrace.ClientTrace - mu sync.Mutex - reused []bool -} - -// newKeepaliveHarness starts a server that writes keepaliveStreamData with -// chunked encoding and then holds the terminating chunk back until it -// receives from release (or the client drops the connection). This mirrors -// the real API, where the terminator arrives in a later segment than -// message_stop, and keeps net/http from seeing EOF together with the last -// event. With holdSeparator, the blank line that ends the message_stop event -// is held back as well and sent only after release. -func newKeepaliveHarness(t *testing.T, release <-chan struct{}, holdSeparator bool) *keepaliveHarness { - t.Helper() - h := &keepaliveHarness{t: t, settled: make(chan struct{}, 4), format: sdktranslator.FormatClaude} - notify := func() { - select { - case h.settled <- struct{}{}: - default: - } - } - h.server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - data := keepaliveStreamData - if holdSeparator { - data = data[:len(data)-1] - } - if h.gzipBody { - prefix, suffix := keepaliveGzipParts(data) - w.Header().Set("Content-Encoding", "gzip") - _, _ = w.Write(prefix) - w.(http.Flusher).Flush() - select { - case <-release: - case <-r.Context().Done(): - return - } - _, _ = w.Write(suffix) - return - } - _, _ = w.Write([]byte(data)) - // Flushing forces chunked transfer encoding. - w.(http.Flusher).Flush() - select { - case <-release: - case <-r.Context().Done(): - return - } - if holdSeparator { - _, _ = w.Write([]byte("\n")) - } - })) - h.server.Config.ConnState = func(_ net.Conn, state http.ConnState) { - switch state { - case http.StateNew: - h.newConns.Add(1) - case http.StateClosed, http.StateHijacked: - notify() - } - } - h.server.Start() - t.Cleanup(h.server.Close) - // Registered after server.Close, so it runs first: the requests are done - // by then, and their usage records must not leak into later tests. - t.Cleanup(func() { flushKeepaliveUsage(t) }) - - base := &http.Transport{} - t.Cleanup(base.CloseIdleConnections) - h.transport = base - h.trace = &httptrace.ClientTrace{ - GotConn: func(info httptrace.GotConnInfo) { - h.mu.Lock() - h.reused = append(h.reused, info.Reused) - h.mu.Unlock() - }, - PutIdleConn: func(err error) { - if err == nil { - notify() - } - }, - } - h.exec = NewClaudeExecutor(&config.Config{}) - h.auth = &cliproxyauth.Auth{Attributes: map[string]string{ - "api_key": "key-keepalive", - "base_url": h.server.URL, - }} - return h -} - -func (h *keepaliveHarness) start(ctx context.Context) <-chan cliproxyexecutor.StreamChunk { - h.t.Helper() - ctx = context.WithValue(ctx, "cliproxy.roundtripper", h.transport) - ctx = httptrace.WithClientTrace(ctx, h.trace) - payload := []byte(`{"model":"claude-opus-5","messages":[{"role":"user","content":"hi"}],"stream":true}`) - if h.format == sdktranslator.FormatOpenAIResponse { - payload = []byte(`{"model":"claude-opus-5","input":"hi","stream":true}`) - } - result, err := h.exec.ExecuteStream(ctx, h.auth, cliproxyexecutor.Request{ - Model: "claude-opus-5", - Payload: payload, - }, cliproxyexecutor.Options{ - SourceFormat: h.format, - ResponseFormat: h.format, - }) - if err != nil { - h.t.Fatalf("ExecuteStream() error = %v", err) - } - return result.Chunks -} - -// drainChunks consumes the stream like a real client and fails if it does not -// close within the fail-safe. -func (h *keepaliveHarness) drainChunks(chunks <-chan cliproxyexecutor.StreamChunk) { - h.t.Helper() - failSafe := time.NewTimer(keepaliveFailSafe) - defer failSafe.Stop() - for { - select { - case chunk, ok := <-chunks: - if !ok { - return - } - if chunk.Err != nil { - h.t.Fatalf("chunk error = %v", chunk.Err) - } - case <-failSafe.C: - h.t.Fatal("Chunks did not close after message_stop") - } - } -} - -// waitSettled waits until the previous connection was pooled or closed, so a -// following request deterministically observes the outcome. -func (h *keepaliveHarness) waitSettled() { - h.t.Helper() - select { - case <-h.settled: - case <-time.After(keepaliveFailSafe): - h.t.Fatal("upstream connection was neither pooled nor closed") - } -} - -func (h *keepaliveHarness) assertSingleConnection() { - h.t.Helper() - h.mu.Lock() - defer h.mu.Unlock() - if got := h.newConns.Load(); got != 1 { - h.t.Fatalf("upstream connections = %d, want 1 (GotConn reused = %v)", got, h.reused) - } - if len(h.reused) != 2 || !h.reused[1] { - h.t.Fatalf("second request did not reuse the connection (GotConn reused = %v)", h.reused) - } -} - -// TestClaudeExecutor_ExecuteStream_ReusesUpstreamConnection guards against the -// stream loop closing the upstream body right after message_stop without -// consuming the chunked terminator, which makes net/http discard the -// connection instead of returning it to the idle pool. -func TestClaudeExecutor_ExecuteStream_ReusesUpstreamConnection(t *testing.T) { - release := make(chan struct{}, 4) - h := newKeepaliveHarness(t, release, false) - // A bare Close never releases the terminator, so the bounded post-close - // drain newer Go versions do inside net/http cannot mask a missing drain. - h.transport = keepaliveReleaseRoundTripper{base: h.transport, total: len(keepaliveStreamData), release: release} - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - h.drainChunks(h.start(ctx)) - h.waitSettled() - h.drainChunks(h.start(ctx)) - h.assertSingleConnection() -} - -// TestClaudeExecutor_ExecuteStream_ReusesUpstreamConnectionWithGzip covers -// compressed upstream responses, where the end of the body also carries the -// gzip trailer: the drain must read the raw body to EOF, not just the decoded -// stream. -func TestClaudeExecutor_ExecuteStream_ReusesUpstreamConnectionWithGzip(t *testing.T) { - release := make(chan struct{}, 4) - h := newKeepaliveHarness(t, release, false) - h.gzipBody = true - prefix, _ := keepaliveGzipParts(keepaliveStreamData) - h.transport = keepaliveReleaseRoundTripper{base: h.transport, total: len(prefix), release: release} - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - h.drainChunks(h.start(ctx)) - h.waitSettled() - h.drainChunks(h.start(ctx)) - h.assertSingleConnection() -} - -// TestClaudeExecutor_ExecuteStream_ReusesUpstreamConnectionAfterDownstreamCancel -// mirrors the real handler, which cancels the request context as soon as -// Chunks closes. The drain after message_stop must not be aborted by that. -func TestClaudeExecutor_ExecuteStream_ReusesUpstreamConnectionAfterDownstreamCancel(t *testing.T) { - release := make(chan struct{}, 4) - h := newKeepaliveHarness(t, release, false) - // The drain's first read past the event data is held until the test has - // cancelled the downstream context, so the drain deterministically runs - // after the cancellation. - cancelled := make(chan struct{}, 4) - failSafe := make(chan struct{}) - t.Cleanup(func() { close(failSafe) }) - h.transport = keepaliveReleaseRoundTripper{base: h.transport, total: len(keepaliveStreamData), release: release, gate: cancelled, failSafe: failSafe} - - for i := 0; i < 2; i++ { - ctx, cancel := context.WithCancel(context.Background()) - h.drainChunks(h.start(ctx)) - cancel() - cancelled <- struct{}{} - if i == 0 { - h.waitSettled() - } - } - h.assertSingleConnection() -} - -// TestClaudeExecutor_ExecuteStream_ClosesChunksWhenUpstreamStallsAfterMessageStop -// ensures stream completion never waits on the best-effort drain: an upstream -// that sends message_stop but never finishes the response must not keep -// Chunks open. -func TestClaudeExecutor_ExecuteStream_ClosesChunksWhenUpstreamStallsAfterMessageStop(t *testing.T) { - stall := make(chan struct{}) - h := newKeepaliveHarness(t, stall, false) - // Registered after the harness, so it runs before server.Close and lets a - // still-running drain finish. - t.Cleanup(func() { close(stall) }) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - h.drainChunks(h.start(ctx)) -} - -// TestClaudeExecutor_ExecuteStream_DownstreamCancelBeforeMessageStopAbortsUpstream -// ensures that, until message_stop, downstream cancellation still aborts the -// upstream request so no tokens are generated for a gone client. -func TestClaudeExecutor_ExecuteStream_DownstreamCancelBeforeMessageStopAbortsUpstream(t *testing.T) { - t.Cleanup(func() { flushKeepaliveUsage(t) }) - upstreamDone := make(chan struct{}) - testDone := make(chan struct{}) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - _, _ = w.Write([]byte(keepaliveStreamStart)) - w.(http.Flusher).Flush() - select { - case <-r.Context().Done(): - close(upstreamDone) - case <-testDone: - // Lets server.Close return when the upstream was never aborted. - } - })) - defer server.Close() - defer close(testDone) - - exec := NewClaudeExecutor(&config.Config{}) - auth := &cliproxyauth.Auth{Attributes: map[string]string{ - "api_key": "key-keepalive", - "base_url": server.URL, - }} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - result, err := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{ - Model: "claude-opus-5", - Payload: []byte(`{"model":"claude-opus-5","messages":[{"role":"user","content":"hi"}],"stream":true}`), - }, cliproxyexecutor.Options{ - SourceFormat: sdktranslator.FormatClaude, - ResponseFormat: sdktranslator.FormatClaude, - }) - if err != nil { - t.Fatalf("ExecuteStream() error = %v", err) - } - - failSafe := time.NewTimer(keepaliveFailSafe) - defer failSafe.Stop() - select { - case chunk := <-result.Chunks: - if chunk.Err != nil { - t.Fatalf("chunk error = %v", chunk.Err) - } - case <-failSafe.C: - t.Fatal("did not receive message_start") - } - cancel() - - select { - case <-upstreamDone: - case <-failSafe.C: - t.Fatal("downstream cancel before message_stop did not abort the upstream request") - } - for { - select { - case _, ok := <-result.Chunks: - if !ok { - return - } - case <-failSafe.C: - t.Fatal("Chunks did not close after downstream cancel") - } - } -} - -// TestClaudeExecutor_ExecuteStream_Translated_ReusesUpstreamConnectionAfterCancelOnTerminalEvent -// covers the translated path: translation runs per line, so the message_stop -// data line already yields response.completed, and the Responses handler -// cancels on its delivery before the executor reads the event's blank -// separator. The upstream request must be detached before that output is -// delivered, so the connection is still pooled. -func TestClaudeExecutor_ExecuteStream_Translated_ReusesUpstreamConnectionAfterCancelOnTerminalEvent(t *testing.T) { - release := make(chan struct{}, 4) - h := newKeepaliveHarness(t, release, true) - h.format = sdktranslator.FormatOpenAIResponse - // The executor's read of the held-back separator waits until the client - // has cancelled on response.completed. - cancelled := make(chan struct{}, 4) - failSafe := make(chan struct{}) - t.Cleanup(func() { close(failSafe) }) - h.transport = keepaliveReleaseRoundTripper{base: h.transport, total: len(keepaliveStreamData) - 1, release: release, gate: cancelled, failSafe: failSafe} - - for i := 0; i < 2; i++ { - ctx, cancel := context.WithCancel(context.Background()) - chunks := h.start(ctx) - timer := time.NewTimer(keepaliveFailSafe) - sawTerminal := false - read: - for { - select { - case chunk, ok := <-chunks: - if !ok { - break read - } - if chunk.Err != nil { - t.Fatalf("request %d: chunk error = %v", i+1, chunk.Err) - } - if !sawTerminal && strings.Contains(string(chunk.Payload), "response.completed") { - // Like the Responses handler: cancel as soon as the - // terminal event was delivered. - sawTerminal = true - cancel() - cancelled <- struct{}{} - } - case <-timer.C: - t.Fatalf("request %d: Chunks did not close", i+1) - } - } - timer.Stop() - cancel() - if !sawTerminal { - t.Fatalf("request %d: no response.completed event", i+1) - } - if i == 0 { - h.waitSettled() - } - } - h.assertSingleConnection() -} - -// TestClaudeExecutor_ExecuteStream_Translated_ClosesChunksWhenSeparatorStalls -// ensures the translated path treats the message_stop data line as completion: -// an upstream that never sends the event's blank separator (until after Chunks -// closes) must not keep the stream open. -func TestClaudeExecutor_ExecuteStream_Translated_ClosesChunksWhenSeparatorStalls(t *testing.T) { - stall := make(chan struct{}) - h := newKeepaliveHarness(t, stall, true) - h.format = sdktranslator.FormatOpenAIResponse - // Registered after the harness, so it runs before server.Close and lets the - // background drain finish. - t.Cleanup(func() { close(stall) }) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - h.drainChunks(h.start(ctx)) -} - -// keepaliveGzipParts gzips data and splits the result after a sync flush: the -// prefix decodes to all of data, the suffix holds the final block and the -// gzip trailer. -func keepaliveGzipParts(data string) (prefix, suffix []byte) { - var buf bytes.Buffer - zw := gzip.NewWriter(&buf) - _, _ = zw.Write([]byte(data)) - _ = zw.Flush() - prefix = bytes.Clone(buf.Bytes()) - _ = zw.Close() - return prefix, bytes.Clone(buf.Bytes()[len(prefix):]) -} - -// TestClaudeExecutor_ExecuteStream_Translated_MalformedMessageStopIsNotCompletion -// ensures the early completion on the message_stop data line only accepts -// valid JSON, like the event observer: a truncated line must still end in the -// incomplete-stream error. -func TestClaudeExecutor_ExecuteStream_Translated_MalformedMessageStopIsNotCompletion(t *testing.T) { - t.Cleanup(func() { flushKeepaliveUsage(t) }) - valid := `data: {"type":"message_stop"}` - cut := strings.Index(keepaliveStreamData, valid) - if cut < 0 { - t.Fatal("stream data has no message_stop line") - } - data := keepaliveStreamData[:cut] + `data: {"type":"message_stop"` + "\n\n" - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - _, _ = w.Write([]byte(data)) - })) - defer server.Close() - - exec := NewClaudeExecutor(&config.Config{}) - auth := &cliproxyauth.Auth{Attributes: map[string]string{ - "api_key": "key-keepalive", - "base_url": server.URL, - }} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - result, err := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{ - Model: "claude-opus-5", - Payload: []byte(`{"model":"claude-opus-5","input":"hi","stream":true}`), - }, cliproxyexecutor.Options{ - SourceFormat: sdktranslator.FormatOpenAIResponse, - ResponseFormat: sdktranslator.FormatOpenAIResponse, - }) - if err != nil { - t.Fatalf("ExecuteStream() error = %v", err) - } - var streamErr error - failSafe := time.NewTimer(keepaliveFailSafe) - defer failSafe.Stop() - for done := false; !done; { - select { - case chunk, ok := <-result.Chunks: - if !ok { - done = true - break - } - if chunk.Err != nil { - streamErr = chunk.Err - } - case <-failSafe.C: - t.Fatal("Chunks did not close") - } - } - if streamErr == nil || !strings.Contains(streamErr.Error(), "before message_stop") { - t.Fatalf("stream error = %v, want the incomplete-stream error", streamErr) - } -} - -// flushKeepaliveUsage waits until every usage record published so far has been -// dispatched, so records from these tests cannot reach a later test's usage -// plugin. The default usage queue is FIFO with a single worker, so once a -// sentinel record arrives, all earlier records were delivered. -func flushKeepaliveUsage(t *testing.T) { - t.Helper() - const name = "keepalive-usage-flush" - id := "keepalive-sentinel-" + t.Name() - seen := make(chan struct{}, 1) - usage.RegisterNamedPlugin(name, keepaliveSentinelPlugin{id: id, seen: seen}) - defer usage.RegisterNamedPlugin(name, noopClaudeUsagePlugin{}) - usage.PublishRecord(context.Background(), usage.Record{Provider: "keepalive-sentinel", RequestID: id}) - select { - case <-seen: - case <-time.After(keepaliveFailSafe): - t.Fatal("usage queue did not flush") - } -} - -type keepaliveSentinelPlugin struct { - id string - seen chan<- struct{} -} - -func (p keepaliveSentinelPlugin) HandleUsage(_ context.Context, record usage.Record) { - if record.RequestID != p.id { - return - } - select { - case p.seen <- struct{}{}: - default: - } -} - -// keepaliveReleaseRoundTripper wraps response bodies so the test server is -// released once the client asks for more than the event data. With a gate, that -// first read past the data waits for one gate signal (or the fail-safe) before -// going on. -type keepaliveReleaseRoundTripper struct { - base http.RoundTripper - total int - release chan<- struct{} - gate <-chan struct{} - failSafe <-chan struct{} -} - -func (rt keepaliveReleaseRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - resp, err := rt.base.RoundTrip(req) - if err != nil { - return nil, err - } - resp.Body = &keepaliveReleaseBody{ReadCloser: resp.Body, rt: rt} - return resp, nil -} - -type keepaliveReleaseBody struct { - io.ReadCloser - rt keepaliveReleaseRoundTripper - read int - once sync.Once -} - -func (b *keepaliveReleaseBody) Read(p []byte) (int, error) { - if b.read >= b.rt.total { - b.once.Do(func() { - if b.rt.gate != nil { - select { - case <-b.rt.gate: - case <-b.rt.failSafe: - } - } - b.rt.release <- struct{}{} - }) - } - n, err := b.ReadCloser.Read(p) - b.read += n - return n, err -} diff --git a/internal/runtime/executor/claude_executor_stream_terminal_test.go b/internal/runtime/executor/claude_executor_stream_terminal_test.go index b68f5a1d8b5..8c45659ecc6 100644 --- a/internal/runtime/executor/claude_executor_stream_terminal_test.go +++ b/internal/runtime/executor/claude_executor_stream_terminal_test.go @@ -2,9 +2,14 @@ package executor import ( "context" + "io" + "net" "net/http" "net/http/httptest" + "net/http/httptrace" "strings" + "sync" + "sync/atomic" "testing" "time" @@ -224,3 +229,161 @@ func TestClaudeExecutor_ExecuteStream_Passthrough_ClientDisconnectAfterTerminalE t.Fatal("timed out waiting for usage record") } } + +func TestClaudeExecutor_ExecuteStream_DoesNotDrainOrReuseUpstreamConnectionAfterMessageStop(t *testing.T) { + const streamData = "event: message_start\n" + + `data: {"type":"message_start","message":{"id":"msg_123","type":"message","role":"assistant","content":[],"model":"claude-opus-5","stop_reason":null,"usage":{"input_tokens":1,"output_tokens":1}}}` + "\n\n" + + "event: content_block_start\n" + + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}` + "\n\n" + + "event: content_block_delta\n" + + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}` + "\n\n" + + "event: content_block_stop\n" + + `data: {"type":"content_block_stop","index":0}` + "\n\n" + + "event: message_delta\n" + + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}` + "\n\n" + + "event: message_stop\n" + + `data: {"type":"message_stop"}` + "\n\n" + + var ( + newConns atomic.Int32 + release = make(chan struct{}, 4) + closed = make(chan struct{}, 4) + done = make(chan struct{}) + mu sync.Mutex + reused []bool + ) + defer close(done) + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte(streamData)) + w.(http.Flusher).Flush() + // Hold the chunked terminator back until the client either attempts a + // post-message_stop drain read or closes the connection. + select { + case <-release: + case <-r.Context().Done(): + case <-done: + } + })) + server.Config.ConnState = func(_ net.Conn, state http.ConnState) { + switch state { + case http.StateNew: + newConns.Add(1) + case http.StateClosed, http.StateHijacked: + select { + case closed <- struct{}{}: + default: + } + } + } + server.Start() + defer server.Close() + + baseTransport := &http.Transport{} + t.Cleanup(baseTransport.CloseIdleConnections) + transport := postMessageStopReadReleaseRoundTripper{ + base: baseTransport, + total: len(streamData), + release: release, + } + trace := &httptrace.ClientTrace{ + GotConn: func(info httptrace.GotConnInfo) { + mu.Lock() + reused = append(reused, info.Reused) + mu.Unlock() + }, + PutIdleConn: func(err error) { + if err == nil { + select { + case closed <- struct{}{}: + default: + } + } + }, + } + + exec := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Attributes: map[string]string{ + "api_key": "key-no-drain", + "base_url": server.URL, + }, + } + payload := []byte(`{"model":"claude-opus-5","messages":[{"role":"user","content":"hi"}],"stream":true}`) + + for i := 0; i < 2; i++ { + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + ctx = httptrace.WithClientTrace(ctx, trace) + result, err := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{ + Model: "claude-opus-5", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + ResponseFormat: sdktranslator.FormatClaude, + }) + if err != nil { + t.Fatalf("round %d ExecuteStream() error = %v", i+1, err) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("round %d chunk error = %v", i+1, chunk.Err) + } + } + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Fatalf("round %d connection did not settle", i+1) + } + } + + mu.Lock() + gotReused := append([]bool(nil), reused...) + mu.Unlock() + if got := newConns.Load(); got != 2 { + t.Fatalf("stream upstream connections = %d, want 2 (reused = %v)", got, gotReused) + } + if len(gotReused) != 2 || gotReused[0] || gotReused[1] { + t.Fatalf("stream GotConn reused = %v, want [false false]", gotReused) + } +} + +type postMessageStopReadReleaseRoundTripper struct { + base http.RoundTripper + total int + release chan<- struct{} +} + +func (rt postMessageStopReadReleaseRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + resp, err := rt.base.RoundTrip(req) + if err != nil { + return nil, err + } + resp.Body = &postMessageStopReadReleaseBody{ + ReadCloser: resp.Body, + total: rt.total, + release: rt.release, + } + return resp, nil +} + +type postMessageStopReadReleaseBody struct { + io.ReadCloser + total int + read int + release chan<- struct{} + once sync.Once +} + +func (b *postMessageStopReadReleaseBody) Read(p []byte) (int, error) { + if b.read >= b.total { + b.once.Do(func() { + select { + case b.release <- struct{}{}: + default: + } + }) + } + n, err := b.ReadCloser.Read(p) + b.read += n + return n, err +} diff --git a/internal/runtime/executor/claude_executor_subagent_ttl_regression_test.go b/internal/runtime/executor/claude_executor_subagent_ttl_regression_test.go index 0d995a078f8..50b25dcb6de 100644 --- a/internal/runtime/executor/claude_executor_subagent_ttl_regression_test.go +++ b/internal/runtime/executor/claude_executor_subagent_ttl_regression_test.go @@ -55,7 +55,7 @@ func TestClaudeExecutor_SubagentPreserves1hTTLAndExtendedCacheBetaWhenRequested( }] }`) incomingHeaders := http.Header{} - incomingHeaders.Set("User-Agent", "claude-cli/2.1.281 (external, cli)") + incomingHeaders.Set("User-Agent", "claude-cli/2.1.322 (external, cli)") incomingHeaders.Set("X-Claude-Code-Agent-Id", "agent-sub-123") incomingHeaders.Set("Anthropic-Beta", "claude-code-20250219,oauth-2025-04-20,extended-cache-ttl-2025-04-11") @@ -132,7 +132,7 @@ func TestClaudeExecutor_SubagentPreserves1hTTLAndExtendedCacheBetaWhenRequested_ }] }`) incomingHeaders := http.Header{} - incomingHeaders.Set("User-Agent", "claude-cli/2.1.281 (external, cli)") + incomingHeaders.Set("User-Agent", "claude-cli/2.1.322 (external, cli)") incomingHeaders.Set("X-Claude-Code-Agent-Id", "agent-sub-stream-456") incomingHeaders.Set("Anthropic-Beta", "claude-code-20250219,oauth-2025-04-20,extended-cache-ttl-2025-04-11") @@ -202,7 +202,7 @@ func TestClaudeExecutor_SubagentWithout1hKeepsDefault5m(t *testing.T) { }] }`) incomingHeaders := http.Header{} - incomingHeaders.Set("User-Agent", "claude-cli/2.1.281 (external, cli)") + incomingHeaders.Set("User-Agent", "claude-cli/2.1.322 (external, cli)") incomingHeaders.Set("X-Claude-Code-Agent-Id", "agent-sub-default-789") incomingHeaders.Set("Anthropic-Beta", "claude-code-20250219,oauth-2025-04-20") @@ -268,7 +268,7 @@ func TestClaudeExecutor_APIKeySubagentPreserves1hTTLAndInjectsBeta(t *testing.T) }] }`) incomingHeaders := http.Header{} - incomingHeaders.Set("User-Agent", "claude-cli/2.1.281 (external, cli)") + incomingHeaders.Set("User-Agent", "claude-cli/2.1.322 (external, cli)") incomingHeaders.Set("X-Claude-Code-Agent-Id", "agent-sub-apikey-101") incomingHeaders.Set("Anthropic-Beta", "claude-code-20250219") // Note: NO extended-cache-ttl beta in incoming header @@ -334,7 +334,7 @@ func TestClaudeExecutor_APIKeySubagentPreserves1hTTLAndInjectsBeta_Stream(t *tes }] }`) incomingHeaders := http.Header{} - incomingHeaders.Set("User-Agent", "claude-cli/2.1.281 (external, cli)") + incomingHeaders.Set("User-Agent", "claude-cli/2.1.322 (external, cli)") incomingHeaders.Set("X-Claude-Code-Agent-Id", "agent-sub-apikey-stream-202") incomingHeaders.Set("Anthropic-Beta", "claude-code-20250219") // Note: NO extended-cache-ttl beta in incoming header diff --git a/internal/runtime/executor/claude_executor_test.go b/internal/runtime/executor/claude_executor_test.go index c9d39fed00e..3063c02822f 100644 --- a/internal/runtime/executor/claude_executor_test.go +++ b/internal/runtime/executor/claude_executor_test.go @@ -28,6 +28,7 @@ import ( cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + log "github.com/sirupsen/logrus" ) func resetClaudeDeviceProfileCache() { @@ -816,7 +817,7 @@ func TestClaudeExecutor_NonClaudeRequestUsesClaudeCode220CLIFingerprint(t *testi t.Fatalf("Execute() error = %v", errExecute) } - assertClaudeFingerprint(t, seenHeaders, "claude-cli/2.1.280 (external, cli)", "0.112.1", "v26.3.0", "MacOS", "arm64") + assertClaudeFingerprint(t, seenHeaders, "claude-cli/2.1.321 (external, cli)", "0.128.0", "v26.12.1", "MacOS", "arm64") if got := seenHeaders.Get("X-App"); got != "cli" { t.Fatalf("X-App = %q, want cli", got) } @@ -828,8 +829,8 @@ func TestClaudeExecutor_NonClaudeRequestUsesClaudeCode220CLIFingerprint(t *testi if len(system) != 2 { t.Fatalf("system block count = %d, want 2: %s", len(system), seenBody) } - if got := system[0].Get("text").String(); got != "x-anthropic-billing-header: cc_version=2.1.280.d7b; cc_entrypoint=cli;" { - t.Fatalf("billing header = %q, want 2.1.280 CLI fingerprint", got) + if got := system[0].Get("text").String(); got != "x-anthropic-billing-header: cc_version=2.1.321.cf7; cc_entrypoint=cli;" { + t.Fatalf("billing header = %q, want 2.1.321 CLI fingerprint", got) } if got := system[1].Get("text").String(); got != claudeCodeCLIIdentity { t.Fatalf("system[1].text = %q, want official CLI identity", got) @@ -877,12 +878,12 @@ func TestClaudeExecutor_ConfirmedNewerPatchClaudeCodeRequestPreservesInteractive const userID = `{"device_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","account_uuid":"","session_id":"11111111-2222-4333-8444-555555555555"}` payload := []byte(`{"model":"claude-opus-4-6","system":[{"type":"text","text":"interactive-system","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"x"}],"metadata":{"user_id":` + fmt.Sprintf("%q", userID) + `}}`) incoming := http.Header{ - "User-Agent": {"claude-cli/2.1.281 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.322 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219,interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,effort-2025-11-24"}, "X-Claude-Code-Session-Id": {sessionID}, - "X-Stainless-Package-Version": {"0.112.1"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Package-Version": {"0.128.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, "X-Stainless-Os": {"MacOS"}, "X-Stainless-Arch": {"arm64"}, } @@ -904,7 +905,7 @@ func TestClaudeExecutor_ConfirmedNewerPatchClaudeCodeRequestPreservesInteractive t.Fatalf("Execute() error = %v", errExecute) } - assertClaudeFingerprint(t, seenHeaders, "claude-cli/2.1.281 (external, cli)", "0.112.1", "v26.3.0", "MacOS", "arm64") + assertClaudeFingerprint(t, seenHeaders, "claude-cli/2.1.322 (external, cli)", "0.128.0", "v26.12.1", "MacOS", "arm64") if got := ojson.GetBytes(seenBody, "system.0.text").String(); got != "interactive-system" { t.Fatalf("system.0.text = %q, want confirmed client system preserved", got) } @@ -947,7 +948,7 @@ func TestClaudeExecutor_ConfirmedClaudeCodeWithoutCacheControlPreservesContent(t const userID = `{"device_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","account_uuid":"","session_id":"11111111-2222-4333-8444-555555555555"}` payload := []byte(`{"model":"claude-opus-4-6","messages":[{"role":"user","content":"x"}],"metadata":{"user_id":` + fmt.Sprintf("%q", userID) + `}}`) incoming := http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}, "X-Claude-Code-Session-Id": {sessionID}, @@ -1006,7 +1007,7 @@ func TestClaudeExecutor_ConfirmedCLIForwardsNativeOpus55Shape(t *testing.T) { const betas = "claude-code-20250219,oauth-2025-04-20,mid-conversation-system-clear-at-2026-08-21,thinking-binding-controls-2026-08-01,extended-cache-ttl-2025-04-11" payload := []byte(`{"model":"claude-opus-5-5","system":[{"type":"text","text":` + fmt.Sprintf("%q", billing) + `},{"type":"text","text":"native identity"},{"type":"text","text":"native model block"}],"messages":[{"role":"user","content":"hello"}],"metadata":{"user_id":` + fmt.Sprintf("%q", userID) + `},"fallbacks":[{"model":"claude-opus-4-8"}],"thinking":{"type":"adaptive","display":"updates"}}`) incoming := http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {betas}, "X-Claude-Code-Session-Id": {"11111111-2222-4333-8444-555555555555"}, @@ -1062,7 +1063,7 @@ func TestClaudeExecutor_ConfirmedVSCodeAgentSDKRequestPreservesIdentity(t *testi const sessionID = "22222222-3333-4444-8555-666666666666" const userID = `{"device_id":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","account_uuid":"","session_id":"22222222-3333-4444-8555-666666666666"}` - const vscodeUA = "claude-cli/2.1.280 (external, claude-vscode, agent-sdk/0.3.220)" + const vscodeUA = "claude-cli/2.1.321 (external, claude-vscode, agent-sdk/0.3.220)" const billingHeader = "x-anthropic-billing-header: cc_version=2.1.258.9cb; cc_entrypoint=claude-vscode;" payload := []byte(`{"model":"claude-opus-4-6","system":[{"type":"text","text":` + fmt.Sprintf("%q", billingHeader) + `},{"type":"text","text":"You are a Claude agent, built on Anthropic's Claude Agent SDK.","cache_control":{"type":"ephemeral","ttl":"1h"}},{"type":"text","text":"vscode-agent-system"}],"messages":[{"role":"user","content":"x"}],"metadata":{"user_id":` + fmt.Sprintf("%q", userID) + `}}`) incoming := http.Header{ @@ -1071,8 +1072,8 @@ func TestClaudeExecutor_ConfirmedVSCodeAgentSDKRequestPreservesIdentity(t *testi "Anthropic-Beta": {"claude-code-20250219,interleaved-thinking-2025-05-14"}, "Anthropic-Dangerous-Direct-Browser-Access": {"true"}, "X-Claude-Code-Session-Id": {sessionID}, - "X-Stainless-Package-Version": {"0.112.1"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Package-Version": {"0.128.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, "X-Stainless-Os": {"MacOS"}, "X-Stainless-Arch": {"arm64"}, } @@ -1095,7 +1096,7 @@ func TestClaudeExecutor_ConfirmedVSCodeAgentSDKRequestPreservesIdentity(t *testi t.Fatalf("Execute() error = %v", errExecute) } - assertClaudeFingerprint(t, seenHeaders, vscodeUA, "0.112.1", "v26.3.0", "MacOS", "arm64") + assertClaudeFingerprint(t, seenHeaders, vscodeUA, "0.128.0", "v26.12.1", "MacOS", "arm64") if got := seenHeaders.Get("Anthropic-Dangerous-Direct-Browser-Access"); got != "true" { t.Fatalf("Anthropic-Dangerous-Direct-Browser-Access = %q, want preserved true", got) } @@ -1147,7 +1148,7 @@ func TestClaudeExecutor_CopiedVSCodeAgentSDKHeadersWithoutMetadataAreCloaked(t * SourceFormat: sdktranslator.FormatClaude, OriginalRequest: payload, Headers: http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, claude-vscode, agent-sdk/0.3.220)"}, + "User-Agent": {"claude-cli/2.1.321 (external, claude-vscode, agent-sdk/0.3.220)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}, }, @@ -1156,7 +1157,7 @@ func TestClaudeExecutor_CopiedVSCodeAgentSDKHeadersWithoutMetadataAreCloaked(t * t.Fatalf("Execute() error = %v", errExecute) } - if got := seenHeaders.Get("User-Agent"); got != "claude-cli/2.1.280 (external, cli)" { + if got := seenHeaders.Get("User-Agent"); got != "claude-cli/2.1.321 (external, cli)" { t.Fatalf("User-Agent = %q, want CLI cloak", got) } if got := ojson.GetBytes(seenBody, "system.#").Int(); got != 3 { @@ -1201,7 +1202,7 @@ func TestClaudeExecutor_AgentSDKEntrypointWithStrongSignalsUsesCLICloak(t *testi SourceFormat: sdktranslator.FormatClaude, OriginalRequest: payload, Headers: http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, sdk-ts, agent-sdk/0.3.220)"}, + "User-Agent": {"claude-cli/2.1.321 (external, sdk-ts, agent-sdk/0.3.220)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}, }, @@ -1210,7 +1211,7 @@ func TestClaudeExecutor_AgentSDKEntrypointWithStrongSignalsUsesCLICloak(t *testi t.Fatalf("Execute() error = %v", errExecute) } - if got := seenHeaders.Get("User-Agent"); got != "claude-cli/2.1.280 (external, cli)" { + if got := seenHeaders.Get("User-Agent"); got != "claude-cli/2.1.321 (external, cli)" { t.Fatalf("User-Agent = %q, want CLI cloak", got) } if got := ojson.GetBytes(seenBody, "system.0.text").String(); !strings.Contains(got, "cc_entrypoint=cli;") { @@ -1256,11 +1257,11 @@ func TestClaudeExecutor_ConfirmedVSCodeOAuthPreservesToolNames(t *testing.T) { SourceFormat: sdktranslator.FormatClaude, OriginalRequest: payload, Headers: http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, claude-vscode, agent-sdk/0.3.220)"}, + "User-Agent": {"claude-cli/2.1.321 (external, claude-vscode, agent-sdk/0.3.220)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}, - "X-Stainless-Package-Version": {"0.112.1"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Package-Version": {"0.128.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, }, }) if errExecute != nil { @@ -1300,7 +1301,7 @@ func TestClaudeExecutor_ConfirmedSDKTSAgentSDKRequestPassesThroughWithRealProfil const sessionID = "33333333-4444-4555-8666-777777777777" const userID = `{"account_uuid":"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa","device_id":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","session_id":"33333333-4444-4555-8666-777777777777"}` - const sdkTSUA = "claude-cli/2.1.304 (external, sdk-ts, agent-sdk/0.3.276)" + const sdkTSUA = "claude-cli/2.1.345 (external, sdk-ts, agent-sdk/0.3.276)" const billingHeader = "x-anthropic-billing-header: cc_version=2.1.304.179; cc_entrypoint=sdk-ts;" payload := []byte(`{"model":"claude-sonnet-5-5","max_tokens":1024,"system":[{"type":"text","text":` + fmt.Sprintf("%q", billingHeader) + `},{"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.","cache_control":{"type":"ephemeral","ttl":"1h"}},{"type":"text","text":"t3-code-system-prompt","cache_control":{"type":"ephemeral","ttl":"1h"}}],"tools":[{"name":"Agent","description":"subagent","input_schema":{"type":"object"}},{"name":"Bash","description":"shell","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hello"}]}],"metadata":{"user_id":` + fmt.Sprintf("%q", userID) + `},"thinking":{"type":"adaptive","display":"summarized"},"output_config":{"effort":"low"}}`) incoming := http.Header{ @@ -1310,7 +1311,7 @@ func TestClaudeExecutor_ConfirmedSDKTSAgentSDKRequestPassesThroughWithRealProfil "Anthropic-Dangerous-Direct-Browser-Access": {"true"}, "X-Claude-Code-Session-Id": {sessionID}, "X-Stainless-Package-Version": {"0.128.0"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, "X-Stainless-Os": {"MacOS"}, "X-Stainless-Arch": {"arm64"}, } @@ -1340,7 +1341,7 @@ func TestClaudeExecutor_ConfirmedSDKTSAgentSDKRequestPassesThroughWithRealProfil t.Fatalf("Execute() error = %v", errExecute) } - assertClaudeFingerprint(t, seenHeaders, sdkTSUA, "0.128.0", "v26.3.0", "MacOS", "arm64") + assertClaudeFingerprint(t, seenHeaders, sdkTSUA, "0.128.0", "v26.12.1", "MacOS", "arm64") if got := ojson.GetBytes(seenBody, "system.#").Int(); got != 3 { t.Fatalf("system block count = %d, want 3: %s", got, seenBody) } @@ -1381,7 +1382,7 @@ func TestClaudeExecutor_ConfiguredNativeEntrypointPassesThroughWithRealProfile(t const sessionID = "33333333-4444-4555-8666-777777777777" const userID = `{"account_uuid":"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa","device_id":"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc","session_id":"33333333-4444-4555-8666-777777777777"}` - const t3CodeUA = "claude-cli/2.1.316 (external, t3-code, agent-sdk/0.3.276)" + const t3CodeUA = "claude-cli/2.1.357 (external, t3-code, agent-sdk/0.3.276)" const billingHeader = "x-anthropic-billing-header: cc_version=2.1.316.179; cc_entrypoint=t3-code;" payload := []byte(`{"model":"claude-sonnet-5-5","max_tokens":1024,"system":[{"type":"text","text":` + fmt.Sprintf("%q", billingHeader) + `},{"type":"text","text":"You are a Claude agent, built on Anthropic's Claude Agent SDK.","cache_control":{"type":"ephemeral","ttl":"1h"}},{"type":"text","text":"t3-code-system-prompt","cache_control":{"type":"ephemeral","ttl":"1h"}}],"tools":[{"name":"Agent","description":"subagent","input_schema":{"type":"object"}},{"name":"Bash","description":"shell","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hello"}]}],"metadata":{"user_id":` + fmt.Sprintf("%q", userID) + `},"thinking":{"type":"adaptive","display":"summarized"},"output_config":{"effort":"low"}}`) incoming := http.Header{ @@ -1391,7 +1392,7 @@ func TestClaudeExecutor_ConfiguredNativeEntrypointPassesThroughWithRealProfile(t "Anthropic-Dangerous-Direct-Browser-Access": {"true"}, "X-Claude-Code-Session-Id": {sessionID}, "X-Stainless-Package-Version": {"0.128.0"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, "X-Stainless-Os": {"MacOS"}, "X-Stainless-Arch": {"arm64"}, } @@ -1425,7 +1426,7 @@ func TestClaudeExecutor_ConfiguredNativeEntrypointPassesThroughWithRealProfile(t t.Fatalf("Execute() error = %v", errExecute) } - assertClaudeFingerprint(t, seenHeaders, t3CodeUA, "0.128.0", "v26.3.0", "MacOS", "arm64") + assertClaudeFingerprint(t, seenHeaders, t3CodeUA, "0.128.0", "v26.12.1", "MacOS", "arm64") if got := ojson.GetBytes(seenBody, "system.#").Int(); got != 3 { t.Fatalf("system block count = %d, want 3: %s", got, seenBody) } @@ -1466,7 +1467,7 @@ func TestClaudeExecutor_CloakModeNeverPreservesConfirmedShapeClaudeCodeCallerHea const sessionID = "44444444-5555-4666-8777-888888888888" const userID = `{"account_uuid":"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa","device_id":"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd","session_id":"44444444-5555-4666-8777-888888888888"}` - const callerUA = "claude-cli/2.1.304 (external, sdk-py, agent-sdk/0.3.276)" + const callerUA = "claude-cli/2.1.345 (external, sdk-py, agent-sdk/0.3.276)" payload := []byte(`{"model":"claude-haiku-5-5","max_tokens":1024,"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.304.c80; cc_entrypoint=sdk-py"},{"type":"text","text":"You are a Claude agent, built on Anthropic's Claude Agent SDK."},{"type":"text","text":"You are naming a coding session."}],"tools":[],"messages":[{"role":"user","content":[{"type":"text","text":"name session"}]}],"metadata":{"user_id":` + fmt.Sprintf("%q", userID) + `}}`) incoming := http.Header{ "User-Agent": {callerUA}, @@ -1475,7 +1476,7 @@ func TestClaudeExecutor_CloakModeNeverPreservesConfirmedShapeClaudeCodeCallerHea "Anthropic-Dangerous-Direct-Browser-Access": {"true"}, "X-Claude-Code-Session-Id": {sessionID}, "X-Stainless-Package-Version": {"0.128.0"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, "X-Stainless-Os": {"MacOS"}, "X-Stainless-Arch": {"arm64"}, } @@ -1506,7 +1507,7 @@ func TestClaudeExecutor_CloakModeNeverPreservesConfirmedShapeClaudeCodeCallerHea t.Fatalf("Execute() error = %v", errExecute) } - assertClaudeFingerprint(t, seenHeaders, callerUA, "0.128.0", "v26.3.0", "MacOS", "arm64") + assertClaudeFingerprint(t, seenHeaders, callerUA, "0.128.0", "v26.12.1", "MacOS", "arm64") if bytes.Contains(seenBody, []byte(`"cache_control"`)) { t.Fatalf("cloak_mode: never confirmed-shape helper unexpectedly injected cache_control: %s", seenBody) } @@ -2791,7 +2792,7 @@ func TestClaudeExecutor_CountTokensUpstreamConfirmedVSCodePreservesCustomTool(t }, cliproxyexecutor.Options{ SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, claude-vscode, agent-sdk/0.3.220)"}, + "User-Agent": {"claude-cli/2.1.321 (external, claude-vscode, agent-sdk/0.3.220)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}, }, @@ -2987,7 +2988,7 @@ func TestClaudeExecutor_CountTokensConfirmedNativePreservesMeasuredOAuthBody(t * _, errCount := executor.countTokensUpstream(ctx, auth, cliproxyexecutor.Request{Model: "claude-opus-5", Payload: payload}, cliproxyexecutor.Options{ SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {incomingBetas}, }, @@ -5732,7 +5733,7 @@ func TestClaudeExecutor_RebuildMidSystemMessageDisabledByDefault(t *testing.T) { }} payload := []byte(`{"system":[{"type":"text","text":"Top rule","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]},{"role":"system","content":"Mid rule"},{"role":"user","content":[{"type":"text","text":"continue"}]}],"metadata":{"user_id":"{\"device_id\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"account_uuid\":\"\",\"session_id\":\"11111111-2222-4333-8444-555555555555\"}"}}`) ctx := contextWithGinHeaders(map[string]string{ - "User-Agent": "claude-cli/2.1.280 (external, cli)", + "User-Agent": "claude-cli/2.1.321 (external, cli)", "X-App": "cli", "Anthropic-Beta": "claude-code-20250219", }) @@ -5778,7 +5779,7 @@ func TestClaudeExecutor_RebuildMidSystemMessageOptInMovesSystemMessages(t *testi }} payload := []byte(`{"system":"Top rule","messages":[{"role":"user","content":[{"type":"text","text":"hi"}]},{"role":"system","content":"Mid string rule"},{"role":"assistant","content":[{"type":"text","text":"ok"}]},{"role":"system","content":[{"type":"text","text":"Mid array rule","cache_control":{"type":"ephemeral"}}]},{"role":"user","content":[{"type":"text","text":"continue"}]}],"metadata":{"user_id":"{\"device_id\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"account_uuid\":\"\",\"session_id\":\"11111111-2222-4333-8444-555555555555\"}"}}`) ctx := contextWithGinHeaders(map[string]string{ - "User-Agent": "claude-cli/2.1.280 (external, cli)", + "User-Agent": "claude-cli/2.1.321 (external, cli)", "X-App": "cli", "Anthropic-Beta": "claude-code-20250219", }) @@ -5889,10 +5890,345 @@ func TestApplyCloaking_PreservesConfiguredStrictModeAndSensitiveWordsWhenModeOmi } } +func TestClaudeCloakSensitiveWordsReplaceFromYAML(t *testing.T) { + cfg, errParse := config.ParseConfigBytes([]byte(`claude-api-key: + - api-key: "key-replace-123" + cloak: + mode: "always" + sensitive-words: + - "proxy" + sensitive-words-replace: + "Claude Code": "Claude Assistant" +`)) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "key-replace-123"}} + payload := []byte(`{"messages":[{"role":"user","content":[{"type":"text","text":"Use Claude Code through proxy."}]}]}`) + + out, cloaked, errCloaking := applyCloaking( + context.Background(), + cfg, + auth, + payload, + "key-replace-123", + false, + false, + ) + if errCloaking != nil { + t.Fatalf("applyCloaking() error = %v", errCloaking) + } + if !cloaked { + t.Fatal("applyCloaking() cloaked = false, want true") + } + content := ojson.GetBytes(out, "messages.0.content").Array() + got := content[len(content)-1].Get("text").String() + want := "Use Claude Assistant through p\u200Broxy." + if got != want { + t.Fatalf("user message = %q, want %q", got, want) + } +} + +func TestClaudeCloakSensitivePatternsReplaceFromYAML(t *testing.T) { + cfg, errParse := config.ParseConfigBytes([]byte(`claude-api-key: + - api-key: "key-pattern-123" + cloak: + mode: "always" + sensitive-words: + - "proxy" + sensitive-patterns-replace: + - pattern: '(?m)^You are omp[^\n]*\n?' + replacement: "" + - pattern: 'Claude\s+Code' + replacement: "Claude" +`)) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "key-pattern-123"}} + payload := []byte(`{"messages":[{"role":"user","content":[{"type":"text","text":"You are omp's agent.\nUse Claude Code through proxy."}]}]}`) + + out, cloaked, errCloaking := applyCloaking( + context.Background(), + cfg, + auth, + payload, + "key-pattern-123", + false, + false, + ) + if errCloaking != nil { + t.Fatalf("applyCloaking() error = %v", errCloaking) + } + if !cloaked { + t.Fatal("applyCloaking() cloaked = false, want true") + } + content := ojson.GetBytes(out, "messages.0.content").Array() + got := content[len(content)-1].Get("text").String() + want := "Use Claude through p\u200Broxy." + if got != want { + t.Fatalf("user message = %q, want %q", got, want) + } +} + +func TestClaudeOAuthMetadataSensitiveWordsReplaceAndDisabledCloaking(t *testing.T) { + auth := &cliproxyauth.Auth{ + Attributes: map[string]string{"api_key": "sk-ant-oat-replace-test"}, + Metadata: map[string]any{ + "cloak_mode": "always", + "cloak_sensitive_words_replace": map[string]any{ + "You are Codex, an agent based on GPT-5.": "You are a coding assistant.", + }, + }, + } + payload := []byte(`{"messages":[{"role":"user","content":[{"type":"text","text":"You are Codex, an agent based on GPT-5."}]}]}`) + out, cloaked, errCloak := applyCloaking(context.Background(), &config.Config{}, auth, payload, "sk-ant-oat-replace-test", false, false) + if errCloak != nil { + t.Fatalf("applyCloaking() error = %v", errCloak) + } + if !cloaked { + t.Fatal("expected cloaked = true") + } + content := ojson.GetBytes(out, "messages.0.content").Array() + if got := content[len(content)-1].Get("text").String(); got != "You are a coding assistant." { + t.Fatalf("rewritten message = %q, want %q", got, "You are a coding assistant.") + } + + authNever := &cliproxyauth.Auth{ + Attributes: map[string]string{ + "api_key": "key-never-replace", + "cloak_mode": "never", + "cloak_sensitive_words_replace": `{"Codex":"Assistant"}`, + }, + } + outNever, didCloakNever, errNever := applyCloaking(context.Background(), &config.Config{}, authNever, payload, "key-never-replace", false, false) + if errNever != nil { + t.Fatalf("applyCloaking(never) error = %v", errNever) + } + if didCloakNever { + t.Fatal("expected cloaked = false when cloak_mode=never") + } + if !strings.Contains(string(outNever), "You are Codex, an agent based on GPT-5.") { + t.Fatalf("disabled cloaking should preserve cleartext, got: %s", outNever) + } + + authPattern := &cliproxyauth.Auth{ + Attributes: map[string]string{"api_key": "sk-ant-oat-pattern-test"}, + Metadata: map[string]any{ + "cloak_mode": "always", + "cloak_sensitive_patterns_replace": []map[string]any{ + {"pattern": `(?m)^You are omp[^\n]*\n?`, "replacement": ""}, + }, + }, + } + patternPayload := []byte(`{"messages":[{"role":"user","content":[{"type":"text","text":"You are omp's assistant.\nKeep me."}]}]}`) + outPattern, cloakedPattern, errPattern := applyCloaking(context.Background(), &config.Config{}, authPattern, patternPayload, "sk-ant-oat-pattern-test", false, false) + if errPattern != nil { + t.Fatalf("applyCloaking(patterns) error = %v", errPattern) + } + if !cloakedPattern { + t.Fatal("expected cloaked = true for pattern metadata") + } + patternContent := ojson.GetBytes(outPattern, "messages.0.content").Array() + if got := patternContent[len(patternContent)-1].Get("text").String(); got != "Keep me." { + t.Fatalf("rewritten pattern message = %q, want %q", got, "Keep me.") + } + + // Verify matcher cache reuse and single invalid-regex log across repeated resolutions. + claudeMatcherCacheMu.Lock() + savedCache := claudeMatcherCache + savedOrder := claudeMatcherCacheOrder + claudeMatcherCache = make(map[string]*helps.SensitiveWordMatcher) + claudeMatcherCacheOrder = nil + claudeMatcherCacheMu.Unlock() + t.Cleanup(func() { + claudeMatcherCacheMu.Lock() + claudeMatcherCache = savedCache + claudeMatcherCacheOrder = savedOrder + claudeMatcherCacheMu.Unlock() + }) + + var logBuf bytes.Buffer + origOut := log.StandardLogger().Out + log.SetOutput(&logBuf) + defer log.SetOutput(origOut) + + authInvalid := &cliproxyauth.Auth{ + Attributes: map[string]string{"api_key": "sk-ant-oat-invalid-cache-test"}, + Metadata: map[string]any{ + "cloak_mode": "always", + "cloak_sensitive_patterns_replace": []map[string]any{ + {"pattern": `[invalid-claude-cache-test`, "replacement": ""}, + {"pattern": `(?m)^DropMe[^\n]*\n?`, "replacement": ""}, + }, + }, + } + _, settings1 := resolveClaudeWirePolicy(&config.Config{}, authInvalid, "sk-ant-oat-invalid-cache-test", false) + _, settings2 := resolveClaudeWirePolicy(&config.Config{}, authInvalid, "sk-ant-oat-invalid-cache-test", false) + m1 := settings1.buildSensitiveWordMatcher() + m2 := settings2.buildSensitiveWordMatcher() + if m1 == nil || m1 != m2 { + t.Fatalf("expected cached Claude matcher reuse, got m1=%p m2=%p", m1, m2) + } + if warnCount := strings.Count(logBuf.String(), "invalid-claude-cache-test"); warnCount != 1 { + t.Fatalf("expected 1 invalid-regex warning across repeated resolutions, got %d in %q", warnCount, logBuf.String()) + } + + // Verify Home credential_options.cloak.sensitive-patterns-replace end-to-end. + homeAuth := &cliproxyauth.Auth{ + Attributes: map[string]string{"api_key": "sk-ant-home-pattern-test"}, + Metadata: map[string]any{ + "credential_options": map[string]any{ + "cloak": map[string]any{ + "mode": "always", + "sensitive-patterns-replace": []map[string]any{ + {"pattern": `(?m)^You are omp[^\n]*\n?`, "replacement": ""}, + }, + }, + }, + }, + } + homeCfg := &config.Config{Home: config.HomeConfig{Enabled: true}} + homePayload := []byte(`{"messages":[{"role":"user","content":[{"type":"text","text":"You are omp's assistant.\nKeep Home rule."}]}]}`) + outHome, cloakedHome, errHome := applyCloaking(context.Background(), homeCfg, homeAuth, homePayload, "sk-ant-home-pattern-test", false, false) + if errHome != nil { + t.Fatalf("applyCloaking(home patterns) error = %v", errHome) + } + if !cloakedHome { + t.Fatal("expected cloaked = true for Home cloak patterns") + } + homeContent := ojson.GetBytes(outHome, "messages.0.content").Array() + if got := homeContent[len(homeContent)-1].Get("text").String(); got != "Keep Home rule." { + t.Fatalf("Home pattern message = %q, want %q", got, "Keep Home rule.") + } +} + +func TestHomeV8ClaudeCloakCredentialOptions(t *testing.T) { + // Pure credential_options.cloak WITHOUT duplicate cloak_* attributes or top-level metadata, + // isolating resolveClaudeKeyCloakConfig's Home path directly. + optionsOnlyAuth := &cliproxyauth.Auth{ + Provider: "claude", + Attributes: map[string]string{ + "api_key": "sk-ant-home-key", + "auth_kind": cliproxyauth.AuthKindAPIKey, + }, + Metadata: map[string]any{ + "credential_options": map[string]any{ + "cloak": map[string]any{ + "sensitive-words": []any{"ACME, Inc."}, + "sensitive-words-replace": map[string]any{"You are Codex, an agent based on GPT-5.": "You are a coding assistant."}, + }, + }, + }, + } + payload := []byte(`{"messages":[{"role":"user","content":[{"type":"text","text":"You are Codex, an agent based on GPT-5. Contact ACME, Inc. or Beta Inc."}]}]}`) + + // 1. Omitted cloak.mode must respect shared DisableClaudeCloakMode=true. + cfgDisabled := &config.Config{ + Home: config.HomeConfig{Enabled: true}, + DisableClaudeCloakMode: true, + } + outDisabled, didCloakDisabled, errDisabled := applyCloaking(context.Background(), cfgDisabled, optionsOnlyAuth, payload, "sk-ant-home-key", false, false) + if errDisabled != nil { + t.Fatalf("applyCloaking(disabled) error = %v", errDisabled) + } + if didCloakDisabled { + t.Fatalf("expected didCloak=false when DisableClaudeCloakMode=true and cloak.mode is omitted, got body=%s", outDisabled) + } + + // 2. When DisableClaudeCloakMode=false, credential_options.cloak alone enables cloaking + // and preserves comma-containing sensitive-words without splitting on ','. + cfgEnabled := &config.Config{ + Home: config.HomeConfig{Enabled: true}, + } + outEnabled, didCloakEnabled, errEnabled := applyCloaking(context.Background(), cfgEnabled, optionsOnlyAuth, payload, "sk-ant-home-key", false, false) + if errEnabled != nil { + t.Fatalf("applyCloaking(enabled) error = %v", errEnabled) + } + if !didCloakEnabled { + t.Fatal("expected didCloak=true when Home credential_options.cloak is present") + } + content := ojson.GetBytes(outEnabled, "messages.0.content").Array() + gotText := content[len(content)-1].Get("text").String() + wantText := "You are a coding assistant. Contact A\u200BCME, Inc. or Beta Inc." + if gotText != wantText { + t.Fatalf("rewritten text = %q, want %q", gotText, wantText) + } + + // 3. Empty cloak block (cloak: {}) enables CLI cloaking when DisableClaudeCloakMode=false, + // and stays disabled when DisableClaudeCloakMode=true. + emptyCloakAuth := &cliproxyauth.Auth{ + Provider: "claude", + Attributes: map[string]string{"api_key": "sk-ant-empty-cloak", "auth_kind": cliproxyauth.AuthKindAPIKey}, + Metadata: map[string]any{"credential_options": map[string]any{"cloak": map[string]any{}}}, + } + if _, didEmptyEnabled, errEmpty := applyCloaking(context.Background(), cfgEnabled, emptyCloakAuth, payload, "sk-ant-empty-cloak", false, false); errEmpty != nil || !didEmptyEnabled { + t.Fatalf("empty cloak block with DisableClaudeCloakMode=false: didCloak=%v, err=%v", didEmptyEnabled, errEmpty) + } + if _, didEmptyDisabled, errEmptyDis := applyCloaking(context.Background(), cfgDisabled, emptyCloakAuth, payload, "sk-ant-empty-cloak", false, false); errEmptyDis != nil || didEmptyDisabled { + t.Fatalf("empty cloak block with DisableClaudeCloakMode=true: didCloak=%v, err=%v", didEmptyDisabled, errEmptyDis) + } + + // 4. Explicit mode="always" in credential_options.cloak overrides DisableClaudeCloakMode=true. + explicitAlwaysAuth := &cliproxyauth.Auth{ + Provider: "claude", + Attributes: map[string]string{"api_key": "sk-ant-explicit-always", "auth_kind": cliproxyauth.AuthKindAPIKey}, + Metadata: map[string]any{"credential_options": map[string]any{"cloak": map[string]any{"mode": "always"}}}, + } + if _, didExplicit, errExplicit := applyCloaking(context.Background(), cfgDisabled, explicitAlwaysAuth, payload, "sk-ant-explicit-always", false, false); errExplicit != nil || !didExplicit { + t.Fatalf("explicit mode=always failed to override DisableClaudeCloakMode=true: didCloak=%v, err=%v", didExplicit, errExplicit) + } + + // 5. Standalone mode (Home.Enabled == false) ignores Home-only credential_options.cloak, + // while []string cloak_sensitive_words in OAuth metadata works concurrently under claudeDevicePoolMu. + _, didCloakStandalone, errStandalone := applyCloaking(context.Background(), &config.Config{}, explicitAlwaysAuth, payload, "sk-ant-explicit-always", false, false) + if errStandalone != nil || didCloakStandalone { + t.Fatalf("standalone mode consumed Home credential_options.cloak: didCloak=%v, err=%v", didCloakStandalone, errStandalone) + } + oauthSliceAuth := &cliproxyauth.Auth{ + Provider: "claude", + Attributes: map[string]string{"api_key": "sk-ant-oat-slice", "auth_kind": cliproxyauth.AuthKindOAuth}, + Metadata: map[string]any{ + "cloak_mode": "always", + "cloak_sensitive_words": []string{"ACME, Inc."}, + }, + } + outSlice, didSlice, errSlice := applyCloaking(context.Background(), cfgEnabled, oauthSliceAuth, payload, "sk-ant-oat-slice", false, false) + if errSlice != nil || !didSlice { + t.Fatalf("oauth slice applyCloaking: did=%v err=%v", didSlice, errSlice) + } + sliceBlocks := ojson.GetBytes(outSlice, "messages.0.content").Array() + if got := sliceBlocks[len(sliceBlocks)-1].Get("text").String(); !strings.Contains(got, "A\u200BCME, Inc.") || strings.Contains(got, "Beta I\u200Bnc.") { + t.Fatalf("unexpected []string sensitive-words obfuscation: %q", got) + } + + // Concurrent metadata lock test across StoreDeviceIDPool, ReadMetadataHomeCloak, + // ReadMetadataStringSlice, and ReadMetadataStringMap. + done := make(chan struct{}) + go func() { + defer close(done) + for i := 0; i < 50; i++ { + claudeauth.StoreDeviceIDPool(&optionsOnlyAuth.Metadata, []string{"device-1"}) + } + }() + for i := 0; i < 50; i++ { + _, _, words, repls, _, ok := claudeauth.ReadMetadataHomeCloak(&optionsOnlyAuth.Metadata) + if !ok || len(words) != 1 || len(repls) != 1 { + t.Fatalf("ReadMetadataHomeCloak concurrent read failed: ok=%v words=%v repls=%v", ok, words, repls) + } + _ = claudeauth.ReadMetadataStringSlice(&oauthSliceAuth.Metadata, "cloak_sensitive_words") + _ = claudeauth.ReadMetadataStringMap(&optionsOnlyAuth.Metadata, "cloak_sensitive_words_replace") + } + <-done +} + func TestApplyCloaking_Opus55FallbackOnlyForUnconfirmedClients(t *testing.T) { - cfg := &config.Config{ClaudeKey: []config.ClaudeKey{{ - APIKey: "sk-ant-oat-opus55-test", Cloak: &config.CloakConfig{}, - }}} + cfg := &config.Config{ + Claude: config.ClaudeConfig{ServerSideFallback: true}, + ClaudeKey: []config.ClaudeKey{{ + APIKey: "sk-ant-oat-opus55-test", Cloak: &config.CloakConfig{}, + }}, + } auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "sk-ant-oat-opus55-test"}} for _, tt := range []struct { name string @@ -5946,7 +6282,7 @@ func TestClaudeExecutor_CloakedOpus55PairsFallbackAndBetas(t *testing.T) { "api_key": "sk-ant-oat-cloaked-opus55", "base_url": server.URL, }} payload := []byte(`{"model":"claude-opus-5-5","thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"test"}]}`) - executor := NewClaudeExecutor(&config.Config{}) + executor := NewClaudeExecutor(&config.Config{Claude: config.ClaudeConfig{ServerSideFallback: true}}) _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ Model: "claude-opus-5-5", Payload: payload, }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude}) @@ -6005,6 +6341,7 @@ func TestClaudeOpus55FallbackReconcilesAfterModelOverride(t *testing.T) { func TestApplyCloaking_FableInjectsFallbacksAndDisplayUpdates(t *testing.T) { cfg := &config.Config{ + Claude: config.ClaudeConfig{ServerSideFallback: true}, ClaudeKey: []config.ClaudeKey{{ APIKey: "sk-ant-oat-fable-test", Cloak: &config.CloakConfig{}, @@ -6360,7 +6697,7 @@ func TestClaudeExecutor_SubagentAndProbeOmit1hCacheTTLAndBeta(t *testing.T) { }, cliproxyexecutor.Options{ SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-Claude-Code-Agent-Id": {"subagent-confirmed-456"}, "Anthropic-Beta": {"claude-code-20250219,oauth-2025-04-20,effort-2025-11-24"}, }, @@ -6383,6 +6720,7 @@ func TestClaudeExecutor_PayloadOverrideFableModelLeavesBuiltinsUnchanged(t *test defer server.Close() cfg := &config.Config{ + Claude: config.ClaudeConfig{ServerSideFallback: true}, ClaudeKey: []config.ClaudeKey{{ APIKey: "sk-ant-oat-payload-fable-test", Cloak: &config.CloakConfig{}, @@ -6439,6 +6777,7 @@ func TestClaudeExecutor_PayloadOverrideNonFableModelDoesNotInjectFableBuiltins(t defer server.Close() cfg := &config.Config{ + Claude: config.ClaudeConfig{ServerSideFallback: true}, ClaudeKey: []config.ClaudeKey{{ APIKey: "sk-ant-oat-payload-fable-test-2", Cloak: &config.CloakConfig{}, @@ -6550,6 +6889,7 @@ func TestClaudeExecutor_PayloadUnrelatedRuleLeavesBuiltinFallbacksUnchanged(t *t defer server.Close() cfg := &config.Config{ + Claude: config.ClaudeConfig{ServerSideFallback: true}, ClaudeKey: []config.ClaudeKey{{ APIKey: "sk-ant-oat-payload-fable-test-4", Cloak: &config.CloakConfig{}, @@ -6664,6 +7004,7 @@ func TestClaudeExecutor_PayloadFableProbeOverrideKeepsBuiltinAdditions(t *testin defer server.Close() cfg := &config.Config{ + Claude: config.ClaudeConfig{ServerSideFallback: true}, ClaudeKey: []config.ClaudeKey{{ APIKey: "sk-ant-oat-payload-fable-probe-strip-test", Cloak: &config.CloakConfig{}, @@ -6719,6 +7060,7 @@ func TestClaudeExecutor_PayloadProbeToNormalDoesNotReinitializeBuiltins(t *testi defer server.Close() cfg := &config.Config{ + Claude: config.ClaudeConfig{ServerSideFallback: true}, ClaudeKey: []config.ClaudeKey{{ APIKey: "sk-ant-oat-payload-declassify-probe-test", Cloak: &config.CloakConfig{}, @@ -7735,6 +8077,7 @@ func TestClaudeExecutor_PayloadFilterFallbacksPreservesRemovalOnFable(t *testing defer server.Close() cfg := &config.Config{ + Claude: config.ClaudeConfig{ServerSideFallback: true}, ClaudeKey: []config.ClaudeKey{{ APIKey: "sk-ant-oat-payload-fable-filter-test", Cloak: &config.CloakConfig{}, @@ -8603,7 +8946,7 @@ func TestClaudeExecutor_ExecuteOAuthCustomToolMCPAliasRoundTrip(t *testing.T) { if _, ok := claudeBillingCCHDigitsOffset(upstreamBody); !ok { t.Fatalf("Claude OAuth custom BaseURL body is missing CCH: %s", upstreamBody) } - if got := upstreamHeaders.Get("User-Agent"); got != "claude-cli/2.1.280 (external, cli)" { + if got := upstreamHeaders.Get("User-Agent"); got != "claude-cli/2.1.321 (external, cli)" { t.Fatalf("Messages User-Agent = %q, want CLI identity", got) } wantBetas := claudeCodeCLIBetas(payload, nil, true) @@ -8683,7 +9026,7 @@ func TestClaudeExecutor_ExecuteStreamOAuthCustomToolMCPAliasRoundTrip(t *testing if _, ok := claudeBillingCCHDigitsOffset(upstreamBody); !ok { t.Fatalf("streaming Claude OAuth custom BaseURL body is missing CCH: %s", upstreamBody) } - if got := upstreamHeaders.Get("User-Agent"); got != "claude-cli/2.1.280 (external, cli)" { + if got := upstreamHeaders.Get("User-Agent"); got != "claude-cli/2.1.321 (external, cli)" { t.Fatalf("streaming User-Agent = %q, want CLI identity", got) } wantBetas := claudeCodeCLIBetas(payload, nil, true) @@ -8825,7 +9168,7 @@ func TestInsertClaudeMidConversationSystemMessages_IsIdempotent(t *testing.T) { // baseline to Claude Code 2.1.220 behavior captured against api.anthropic.com. // The OAuth profile was reverified on 2026-08-03 with two distinct accounts. func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { - const constants = "claude-code-20250219,interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05" + const constants = "claude-code-20250219,interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,context-management-2025-06-27,prompt-caching-scope-2026-01-05" tests := []struct { name string @@ -8837,7 +9180,7 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { { name: "legacy model without tools omits both conditional betas", body: `{"model":"claude-opus-4-6"}`, - want: constants + ",effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "context 1m sits right after claude-code, not at the end", @@ -8845,8 +9188,8 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { requested: map[string]bool{claudeContext1MBeta: true}, want: "claude-code-20250219,context-1m-2025-08-07," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,effort-2025-11-24", + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "opus-5 1m variant reproduces the full observed order", @@ -8858,8 +9201,8 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { }, want: "claude-code-20250219,context-1m-2025-08-07," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01," + + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + "advanced-tool-use-2025-11-20,effort-2025-11-24," + "server-side-fallback-2026-06-01,fallback-credit-2026-06-01", }, @@ -8867,48 +9210,52 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { name: "structured outputs trails effort", body: `{"model":"claude-opus-4-6"}`, requested: map[string]bool{claudeStructuredOutputsBeta: true}, - want: constants + ",effort-2025-11-24,structured-outputs-2025-12-15", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24,structured-outputs-2025-12-15", }, { name: "unknown caller beta is not smuggled into the baseline", body: `{"model":"claude-opus-4-6"}`, requested: map[string]bool{"totally-made-up-2030-01-01": true}, - want: constants + ",effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "claude-sonnet-5 accepts role=system", body: `{"model":"claude-sonnet-5"}`, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24", }, { name: "claude-sonnet-5-5 carries tool changes beta unlike sonnet-5", body: `{"model":"claude-sonnet-5-5"}`, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24", + want: constants + ",per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + + "mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24", }, { name: "claude-opus-4-8 accepts role=system", body: `{"model":"claude-opus-4-8"}`, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01,effort-2025-11-24", + want: constants + ",mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "claude-fable-5 accepts role=system", body: `{"model":"claude-fable-5"}`, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01,effort-2025-11-24", + want: constants + ",mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "opus-5-5 carries capability betas without optional body fields", body: `{"model":"claude-opus-5-5","thinking":{"type":"adaptive"}}`, - want: constants + ",mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24,thinking-binding-controls-2026-08-01", + want: constants + ",per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + + "mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24,thinking-binding-controls-2026-08-01", }, { name: "opus-5-5 without thinking still carries clear-at capability", body: `{"model":"claude-opus-5-5"}`, - want: constants + ",mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24", + want: constants + ",per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + + "mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24", }, { name: "fable-5-1 carries per-turn-control but not timing unless the body asks", body: `{"model":"claude-fable-5-1"}`, - want: constants + ",mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24", + want: constants + ",per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + + "mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24", }, { name: "opus-5-5 timing and the other 2.1.280 gated betas keep wire order", @@ -8916,15 +9263,15 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { requested: map[string]bool{ claudeThinkingResumptionBeta: true, }, - want: constants + ",mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,timing-2026-09-09," + - "mid-conversation-tool-changes-2026-07-01,inline-tools-2026-09-15," + - "mid-conversation-system-clear-at-2026-08-21,dangerous-tool-use-2026-09-03,effort-2025-11-24," + - "thinking-binding-controls-2026-08-01,thinking-resumption-2026-07-17,prompt-caching-evict-2026-05-12", + want: constants + ",per-turn-control-2026-07-01,timing-2026-09-09,mid-conversation-tool-changes-2026-07-01," + + "inline-tools-2026-09-15,thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21," + + "effort-2025-11-24,dangerous-tool-use-2026-09-03,thinking-binding-controls-2026-08-01," + + "thinking-resumption-2026-07-17,prompt-caching-evict-2026-05-12", }, { name: "claude-opus-4-7 stays on the reminder path", body: `{"model":"claude-opus-4-7"}`, - want: constants + ",effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "oauth uses tool search and the current cache TTL trailer", @@ -8932,8 +9279,8 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { oauth: true, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,advanced-tool-use-2025-11-20," + + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20," + "effort-2025-11-24,extended-cache-ttl-2025-04-11", }, { @@ -8945,110 +9292,111 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { claudeServerSideFallbackBeta: true, claudeFallbackCreditBeta: true, }, - want: "claude-code-20250219,oauth-2025-04-20,context-1m-2025-08-07," + - "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01," + - "advanced-tool-use-2025-11-20,effort-2025-11-24," + - "server-side-fallback-2026-06-01,fallback-credit-2026-06-01," + - "extended-cache-ttl-2025-04-11", + want: "claude-code-20250219,oauth-2025-04-20," + + "context-1m-2025-08-07,interleaved-thinking-2025-05-14," + + "redact-thinking-2026-02-12,context-management-2025-06-27," + + "prompt-caching-scope-2026-01-05,mid-conversation-tool-changes-2026-07-01," + + "thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20," + + "effort-2025-11-24,server-side-fallback-2026-06-01," + + "fallback-credit-2026-06-01,extended-cache-ttl-2025-04-11", }, { name: "api key path sends neither oauth beta", body: `{"model":"claude-opus-4-6"}`, - want: constants + ",effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "claude-haiku-4-5-20251001 stays on the reminder path and omits effort", body: `{"model":"claude-haiku-4-5-20251001"}`, - want: constants, + want: constants + ",thinking-token-count-2026-05-13", }, { name: "legacy model with inline tools no longer adds advanced tool use", body: `{"model":"claude-sonnet-4-6","tools":[{"name":"Read"}]}`, - want: constants + ",effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "deferred tool adds advanced tool use", body: `{"model":"claude-sonnet-4-6","tools":[{"name":"Read","defer_loading":true}]}`, - want: constants + ",advanced-tool-use-2025-11-20,effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24", }, { name: "tool search server tool adds advanced tool use", body: `{"model":"claude-sonnet-4-6","tools":[{"type":"tool_search_tool_regex_20251119","name":"tool_search_tool_regex"},{"name":"Read"}]}`, - want: constants + ",advanced-tool-use-2025-11-20,effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24", }, { name: "tool use examples add advanced tool use", body: `{"model":"claude-sonnet-4-6","tools":[{"name":"Read","input_examples":[{"path":"a.go"}]}]}`, - want: constants + ",advanced-tool-use-2025-11-20,effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24", }, { name: "programmatic tool calling adds advanced tool use", body: `{"model":"claude-sonnet-4-6","tools":[{"name":"Read","allowed_callers":["code_execution_20250825"]}]}`, - want: constants + ",advanced-tool-use-2025-11-20,effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24", }, { name: "requested advanced tool use is honored for inline tools", body: `{"model":"claude-sonnet-4-6","tools":[{"name":"Read"}]}`, requested: map[string]bool{claudeAdvancedToolUseBeta: true}, - want: constants + ",advanced-tool-use-2025-11-20,effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24", }, { name: "role=system model without tools adds mid conversation system only", body: `{"model":"claude-opus-5"}`, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01,effort-2025-11-24", + want: constants + ",mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "role=system model with tool search adds both in wire order", body: `{"model":"claude-opus-5","tools":[{"name":"Read","defer_loading":true}]}`, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01,advanced-tool-use-2025-11-20,effort-2025-11-24", + want: constants + ",mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24", }, { name: "empty tools array does not add advanced tool use", body: `{"model":"claude-opus-4-6","tools":[]}`, - want: constants + ",effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "unknown future model keeps the optimistic role=system default", body: `{"model":"claude-future-9"}`, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01,effort-2025-11-24", + want: constants + ",mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "thinking display summarized drops redact-thinking", body: `{"model":"claude-opus-5","thinking":{"type":"adaptive","display":"summarized"}}`, want: "claude-code-20250219,interleaved-thinking-2025-05-14," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01," + + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + "effort-2025-11-24", }, { name: "thinking display omitted drops redact-thinking as well", body: `{"model":"claude-opus-4-6","thinking":{"type":"enabled","budget_tokens":2048,"display":"omitted"}}`, want: "claude-code-20250219,interleaved-thinking-2025-05-14," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,effort-2025-11-24", + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "thinking without display keeps redact-thinking", body: `{"model":"claude-opus-4-6","thinking":{"type":"adaptive"}}`, - want: constants + ",effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "blank display value keeps redact-thinking", body: `{"model":"claude-opus-4-6","thinking":{"type":"adaptive","display":" "}}`, - want: constants + ",effort-2025-11-24", + want: constants + ",thinking-token-count-2026-05-13,effort-2025-11-24", }, { name: "advisor tool beta requested placed before advanced-tool-use", body: `{"model":"claude-opus-5","tools":[{"name":"Read","defer_loading":true}]}`, requested: map[string]bool{"advisor-tool-2026-03-01": true}, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01,advisor-tool-2026-03-01,advanced-tool-use-2025-11-20,effort-2025-11-24", + want: constants + ",mid-conversation-tool-changes-2026-07-01,advisor-tool-2026-03-01,thinking-token-count-2026-05-13," + + "advanced-tool-use-2025-11-20,effort-2025-11-24", }, { name: "body with advisor server tool automatically adds advisor-tool beta", body: `{"model":"claude-opus-5","tools":[{"type":"advisor_20260301","name":"advisor"}]}`, - want: constants + ",mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01,advisor-tool-2026-03-01,effort-2025-11-24", + want: constants + ",mid-conversation-tool-changes-2026-07-01,advisor-tool-2026-03-01,thinking-token-count-2026-05-13,effort-2025-11-24", }, { // Captured 2026-09-02 from Claude Code 2.1.258 (cli entrypoint, OAuth, @@ -9063,10 +9411,12 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { }, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01," + - "advisor-tool-2026-03-01,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24,thinking-binding-controls-2026-08-01," + - "afk-mode-2026-01-31,extended-cache-ttl-2025-04-11", + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01," + + "advisor-tool-2026-03-01,thinking-token-count-2026-05-13," + + "mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24," + + "thinking-binding-controls-2026-08-01,afk-mode-2026-01-31," + + "extended-cache-ttl-2025-04-11", }, { name: "afk-mode sits between fast-mode and extended-cache-ttl", @@ -9075,8 +9425,8 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { requested: map[string]bool{claudeAFKModeBeta: true}, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01," + + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + "effort-2025-11-24,fast-mode-2026-02-01," + "afk-mode-2026-01-31,extended-cache-ttl-2025-04-11", }, @@ -9086,22 +9436,25 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { oauth: true, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-tool-changes-2026-07-01," + + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + "effort-2025-11-24,extended-cache-ttl-2025-04-11", }, { name: "thinking display updates emits thinking-display-updates beta and drops redact-thinking", body: `{"model":"claude-fable-5-1","thinking":{"type":"adaptive","display":"updates"}}`, want: "claude-code-20250219,interleaved-thinking-2025-05-14," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01," + - "mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24,thinking-binding-controls-2026-08-01,thinking-display-updates-2026-08-18", + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01," + + "thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21," + + "effort-2025-11-24,thinking-binding-controls-2026-08-01," + + "thinking-display-updates-2026-08-18", }, { name: "body with fallbacks automatically adds server-side-fallback beta", body: `{"model":"claude-fable-5-1","fallbacks":[{"model":"claude-opus-5"}]}`, - want: constants + ",mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24,server-side-fallback-2026-06-01", + want: constants + ",per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,thinking-token-count-2026-05-13," + + "mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24,server-side-fallback-2026-06-01", }, { name: "subagent request omits extended-cache-ttl beta", @@ -9109,18 +9462,17 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { oauth: true, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-system-clear-at-2026-08-21," + + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21," + "effort-2025-11-24", }, { name: "probe request max_tokens=1 omits effort and extended-cache-ttl betas", body: `{"model":"claude-sonnet-5","max_tokens":1}`, oauth: true, - want: "claude-code-20250219,oauth-2025-04-20," + - "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-system-clear-at-2026-08-21", + want: "oauth-2025-04-20,interleaved-thinking-2025-05-14," + + "redact-thinking-2026-02-12,context-management-2025-06-27," + + "prompt-caching-scope-2026-01-05,mid-conversation-system-clear-at-2026-08-21", }, { name: "haiku model omits effort beta even if requested", @@ -9129,9 +9481,8 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { oauth: true, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05," + - "extended-cache-ttl-2025-04-11", + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "thinking-token-count-2026-05-13,extended-cache-ttl-2025-04-11", }, { name: "disabled thinking omits effort beta even if requested", @@ -9140,8 +9491,8 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { oauth: true, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-system-clear-at-2026-08-21," + + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21," + "extended-cache-ttl-2025-04-11", }, { @@ -9150,9 +9501,10 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { oauth: true, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-system-clear-at-2026-08-21," + - "effort-2025-11-24,fallback-credit-2026-06-01,extended-cache-ttl-2025-04-11", + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21," + + "effort-2025-11-24,fallback-credit-2026-06-01," + + "extended-cache-ttl-2025-04-11", }, { name: "oauth body with fallbacks automatically adds fallback-credit beta", @@ -9160,10 +9512,11 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { oauth: true, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01," + - "mid-conversation-system-clear-at-2026-08-21,effort-2025-11-24,server-side-fallback-2026-06-01,fallback-credit-2026-06-01," + - "extended-cache-ttl-2025-04-11", + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01," + + "thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21," + + "effort-2025-11-24,server-side-fallback-2026-06-01," + + "fallback-credit-2026-06-01,extended-cache-ttl-2025-04-11", }, { name: "requested fallback-credit beta is honored", @@ -9172,9 +9525,10 @@ func TestClaudeCodeCLIBetas_MatchesObservedClientMatrix(t *testing.T) { oauth: true, want: "claude-code-20250219,oauth-2025-04-20," + "interleaved-thinking-2025-05-14,redact-thinking-2026-02-12," + - "thinking-token-count-2026-05-13,context-management-2025-06-27," + - "prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,mid-conversation-system-clear-at-2026-08-21," + - "effort-2025-11-24,fallback-credit-2026-06-01,extended-cache-ttl-2025-04-11", + "context-management-2025-06-27,prompt-caching-scope-2026-01-05," + + "thinking-token-count-2026-05-13,mid-conversation-system-clear-at-2026-08-21," + + "effort-2025-11-24,fallback-credit-2026-06-01," + + "extended-cache-ttl-2025-04-11", }, } @@ -10585,7 +10939,7 @@ func runClaudeExecutorCapture(t *testing.T, cfg *config.Config, cloakMode string } func TestClaudeExecutor_PreservedThinkingReplayInjectsDropBlock(t *testing.T) { - for _, model := range []string{"claude-haiku-5-5", "claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-1"} { + for _, model := range []string{"claude-haiku-5-5", "claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-1", "claude-fable-5-2", "claude-fable-5-2[1m]"} { t.Run(model, func(t *testing.T) { seenBody, seenHeaders := runClaudeExecutorCapture(t, nil, "", false, model, preservedThinkingReplayPayload(model)) if got := ojson.GetBytes(seenBody, "thinking.block_binding.prefix_mismatch_behavior").String(); got != "drop_block" { @@ -10642,7 +10996,7 @@ func TestClaudeExecutor_PreservedThinkingRequiresSignedBlock(t *testing.T) { } func TestClaudeExecutor_PreservedThinkingOmittedThinkingSynthesizesAdaptiveBinding(t *testing.T) { - for _, model := range []string{"claude-haiku-5-5", "claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-1"} { + for _, model := range []string{"claude-haiku-5-5", "claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-1", "claude-fable-5-2"} { for _, tc := range []struct { name string block string diff --git a/internal/runtime/executor/claude_executor_thread_beta_policy_test.go b/internal/runtime/executor/claude_executor_thread_beta_policy_test.go new file mode 100644 index 00000000000..182c7f5aae4 --- /dev/null +++ b/internal/runtime/executor/claude_executor_thread_beta_policy_test.go @@ -0,0 +1,267 @@ +package executor + +import ( + "context" + "errors" + "fmt" + "net/http" + "path/filepath" + "strings" + "testing" + + "github.com/google/uuid" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home" + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestClaudeThreadCachedProfileRejectsMissingCapabilities(t *testing.T) { + for _, addition := range []string{`"speed":"fast"`, `"thinking":{"type":"adaptive","block_binding":{"prefix_mismatch_behavior":"drop_block"}}`} { + t.Run(addition, func(t *testing.T) { + calls := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-new-capability"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12"}}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},` + addition + `,"messages":[{"role":"user","content":"second"}]}`) + _, errExecute := executor.Execute(ctx, auth, request, opts) + var requestErr cliproxyexecutor.RequestScopedError + if errExecute == nil || !errors.As(errExecute, &requestErr) || !requestErr.IsRequestScoped() || calls != 1 { + t.Fatalf("incompatible capability: error=%v, sends=%d, want request-scoped conflict without sending", errExecute, calls) + } + }) + } +} + +func TestClaudeThreadDynamicBetaPolicyCannotBeOverridden(t *testing.T) { + calls := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-dynamic", "base_url": "https://gateway.example.com", "header:Anthropic-Beta": "$X-Upstream-Betas"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12"}, "X-Upstream-Betas": []string{"configured-a"}}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + opts.Headers.Set("X-Upstream-Betas", "configured-b") + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"messages":[{"role":"user","content":"second"}]}`) + _, errExecute := executor.Execute(ctx, auth, request, opts) + var requestErr cliproxyexecutor.RequestScopedError + if errExecute == nil || !errors.As(errExecute, &requestErr) || !requestErr.IsRequestScoped() || calls != 1 { + t.Fatalf("dynamic configured beta was overwritten: error=%v, sends=%d", errExecute, calls) + } +} + +func TestClaudeThreadUnknownProfileRequiresReplay(t *testing.T) { + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + t.Error("sent an unverified Thread beta guess") + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_unknown")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-unknown"}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_unknown"},"messages":[{"role":"user","content":"second"}]}`)} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12"}}} + if _, errExecute := NewClaudeExecutor(&config.Config{}).Execute(ctx, auth, request, opts); errExecute == nil { + t.Fatal("missing actual snapshot was accepted instead of requiring replay") + } +} + +func TestClaudeThreadCallerBodyBetasMayBeOmittedOnContinuation(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) { + var sent []string + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + sent = append(sent, strings.Join(helps.HeaderValuesCaseInsensitive(req.Header, "Anthropic-Beta"), ",")) + if stream { + return claudeThreadTestResponse(req, http.StatusOK, "text/event-stream", claudeThreadTestSSE("msg_thread_1")), nil + } + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-body-declaration"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12"}}} + for _, body := range []string{ + `{"model":"claude-opus-5","thread":{"type":"create"},"betas":["effort-2025-11-24"],"messages":[{"role":"user","content":"first"}]}`, + `{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"second"}]}`, + } { + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(body)} + if stream { + result, errStream := executor.ExecuteStream(ctx, auth, request, opts) + if errStream != nil { + t.Fatal(errStream) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + } + if len(sent) != 2 || sent[0] != sent[1] || !strings.Contains(sent[0], "effort-2025-11-24") { + t.Fatalf("caller body declaration was not retained: %q", sent) + } + }) + } +} + +func TestClaudeThreadPayloadFilterDoesNotConstrainIndependentHeaderDeclarations(t *testing.T) { + var sent []string + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + sent = append(sent, strings.Join(helps.HeaderValuesCaseInsensitive(req.Header, "Anthropic-Beta"), ",")) + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "sk-ant-oat-header-declaration"}, Metadata: map[string]any{"account_uuid": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12,effort-2025-11-24"}}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"betas":["effort-2025-11-24"],"safeguards":{},"messages":[{"role":"user","content":"first"}]}`)} + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + cfg := &config.Config{Payload: config.PayloadConfig{Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "claude-opus-5"}}, Params: []string{"betas"}}}}} + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"betas":["effort-2025-11-24"],"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"second"}]}`) + if _, errExecute := executor.WithConfig(cfg).Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatalf("body filter invalidated an independently declared header capability: %v", errExecute) + } + if len(sent) != 2 || sent[0] != sent[1] { + t.Fatalf("header declarations changed while body declarations were filtered: %q", sent) + } +} + +func TestClaudeThreadManagerRoutesToOriginalCredential(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, sameKey := range []bool{false, true} { + for _, variant := range []string{"normal", "disabled owner", "conflicting pin", "foreign caller"} { + t.Run(fmt.Sprintf("stream=%v/same-key=%v/%s", stream, sameKey, variant), func(t *testing.T) { + caller := t.Name() + uuid.NewString() + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewClaudeExecutor(&config.Config{})) + if _, sticky := manager.Selector().(*cliproxyauth.SessionAffinitySelector); sticky { + t.Fatal("test requires default round-robin without session affinity") + } + auths := make([]*cliproxyauth.Auth, 0, 2) + for i := range 2 { + key := "key-thread-routing" + if !sameKey { + key += fmt.Sprint(i) + } + auth := &cliproxyauth.Auth{ID: fmt.Sprintf("%s-%d", caller, i), Provider: "claude", Attributes: map[string]string{"api_key": key}} + registry.GetGlobalRegistry().RegisterClient(auth.ID, "claude", []*registry.ModelInfo{{ID: "claude-opus-5"}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + auths = append(auths, auth) + } + calls := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if stream { + return claudeThreadTestResponse(req, http.StatusOK, "text/event-stream", claudeThreadTestSSE("msg_thread_1")), nil + } + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + var selected []string + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12"}}, Metadata: map[string]any{ + cliproxyexecutor.CallerScopeMetadataKey: caller, + cliproxyexecutor.SelectedAuthCallbackMetadataKey: func(id string) { selected = append(selected, id) }, + }} + execute := func(request cliproxyexecutor.Request) error { + if stream { + result, errStream := manager.ExecuteStream(ctx, []string{"claude"}, request, opts) + if errStream != nil { + return errStream + } + for chunk := range result.Chunks { + if chunk.Err != nil { + return chunk.Err + } + } + return nil + } + _, errExecute := manager.Execute(ctx, []string{"claude"}, request, opts) + return errExecute + } + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + if errExecute := execute(request); errExecute != nil { + t.Fatal(errExecute) + } + if len(selected) != 1 { + t.Fatalf("initial selections = %v", selected) + } + switch variant { + case "disabled owner": + owner, _ := manager.GetByID(selected[0]) + owner.Disabled = true + if _, errUpdate := manager.Update(ctx, owner); errUpdate != nil { + t.Fatal(errUpdate) + } + case "conflicting pin": + for _, auth := range auths { + if auth.ID != selected[0] { + opts.Metadata[cliproxyexecutor.PinnedAuthMetadataKey] = auth.ID + } + } + case "foreign caller": + opts.Metadata[cliproxyexecutor.CallerScopeMetadataKey] = "foreign-" + caller + } + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"messages":[{"role":"user","content":"second"}]}`) + errExecute := execute(request) + if variant == "normal" { + if errExecute != nil || calls != 2 || len(selected) != 2 || selected[1] != selected[0] { + t.Fatalf("Thread lost original credential: error=%v, calls=%d, selections=%v", errExecute, calls, selected) + } + } else { + if errExecute == nil || calls != 1 { + t.Fatalf("unsafe continuation: error=%v, calls=%d, selections=%v", errExecute, calls, selected) + } + if variant != "foreign caller" && len(selected) != 1 { + t.Fatalf("selected a different credential instead of honoring ownership: %v", selected) + } + } + }) + } + } + } +} + +func claudeThreadTestKVStore(t *testing.T) string { + t.Helper() + homekv.ClearCurrent() + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + path := filepath.Join(t.TempDir(), "kv.db") + if errConfigure := kvstore.ConfigureLocal(true, path); errConfigure != nil { + t.Fatal(errConfigure) + } + t.Cleanup(func() { + homekv.ClearCurrent() + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Error(errShutdown) + } + }) + return path +} diff --git a/internal/runtime/executor/claude_executor_thread_beta_test.go b/internal/runtime/executor/claude_executor_thread_beta_test.go new file mode 100644 index 00000000000..a0d72a72080 --- /dev/null +++ b/internal/runtime/executor/claude_executor_thread_beta_test.go @@ -0,0 +1,591 @@ +package executor + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +// Changing thinking or safeguards between turns must not change the wire beta +// profile that Anthropic bound to the Thread's first successful message. +func TestClaudeThreadBetasRemainStable(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, callerBetas := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v/caller-betas=%v", stream, callerBetas), func(t *testing.T) { + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-beta"}} + headers := http.Header{} + if callerBetas { + headers.Set("Anthropic-Beta", "message-threads-2026-08-12,effort-2025-11-24") + } else { + auth.Attributes["api_key"] = "sk-ant-oat-thread-beta" + auth.Metadata = map[string]any{"account_uuid": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"} + } + var sent []string + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, errRead := io.ReadAll(req.Body) + if errRead != nil { + return nil, errRead + } + betas := strings.Join(helps.HeaderValuesCaseInsensitive(req.Header, "Anthropic-Beta"), ",") + sent = append(sent, betas) + if len(sent) > 1 { + if got := ojson.GetBytes(body, "thread.previous_message_id").String(); got != "msg_thread_1" { + t.Errorf("previous_message_id = %q, want msg_thread_1", got) + } + if betas != sent[0] { + return claudeThreadTestResponse(req, http.StatusBadRequest, "application/json", `{"type":"error","error":{"type":"invalid_request_error","message":"differing field(s): anthropic-beta. These fields must stay the same across a Thread's turns"}}`), nil + } + } + id := fmt.Sprintf("msg_thread_%d", len(sent)) + if ojson.GetBytes(body, "stream").Bool() { + return claudeThreadTestResponse(req, http.StatusOK, "text/event-stream", claudeThreadTestSSE(id)), nil + } + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage(id)), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: headers} + bodies := []string{ + `{"model":"claude-opus-5","max_tokens":2048,"thread":{"type":"create"},"thinking":{"type":"enabled","budget_tokens":1024},"safeguards":{},"messages":[{"role":"user","content":"first"}]}`, + `{"model":"claude-opus-5","max_tokens":2048,"thread":{"type":"continue","previous_message_id":"msg_thread_1"},"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"second"}]}`, + } + for turn, body := range bodies { + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(body)} + if stream { + result, errStream := executor.ExecuteStream(ctx, auth, request, opts) + if errStream != nil { + t.Fatalf("turn %d ExecuteStream: %v; wire betas=%q", turn+1, errStream, sent) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("turn %d stream: %v", turn+1, chunk.Err) + } + } + } else if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatalf("turn %d Execute: %v; wire betas=%q", turn+1, errExecute, sent) + } + } + if len(sent) != 2 || sent[0] == "" || sent[0] != sent[1] { + t.Fatalf("wire betas = %q, want two identical nonempty profiles", sent) + } + }) + } + } +} + +// Declared Thread capabilities must survive the first turn even if that turn +// does not exercise them: later turns cannot add them to the bound profile. +func TestClaudeThreadFirstTurnKeepsDeclaredCapabilities(t *testing.T) { + const betas = "message-threads-2026-08-12,effort-2025-11-24,thinking-display-updates-2026-08-18,extended-cache-ttl-2025-04-11" + for _, confirmed := range []bool{false, true} { + t.Run(fmt.Sprintf("confirmed=%v", confirmed), func(t *testing.T) { + body := []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hello"}]}`) + req, errRequest := http.NewRequest(http.MethodPost, "https://api.anthropic.com/v1/messages", nil) + if errRequest != nil { + t.Fatal(errRequest) + } + incoming := http.Header{"Anthropic-Beta": []string{betas}} + auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "key-thread-declarations"}} + if errHeaders := applyClaudeHeaders(req, auth, "key-thread-declarations", false, nil, body, nil, incoming, confirmed); errHeaders != nil { + t.Fatal(errHeaders) + } + if got := req.Header.Get("Anthropic-Beta"); got != betas { + t.Fatalf("first-turn betas = %q, want declared Thread capabilities %q", got, betas) + } + }) + } +} + +func TestClaudeThreadFirstTurnKeepsRequiredBetas(t *testing.T) { + for _, test := range []struct { + name string + body string + beta string + }{ + {name: "fast", body: `"speed":"fast"`, beta: "fast-mode-2026-02-01"}, + {name: "advisor", body: `"tools":[{"type":"advisor_20260301","name":"advisor"}]`, beta: "advisor-tool-2026-03-01"}, + } { + t.Run(test.name, func(t *testing.T) { + body := []byte(`{"model":"claude-opus-5","thread":{"type":"create"},` + test.body + `,"messages":[{"role":"user","content":"hello"}]}`) + req, errRequest := http.NewRequest(http.MethodPost, "https://api.anthropic.com/v1/messages", nil) + if errRequest != nil { + t.Fatal(errRequest) + } + incoming := http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12"}} + auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "key-thread-required"}} + if errHeaders := applyClaudeHeaders(req, auth, "key-thread-required", false, nil, body, nil, incoming, false); errHeaders != nil { + t.Fatal(errHeaders) + } + if got := req.Header.Get("Anthropic-Beta"); !strings.Contains(got, test.beta) { + t.Fatalf("first-turn beta = %q, missing required %s", got, test.beta) + } + }) + } +} + +func TestClaudeThreadOrdinaryRefusalCanContinue(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) { + calls := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if stream && calls == 1 { + return claudeThreadTestResponse(req, http.StatusOK, "text/event-stream", strings.ReplaceAll(claudeThreadTestSSE("msg_thread_1"), "end_turn", "refusal")), nil + } + return claudeThreadTestResponse(req, http.StatusOK, "application/json", strings.ReplaceAll(claudeThreadTestMessage(fmt.Sprintf("msg_thread_%d", calls)), "end_turn", "refusal")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-refusal"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12"}}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + if stream { + result, errStream := executor.ExecuteStream(ctx, auth, request, opts) + if errStream != nil { + t.Fatal(errStream) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"messages":[{"role":"user","content":"second"}]}`) + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatalf("continuation after successful ordinary refusal: %v", errExecute) + } + if calls != 2 { + t.Fatalf("upstream requests = %d, want 2", calls) + } + }) + } +} + +// The reader is paused exactly before message_stop. Once its gate is reached, +// all earlier sends have happened and the producer cannot enqueue more output. +// Draining the channel at that point deterministically exposes early completion. +func TestClaudeThreadStreamPublishesStateBeforeCompletion(t *testing.T) { + for _, test := range []struct { + format sdktranslator.Format + oauth bool + }{ + {format: sdktranslator.FormatClaude}, + {format: sdktranslator.FormatOpenAI}, + {format: sdktranslator.FormatOpenAIResponse}, + {format: sdktranslator.FormatClaude, oauth: true}, + {format: sdktranslator.FormatOpenAI, oauth: true}, + {format: sdktranslator.FormatOpenAIResponse, oauth: true}, + } { + t.Run(fmt.Sprintf("%s/oauth=%v", test.format, test.oauth), func(t *testing.T) { + waitingStop := make(chan struct{}) + releaseStop := make(chan struct{}) + defer func() { + select { + case <-releaseStop: + default: + close(releaseStop) + } + }() + prefix, suffix, ok := strings.Cut(claudeThreadTestSSE("msg_thread_1"), "event: message_stop") + if !ok { + t.Fatal("SSE fixture has no message_stop") + } + body := &claudeThreadGatedReader{prefix: strings.NewReader(prefix), suffix: strings.NewReader("event: message_stop" + suffix), waiting: waitingStop, release: releaseStop} + var sent []string + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + sent = append(sent, strings.Join(helps.HeaderValuesCaseInsensitive(req.Header, "Anthropic-Beta"), ",")) + if len(sent) == 1 { + resp := claudeThreadTestResponse(req, http.StatusOK, "text/event-stream", "") + resp.Body = io.NopCloser(body) + return resp, nil + } + if sent[0] != sent[1] { + t.Errorf("continuation beta changed: %q", sent) + } + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_2")), nil + }) + ctx, cancel := context.WithCancel(context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport))) + defer cancel() + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-timing"}} + if test.oauth { + auth.Attributes["api_key"] = "sk-ant-oat-thread-timing" + auth.Metadata = map[string]any{"account_uuid": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"} + } + headers := http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12,effort-2025-11-24"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, ResponseFormat: test.format, Headers: headers} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","max_tokens":2048,"thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + result, errStream := executor.ExecuteStream(ctx, auth, request, opts) + if errStream != nil { + t.Fatal(errStream) + } + var beforeStop [][]byte + waiting: + for { + select { + case chunk, open := <-result.Chunks: + if !open || chunk.Err != nil { + t.Fatalf("stream ended before stop gate: %v", chunk.Err) + } + beforeStop = append(beforeStop, chunk.Payload) + case <-waitingStop: + for len(result.Chunks) > 0 { + chunk := <-result.Chunks + beforeStop = append(beforeStop, chunk.Payload) + } + break waiting + } + } + for _, payload := range beforeStop { + if claudeThreadTestTerminal(payload) { + t.Errorf("completion escaped before upstream message_stop: %s", payload) + } + } + close(releaseStop) + continued := false + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("stream: %v", chunk.Err) + } + if !continued && claudeThreadTestTerminal(chunk.Payload) { + continued = true + request.Payload = []byte(`{"model":"claude-opus-5","max_tokens":2048,"thread":{"type":"continue","previous_message_id":"msg_thread_1"},"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"second"}]}`) + opts.ResponseFormat = sdktranslator.FormatClaude + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Errorf("immediate continuation after first completion: %v", errExecute) + } + } + } + if !continued || len(sent) != 2 { + t.Fatalf("continued=%v, upstream requests=%d, want successful immediate continuation", continued, len(sent)) + } + }) + } +} + +func TestClaudeThreadBetasSharedAcrossScopedCopiesAndIsolated(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) { + calls := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if got := strings.Join(helps.HeaderValuesCaseInsensitive(req.Header, "Anthropic-Beta"), ","); got != "gateway-thread-beta" { + t.Errorf("final configured wire profile = %q, want gateway-thread-beta", got) + } + if stream && calls == 1 { + return claudeThreadTestResponse(req, http.StatusOK, "text/event-stream", claudeThreadTestSSE("msg_thread_1")), nil + } + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + registered := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: "credential-a", Attributes: map[string]string{"api_key": "key-scoped-thread", "base_url": "https://gateway.example.com", "header:Anthropic-Beta": "gateway-thread-beta"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "caller-a"}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + first := registered.ForAPIKey() + if stream { + result, errStream := first.ExecuteStream(ctx, auth, request, opts) + if errStream != nil { + t.Fatal(errStream) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, errExecute := first.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"second"}]}`) + second := registered.ForAPIKey() + if _, errExecute := second.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatalf("continuation via a fresh scoped executor: %v", errExecute) + } + for _, isolated := range []string{"caller", "credential", "upstream"} { + otherAuth := auth.Clone() + otherOpts := opts + switch isolated { + case "caller": + otherOpts.Metadata = map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "caller-b"} + case "credential": + otherAuth.ID = "credential-b" + case "upstream": + otherAuth.Attributes["base_url"] = "https://other.example.com" + } + _, errExecute := second.Execute(ctx, otherAuth, request, otherOpts) + var requestErr cliproxyexecutor.RequestScopedError + if errExecute == nil || !errors.As(errExecute, &requestErr) || !requestErr.IsRequestScoped() { + t.Errorf("%s isolation error = %v, want request-scoped missing Thread", isolated, errExecute) + } + } + if calls != 2 { + t.Fatalf("upstream requests = %d, want no sends for foreign Thread state", calls) + } + }) + } +} + +func TestClaudeThreadRejectsChangedBetaPolicy(t *testing.T) { + for _, operation := range []string{"strip", "append", "payload replace", "payload filter"} { + t.Run(operation, func(t *testing.T) { + calls := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + initial := &config.Config{} + if strings.HasPrefix(operation, "payload") { + initial.Payload.Override = []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "claude-opus-5"}}, Params: map[string]any{"betas": []string{"payload-a-2099-01-01"}}}} + } + executor := NewClaudeExecutor(initial) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-policy"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12,effort-2025-11-24"}}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + cfg := &config.Config{} + switch operation { + case "strip": + cfg.ClaudeHeaderDefaults.AnthropicBetaStrip = []string{"effort-2025-11-24"} + case "append": + cfg.ClaudeHeaderDefaults.AnthropicBetaAppend = []string{"operator-beta-2099-01-01"} + case "payload replace": + cfg.Payload.Override = []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "claude-opus-5"}}, Params: map[string]any{"betas": []string{"payload-b-2099-01-01"}}}} + case "payload filter": + cfg.Payload.Override = initial.Payload.Override + cfg.Payload.Filter = []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "claude-opus-5"}}, Params: []string{"betas"}}} + } + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"messages":[{"role":"user","content":"second"}]}`) + _, errExecute := executor.WithConfig(cfg).Execute(ctx, auth, request, opts) + var requestErr cliproxyexecutor.RequestScopedError + if errExecute == nil || !errors.As(errExecute, &requestErr) || !requestErr.IsRequestScoped() { + t.Fatalf("changed beta policy error = %v, want request-scoped replay requirement", errExecute) + } + if calls != 1 { + t.Fatalf("sent %d requests, want no send that violates configured beta policy", calls) + } + }) + } +} + +func TestClaudeThreadCallerProfileSurvivesMissingCache(t *testing.T) { + for _, missing := range []string{"restart", "eviction", "body restart", "body eviction", "body only restart", "body only eviction", "derived restart", "derived eviction"} { + t.Run(missing, func(t *testing.T) { + dbPath := claudeThreadTestKVStore(t) + const betas = "message-threads-2026-08-12,effort-2025-11-24" + wantBetas := betas + callerBetas := betas + bodyField := "" + if strings.HasPrefix(missing, "body") { + wantBetas += ",context-1m-2025-08-07" + bodyField = `"betas":["context-1m-2025-08-07"],` + } + if strings.Contains(missing, "only") { + callerBetas = "" + bodyField = `"betas":["message-threads-2026-08-12","effort-2025-11-24","context-1m-2025-08-07"],` + } + initialFields := bodyField + if strings.HasPrefix(missing, "derived") { + wantBetas += ",fast-mode-2026-02-01" + initialFields += `"speed":"fast",` + } + calls := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if got := strings.Join(helps.HeaderValuesCaseInsensitive(req.Header, "Anthropic-Beta"), ","); got != wantBetas { + t.Errorf("wire beta = %q, want client's stable profile %q", got, wantBetas) + } + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage(fmt.Sprintf("msg_thread_%d", calls))), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-cold-cache"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{callerBetas}}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{` + initialFields + `"model":"claude-opus-5","thread":{"type":"create"},"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"first"}]}`)} + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + if strings.HasSuffix(missing, "restart") { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + if errConfigure := kvstore.ConfigureLocal(true, dbPath); errConfigure != nil { + t.Fatal(errConfigure) + } + executor = NewClaudeExecutor(&config.Config{}) + } else { + otherOpts := opts + otherOpts.Metadata = map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "other-caller"} + for range 1024 { + if _, errExecute := executor.Execute(ctx, auth, request, otherOpts); errExecute != nil { + t.Fatal(errExecute) + } + } + } + request.Payload = []byte(`{` + bodyField + `"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"second"}]}`) + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatalf("valid caller-owned Thread rejected after %s: %v", missing, errExecute) + } + }) + } +} + +func TestClaudeThreadNativeOAuthResumesWithoutCache(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) { + claudeThreadTestKVStore(t) + var sent []string + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, errRead := io.ReadAll(req.Body) + if errRead != nil { + return nil, errRead + } + sent = append(sent, strings.Join(helps.HeaderValuesCaseInsensitive(req.Header, "Anthropic-Beta"), ",")) + if len(sent) > 1 && sent[1] != sent[0] { + t.Errorf("native OAuth profile changed after restart: %q", sent) + } + if ojson.GetBytes(body, "stream").Bool() { + return claudeThreadTestResponse(req, http.StatusOK, "text/event-stream", claudeThreadTestSSE("msg_thread_1")), nil + } + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + auth := claudeNativeHelperOAuthAuth("") + headers := claudeNativeHelperHeaders("claude-code-20250219,interleaved-thinking-2025-05-14,message-threads-2026-08-12,advanced-tool-use-2025-11-20,effort-2025-11-24,advisor-tool-2026-03-01", "gzip, deflate, br, zstd") + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: headers} + for turn := range 2 { + doc := ojson.NewDocString(`{"model":"claude-opus-5","max_tokens":2048,"thread":{"type":"create"},"messages":[{"role":"user","content":"hello"}]}`) + if errSet := doc.Set("betas", []string{"context-1m-2025-08-07"}); errSet != nil { + t.Fatal(errSet) + } + if errSet := doc.Set("metadata.user_id", claudeNativeHelperUserID); errSet != nil { + t.Fatal(errSet) + } + if turn == 1 { + if errSet := doc.Set("thread", map[string]string{"type": "continue", "previous_message_id": "msg_thread_1"}); errSet != nil { + t.Fatal(errSet) + } + if errSet := doc.Set("thinking.type", "disabled"); errSet != nil { + t.Fatal(errSet) + } + } + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: doc.Bytes()} + // A new executor on each turn models a restart with no cached state. + executor := NewClaudeExecutor(&config.Config{}) + if stream { + result, errStream := executor.ExecuteStream(ctx, auth, request, opts) + if errStream != nil { + t.Fatalf("turn %d: %v", turn+1, errStream) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatalf("turn %d: %v", turn+1, errExecute) + } + } + if len(sent) != 2 { + t.Fatalf("upstream requests = %d, want 2", len(sent)) + } + }) + } +} + +func TestClaudeThreadSnapshotCannotUndoUncloak(t *testing.T) { + calls := 0 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + return claudeThreadTestResponse(req, http.StatusOK, "application/json", claudeThreadTestMessage("msg_thread_1")), nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ID: t.Name(), Attributes: map[string]string{"api_key": "key-thread-uncloak", "cloak_mode": "always"}} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + auth.Attributes["cloak_mode"] = "uncloak" + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_thread_1"},"messages":[{"role":"user","content":"second"}]}`) + if _, errExecute := executor.Execute(ctx, auth, request, opts); errExecute == nil { + t.Fatal("continuation restored a cloaked profile after explicit uncloak; want a Thread replay error") + } + if calls != 1 { + t.Fatalf("sent %d requests, want no send after incompatible identity policy change", calls) + } +} + +type claudeThreadGatedReader struct { + prefix *strings.Reader + suffix *strings.Reader + waiting chan struct{} + release chan struct{} + paused bool +} + +func (r *claudeThreadGatedReader) Read(p []byte) (int, error) { + if r.prefix.Len() > 0 { + return r.prefix.Read(p) + } + if !r.paused { + r.paused = true + close(r.waiting) + <-r.release + } + return r.suffix.Read(p) +} + +func claudeThreadTestTerminal(payload []byte) bool { + for _, line := range strings.Split(string(payload), "\n") { + line = strings.TrimSpace(line) + if !strings.HasPrefix(line, "data:") && !strings.HasPrefix(line, "{") { + continue + } + root := ojson.Parse(strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + switch root.Get("type").String() { + case "message_delta": + return root.Get("delta.stop_reason").String() != "" + case "message_stop", "response.completed", "response.incomplete": + return true + } + if value := root.Get("choices.0.finish_reason"); value.Exists() && value.Type != ojson.Null { + return true + } + } + return false +} + +func claudeThreadTestResponse(req *http.Request, status int, contentType, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + } +} + +func claudeThreadTestMessage(id string) string { + return fmt.Sprintf(`{"id":%q,"type":"message","model":"claude-opus-5","role":"assistant","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":1,"output_tokens":1}}`, id) +} + +func claudeThreadTestSSE(id string) string { + return fmt.Sprintf("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":%q,\"type\":\"message\",\"model\":\"claude-opus-5\",\"role\":\"assistant\",\"content\":[],\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"ok\"}}\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n", id) +} diff --git a/internal/runtime/executor/claude_executor_tokens.go b/internal/runtime/executor/claude_executor_tokens.go index 0ffa329f5c1..541979658a8 100644 --- a/internal/runtime/executor/claude_executor_tokens.go +++ b/internal/runtime/executor/claude_executor_tokens.go @@ -70,6 +70,7 @@ func (e *ClaudeExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut if rebuildMidSystemMessageEnabled(e.cfg, auth) { rebuildMidSystemMessagesToTopLevelDoc(doc) } + helps.NormalizeClaudeToolPropertyNamesDoc(doc) sanitizeClaudeMessagesForClaudeUpstreamWithDebugDoc(ctx, doc, baseModel, helps.APIKeyModelIsCompat(req)) applyClaudePreservedThinkingBindingDoc(doc) finalize := helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslatedForPayload, req, opts) @@ -212,8 +213,8 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy } } relocateClaudeSystemPromptForCountTokensWithPolicyDoc(doc, settings.strictMode, explicitCacheMode, !policy.OAuth) - if len(settings.sensitiveWords) > 0 { - helps.ObfuscateSensitiveWordsDoc(doc, helps.BuildSensitiveWordMatcher(settings.sensitiveWords)) + if matcher := settings.buildSensitiveWordMatcher(); matcher != nil { + helps.ObfuscateSensitiveWordsDoc(doc, matcher) } } else if policy.Uncloak { uncloakClaudeCodePayloadDoc(doc, confirmedClaudeCode) @@ -233,6 +234,7 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy mcpAliases := resolveClaudeMCPAliasOptions(ctx, opts.Metadata, req.Metadata) prepareClaudeOAuthToolNamesForUpstreamDoc(doc, mcpAliases) } + helps.NormalizeClaudeToolPropertyNamesDoc(doc) sanitizeClaudeMessagesForClaudeUpstreamWithDebugDoc(ctx, doc, baseModel, helps.APIKeyModelIsCompat(req)) applyClaudePreservedThinkingBindingDoc(doc) stripPromptCacheOptionsDoc(doc) @@ -314,13 +316,15 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy return cliproxyexecutor.Response{}, classifyClaudeUpstreamErrorWithCooling(resp.StatusCode, resp.Header, []byte(msg), e.modelLevelCooling()) } b, readErr := io.ReadAll(errBody) + helps.AppendAPIResponseChunk(ctx, e.cfg, b) if readErr != nil { helps.RecordAPIResponseError(ctx, e.cfg, readErr) msg := fmt.Sprintf("failed to read error response body: %v", readErr) helps.LogWithRequestID(ctx).Warn(msg) - b = []byte(msg) + if len(b) == 0 { + b = []byte(msg) + } } - helps.AppendAPIResponseChunk(ctx, e.cfg, b) if errClose := errBody.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } @@ -340,11 +344,11 @@ func (e *ClaudeExecutor) countTokensUpstream(ctx context.Context, auth *cliproxy } }() data, err := io.ReadAll(decodedBody) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return cliproxyexecutor.Response{}, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) count := ojson.GetBytesNoCopy(data, "input_tokens").Int() out := sdktranslator.TranslateTokenCount(ctx, to, responseFormat, count, data) return cliproxyexecutor.Response{Payload: out, Headers: resp.Header.Clone()}, nil diff --git a/internal/runtime/executor/claude_fingerprint_policy_test.go b/internal/runtime/executor/claude_fingerprint_policy_test.go index a187eb43d18..b0a45477951 100644 --- a/internal/runtime/executor/claude_fingerprint_policy_test.go +++ b/internal/runtime/executor/claude_fingerprint_policy_test.go @@ -1249,14 +1249,14 @@ func TestClaudeExecutor_OfficialAPIKeyCloakNeverStripsClaudeCodeIdentity(t *test const userID = `{"device_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","account_uuid":"11111111-2222-4333-8444-555555555555","session_id":"11111111-2222-4333-8444-555555555555"}` const billing = "x-anthropic-billing-header: cc_version=2.1.280.d7b; cc_entrypoint=cli; cch=00000; cc_turn_origin=human;" incoming := http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,redact-thinking-2026-02-12,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,effort-2025-11-24,cache-diagnosis-2026-04-07"}, "Anthropic-Dangerous-Direct-Browser-Access": {"true"}, "X-Claude-Code-Session-Id": {sessionID}, "X-Claude-Code-Request-Class": {"main"}, - "X-Stainless-Package-Version": {"0.112.1"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Package-Version": {"0.128.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, "X-Stainless-Os": {"MacOS"}, "X-Stainless-Arch": {"arm64"}, } @@ -1461,13 +1461,13 @@ func TestClaudeExecutor_GlobalDisableClaudeCloakModePreservesConfirmedCallerIden const userID = `{"device_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","account_uuid":"11111111-2222-4333-8444-555555555555","session_id":"11111111-2222-4333-8444-555555555555"}` const billing = "x-anthropic-billing-header: cc_version=2.1.280.d7b; cc_entrypoint=cli; cch=00000; cc_turn_origin=human;" incoming := http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219,interleaved-thinking-2025-05-14"}, "Anthropic-Dangerous-Direct-Browser-Access": {"true"}, "X-Claude-Code-Session-Id": {sessionID}, - "X-Stainless-Package-Version": {"0.112.1"}, - "X-Stainless-Runtime-Version": {"v26.3.0"}, + "X-Stainless-Package-Version": {"0.128.0"}, + "X-Stainless-Runtime-Version": {"v26.12.1"}, "X-Stainless-Os": {"MacOS"}, "X-Stainless-Arch": {"arm64"}, } diff --git a/internal/runtime/executor/claude_issue7389_test.go b/internal/runtime/executor/claude_issue7389_test.go new file mode 100644 index 00000000000..8342c1c178b --- /dev/null +++ b/internal/runtime/executor/claude_issue7389_test.go @@ -0,0 +1,333 @@ +package executor + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "regexp" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +var claudeIssue7389PropertyKeyPattern = regexp.MustCompile(`^[a-zA-Z0-9_.-]{1,64}$`) + +const claudeIssue7389Schema = `{"type":"object","properties":{"not[labels]":{"type":"string","description":"Labels to exclude"},"state":{"type":"string"}},"required":["not[labels]"]}` + +const claudeIssue7389ProjectSchema = `{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]}` + +var claudeIssue7389ResponsesPayload = `{"model":"claude-opus-5-5","input":[` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"list"}]},` + + `{"type":"function_call","call_id":"call_1","name":"list_merge_requests","arguments":"{\"not[labels]\":\"bug\",\"state\":\"opened\"}"},` + + `{"type":"function_call_output","call_id":"call_1","output":"[]"},` + + `{"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]}],` + + `"tools":[{"type":"function","name":"list_merge_requests","description":"List merge requests.","parameters":` + claudeIssue7389Schema + `},` + + `{"type":"function","name":"get_project","description":"Get a project.","parameters":` + claudeIssue7389ProjectSchema + `}]}` + +var claudeIssue7389ClaudePayload = `{"model":"claude-opus-5-5","max_tokens":256,"messages":[` + + `{"role":"user","content":"list"},` + + `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"list_merge_requests","input":{"not[labels]":"bug","state":"opened"}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"[]"},{"type":"text","text":"again"}]}],` + + `"tools":[{"name":"list_merge_requests","description":"List merge requests.","strict":true,"input_schema":` + claudeIssue7389Schema + `},` + + `{"name":"get_project","description":"Get a project.","input_schema":` + claudeIssue7389ProjectSchema + `}]}` + +func TestClaudeIssue7389RejectedPropertyNamesDoNotBreakRequests(t *testing.T) { + sources := []struct { + name string + format sdktranslator.Format + payload string + }{ + {name: "openai responses", format: sdktranslator.FormatOpenAIResponse, payload: claudeIssue7389ResponsesPayload}, + {name: "claude", format: sdktranslator.FormatClaude, payload: claudeIssue7389ClaudePayload}, + } + auths := []struct { + name string + attrs map[string]string + }{ + {name: "api key", attrs: map[string]string{"api_key": "key-7389"}}, + {name: "claude code mcp alias", attrs: map[string]string{"api_key": "key-7389-cli", "fingerprint_profile": "claude-code-cli", "cloak_mode": "always"}}, + } + for _, authCase := range auths { + for _, source := range sources { + for _, stream := range []bool{false, true} { + name := authCase.name + " " + source.name + if stream { + name += " stream" + } + t.Run(name, func(t *testing.T) { + claudeIssue7389RunRoundTrip(t, authCase.attrs, source.format, source.payload, stream) + }) + } + } + } +} + +func claudeIssue7389RunRoundTrip(t *testing.T, attrs map[string]string, format sdktranslator.Format, sourcePayload string, stream bool) { + t.Helper() + var upstreamBody []byte + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + upstreamBody, _ = io.ReadAll(req.Body) + toolName := claudeIssue7389Tool(upstreamBody, "List merge requests.").Get("name").String() + contentType := "application/json" + body := claudeIssue7389JSONResponse(toolName) + if ojson.GetBytes(upstreamBody, "stream").Bool() { + contentType = "text/event-stream" + body = claudeIssue7389SSEResponse(toolName) + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: attrs} + payload := sourcePayload + if stream && format == sdktranslator.FormatClaude { + payload = strings.Replace(payload, `"max_tokens":256,`, `"max_tokens":256,"stream":true,`, 1) + } + request := cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: []byte(payload)} + options := cliproxyexecutor.Options{SourceFormat: format, Stream: stream} + + var output []byte + if stream { + result, err := executor.ExecuteStream(ctx, auth, request, options) + if err != nil { + t.Fatalf("ExecuteStream() error = %v", err) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("stream chunk error = %v", chunk.Err) + } + output = append(output, chunk.Payload...) + output = append(output, '\n') + } + } else { + resp, err := executor.Execute(ctx, auth, request, options) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + output = resp.Payload + } + + claudeIssue7389AssertUpstream(t, upstreamBody) + if attrs["fingerprint_profile"] != "" && claudeIssue7389Tool(upstreamBody, "List merge requests.").Get("name").String() == "list_merge_requests" { + t.Fatalf("expected an MCP tool alias upstream: %s", ojson.GetBytes(upstreamBody, "tools").Raw) + } + args := claudeIssue7389ClientArguments(t, format, stream, output) + fields := claudeIssue7389ObjectFields(args) + if fields["not[labels]"] != `"feature"` || fields["state"] != `"closed"` || len(fields) != 2 { + t.Fatalf("client tool arguments = %s, want the original property names; output=%s", args, output) + } +} + +func TestClaudeIssue7389CountTokensDoesNotSendRejectedPropertyNames(t *testing.T) { + var upstreamBody []byte + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + upstreamBody, _ = io.ReadAll(req.Body) + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"input_tokens":12}`)), Request: req}, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "key-7389"}} + request := cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: []byte(claudeIssue7389ClaudePayload)} + if _, err := executor.CountTokens(ctx, auth, request, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude}); err != nil { + t.Fatalf("CountTokens() error = %v", err) + } + claudeIssue7389AssertUpstream(t, upstreamBody) +} + +// User payload rules are the final semantic barrier: values they configure +// must reach upstream exactly as configured. +func TestClaudeIssue7389PayloadRulesRunAfterSchemaFallback(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) { + var upstreamBody []byte + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + upstreamBody, _ = io.ReadAll(req.Body) + body := claudeIssue7389SSEResponse("list_merge_requests") + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + models := []config.PayloadModelRule{{Name: "claude-opus-5-5"}} + cfg := &config.Config{Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{Models: models, Params: map[string]any{"tools.0.description": "configured"}}}, + OverrideRaw: []config.PayloadRule{{Models: models, Params: map[string]any{"tools.0.input_schema": `{"type":"object","properties":{"configured[x]":{"type":"string"}}}`}}}, + }} + executor := NewClaudeExecutor(cfg) + auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "key-7389"}} + request := cliproxyexecutor.Request{Model: "claude-opus-5-5", Payload: []byte(claudeIssue7389ResponsesPayload)} + options := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, Stream: stream} + if stream { + result, err := executor.ExecuteStream(ctx, auth, request, options) + if err != nil { + t.Fatalf("ExecuteStream() error = %v", err) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("stream chunk error = %v", chunk.Err) + } + } + } else if _, err := executor.Execute(ctx, auth, request, options); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if got := ojson.GetBytes(upstreamBody, "tools.0.input_schema").Raw; got != `{"type":"object","properties":{"configured[x]":{"type":"string"}}}` { + t.Fatalf("configured input_schema = %s, want the payload rule value", got) + } + if got := ojson.GetBytes(upstreamBody, "tools.0.description").String(); got != "configured" { + t.Fatalf("configured description = %q, want the payload rule value", got) + } + }) + } +} + +// claudeIssue7389Tool returns the upstream declaration whose description +// starts with prefix, whatever name aliasing the request path applied. +func claudeIssue7389Tool(body []byte, prefix string) ojson.Result { + var found ojson.Result + ojson.GetBytes(body, "tools").ForEach(func(_, tool ojson.Result) bool { + if strings.HasPrefix(tool.Get("description").String(), prefix) { + found = tool + return false + } + return true + }) + return found +} + +// claudeIssue7389AssertPropertyKeys checks every properties map in a schema. +func claudeIssue7389AssertPropertyKeys(t *testing.T, node ojson.Result, propertyMap bool) { + t.Helper() + if node.Type != ojson.JSON { + return + } + object := node.IsObject() + node.ForEach(func(key, value ojson.Result) bool { + if object && propertyMap && !claudeIssue7389PropertyKeyPattern.MatchString(key.String()) { + t.Fatalf("upstream property key %q does not match Claude pattern", key.String()) + } + claudeIssue7389AssertPropertyKeys(t, value, object && !propertyMap && key.String() == "properties") + return true + }) +} + +func claudeIssue7389AssertUpstream(t *testing.T, body []byte) { + t.Helper() + if len(body) == 0 { + t.Fatal("upstream request was not captured") + } + ojson.GetBytes(body, "tools").ForEach(func(_, tool ojson.Result) bool { + claudeIssue7389AssertPropertyKeys(t, tool.Get("input_schema"), false) + return true + }) + + reported := claudeIssue7389Tool(body, "List merge requests.") + if got := reported.Get("input_schema").Raw; got != `{"type":"object"}` { + t.Fatalf("reported tool input_schema = %s, want an open object", got) + } + if reported.Get("strict").Exists() { + t.Fatalf("reported tool keeps strict: %s", reported.Raw) + } + description := reported.Get("description").String() + if !strings.Contains(description, `"not[labels]":{"type":"string","description":"Labels to exclude"}`) || !strings.Contains(description, `"required":["not[labels]"]`) { + t.Fatalf("reported tool description does not carry the original schema: %q", description) + } + + project := claudeIssue7389Tool(body, "Get a project.") + if got := project.Get("description").String(); got != "Get a project." { + t.Fatalf("valid tool description = %q, want unchanged", got) + } + if !project.Get("input_schema.properties.id").Exists() || project.Get("input_schema.required.0").String() != "id" { + t.Fatalf("valid tool input_schema changed: %s", project.Get("input_schema").Raw) + } + + foundHistory := false + ojson.GetBytes(body, "messages").ForEach(func(_, message ojson.Result) bool { + message.Get("content").ForEach(func(_, block ojson.Result) bool { + if block.Get("type").String() != "tool_use" { + return true + } + foundHistory = true + fields := claudeIssue7389ObjectFields([]byte(block.Get("input").Raw)) + if fields["not[labels]"] != `"bug"` || fields["state"] != `"opened"` || len(fields) != 2 { + t.Fatalf("upstream history tool_use input = %s, want the original arguments", block.Get("input").Raw) + } + return true + }) + return true + }) + if !foundHistory { + t.Fatalf("upstream history tool_use not found: %s", body) + } +} + +func claudeIssue7389ObjectFields(raw []byte) map[string]string { + fields := make(map[string]string) + ojson.ParseBytes(raw).ForEach(func(k, v ojson.Result) bool { + fields[strings.Clone(k.String())] = strings.Clone(v.Raw) + return true + }) + return fields +} + +func claudeIssue7389JSONResponse(toolName string) string { + return `{"id":"msg_7389","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"tool_use","id":"toolu_2","name":` + + string(ojson.AppendJSONString(nil, toolName)) + `,"input":{"not[labels]":"feature","state":"closed"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"output_tokens":1}}` +} + +func claudeIssue7389SSEResponse(toolName string) string { + var b strings.Builder + writeEvent := func(event, data string) { + b.WriteString("event: " + event + "\ndata: " + data + "\n\n") + } + writeEvent("message_start", `{"type":"message_start","message":{"id":"msg_7389","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":1,"output_tokens":0}}}`) + writeEvent("content_block_start", `{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_2","name":`+string(ojson.AppendJSONString(nil, toolName))+`,"input":{}}}`) + for _, fragment := range []string{"", `{"not[la`, `bels]": "fea`, `ture", "state"`, `: "closed"}`} { + writeEvent("content_block_delta", `{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":`+string(ojson.AppendJSONString(nil, fragment))+`}}`) + } + writeEvent("content_block_stop", `{"type":"content_block_stop","index":0}`) + writeEvent("message_delta", `{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":1}}`) + writeEvent("message_stop", `{"type":"message_stop"}`) + return b.String() +} + +// claudeIssue7389ClientArguments extracts the final tool arguments the client sees. +func claudeIssue7389ClientArguments(t *testing.T, format sdktranslator.Format, stream bool, output []byte) []byte { + t.Helper() + switch { + case format == sdktranslator.FormatClaude && !stream: + return []byte(ojson.GetBytes(output, `content.#(type=="tool_use").input`).Raw) + case format == sdktranslator.FormatClaude && stream: + var args strings.Builder + for _, line := range bytes.Split(output, []byte("\n")) { + line = bytes.TrimSpace(line) + if !bytes.HasPrefix(line, []byte("data:")) { + continue + } + event := ojson.ParseBytes(bytes.TrimSpace(line[len("data:"):])) + if event.Get("delta.type").String() == "input_json_delta" { + args.WriteString(event.Get("delta.partial_json").String()) + } + } + return []byte(args.String()) + case !stream: + return []byte(ojson.GetBytes(output, `output.#(type=="function_call").arguments`).String()) + default: + for _, line := range bytes.Split(output, []byte("\n")) { + line = bytes.TrimSpace(line) + if !bytes.HasPrefix(line, []byte("data:")) { + continue + } + event := ojson.ParseBytes(bytes.TrimSpace(line[len("data:"):])) + if event.Get("type").String() == "response.function_call_arguments.done" { + return []byte(event.Get("arguments").String()) + } + } + } + t.Fatalf("tool arguments not found in client output: %s", output) + return nil +} diff --git a/internal/runtime/executor/claude_issue7440_test.go b/internal/runtime/executor/claude_issue7440_test.go new file mode 100644 index 00000000000..43efc9a55e2 --- /dev/null +++ b/internal/runtime/executor/claude_issue7440_test.go @@ -0,0 +1,400 @@ +package executor + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestClaudeExecutor_CloakedOAuthOmitsServerSideFallbackByDefault_Issue7440(t *testing.T) { + models := []string{"claude-opus-5-5", "claude-fable-5-1"} + formats := []struct { + name string + format sdktranslator.Format + payload func(model string) []byte + }{ + { + name: "openai-chat", + format: sdktranslator.FormatOpenAI, + payload: func(model string) []byte { + return []byte(fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hello"}]}`, model)) + }, + }, + { + name: "claude-messages", + format: sdktranslator.FormatClaude, + payload: func(model string) []byte { + return []byte(fmt.Sprintf(`{"model":%q,"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"hello"}]}`, model)) + }, + }, + } + + for _, model := range models { + for _, source := range formats { + for _, stream := range []bool{false, true} { + mode := "execute" + if stream { + mode = "stream" + } + t.Run(model+"/"+source.name+"/"+mode, func(t *testing.T) { + var seenBody []byte + var seenHeaders http.Header + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seenBody, _ = io.ReadAll(r.Body) + seenHeaders = r.Header.Clone() + if ojson.GetBytes(seenBody, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprint(w, + "event: message_start\n"+ + `data: {"type":"message_start","message":{"id":"msg_7440","type":"message","role":"assistant","model":"claude-opus-4-8","content":[],"stop_reason":null,"usage":{"input_tokens":5,"output_tokens":0}}}`+"\n\n"+ + "event: content_block_start\n"+ + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`+"\n\n"+ + "event: content_block_delta\n"+ + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`+"\n\n"+ + "event: content_block_stop\n"+ + `data: {"type":"content_block_stop","index":0}`+"\n\n"+ + "event: message_delta\n"+ + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`+"\n\n"+ + "event: message_stop\n"+ + `data: {"type":"message_stop"}`+"\n\n", + ) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"msg_7440","type":"message","model":"claude-opus-4-8","role":"assistant","content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":2}}`)) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: "oauth-issue-7440-" + model, + Metadata: claudeOAuthTestMetadata(), + Attributes: map[string]string{ + "api_key": "sk-ant-oat-issue-7440", + "base_url": server.URL, + "cloak_mode": "always", + }, + } + executor := NewClaudeExecutor(&config.Config{}) + req := cliproxyexecutor.Request{ + Model: model, + Payload: source.payload(model), + } + opts := cliproxyexecutor.Options{ + SourceFormat: source.format, + Stream: stream, + } + + if stream { + res, errStream := executor.ExecuteStream(context.Background(), auth, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var chunks [][]byte + for chunk := range res.Chunks { + if chunk.Err != nil { + t.Fatalf("stream chunk error = %v", chunk.Err) + } + if len(chunk.Payload) > 0 { + chunks = append(chunks, chunk.Payload) + } + } + if source.format == sdktranslator.FormatOpenAI { + if len(chunks) == 0 { + t.Fatal("expected non-empty translated OpenAI stream chunks") + } + for i, rawChunk := range chunks { + gotModel := ojson.GetBytesNoCopy(rawChunk, "model").String() + if gotModel != "claude-opus-4-8" { + t.Fatalf("chunk[%d] model = %q, want claude-opus-4-8; payload=%s", i, gotModel, rawChunk) + } + } + } + } else { + resp, errExec := executor.Execute(context.Background(), auth, req, opts) + if errExec != nil { + t.Fatalf("Execute() error = %v", errExec) + } + if source.format == sdktranslator.FormatOpenAI { + if gotModel := ojson.GetBytesNoCopy(resp.Payload, "model").String(); gotModel != "claude-opus-4-8" { + t.Fatalf("response model = %q, want claude-opus-4-8; payload=%s", gotModel, resp.Payload) + } + } + } + + if ojson.GetBytesNoCopy(seenBody, "fallbacks").Exists() { + t.Fatalf("default cloaking injected unsolicited fallbacks: %s", ojson.GetBytesNoCopy(seenBody, "fallbacks").Raw) + } + betas := seenHeaders.Get("Anthropic-Beta") + if strings.Contains(betas, claudeServerSideFallbackBeta) { + t.Fatalf("Anthropic-Beta = %q, must not include %s by default", betas, claudeServerSideFallbackBeta) + } + if strings.Contains(betas, claudeFallbackCreditBeta) { + t.Fatalf("Anthropic-Beta = %q, must not include %s by default", betas, claudeFallbackCreditBeta) + } + }) + } + } + } +} + +func TestClaudeExecutor_ServerSideFallbackOptInAndPayloadFilter_Issue7440(t *testing.T) { + optInCfg, errParse := config.ParseConfigBytes([]byte("config-version: 8\nupstream:\n claude:\n server-side-fallback: true\n")) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + + var seenBody []byte + var seenHeaders http.Header + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seenBody, _ = io.ReadAll(r.Body) + seenHeaders = r.Header.Clone() + if ojson.GetBytes(seenBody, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprint(w, + "event: message_start\n"+ + `data: {"type":"message_start","message":{"id":"msg_optin","type":"message","role":"assistant","model":"claude-opus-4-8","content":[],"stop_reason":null,"usage":{"input_tokens":4,"output_tokens":0}}}`+"\n\n"+ + "event: content_block_start\n"+ + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`+"\n\n"+ + "event: content_block_delta\n"+ + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`+"\n\n"+ + "event: content_block_stop\n"+ + `data: {"type":"content_block_stop","index":0}`+"\n\n"+ + "event: message_delta\n"+ + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`+"\n\n"+ + "event: message_stop\n"+ + `data: {"type":"message_stop"}`+"\n\n", + ) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"msg_optin","type":"message","model":"claude-opus-4-8","role":"assistant","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":4,"output_tokens":1}}`)) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: "oauth-optin-7440", + Metadata: claudeOAuthTestMetadata(), + Attributes: map[string]string{ + "api_key": "sk-ant-oat-optin-7440", + "base_url": server.URL, + "cloak_mode": "always", + }, + } + req := cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hello"}]}`), + } + + if _, errExec := NewClaudeExecutor(optInCfg).Execute(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI}); errExec != nil { + t.Fatalf("Execute(optIn) error = %v", errExec) + } + if got := ojson.GetBytesNoCopy(seenBody, "fallbacks.0.model").String(); got != "claude-opus-4-8" { + t.Fatalf("opt-in fallbacks.0.model = %q, want claude-opus-4-8; body=%s", got, seenBody) + } + for _, beta := range []string{claudeServerSideFallbackBeta, claudeFallbackCreditBeta} { + if !strings.Contains(seenHeaders.Get("Anthropic-Beta"), beta) { + t.Fatalf("Anthropic-Beta = %q, missing %s when server-side-fallback is enabled", seenHeaders.Get("Anthropic-Beta"), beta) + } + } + + // Payload filter remains the final barrier even when server-side-fallback is enabled. + filteredCfg, errParseFilter := config.ParseConfigBytes([]byte("config-version: 8\nupstream:\n claude:\n server-side-fallback: true\nrequests:\n payload:\n filter:\n - models:\n - name: \"claude-opus-5-5\"\n protocol: \"claude\"\n params:\n - \"fallbacks\"\n")) + if errParseFilter != nil { + t.Fatalf("ParseConfigBytes(filtered) error = %v", errParseFilter) + } + if _, errExec := NewClaudeExecutor(filteredCfg).Execute(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI}); errExec != nil { + t.Fatalf("Execute(filtered) error = %v", errExec) + } + if ojson.GetBytesNoCopy(seenBody, "fallbacks").Exists() { + t.Fatalf("payload.filter failed to remove fallbacks: %s", ojson.GetBytesNoCopy(seenBody, "fallbacks").Raw) + } + for _, beta := range []string{claudeServerSideFallbackBeta, claudeFallbackCreditBeta} { + if strings.Contains(seenHeaders.Get("Anthropic-Beta"), beta) { + t.Fatalf("Anthropic-Beta = %q, must omit %s after payload.filter removes fallbacks", seenHeaders.Get("Anthropic-Beta"), beta) + } + } +} + +func TestClaudeExecutor_DefaultNoFallbackPreservesCallerFallbackAndRefusalTransparency_Issue7440(t *testing.T) { + // 1. Explicit caller fallbacks are still honored when server-side-fallback defaults to false. + var seenBody []byte + var seenHeaders http.Header + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seenBody, _ = io.ReadAll(r.Body) + seenHeaders = r.Header.Clone() + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"msg_caller_fb","type":"message","model":"claude-sonnet-5","role":"assistant","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":4,"output_tokens":1}}`)) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: "oauth-caller-fb-7440", + Metadata: claudeOAuthTestMetadata(), + Attributes: map[string]string{ + "api_key": "sk-ant-oat-caller-fb-7440", + "base_url": server.URL, + "cloak_mode": "always", + }, + } + callerFallbackReq := cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","fallbacks":[{"model":"claude-sonnet-5"}],"messages":[{"role":"user","content":"hello"}]}`), + } + if _, errExec := NewClaudeExecutor(&config.Config{}).Execute(context.Background(), auth, callerFallbackReq, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude}); errExec != nil { + t.Fatalf("Execute(caller fallback) error = %v", errExec) + } + if got := ojson.GetBytesNoCopy(seenBody, "fallbacks.0.model").String(); got != "claude-sonnet-5" { + t.Fatalf("caller fallback = %q, want claude-sonnet-5", got) + } + if !strings.Contains(seenHeaders.Get("Anthropic-Beta"), claudeServerSideFallbackBeta) { + t.Fatalf("Anthropic-Beta = %q, want %s for explicit caller fallback", seenHeaders.Get("Anthropic-Beta"), claudeServerSideFallbackBeta) + } + + // 2. When server-side-fallback is off and Opus 5.5 declines with reasoning_extraction refusal, + // both Execute and ExecuteStream surface the refusal transparently on OpenAI Chat Completions. + refusalServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + if ojson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprint(w, + "event: message_start\n"+ + `data: {"type":"message_start","message":{"id":"msg_refusal_7440","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":6,"output_tokens":0}}}`+"\n\n"+ + "event: message_delta\n"+ + `data: {"type":"message_delta","delta":{"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":"reasoning_extraction","explanation":"Request declined under reasoning extraction safeguards."}},"usage":{"output_tokens":0}}`+"\n\n"+ + "event: message_stop\n"+ + `data: {"type":"message_stop"}`+"\n\n", + ) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"msg_refusal_7440","type":"message","model":"claude-opus-5-5","role":"assistant","content":[],"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":"reasoning_extraction","explanation":"Request declined under reasoning extraction safeguards."},"usage":{"input_tokens":6,"output_tokens":0}}`)) + })) + defer refusalServer.Close() + + refusalAuth := &cliproxyauth.Auth{ + ID: "oauth-refusal-7440", + Metadata: claudeOAuthTestMetadata(), + Attributes: map[string]string{ + "api_key": "sk-ant-oat-refusal-7440", + "base_url": refusalServer.URL, + "cloak_mode": "always", + }, + } + chatReq := cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hello"}]}`), + } + + _, errRefusalExec := NewClaudeExecutor(&config.Config{}).Execute(context.Background(), refusalAuth, chatReq, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI}) + if errRefusalExec == nil || !strings.Contains(errRefusalExec.Error(), "reasoning_extraction") { + t.Fatalf("Execute(refusal) err = %v, want reasoning_extraction refusal error", errRefusalExec) + } + + streamRes, errRefusalStream := NewClaudeExecutor(&config.Config{}).ExecuteStream(context.Background(), refusalAuth, chatReq, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI, Stream: true}) + if errRefusalStream != nil { + t.Fatalf("ExecuteStream(refusal) initial err = %v", errRefusalStream) + } + sawContentFilter := false + var terminalStreamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + terminalStreamErr = chunk.Err + continue + } + if ojson.GetBytesNoCopy(chunk.Payload, "choices.0.finish_reason").String() == "content_filter" { + sawContentFilter = true + } + if gotModel := ojson.GetBytesNoCopy(chunk.Payload, "model").String(); gotModel != "claude-opus-5-5" { + t.Fatalf("refusal stream chunk model = %q, want claude-opus-5-5", gotModel) + } + } + if !sawContentFilter { + t.Fatal("expected finish_reason=content_filter chunk before refusal termination") + } + if terminalStreamErr == nil || !strings.Contains(terminalStreamErr.Error(), "reasoning_extraction") { + t.Fatalf("refusal stream terminal err = %v, want reasoning_extraction refusal error", terminalStreamErr) + } +} + +func TestClaudeExecutor_OpenAIResponsesSurfacesServingModelAndFallbackWhenOptedIn_Issue7440(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprint(w, + "event: message_start\n"+ + `data: {"type":"message_start","message":{"id":"msg_resp_e2e_7440","type":"message","role":"assistant","model":"claude-opus-4-8","content":[],"stop_reason":null,"usage":{"input_tokens":6,"output_tokens":0}}}`+"\n\n"+ + "event: content_block_start\n"+ + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`+"\n\n"+ + "event: content_block_delta\n"+ + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"fallback via responses"}}`+"\n\n"+ + "event: content_block_stop\n"+ + `data: {"type":"content_block_stop","index":0}`+"\n\n"+ + "event: message_delta\n"+ + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":4,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":0},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":4}]}}`+"\n\n"+ + "event: message_stop\n"+ + `data: {"type":"message_stop"}`+"\n\n", + ) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: "oauth-responses-fb-7440", + Metadata: claudeOAuthTestMetadata(), + Attributes: map[string]string{ + "api_key": "sk-ant-oat-responses-fb-7440", + "base_url": server.URL, + "cloak_mode": "always", + }, + } + cfg := &config.Config{Claude: config.ClaudeConfig{ServerSideFallback: true}} + exec := NewClaudeExecutor(cfg) + req := cliproxyexecutor.Request{ + Model: "claude-opus-5-5", + Payload: []byte(`{"model":"claude-opus-5-5","input":[{"role":"user","content":"hello"}]}`), + } + + nonStreamResp, errExec := exec.Execute(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse}) + if errExec != nil { + t.Fatalf("Execute(OpenAIResponses) error = %v", errExec) + } + if got := ojson.GetBytesNoCopy(nonStreamResp.Payload, "model").String(); got != "claude-opus-4-8" { + t.Fatalf("Execute(OpenAIResponses) model = %q, want claude-opus-4-8; payload=%s", got, string(nonStreamResp.Payload)) + } + if fb := ojson.GetBytesNoCopy(nonStreamResp.Payload, "fallback"); !fb.Exists() || fb.Get("from.model").String() != "claude-opus-5-5" || fb.Get("to.model").String() != "claude-opus-4-8" { + t.Fatalf("Execute(OpenAIResponses) fallback = %s, want from=5-5 to=4-8", fb.Raw) + } + + streamResp, errStream := exec.ExecuteStream(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, Stream: true}) + if errStream != nil { + t.Fatalf("ExecuteStream(OpenAIResponses) error = %v", errStream) + } + var completedModel string + var sawCompletedFallback bool + for chunk := range streamResp.Chunks { + if chunk.Err != nil { + t.Fatalf("stream chunk error = %v", chunk.Err) + } + for _, line := range strings.Split(string(chunk.Payload), "\n") { + if !strings.HasPrefix(line, "data: ") { + continue + } + ev := ojson.Parse(strings.TrimSpace(strings.TrimPrefix(line, "data: "))) + if ev.Get("type").String() == "response.completed" { + completedModel = ev.Get("response.model").String() + sawCompletedFallback = ev.Get("response.fallback.to.model").String() == "claude-opus-4-8" + } + } + } + if completedModel != "claude-opus-4-8" || !sawCompletedFallback { + t.Fatalf("ExecuteStream(OpenAIResponses) completedModel=%q sawCompletedFallback=%v, want claude-opus-4-8 and true", completedModel, sawCompletedFallback) + } +} diff --git a/internal/runtime/executor/claude_signing.go b/internal/runtime/executor/claude_signing.go index 6d4c7601ac3..503b6a20046 100644 --- a/internal/runtime/executor/claude_signing.go +++ b/internal/runtime/executor/claude_signing.go @@ -10,6 +10,7 @@ import ( "github.com/MoeForge/moego/ojson" xxHash64 "github.com/pierrec/xxHash/xxHash64" + claudeauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/claude" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" @@ -650,6 +651,38 @@ func resolveClaudeKeyConfig(cfg *config.Config, auth *cliproxyauth.Auth) *config // resolveClaudeKeyCloakConfig finds the matching ClaudeKey config and returns its CloakConfig. func resolveClaudeKeyCloakConfig(cfg *config.Config, auth *cliproxyauth.Auth) *config.CloakConfig { + if cfg != nil && cfg.Home.Enabled && auth != nil { + if mode, strictMode, words, replacements, cacheUserID, ok := claudeauth.ReadMetadataHomeCloak(&auth.Metadata); ok { + rawPatterns := claudeauth.ReadMetadataHomeCloakPatterns(&auth.Metadata) + var patterns []config.SensitivePatternRule + if len(rawPatterns) > 0 { + patterns = make([]config.SensitivePatternRule, 0, len(rawPatterns)) + for _, pair := range rawPatterns { + if strings.TrimSpace(pair[0]) == "" { + continue + } + patterns = append(patterns, config.SensitivePatternRule{ + Pattern: pair[0], + Replacement: pair[1], + }) + } + } + var normalizedWords []string + for _, w := range words { + if trimmed := strings.TrimSpace(w); trimmed != "" { + normalizedWords = append(normalizedWords, trimmed) + } + } + return &config.CloakConfig{ + Mode: strings.TrimSpace(mode), + StrictMode: strictMode, + SensitiveWords: normalizedWords, + SensitiveWordsReplace: config.NormalizeSensitiveWordsReplace(replacements), + SensitivePatternsReplace: patterns, + CacheUserID: cacheUserID, + } + } + } entry := resolveClaudeKeyConfig(cfg, auth) if entry == nil { return nil diff --git a/internal/runtime/executor/claude_thinking_replay_test.go b/internal/runtime/executor/claude_thinking_replay_test.go index 9968b8e22a4..546a1a3a0cb 100644 --- a/internal/runtime/executor/claude_thinking_replay_test.go +++ b/internal/runtime/executor/claude_thinking_replay_test.go @@ -33,17 +33,17 @@ func claudeReplayTestAuth(baseURL string) *cliproxyauth.Auth { func claudeReplayTestRequest(payload []byte, sessionID string, isCompat bool, source sdktranslator.Format) (cliproxyexecutor.Request, cliproxyexecutor.Options) { return cliproxyexecutor.Request{ - Model: "claude-synthetic-4772", - Payload: payload, - Metadata: map[string]any{ - claudeReplayResolvedModelInfoKey: ®istry.ModelInfo{IsCompat: isCompat}, - }, - }, cliproxyexecutor.Options{ - SourceFormat: source, - Metadata: map[string]any{ - cliproxyexecutor.ExecutionSessionMetadataKey: sessionID, - }, - } + Model: "claude-synthetic-4772", + Payload: payload, + Metadata: map[string]any{ + claudeReplayResolvedModelInfoKey: ®istry.ModelInfo{IsCompat: isCompat}, + }, + }, cliproxyexecutor.Options{ + SourceFormat: source, + Metadata: map[string]any{ + cliproxyexecutor.ExecutionSessionMetadataKey: sessionID, + }, + } } func TestClaudeThinkingReplayEnabledRequiresCompatClaudeAPIKey(t *testing.T) { diff --git a/internal/runtime/executor/claude_user_agent_extensions_test.go b/internal/runtime/executor/claude_user_agent_extensions_test.go new file mode 100644 index 00000000000..f5e25404862 --- /dev/null +++ b/internal/runtime/executor/claude_user_agent_extensions_test.go @@ -0,0 +1,140 @@ +package executor + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestClaudeExecutorUserAgentFieldsPreserveNativePayload(t *testing.T) { + for _, testCase := range []struct { + name string + stabilize bool + }{ + {name: "default"}, + {name: "stabilized", stabilize: true}, + } { + t.Run(testCase.name, func(t *testing.T) { + testClaudeExecutorUserAgentFields(t, testCase.stabilize) + }) + } +} + +func testClaudeExecutorUserAgentFields(t *testing.T, stabilize bool) { + t.Helper() + for _, path := range []string{"messages", "stream", "count_tokens"} { + t.Run(path, func(t *testing.T) { + doc := ojson.NewDoc([]byte(`{"model":"claude-sonnet-4-6","system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.312; cc_entrypoint=cli; cch=00000;"},{"type":"text","text":"Stable caller instructions","cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"Check the task","cache_control":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{}}}]}`)) + if path != "count_tokens" { + if errSet := doc.Set("metadata.user_id", claudeNativeHelperUserID); errSet != nil { + t.Fatal(errSet) + } + } else if errDelete := doc.Delete("system"); errDelete != nil { + t.Fatal(errDelete) + } + payload := doc.Bytes() + var nativeSystem string + for _, testCase := range []struct { + userAgent, stabilizedUserAgent, xApp string + }{ + {userAgent: "claude-cli/2.1.353 (external, cli)", stabilizedUserAgent: "claude-cli/2.1.353 (external, cli)", xApp: "cli"}, + {userAgent: "claude-cli/2.1.353 (external, cli)", stabilizedUserAgent: "claude-cli/2.1.353 (external, cli)", xApp: "cli-bg"}, + {userAgent: "claude-cli/2.1.353 (external, cli, workload/cron)", stabilizedUserAgent: "claude-cli/2.1.353 (external, cli, workload/cron)", xApp: "cli"}, + {userAgent: "claude-cli/2.1.353 (external, cli, future-feature/value, agent-sdk/0.2.133)", stabilizedUserAgent: "claude-cli/2.1.353 (external, cli, agent-sdk/0.2.133, future-feature/value)", xApp: "cli"}, + {userAgent: "claude-cli/2.1.353 (external, cli, request-phase/background, agent-sdk/0.2.133, workload/cron)", stabilizedUserAgent: "claude-cli/2.1.353 (external, cli, agent-sdk/0.2.133, request-phase/background, workload/cron)", xApp: "cli"}, + } { + t.Run(testCase.userAgent+"/"+testCase.xApp, func(t *testing.T) { + var upstreamBody []byte + var upstreamHeaders http.Header + transport := roundTripperFunc(func(request *http.Request) (*http.Response, error) { + body, errRead := io.ReadAll(request.Body) + if errRead != nil { + return nil, errRead + } + upstreamBody, upstreamHeaders = body, request.Header.Clone() + contentType := "application/json" + responseBody := `{"id":"msg_ua_fields","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":1,"output_tokens":1}}` + if path == "count_tokens" { + responseBody = `{"input_tokens":1}` + } else if path == "stream" { + contentType = "text/event-stream" + responseBody = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_ua_fields\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4-6\",\"content\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {contentType}}, Body: io.NopCloser(strings.NewReader(responseBody)), Request: request}, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + headers := http.Header{} + headers.Set("User-Agent", testCase.userAgent) + headers.Set("X-App", testCase.xApp) + headers.Set("Anthropic-Beta", "claude-code-20250219,oauth-2025-04-20,extended-cache-ttl-2025-04-11") + auth := &cliproxyauth.Auth{ID: "ua-fields-" + t.Name(), Metadata: claudeOAuthTestMetadata(), Attributes: map[string]string{"api_key": "sk-ant-oat-ua-fields"}} + executor := NewClaudeExecutor(&config.Config{ClaudeHeaderDefaults: config.ClaudeHeaderDefaults{ + UserAgent: "claude-cli/2.1.353 (external, cli)", StabilizeDeviceProfile: &stabilize, + }}) + request := cliproxyexecutor.Request{Model: "claude-sonnet-4-6", Payload: payload} + options := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, OriginalRequest: payload, Headers: headers} + switch path { + case "messages": + if _, errExecute := executor.Execute(ctx, auth, request, options); errExecute != nil { + t.Fatal(errExecute) + } + case "stream": + result, errStream := executor.ExecuteStream(ctx, auth, request, options) + if errStream != nil { + t.Fatal(errStream) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + case "count_tokens": + if _, errCount := executor.CountTokens(ctx, auth, request, options); errCount != nil { + t.Fatal(errCount) + } + } + if upstreamBody == nil { + t.Fatal("upstream was not called") + } + for _, field := range []string{"messages", "tools"} { + if got, want := ojson.GetBytes(upstreamBody, field).Raw, ojson.GetBytes(payload, field).Raw; got != want { + t.Fatalf("native %s changed\n got: %s\nwant: %s", field, got, want) + } + } + // Signing may update billing, but both UAs must produce the same prefix. + system := ojson.GetBytes(upstreamBody, "system") + if path == "count_tokens" { + if system.Exists() { + t.Fatalf("native count_tokens gained a system prompt: %s", system.Raw) + } + } else if len(system.Array()) != 2 || system.Get("1").Raw != ojson.GetBytes(payload, "system.1").Raw { + t.Fatalf("native system blocks were rebuilt: %s", system.Raw) + } + if nativeSystem == "" { + nativeSystem = system.Raw + } else if system.Raw != nativeSystem { + t.Fatalf("extended UA changed the native prefix\n got: %s\nwant: %s", system.Raw, nativeSystem) + } + wantUserAgent := testCase.userAgent + if stabilize { + wantUserAgent = testCase.stabilizedUserAgent + } + if got := upstreamHeaders.Get("User-Agent"); got != wantUserAgent { + t.Fatalf("upstream UA = %q, want %q", got, wantUserAgent) + } + if got := claudeFingerprintHeaderValue(upstreamHeaders, "X-App"); got != testCase.xApp { + t.Fatalf("upstream X-App = %q, want %q", got, testCase.xApp) + } + }) + } + }) + } +} diff --git a/internal/runtime/executor/codex_executor_auth.go b/internal/runtime/executor/codex_executor_auth.go index c508e8597a3..fdaccd3d078 100644 --- a/internal/runtime/executor/codex_executor_auth.go +++ b/internal/runtime/executor/codex_executor_auth.go @@ -297,6 +297,10 @@ func (e *CodexExecutor) refreshLocked(ctx context.Context, auth *cliproxyauth.Au needSIWC = hasSIWC } } + // Explicit refresh requests must also respect the server's renewal window. + if earliest, okEarliest := auth.SIWCEarliestRefreshTime(); okEarliest && now.Before(earliest) { + needSIWC = false + } suppressedRejectedOuter := false if !diskRotatedOuter && auth.RejectedRefreshToken != "" && outerRefreshToken == strings.TrimSpace(auth.RejectedRefreshToken) { if needOuter { @@ -447,6 +451,7 @@ func (e *CodexExecutor) refreshLocked(ctx context.Context, auth *cliproxyauth.Au mergedSIWC = make(map[string]any) } delete(mergedSIWC, "expires_at") + delete(mergedSIWC, "earliest_refresh_at") for k, v := range siwcTD.ToMap() { mergedSIWC[k] = v } @@ -511,6 +516,9 @@ func (e *CodexExecutor) refreshLocked(ctx context.Context, auth *cliproxyauth.Au } auth.Metadata = mergedDisk } + if siwcRefreshed { + log.Debug("SIWC token renewal completed") + } return auth, nil } diff --git a/internal/runtime/executor/codex_executor_auth_test.go b/internal/runtime/executor/codex_executor_auth_test.go index cb182c6c7da..aebb4d25d21 100644 --- a/internal/runtime/executor/codex_executor_auth_test.go +++ b/internal/runtime/executor/codex_executor_auth_test.go @@ -1,6 +1,7 @@ package executor import ( + "bytes" "context" "crypto/tls" "encoding/json" @@ -12,6 +13,7 @@ import ( "os" "path/filepath" "strings" + "sync" "testing" "time" @@ -58,29 +60,34 @@ func startCodexMockOAuthServers(t *testing.T, idToken string) (proxyURL string, mockProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodConnect { - destConn, errDial := net.Dial("tcp", mockAuthServer.Listener.Addr().String()) - if errDial != nil { - http.Error(w, errDial.Error(), http.StatusServiceUnavailable) - return - } - w.WriteHeader(http.StatusOK) hijacker, ok := w.(http.Hijacker) if !ok { - _ = destConn.Close() http.Error(w, "Hijacking not supported", http.StatusInternalServerError) return } - clientConn, clientBuffer, errHijack := hijacker.Hijack() + clientConn, clientBuf, errHijack := hijacker.Hijack() if errHijack != nil { + return + } + destConn, errDial := net.Dial("tcp", mockAuthServer.Listener.Addr().String()) + if errDial != nil { + _, _ = clientConn.Write([]byte("HTTP/1.1 503 Service Unavailable\r\n\r\n")) + _ = clientConn.Close() + return + } + if _, errWrite := clientConn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")); errWrite != nil { _ = destConn.Close() + _ = clientConn.Close() return } + var clientReader io.Reader = clientConn + if clientBuf != nil && clientBuf.Reader != nil { + clientReader = clientBuf.Reader + } go func() { defer func() { _ = destConn.Close() }() defer func() { _ = clientConn.Close() }() - // Hijack may retain the start of the TLS handshake after CONNECT. - // Forward those buffered bytes before reading from the socket. - _, _ = io.Copy(destConn, clientBuffer) + _, _ = io.Copy(destConn, clientReader) }() go func() { defer func() { _ = destConn.Close() }() @@ -112,7 +119,7 @@ func TestCodexExecutorRefresh_MissingPlanTypeDefaultsToFree(t *testing.T) { proxyURL, teardown := startCodexMockOAuthServers(t, idTokenWithoutPlan) defer teardown() - cfg := &config.Config{} + cfg := &config.Config{AuthDir: t.TempDir()} executor := NewCodexExecutor(cfg) storage := &codexauth.CodexTokenStorage{ @@ -188,7 +195,7 @@ func TestCodexExecutorRefresh_ExtractsPlanTypeWhenPresent(t *testing.T) { proxyURL, teardown := startCodexMockOAuthServers(t, idTokenWithPlan) defer teardown() - cfg := &config.Config{} + cfg := &config.Config{AuthDir: t.TempDir()} executor := NewCodexExecutor(cfg) storage := &codexauth.CodexTokenStorage{ @@ -264,7 +271,7 @@ func TestCodexExecutorRefresh_EmptyAttributesSnapshotIsolation(t *testing.T) { proxyURL, teardown := startCodexMockOAuthServers(t, idTokenWithoutPlan) defer teardown() - cfg := &config.Config{} + cfg := &config.Config{AuthDir: t.TempDir()} executor := NewCodexExecutor(cfg) emptyAttrs := map[string]string{} @@ -281,7 +288,7 @@ func TestCodexExecutorRefresh_EmptyAttributesSnapshotIsolation(t *testing.T) { ProxyURL: proxyURL, Attributes: emptyAttrs, Metadata: map[string]any{ - "refresh_token": "valid-refresh-token", + "refresh_token": "valid-refresh-token-empty-attrs", }, } @@ -296,6 +303,9 @@ func TestCodexExecutorRefresh_EmptyAttributesSnapshotIsolation(t *testing.T) { if got := refreshed.Attributes["plan_type"]; got != "free" { t.Errorf("refreshed.Attributes[plan_type] = %q, want free", got) } + if got := refreshed.Metadata["account_id"]; got != "acc-codex-empty-attrs" { + t.Errorf("refreshed.Metadata[account_id] = %v, want acc-codex-empty-attrs", got) + } // Verify original empty map was not modified if _, exists := emptyAttrs["plan_type"]; exists { t.Errorf("original empty Attributes map was modified, plan_type = %q", emptyAttrs["plan_type"]) @@ -342,28 +352,34 @@ func startDualCodexAndSIWCMockOAuthServer(t *testing.T, idToken string, failSIWC mockProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodConnect { - destConn, errDial := net.Dial("tcp", mockAuthServer.Listener.Addr().String()) - if errDial != nil { - http.Error(w, errDial.Error(), http.StatusServiceUnavailable) - return - } - w.WriteHeader(http.StatusOK) hijacker, ok := w.(http.Hijacker) if !ok { - _ = destConn.Close() + http.Error(w, "Hijacking not supported", http.StatusInternalServerError) return } - clientConn, clientBuffer, errHijack := hijacker.Hijack() + clientConn, clientBuf, errHijack := hijacker.Hijack() if errHijack != nil { + return + } + destConn, errDial := net.Dial("tcp", mockAuthServer.Listener.Addr().String()) + if errDial != nil { + _, _ = clientConn.Write([]byte("HTTP/1.1 503 Service Unavailable\r\n\r\n")) + _ = clientConn.Close() + return + } + if _, errWrite := clientConn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")); errWrite != nil { _ = destConn.Close() + _ = clientConn.Close() return } + var clientReader io.Reader = clientConn + if clientBuf != nil && clientBuf.Reader != nil { + clientReader = clientBuf.Reader + } go func() { defer func() { _ = destConn.Close() }() defer func() { _ = clientConn.Close() }() - // Hijack may retain the start of the TLS handshake after CONNECT. - // Forward those buffered bytes before reading from the socket. - _, _ = io.Copy(destConn, clientBuffer) + _, _ = io.Copy(destConn, clientReader) }() go func() { defer func() { _ = destConn.Close() }() @@ -1702,3 +1718,120 @@ func TestCodexExecutorForceRefreshRejectedRefreshTokenWithoutDiskRotation_Issue7 t.Fatal("expected forced Refresh on unchanged rejected refresh_token without disk rotation to return an error, got nil") } } + +type bufferedConnectClientHelloConn struct { + net.Conn + mu sync.Mutex + connectBuf []byte + realRespRead bool + synthResp bytes.Reader +} + +func (c *bufferedConnectClientHelloConn) Write(p []byte) (int, error) { + c.mu.Lock() + if !c.realRespRead && (len(c.connectBuf) == 0 && strings.HasPrefix(string(p), "CONNECT ") || len(c.connectBuf) > 0 && !bytes.HasSuffix(c.connectBuf, []byte("\r\n\r\n"))) { + c.connectBuf = append(c.connectBuf, p...) + if bytes.HasSuffix(c.connectBuf, []byte("\r\n\r\n")) { + c.synthResp.Reset([]byte("HTTP/1.1 200 Connection established\r\n\r\n")) + } + c.mu.Unlock() + return len(p), nil + } + if len(c.connectBuf) > 0 && !c.realRespRead && len(p) > 0 { + c.realRespRead = true + combined := append(append([]byte(nil), c.connectBuf...), p[0]) + c.mu.Unlock() + if _, errWriteFirst := c.Conn.Write(combined); errWriteFirst != nil { + return 0, errWriteFirst + } + var window [4]byte + for { + copy(window[:3], window[1:4]) + if _, errRead := io.ReadFull(c.Conn, window[3:4]); errRead != nil { + return 1, errRead + } + if string(window[:]) == "\r\n\r\n" { + break + } + } + if len(p) == 1 { + return 1, nil + } + n, errWriteRest := c.Conn.Write(p[1:]) + return n + 1, errWriteRest + } + c.mu.Unlock() + return c.Conn.Write(p) +} + +func (c *bufferedConnectClientHelloConn) Read(p []byte) (int, error) { + c.mu.Lock() + if c.synthResp.Len() > 0 { + n, errRead := c.synthResp.Read(p) + c.mu.Unlock() + return n, errRead + } + c.mu.Unlock() + return c.Conn.Read(p) +} + +func TestCodexMockOAuthProxyPreservesBufferedClientHello(t *testing.T) { + idToken := makeTestCodexRefreshJWT("plus", "acc-buffered-hello") + installBufferedDial := func(t *testing.T) { + t.Helper() + baseTransport, ok := http.DefaultTransport.(*http.Transport) + if !ok || baseTransport == nil { + t.Fatal("expected *http.Transport as DefaultTransport") + } + baseTransport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + rawConn, errDial := (&net.Dialer{}).DialContext(ctx, network, addr) + if errDial != nil { + return nil, errDial + } + return &bufferedConnectClientHelloConn{Conn: rawConn}, nil + } + } + + t.Run("single", func(t *testing.T) { + proxyURL, teardown := startCodexMockOAuthServers(t, idToken) + defer teardown() + installBufferedDial(t) + + executor := NewCodexExecutor(&config.Config{AuthDir: t.TempDir()}) + auth := &cliproxyauth.Auth{ + ID: "codex-buffered-hello-single", + Provider: "codex", + ProxyURL: proxyURL, + Metadata: map[string]any{ + "type": "codex", + "access_token": "old-access", + "refresh_token": "valid-refresh-buffered-hello-single", + }, + } + if _, errRefresh := executor.Refresh(context.Background(), auth); errRefresh != nil { + t.Fatalf("executor.Refresh error = %v", errRefresh) + } + }) + + t.Run("dual", func(t *testing.T) { + failSIWC := false + proxyURL, _, _, teardown := startDualCodexAndSIWCMockOAuthServer(t, idToken, &failSIWC) + defer teardown() + installBufferedDial(t) + + executor := NewCodexExecutor(&config.Config{AuthDir: t.TempDir()}) + auth := &cliproxyauth.Auth{ + ID: "codex-buffered-hello-dual", + Provider: "codex", + ProxyURL: proxyURL, + Metadata: map[string]any{ + "type": "codex", + "access_token": "old-access", + "refresh_token": "valid-refresh-buffered-hello-dual", + }, + } + if _, errRefresh := executor.Refresh(context.Background(), auth); errRefresh != nil { + t.Fatalf("executor.Refresh error = %v", errRefresh) + } + }) +} diff --git a/internal/runtime/executor/codex_executor_compact_test.go b/internal/runtime/executor/codex_executor_compact_test.go index abdadae93be..04ff7b09db0 100644 --- a/internal/runtime/executor/codex_executor_compact_test.go +++ b/internal/runtime/executor/codex_executor_compact_test.go @@ -3,6 +3,7 @@ package executor import ( "bytes" "context" + "fmt" "io" "net/http" "net/http/httptest" @@ -13,9 +14,11 @@ import ( "github.com/MoeForge/moego/ojson" "github.com/gorilla/websocket" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) @@ -814,3 +817,1078 @@ func TestCodexExecutorExpandsRecognizedCPACompactionCapsules_Issue7118(t *testin } }) } + +func TestCodexExecutor_IsCompatResponsesCompactionTriggerAndReplay_Issue7406(t *testing.T) { + const marker = "COBALT-7406" + var seenPaths []string + var seenBodies [][]byte + var returnIncomplete bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read upstream body: %v", errRead) + http.Error(w, "read error", http.StatusBadRequest) + return + } + seenPaths = append(seenPaths, r.URL.Path) + seenBodies = append(seenBodies, body) + + w.Header().Set("Content-Type", "text/event-stream") + if returnIncomplete { + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_inc\",\"type\":\"message\",\"status\":\"incomplete\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Partial truncated summary.\"}]}}\n\n"+ + "data: {\"type\":\"response.incomplete\",\"response\":{\"id\":\"resp_inc\",\"object\":\"response\",\"status\":\"incomplete\",\"incomplete_details\":{\"reason\":\"max_output_tokens\"},\"output\":[{\"id\":\"msg_inc\",\"type\":\"message\",\"status\":\"incomplete\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Partial truncated summary.\"}]}],\"usage\":{\"input_tokens\":12,\"output_tokens\":6,\"total_tokens\":18}}}\n\n", + ) + return + } + + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"rs_sum\",\"type\":\"reasoning\",\"status\":\"completed\",\"summary\":[{\"type\":\"summary_text\",\"text\":\"Summarizing session context.\"}]}}\n\n"+ + "data: {\"type\":\"response.output_item.done\",\"output_index\":1,\"item\":{\"id\":\"msg_sum\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Summary retaining "+marker+".\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_sum\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":14,\"output_tokens\":8,\"total_tokens\":22,\"input_tokens_details\":{\"cached_tokens\":5},\"output_tokens_details\":{\"reasoning_tokens\":3}}}}\n\n", + ) + })) + defer server.Close() + + cfg := &config.Config{ + CodexKey: []config.CodexKey{ + { + APIKey: "test-compat-key", + BaseURL: server.URL + "/v1", + Models: []config.CodexModel{ + {Name: "deepseek-v4.1-flash", IsCompat: true}, + {Name: "gpt-5.4", IsCompat: false}, + }, + }, + }, + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "deepseek-v4.1-flash", Protocol: "codex"}}, + Params: map[string]any{ + "max_output_tokens": 2048, + }, + }, + }, + }, + } + + executor := NewCodexExecutor(cfg) + wsExecutor := NewCodexWebsocketsExecutor(cfg) + auth := &cliproxyauth.Auth{ + Provider: "codex", + Attributes: map[string]string{ + "base_url": server.URL + "/v1", + "api_key": "test-compat-key", + }, + } + + triggerPayload := []byte(`{ + "model": "deepseek-v4.1-flash", + "stream": true, + "input": [ + { + "type": "additional_tools", + "tools": [ + { + "type": "function", + "name": "exec_command", + "description": "Execute a shell command", + "parameters": {"type": "object", "properties": {"cmd": {"type": "string"}}} + } + ] + }, + { + "id": "ws_hist_1", + "type": "web_search_call", + "status": "completed", + "action": {"type": "search", "query": "deepseek responses"} + }, + { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "Remember project marker ` + marker + `."}] + }, + {"type": "compaction_trigger"} + ] + }`) + + assertSummaryRequest := func(t *testing.T, path string, body []byte, label string) { + t.Helper() + if path != "/v1/responses" { + t.Fatalf("%s upstream path = %q, want /v1/responses", label, path) + } + if bytes.Contains(body, []byte("compaction_trigger")) { + t.Fatalf("%s summary request leaked compaction_trigger: %s", label, body) + } + if ojson.GetBytes(body, "tools").Exists() { + t.Fatalf("%s summary request unexpectedly carried tools (including image_generation or web_search): %s", label, body) + } + if gotMax := ojson.GetBytes(body, "max_output_tokens").Int(); gotMax != 2048 { + t.Fatalf("%s max_output_tokens = %d, want 2048 from payload override; body=%s", label, gotMax, body) + } + } + + // 1. Streaming ExecuteStream(compaction_trigger) on is-compat codex endpoint. + streamResult, errStream := executor.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: triggerPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + OriginalRequest: triggerPayload, + }) + if errStream != nil { + t.Fatalf("ExecuteStream(compaction_trigger) error = %v", errStream) + } + var streamBuf bytes.Buffer + for chunk := range streamResult.Chunks { + if chunk.Err != nil { + t.Fatalf("stream chunk error = %v", chunk.Err) + } + streamBuf.Write(chunk.Payload) + } + completed := claudeCompactionCompletedResponse(t, streamBuf.String()) + outputItems := completed.Get("response.output").Array() + if len(outputItems) != 1 || outputItems[0].Get("type").String() != "compaction" { + t.Fatalf("expected single compaction item in stream response, got: %s", completed.Raw) + } + capsule := outputItems[0].Get("encrypted_content").String() + if !strings.HasPrefix(capsule, "cpa-ag-compact-v1:") { + t.Fatalf("expected CPA compaction capsule prefix, got %q", capsule) + } + if gotCached := completed.Get("response.usage.input_tokens_details.cached_tokens").Int(); gotCached != 5 { + t.Fatalf("cached_tokens = %d, want 5", gotCached) + } + if gotReasoning := completed.Get("response.usage.output_tokens_details.reasoning_tokens").Int(); gotReasoning != 3 { + t.Fatalf("reasoning_tokens = %d, want 3", gotReasoning) + } + assertSummaryRequest(t, seenPaths[0], seenBodies[0], "ExecuteStream") + + // 2. Non-streaming Execute(compaction_trigger) on is-compat codex endpoint. + nonStreamResp, errExec := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: triggerPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: triggerPayload, + }) + if errExec != nil { + t.Fatalf("Execute(compaction_trigger) error = %v", errExec) + } + if gotObj := ojson.GetBytes(nonStreamResp.Payload, "object").String(); gotObj != "response.compaction" { + t.Fatalf("Execute object = %q, want response.compaction; payload=%s", gotObj, nonStreamResp.Payload) + } + nonStreamItems := ojson.GetBytes(nonStreamResp.Payload, "output").Array() + if len(nonStreamItems) != 1 || nonStreamItems[0].Get("type").String() != "compaction" { + t.Fatalf("expected single compaction item in non-stream response, got: %s", nonStreamResp.Payload) + } + assertSummaryRequest(t, seenPaths[1], seenBodies[1], "Execute") + + // 3. WebSocket executor delegation for compaction_trigger on is-compat codex endpoint. + wsResp, errWSExec := wsExecutor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: triggerPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: triggerPayload, + }) + if errWSExec != nil { + t.Fatalf("wsExecutor.Execute(compaction_trigger) error = %v", errWSExec) + } + if gotObj := ojson.GetBytes(wsResp.Payload, "object").String(); gotObj != "response.compaction" { + t.Fatalf("wsExecutor.Execute object = %q, want response.compaction", gotObj) + } + wsStreamRes, errWSStream := wsExecutor.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: triggerPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + OriginalRequest: triggerPayload, + }) + if errWSStream != nil { + t.Fatalf("wsExecutor.ExecuteStream(compaction_trigger) error = %v", errWSStream) + } + var wsStreamBuf bytes.Buffer + for chunk := range wsStreamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("ws stream chunk error = %v", chunk.Err) + } + wsStreamBuf.Write(chunk.Payload) + } + wsCompleted := claudeCompactionCompletedResponse(t, wsStreamBuf.String()) + if wsItems := wsCompleted.Get("response.output").Array(); len(wsItems) != 1 || wsItems[0].Get("type").String() != "compaction" { + t.Fatalf("expected single compaction item in ws stream response, got: %s", wsCompleted.Raw) + } + + // 4. Subsequent replay on is-compat expands CPA capsule and drops foreign compaction items. + replayPayload := []byte(fmt.Sprintf(`{ + "model": "deepseek-v4.1-flash", + "stream": true, + "input": [ + {"id": "cmp_foreign", "type": "compaction", "encrypted_content": "gAAAAABforeign-openai-compaction"}, + {"id": %q, "type": "compaction", "encrypted_content": %q}, + {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "What is the project marker?"}]} + ] + }`, outputItems[0].Get("id").String(), capsule)) + + contStream, errCont := executor.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: replayPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + OriginalRequest: replayPayload, + }) + if errCont != nil { + t.Fatalf("ExecuteStream(replay) error = %v", errCont) + } + for chunk := range contStream.Chunks { + if chunk.Err != nil { + t.Fatalf("replay stream chunk error = %v", chunk.Err) + } + } + replaySeen := seenBodies[len(seenBodies)-1] + if bytes.Contains(replaySeen, []byte("cpa-ag-compact-v1:")) || bytes.Contains(replaySeen, []byte("gAAAAABforeign-openai-compaction")) { + t.Fatalf("expected both CPA capsule and foreign compaction item to be removed from is-compat upstream payload: %s", replaySeen) + } + if !bytes.Contains(replaySeen, []byte(marker)) { + t.Fatalf("expected expanded summary marker %q in replay upstream payload: %s", marker, replaySeen) + } + + // CountTokens on is-compat also drops foreign compaction items and expands CPA capsule cleanly. + if _, errTokens := executor.CountTokens(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: replayPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: replayPayload, + }); errTokens != nil { + t.Fatalf("CountTokens(replay) error = %v", errTokens) + } + + // 5. Chained second compaction_trigger expands prior CPA capsule before summarizing. + secondTriggerPayload := []byte(fmt.Sprintf(`{ + "model": "deepseek-v4.1-flash", + "input": [ + {"id": %q, "type": "compaction", "encrypted_content": %q}, + {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "And remember SILVER-99."}]}, + {"type": "compaction_trigger"} + ] + }`, outputItems[0].Get("id").String(), capsule)) + + secondResp, errSecond := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: secondTriggerPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: secondTriggerPayload, + }) + if errSecond != nil { + t.Fatalf("Execute(second compaction_trigger) error = %v", errSecond) + } + if gotObj := ojson.GetBytes(secondResp.Payload, "object").String(); gotObj != "response.compaction" { + t.Fatalf("second compaction object = %q, want response.compaction", gotObj) + } + secondSeen := seenBodies[len(seenBodies)-1] + if bytes.Contains(secondSeen, []byte("compaction_trigger")) || bytes.Contains(secondSeen, []byte("cpa-ag-compact-v1:")) { + t.Fatalf("second summary request leaked compaction_trigger or unexpanded capsule: %s", secondSeen) + } + if !bytes.Contains(secondSeen, []byte(marker)) { + t.Fatalf("expected prior summary marker %q in second summary request: %s", marker, secondSeen) + } + + // 6. Incomplete summary must fail closed rather than sealing a truncated capsule. + returnIncomplete = true + if _, errIncExec := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: triggerPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: triggerPayload, + }); errIncExec == nil { + t.Fatal("expected Execute(compaction_trigger) to fail on incomplete summary, got nil") + } + if _, errIncStream := executor.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: triggerPayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + OriginalRequest: triggerPayload, + }); errIncStream == nil { + t.Fatal("expected ExecuteStream(compaction_trigger) to fail on incomplete summary, got nil") + } + returnIncomplete = false + + // 7. Native (is-compat: false) Codex model forwards compaction_trigger untouched without local summary interception. + nativePayload := []byte(`{"model":"gpt-5.4","input":[{"type":"message","role":"user","content":"history"},{"type":"compaction_trigger"}]}`) + nativeResp, errNative := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gpt-5.4", + Payload: nativePayload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: nativePayload, + }) + if errNative != nil { + t.Fatalf("Execute(native gpt-5.4) error = %v", errNative) + } + nativeSeen := seenBodies[len(seenBodies)-1] + if !bytes.Contains(nativeSeen, []byte("compaction_trigger")) { + t.Fatalf("expected native is-compat=false model to forward compaction_trigger untouched, got: %s", nativeSeen) + } + if gotObj := ojson.GetBytes(nativeResp.Payload, "object").String(); gotObj != "response" { + t.Fatalf("native response object = %q, want response", gotObj) + } +} + +func TestCodexExecutor_IsCompatCompactionValidationAndUsage_Issue7406(t *testing.T) { + var upstreamHits int + var mode string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamHits++ + _, _ = io.ReadAll(r.Body) + switch mode { + case "http500": + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusInternalServerError) + _, _ = io.WriteString(w, `{"error":{"message":"upstream boom"}}`) + case "incomplete": + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_1\",\"type\":\"message\",\"status\":\"incomplete\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"partial\"}]}}\n\n"+ + "data: {\"type\":\"response.incomplete\",\"response\":{\"id\":\"resp_inc\",\"object\":\"response\",\"status\":\"incomplete\",\"incomplete_details\":{\"reason\":\"max_output_tokens\"},\"output\":[],\"usage\":{\"input_tokens\":20,\"output_tokens\":10,\"total_tokens\":30,\"input_tokens_details\":{\"cached_tokens\":6},\"output_tokens_details\":{\"reasoning_tokens\":4}}}}\n\n", + ) + case "empty_summary": + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"rs_only\",\"type\":\"reasoning\",\"status\":\"completed\",\"summary\":[{\"type\":\"summary_text\",\"text\":\"only thinking\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_empty\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":20,\"output_tokens\":10,\"total_tokens\":30,\"input_tokens_details\":{\"cached_tokens\":6},\"output_tokens_details\":{\"reasoning_tokens\":4}}}}\n\n", + ) + case "empty_incomplete": + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.incomplete\",\"response\":{\"id\":\"resp_empty_inc\",\"object\":\"response\",\"status\":\"incomplete\",\"output\":[],\"usage\":{\"input_tokens\":20,\"output_tokens\":10,\"total_tokens\":30,\"input_tokens_details\":{\"cached_tokens\":6},\"output_tokens_details\":{\"reasoning_tokens\":4}}}}\n\n", + ) + case "response_failed": + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.failed\",\"response\":{\"id\":\"resp_fail\",\"object\":\"response\",\"status\":\"failed\",\"error\":{\"code\":\"server_error\",\"message\":\"upstream failed mid-summary\"},\"output\":[],\"usage\":{\"input_tokens\":20,\"output_tokens\":10,\"total_tokens\":30,\"input_tokens_details\":{\"cached_tokens\":6},\"output_tokens_details\":{\"reasoning_tokens\":4}}}}\n\n", + ) + default: + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_ok\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Summary text ok.\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ok\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":20,\"output_tokens\":10,\"total_tokens\":30,\"input_tokens_details\":{\"cached_tokens\":6},\"output_tokens_details\":{\"reasoning_tokens\":4}}}}\n\n", + ) + } + })) + defer server.Close() + + cfg := &config.Config{ + CodexKey: []config.CodexKey{{ + APIKey: "test-compat-key", + BaseURL: server.URL, + Models: []config.CodexModel{{Name: "deepseek-v4.1-flash", IsCompat: true}}, + }}, + } + executor := NewCodexExecutor(cfg) + wsExecutor := NewCodexWebsocketsExecutor(cfg) + auth := &cliproxyauth.Auth{ + Provider: "codex", + Attributes: map[string]string{"base_url": server.URL, "api_key": "test-compat-key"}, + } + + // 1. Incremental previous_response_id + compaction_trigger must fail closed without hitting upstream. + incTrigger := []byte(`{"model":"deepseek-v4.1-flash","event_id":"ev_inc","previous_response_id":"resp_real_1","input":[{"type":"compaction_trigger"}]}`) + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, ResponseFormat: sdktranslator.FormatOpenAIResponse, OriginalRequest: incTrigger} + if _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{Model: "deepseek-v4.1-flash", Payload: incTrigger}, opts); err == nil { + t.Fatal("expected HTTP Execute with previous_response_id + compaction_trigger to fail") + } + wsCtx := cliproxyexecutor.WithDownstreamWebsocket(context.Background()) + _, errWSInc := wsExecutor.ExecuteStream(wsCtx, auth, cliproxyexecutor.Request{Model: "deepseek-v4.1-flash", Payload: incTrigger}, opts) + if !cliproxyexecutor.IsUpstreamWebsocketTurnError(errWSInc) { + t.Fatalf("expected UpstreamWebsocketTurnError on websocket incremental trigger, got %v", errWSInc) + } + + // 2. Empty conversation input (only compaction_trigger + additional_tools) must fail closed. + emptyTrigger := []byte(`{"model":"deepseek-v4.1-flash","input":[{"type":"additional_tools","tools":[]},{"type":"compaction_trigger"}]}`) + if _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{Model: "deepseek-v4.1-flash", Payload: emptyTrigger}, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, OriginalRequest: emptyTrigger}); err == nil { + t.Fatal("expected empty-history compaction_trigger to fail") + } + + // 3. Synthetic resp_ag_compact_* previous_response_id on normal turn must never reach upstream. + synthCont := []byte(`{"model":"deepseek-v4.1-flash","previous_response_id":"resp_ag_compact_12345","input":[{"type":"message","role":"user","content":"hi"}]}`) + if _, err := executor.Execute(context.Background(), auth, cliproxyexecutor.Request{Model: "deepseek-v4.1-flash", Payload: synthCont}, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, OriginalRequest: synthCont}); err == nil { + t.Fatal("expected synthetic previous_response_id on HTTP Execute to fail") + } + if _, err := wsExecutor.ExecuteStream(wsCtx, auth, cliproxyexecutor.Request{Model: "deepseek-v4.1-flash", Payload: synthCont}, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, OriginalRequest: synthCont}); !cliproxyexecutor.IsUpstreamWebsocketTurnError(err) { + t.Fatalf("expected UpstreamWebsocketTurnError for synthetic previous_response_id on WS, got %v", err) + } + if upstreamHits != 0 { + t.Fatalf("upstreamHits = %d, want 0 for rejected validation cases", upstreamHits) + } + + // 4. CountTokens semantic consistency: foreign compaction dropped + CPA capsule expanded matches expanded developer message. + capsule, errSeal := helps.SealAntigravityCompaction("Token count summary", "deepseek-v4.1-flash") + if errSeal != nil { + t.Fatalf("SealAntigravityCompaction: %v", errSeal) + } + mixedTokensPayload := []byte(fmt.Sprintf(`{"model":"deepseek-v4.1-flash","input":[{"id":"cmp_foreign","type":"compaction","encrypted_content":"gAAAAABforeign"},{"id":"cmp_ag_compact_1","type":"compaction","encrypted_content":%q},{"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]}]}`, capsule)) + expectedExpandedPayload := []byte(`{"model":"deepseek-v4.1-flash","input":[{"type":"message","role":"developer","content":[{"type":"input_text","text":"Context summary from previous turns:\nToken count summary"}]},{"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]}]}`) + gotCountResp, errGotCount := executor.CountTokens(context.Background(), auth, cliproxyexecutor.Request{Model: "deepseek-v4.1-flash", Payload: mixedTokensPayload}, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse}) + if errGotCount != nil { + t.Fatalf("CountTokens(mixed): %v", errGotCount) + } + wantCountResp, errWantCount := executor.CountTokens(context.Background(), auth, cliproxyexecutor.Request{Model: "deepseek-v4.1-flash", Payload: expectedExpandedPayload}, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse}) + if errWantCount != nil { + t.Fatalf("CountTokens(expected): %v", errWantCount) + } + if string(gotCountResp.Payload) != string(wantCountResp.Payload) { + t.Fatalf("CountTokens mismatch: got %s, want %s", gotCountResp.Payload, wantCountResp.Payload) + } + + // 5. Usage outcome & token accounting across valid, incomplete, empty_summary, http500, and canceled. + validTrigger := []byte(`{"model":"deepseek-v4.1-flash","input":[{"type":"message","role":"user","content":"history"},{"type":"compaction_trigger"}]}`) + for _, tc := range []struct { + name string + mode string + cancelCtx bool + wantErr bool + wantTokens int64 + }{ + {name: "valid", mode: "ok", wantErr: false, wantTokens: 30}, + {name: "incomplete", mode: "incomplete", wantErr: true, wantTokens: 30}, + {name: "empty_summary", mode: "empty_summary", wantErr: true, wantTokens: 30}, + {name: "empty_incomplete_with_usage", mode: "empty_incomplete", wantErr: true, wantTokens: 30}, + {name: "response_failed_with_usage", mode: "response_failed", wantErr: true, wantTokens: 30}, + {name: "http500", mode: "http500", wantErr: true, wantTokens: 0}, + {name: "canceled", mode: "ok", cancelCtx: true, wantErr: true, wantTokens: 0}, + } { + t.Run("usage_"+tc.name, func(t *testing.T) { + mode = tc.mode + alias := t.Name() + capture := &codexResponseModelUsageCapture{alias: alias, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), codexResponseModelNoopUsagePlugin{}) + }) + callCtx := coreusage.WithRequestedModelAlias(context.Background(), alias) + if tc.cancelCtx { + var cancel context.CancelFunc + callCtx, cancel = context.WithCancel(callCtx) + cancel() + } + _, errExec := executor.Execute(callCtx, auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: validTrigger, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: validTrigger, + }) + if (errExec != nil) != tc.wantErr { + t.Fatalf("Execute err = %v, wantErr = %t", errExec, tc.wantErr) + } + rec := capture.await(t) + if rec.Failed != tc.wantErr { + t.Fatalf("usage record Failed = %t, want %t (fail=%+v)", rec.Failed, tc.wantErr, rec.Fail) + } + if rec.Detail.TotalTokens != tc.wantTokens { + t.Fatalf("usage record TotalTokens = %d, want %d (detail=%+v)", rec.Detail.TotalTokens, tc.wantTokens, rec.Detail) + } + if tc.wantTokens > 0 && (rec.Detail.InputTokens != 20 || rec.Detail.OutputTokens != 10 || rec.Detail.ReasoningTokens != 4 || rec.Detail.CachedTokens != 6) { + t.Fatalf("unexpected token breakdown: %+v", rec.Detail) + } + select { + case extra := <-capture.records: + t.Fatalf("unexpected duplicate usage record emitted: %+v", extra) + default: + } + }) + } +} + +func TestCodexExecutor_IsCompatCompactionMatrix_Issue7406(t *testing.T) { + var lastBody []byte + var lastAuthHeader string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + lastAuthHeader = r.Header.Get("Authorization") + lastBody, _ = io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_m\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Matrix summary.\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_m\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":8,\"output_tokens\":4,\"total_tokens\":12}}}\n\n", + ) + })) + defer server.Close() + + cfg := &config.Config{ + CodexKey: []config.CodexKey{{ + APIKey: "outer-key", + BaseURL: server.URL, + Models: []config.CodexModel{{ + Name: "deepseek-v4.1-flash", + IsCompat: true, + Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}}, + }}, + }}, + Payload: config.PayloadConfig{ + Filter: []config.PayloadFilterRule{{ + Models: []config.PayloadModelRule{{Name: "deepseek-v4.1-flash", Protocol: "codex"}}, + Params: []string{"service_tier"}, + }}, + Override: []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "deepseek-v4.1-flash", Protocol: "codex"}}, + Params: map[string]any{"max_output_tokens": 1536}, + }}, + }, + } + executor := NewCodexExecutor(cfg) + siwcAuth := &cliproxyauth.Auth{ + Provider: "codex", + Attributes: map[string]string{"base_url": server.URL, "api_key": "outer-key", "use_siwc": "true"}, + Metadata: map[string]any{"siwc": map[string]any{"access_token": "siwc-secret-token"}}, + } + + trigger := []byte(`{"model":"deepseek-v4.1-flash(high)","service_tier":"priority","input":[{"type":"message","role":"user","content":"summarize me"},{"type":"compaction_trigger"}]}`) + resp, err := executor.Execute(context.Background(), siwcAuth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash(high)", + Payload: trigger, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: trigger, + }) + if err != nil { + t.Fatalf("Execute(SIWC + suffix + payload rules) error = %v", err) + } + if ojson.GetBytes(resp.Payload, "object").String() != "response.compaction" { + t.Fatalf("expected response.compaction, got: %s", resp.Payload) + } + if lastAuthHeader != "Bearer siwc-secret-token" { + t.Fatalf("Authorization = %q, want Bearer siwc-secret-token", lastAuthHeader) + } + if gotEffort := ojson.GetBytes(lastBody, "reasoning.effort").String(); gotEffort != "high" { + t.Fatalf("reasoning.effort = %q, want high; body=%s", gotEffort, lastBody) + } + if ojson.GetBytes(lastBody, "service_tier").Exists() { + t.Fatalf("service_tier should be filtered by payload filter rule: %s", lastBody) + } + if gotMax := ojson.GetBytes(lastBody, "max_output_tokens").Int(); gotMax != 1536 { + t.Fatalf("max_output_tokens = %d, want 1536; body=%s", gotMax, lastBody) + } + + // Authoritative ResolvedModelInfo{IsCompat: false} overrides local config IsCompat: true. + overrideResp, errOverride := executor.Execute(context.Background(), siwcAuth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: trigger, + Metadata: map[string]any{ + "cliproxy.resolved_api_key_model_info": ®istry.ModelInfo{ID: "deepseek-v4.1-flash", IsCompat: false}, + }, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: trigger, + }) + if errOverride != nil { + t.Fatalf("Execute(authoritative IsCompat=false) error = %v", errOverride) + } + if !bytes.Contains(lastBody, []byte("compaction_trigger")) { + t.Fatalf("expected authoritative IsCompat=false to forward compaction_trigger untouched: %s", lastBody) + } + if ojson.GetBytes(overrideResp.Payload, "object").String() != "response" { + t.Fatalf("expected normal response when authoritative IsCompat=false, got: %s", overrideResp.Payload) + } +} + +func TestCodexExecutor_IsCompatCompactionDuplexSession_Issue7406(t *testing.T) { + const marker = "DUPLEX-COMPACT-7406" + wsFrames := make(chan []byte, 8) + httpBodies := make(chan []byte, 4) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if websocket.IsWebSocketUpgrade(r) { + conn, errUp := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUp != nil { + t.Errorf("upgrade ws: %v", errUp) + return + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close upstream websocket: %v", errClose) + } + }() + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + + // Turn 1: initial WS response.create + _, frame1, errRead1 := conn.ReadMessage() + if errRead1 != nil { + return + } + wsFrames <- frame1 + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.created","response":{"id":"resp_ws_1","output":[]}}`)) + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.completed","response":{"id":"resp_ws_1","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ack-1"}]}],"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}`)) + + // Turn 3 (post-compaction root response.create; Turn 2 ran locally via HTTP!) + _, frame2, errRead2 := conn.ReadMessage() + if errRead2 != nil { + return + } + wsFrames <- frame2 + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.created","response":{"id":"resp_ws_3","output":[]}}`)) + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.completed","response":{"id":"resp_ws_3","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ack-3"}]}],"usage":{"input_tokens":8,"output_tokens":3,"total_tokens":11}}}`)) + + // Turn 4 (incremental continuation referencing resp_ws_3) + _, frame3, errRead3 := conn.ReadMessage() + if errRead3 != nil { + return + } + wsFrames <- frame3 + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.created","response":{"id":"resp_ws_4","previous_response_id":"resp_ws_3","output":[]}}`)) + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.completed","response":{"id":"resp_ws_4","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ack-4"}]}],"usage":{"input_tokens":9,"output_tokens":3,"total_tokens":12}}}`)) + + _, _, _ = conn.ReadMessage() + return + } + + body, _ := io.ReadAll(r.Body) + httpBodies <- body + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_sum\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Duplex summary with "+marker+".\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_http_sum\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":10,\"output_tokens\":5,\"total_tokens\":15}}}\n\n", + ) + })) + defer server.Close() + + cfg := &config.Config{ + CodexKey: []config.CodexKey{{ + APIKey: "test-compat-key", + BaseURL: server.URL, + Models: []config.CodexModel{{Name: "deepseek-v4.1-flash", IsCompat: true}}, + }}, + } + cfg.Codex.ResponseSteering = true + cfg.CodexResponseSteering = true + + wsExec := NewCodexWebsocketsExecutor(cfg) + const sessID = "duplex-compat-compaction-7406" + t.Cleanup(func() { wsExec.CloseExecutionSession(sessID) }) + + auth := &cliproxyauth.Auth{ + ID: "auth-duplex-compat-7406", + Provider: "codex", + Attributes: map[string]string{"base_url": server.URL, "api_key": "test-compat-key", "websockets": "true"}, + } + + inputCh := make(chan cliproxyexecutor.WebsocketInput, 8) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx = cliproxyexecutor.WithWebsocketInput(cliproxyexecutor.WithDownstreamWebsocket(ctx), inputCh) + + turn1 := []byte(`{"type":"response.create","model":"client-alias","instructions":"Keep concise.","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Remember ` + marker + `"}]}]}`) + streamRes, errStream := wsExec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: turn1, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + Metadata: map[string]any{cliproxyexecutor.ExecutionSessionMetadataKey: sessID}, + }) + if errStream != nil { + t.Fatalf("ExecuteStream(turn1) error = %v", errStream) + } + + readNextEvent := func(wantTypes ...string) ojson.Result { + t.Helper() + deadline := time.After(5 * time.Second) + for { + select { + case chunk, ok := <-streamRes.Chunks: + if !ok { + t.Fatalf("duplex stream closed unexpectedly while waiting for %v", wantTypes) + } + if chunk.Err != nil { + t.Fatalf("duplex stream chunk error while waiting for %v: %v", wantTypes, chunk.Err) + } + trimmed := bytes.TrimSpace(chunk.Payload) + for _, line := range bytes.Split(trimmed, []byte("\n")) { + line = bytes.TrimSpace(line) + if bytes.HasPrefix(line, []byte("data:")) { + line = bytes.TrimSpace(line[len("data:"):]) + } + if len(line) == 0 || bytes.HasPrefix(line, []byte("event:")) { + continue + } + parsed := ojson.ParseBytes(line) + gotType := parsed.Get("type").String() + wantError := false + for _, want := range wantTypes { + if want == "error" { + wantError = true + } + if gotType == want { + return parsed + } + } + if gotType == "error" && !wantError { + t.Fatalf("unexpected error event while waiting for %v: %s", wantTypes, line) + } + } + case <-deadline: + t.Fatalf("timed out waiting for duplex event %v", wantTypes) + } + } + } + + // Drain Turn 1 completion. + _ = readNextEvent("response.completed") + + // 2a. response.steer carrying compaction_trigger is rejected locally without hitting upstream WS. + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(`{"type":"response.steer","event_id":"ev_steer_bad","previous_response_id":"resp_ws_1","input":[{"type":"compaction_trigger"}]}`)} + steerErrEv := readNextEvent("error") + if steerErrEv.Get("status").Int() != http.StatusBadRequest || steerErrEv.Get("error.event_id").String() != "ev_steer_bad" { + t.Fatalf("unexpected steer error event: %s", steerErrEv.Raw) + } + + // 2b. Incremental response.create with previous_response_id + compaction_trigger returns 409 previous_response_not_found. + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(`{"type":"response.create","event_id":"ev_inc_compact","previous_response_id":"resp_ws_1","input":[{"type":"compaction_trigger"}]}`)} + incErrEv := readNextEvent("error") + if incErrEv.Get("status").Int() != http.StatusConflict || incErrEv.Get("error.code").String() != "previous_response_not_found" || incErrEv.Get("error.event_id").String() != "ev_inc_compact" { + t.Fatalf("unexpected incremental compaction error event: %s", incErrEv.Raw) + } + + // 2c. Full response.create with updated instructions="INSTRUCTIONS_B" + compaction_trigger executes local HTTP summary. + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(`{"type":"response.create","model":"client-alias","instructions":"INSTRUCTIONS_B","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Remember ` + marker + `"}]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ack-1"}]},{"type":"compaction_trigger"}]}`)} + compactCompleted := readNextEvent("response.completed") + synthRespID := compactCompleted.Get("response.id").String() + if !strings.HasPrefix(synthRespID, "resp_ag_compact_") { + t.Fatalf("expected synthetic compaction response ID, got %q (%s)", synthRespID, compactCompleted.Raw) + } + if compactCompleted.Get("response.output.0.type").String() != "compaction" { + t.Fatalf("expected compaction item in duplex compaction output: %s", compactCompleted.Raw) + } + summaryHTTPBody := <-httpBodies + if got := ojson.GetBytes(summaryHTTPBody, "model").String(); got != "deepseek-v4.1-flash" { + t.Fatalf("HTTP summary model = %q, want real model; body=%s", got, summaryHTTPBody) + } + if bytes.Contains(summaryHTTPBody, []byte("compaction_trigger")) || ojson.GetBytes(summaryHTTPBody, "tools").Exists() { + t.Fatalf("duplex HTTP summary body leaked compaction_trigger or tools: %s", summaryHTTPBody) + } + + // Invalid synthetic-parent inputs must be rejected without consuming the parent. + for _, invalid := range []string{`{}`, `42`, `true`, `null`} { + payload := fmt.Sprintf(`{"type":"response.create","event_id":"invalid-input","previous_response_id":%q,"input":%s}`, synthRespID, invalid) + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(payload)} + ev := readNextEvent("error") + if ev.Get("status").Int() != http.StatusBadRequest || ev.Get("error.event_id").String() != "invalid-input" { + t.Fatalf("input %s: expected correlated 400, got %s", invalid, ev.Raw) + } + } + + // 3. response.append without instructions or previous_response_id inherits INSTRUCTIONS_B (not initial Keep concise.) and rewrites to expanded root response.create. + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(`{"type":"response.append","input":"What was the marker?"}`)} + turn3Completed := readNextEvent("response.completed") + if turn3Completed.Get("response.id").String() != "resp_ws_3" { + t.Fatalf("turn 3 response.id = %q, want resp_ws_3", turn3Completed.Get("response.id").String()) + } + firstFrame := <-wsFrames + if got := ojson.GetBytes(firstFrame, "model").String(); got != "deepseek-v4.1-flash" { + t.Fatalf("initial model = %q, want real model; frame=%s", got, firstFrame) + } + wsTurn3 := <-wsFrames + if got := ojson.GetBytes(wsTurn3, "model").String(); got != "deepseek-v4.1-flash" { + t.Fatalf("continuation model = %q, want real model; frame=%s", got, wsTurn3) + } + items := ojson.GetBytes(wsTurn3, "input").Array() + last := items[len(items)-1] + if last.Get("role").String() != "user" || !strings.Contains(last.Raw, "What was the marker?") { + t.Fatalf("synthetic-parent string input lost or not a user message: %s", wsTurn3) + } + if ojson.GetBytes(wsTurn3, "previous_response_id").Exists() { + t.Fatalf("synthetic previous_response_id leaked to upstream WS on turn 3: %s", wsTurn3) + } + if gotInst := ojson.GetBytes(wsTurn3, "instructions").String(); gotInst != "INSTRUCTIONS_B" { + t.Fatalf("turn 3 instructions = %q, want INSTRUCTIONS_B (from compaction turn, not initial); frame=%s", gotInst, wsTurn3) + } + if bytes.Contains(wsTurn3, []byte("cpa-ag-compact-v1:")) || !bytes.Contains(wsTurn3, []byte(marker)) { + t.Fatalf("expected expanded summary marker without raw capsule on turn 3 WS frame: %s", wsTurn3) + } + + // 4. Subsequent incremental continuation referencing resp_ws_3 forwards previous_response_id on upstream WS. + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(`{"type":"response.create","model":"client-alias","previous_response_id":"resp_ws_3","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Follow up 4"}]}]}`)} + turn4Completed := readNextEvent("response.completed") + if turn4Completed.Get("response.id").String() != "resp_ws_4" { + t.Fatalf("turn 4 response.id = %q, want resp_ws_4", turn4Completed.Get("response.id").String()) + } + wsTurn4 := <-wsFrames + if got := ojson.GetBytes(wsTurn4, "model").String(); got != "deepseek-v4.1-flash" { + t.Fatalf("ordinary continuation model = %q, want real model; frame=%s", got, wsTurn4) + } + if gotPrev := ojson.GetBytes(wsTurn4, "previous_response_id").String(); gotPrev != "resp_ws_3" { + t.Fatalf("turn 4 WS previous_response_id = %q, want resp_ws_3; frame=%s", gotPrev, wsTurn4) + } + + // 5. Unknown synthetic resp_ag_compact_* is rejected locally with 409 previous_response_not_found. + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(`{"type":"response.create","event_id":"ev_stale_synth","previous_response_id":"resp_ag_compact_unknown","input":[{"type":"message","role":"user","content":"stale"}]}`)} + staleErrEv := readNextEvent("error") + if staleErrEv.Get("status").Int() != http.StatusConflict || staleErrEv.Get("error.code").String() != "previous_response_not_found" { + t.Fatalf("unexpected stale synthetic ID error: %s", staleErrEv.Raw) + } +} + +func TestCodexExecutor_IsCompatCompactionDuplexEOFCancelsHTTP_Issue7406(t *testing.T) { + httpStarted := make(chan struct{}) + httpCanceled := make(chan struct{}) + closeUpstreamWS := make(chan struct{}) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if websocket.IsWebSocketUpgrade(r) { + conn, errUp := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUp != nil { + return + } + defer func() { _ = conn.Close() }() + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + _, _, errRead := conn.ReadMessage() + if errRead != nil { + return + } + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.created","response":{"id":"resp_ws_1","output":[]}}`)) + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.completed","response":{"id":"resp_ws_1","status":"completed","output":[],"usage":{"input_tokens":2,"output_tokens":1,"total_tokens":3}}}`)) + <-closeUpstreamWS + return + } + + _, _ = io.ReadAll(r.Body) + close(httpStarted) + <-r.Context().Done() + close(httpCanceled) + })) + defer server.Close() + + cfg := &config.Config{ + CodexKey: []config.CodexKey{{ + APIKey: "test-compat-key", + BaseURL: server.URL, + Models: []config.CodexModel{{Name: "deepseek-v4.1-flash", IsCompat: true}}, + }}, + } + cfg.Codex.ResponseSteering = true + cfg.CodexResponseSteering = true + + wsExec := NewCodexWebsocketsExecutor(cfg) + const sessID = "duplex-compat-eof-7406" + t.Cleanup(func() { wsExec.CloseExecutionSession(sessID) }) + auth := &cliproxyauth.Auth{ + ID: "auth-duplex-eof-7406", + Provider: "codex", + Attributes: map[string]string{"base_url": server.URL, "api_key": "test-compat-key", "websockets": "true"}, + } + + inputCh := make(chan cliproxyexecutor.WebsocketInput, 4) + ctx := cliproxyexecutor.WithWebsocketInput(cliproxyexecutor.WithDownstreamWebsocket(context.Background()), inputCh) + streamRes, errStream := wsExec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: []byte(`{"type":"response.create","model":"deepseek-v4.1-flash","input":[{"type":"message","role":"user","content":"turn1"}]}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + Metadata: map[string]any{cliproxyexecutor.ExecutionSessionMetadataKey: sessID}, + }) + if errStream != nil { + t.Fatalf("ExecuteStream error = %v", errStream) + } + + // Drain Turn 1 response.completed. + for chunk := range streamRes.Chunks { + if ojson.GetBytes(bytes.TrimSpace(chunk.Payload), "type").String() == "response.completed" { + break + } + } + + // Trigger in-flight HTTP compaction, wait at synchronization barrier, then drop upstream WS. + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(`{"type":"response.create","event_id":"ev_compact_eof","model":"deepseek-v4.1-flash","input":[{"type":"message","role":"user","content":"turn1"},{"type":"compaction_trigger"}]}`)} + select { + case <-httpStarted: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for duplex HTTP compaction to start") + } + close(closeUpstreamWS) + + select { + case <-httpCanceled: + case <-time.After(5 * time.Second): + t.Fatal("upstream WS EOF did not cancel in-flight duplex HTTP compaction") + } + + var gotTurnErr *cliproxyexecutor.UpstreamWebsocketTurnError + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + if uErr, ok := chunk.Err.(*cliproxyexecutor.UpstreamWebsocketTurnError); ok { + gotTurnErr = uErr + } + } + } + if gotTurnErr == nil { + t.Fatal("expected UpstreamWebsocketTurnError on duplex WS EOF during compaction") + } + if len(gotTurnErr.Abandoned) != 1 || gotTurnErr.Abandoned[0].EventID != "ev_compact_eof" || !gotTurnErr.Abandoned[0].NotSent { + t.Fatalf("expected correlated NotSent abandoned error for ev_compact_eof, got idle=%t abandoned=%+v", gotTurnErr.Idle, gotTurnErr.Abandoned) + } +} + +func TestCodexExecutor_IsCompatCompactionDuplexDeliveryOrder_Issue7406(t *testing.T) { + sendTurn1Complete := make(chan struct{}) + httpStarted := make(chan struct{}) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if websocket.IsWebSocketUpgrade(r) { + conn, errUp := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUp != nil { + return + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close upstream websocket: %v", errClose) + } + }() + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + _, _, errRead := conn.ReadMessage() + if errRead != nil { + return + } + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.created","response":{"id":"resp_turn1","output":[]}}`)) + <-sendTurn1Complete + _ = conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.completed","response":{"id":"resp_turn1","status":"completed","output":[],"usage":{"input_tokens":2,"output_tokens":1,"total_tokens":3}}}`)) + _, _, _ = conn.ReadMessage() + return + } + + _, _ = io.ReadAll(r.Body) + close(httpStarted) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_s\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Ordered summary.\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_s\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":4,\"output_tokens\":2,\"total_tokens\":6}}}\n\n", + ) + })) + defer server.Close() + + cfg := &config.Config{ + CodexKey: []config.CodexKey{{ + APIKey: "test-compat-key", + BaseURL: server.URL, + Models: []config.CodexModel{{Name: "deepseek-v4.1-flash", IsCompat: true}}, + }}, + } + cfg.Codex.ResponseSteering = true + cfg.CodexResponseSteering = true + + wsExec := NewCodexWebsocketsExecutor(cfg) + terminalPending := make(chan struct{}, 1) + compactionReady := make(chan bool, 8) + wsExec.duplexStateObserver = func(event string, ready bool) { + switch event { + case "terminal_pending": + terminalPending <- struct{}{} + case "compaction_wait": + compactionReady <- ready + } + } + const sessID = "duplex-compat-order-7406" + t.Cleanup(func() { wsExec.CloseExecutionSession(sessID) }) + auth := &cliproxyauth.Auth{ + ID: "auth-duplex-order-7406", + Provider: "codex", + Attributes: map[string]string{"base_url": server.URL, "api_key": "test-compat-key", "websockets": "true"}, + } + + inputCh := make(chan cliproxyexecutor.WebsocketInput, 4) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx = cliproxyexecutor.WithWebsocketInput(cliproxyexecutor.WithDownstreamWebsocket(ctx), inputCh) + + streamRes, errStream := wsExec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{ + Model: "deepseek-v4.1-flash", + Payload: []byte(`{"type":"response.create","model":"deepseek-v4.1-flash","input":[{"type":"message","role":"user","content":"turn1"}]}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Stream: true, + Metadata: map[string]any{cliproxyexecutor.ExecutionSessionMetadataKey: sessID}, + }) + if errStream != nil { + t.Fatalf("ExecuteStream error = %v", errStream) + } + + // Read Turn 1 response.created so inputReady is open. + firstChunk := <-streamRes.Chunks + if ojson.GetBytes(bytes.TrimSpace(firstChunk.Payload), "type").String() != "response.created" { + t.Fatalf("expected Turn 1 response.created first, got %s", firstChunk.Payload) + } + + // Let the reader finish terminal bookkeeping, but leave its unbuffered send + // blocked. Only then enqueue compaction and observe the writer evaluating its + // fence. This proves both goroutines reached the disputed delivery window. + close(sendTurn1Complete) + select { + case <-terminalPending: + case <-time.After(5 * time.Second): + t.Fatal("reader did not reach terminal delivery") + } + inputCh <- cliproxyexecutor.WebsocketInput{Payload: []byte(`{"type":"response.create","model":"deepseek-v4.1-flash","input":[{"type":"message","role":"user","content":"turn1"},{"type":"compaction_trigger"}]}`)} + select { + case ready := <-compactionReady: + if ready { + t.Fatal("compaction fence opened before prior terminal delivery") + } + case <-time.After(5 * time.Second): + t.Fatal("writer did not evaluate the compaction fence") + } + + secondChunk := <-streamRes.Chunks + if ojson.GetBytes(bytes.TrimSpace(secondChunk.Payload), "type").String() != "response.completed" || + ojson.GetBytes(bytes.TrimSpace(secondChunk.Payload), "response.id").String() != "resp_turn1" { + t.Fatalf("expected Turn 1 response.completed before any Turn 2 synthetic event, got: %s", secondChunk.Payload) + } + + // Now Turn 2 synthetic events must follow in order ending with synthetic response.completed. + var sawSynthCreated, sawSynthCompleted bool + for !sawSynthCompleted { + chunk := <-streamRes.Chunks + for _, line := range bytes.Split(chunk.Payload, []byte("\n")) { + line = bytes.TrimSpace(line) + if bytes.HasPrefix(line, []byte("data:")) { + line = bytes.TrimSpace(line[len("data:"):]) + } + if len(line) == 0 || bytes.HasPrefix(line, []byte("event:")) { + continue + } + evType := ojson.GetBytes(line, "type").String() + if evType == "response.created" { + sawSynthCreated = true + } + if evType == "response.completed" { + if !sawSynthCreated { + t.Fatalf("synthetic response.completed arrived before response.created: %s", line) + } + sawSynthCompleted = true + } + } + } +} diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index 2750ed4b3ef..fae2f322010 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -17,19 +17,110 @@ import ( log "github.com/sirupsen/logrus" ) +type codexCompactionSummaryContextKey struct{} + +type codexCompactionSummaryState struct { + baseModel string +} + +func withCodexCompactionSummary(ctx context.Context, baseModel string) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, codexCompactionSummaryContextKey{}, &codexCompactionSummaryState{baseModel: baseModel}) +} + +func codexCompactionSummaryStateFromContext(ctx context.Context) *codexCompactionSummaryState { + if ctx == nil { + return nil + } + state, _ := ctx.Value(codexCompactionSummaryContextKey{}).(*codexCompactionSummaryState) + return state +} + +func codexCompactionSummaryFromContext(ctx context.Context) bool { + return codexCompactionSummaryStateFromContext(ctx) != nil +} + +func rejectSyntheticCompactionPreviousResponseID(ctx context.Context, payload []byte) error { + prevID := strings.TrimSpace(ojson.GetBytesNoCopy(payload, "previous_response_id").String()) + if !helps.RecognizedResponsesCompactionResponseID(prevID) { + return nil + } + if cliproxyexecutor.DownstreamWebsocket(ctx) { + return &cliproxyexecutor.UpstreamWebsocketTurnError{ + FullContextRequired: true, + EventID: strings.Clone(strings.TrimSpace(ojson.GetBytesNoCopy(payload, "event_id").String())), + } + } + return statusErr{ + code: http.StatusBadRequest, + msg: "previous_response_id references a local compaction response; resend full conversation input without previous_response_id", + } +} + +func validateCodexLocalCompactionSource(ctx context.Context, payload []byte) error { + prevID := strings.TrimSpace(ojson.GetBytesNoCopy(payload, "previous_response_id").String()) + reqType := strings.TrimSpace(ojson.GetBytesNoCopy(payload, "type").String()) + if prevID != "" || reqType == "response.append" { + if cliproxyexecutor.DownstreamWebsocket(ctx) { + return &cliproxyexecutor.UpstreamWebsocketTurnError{ + FullContextRequired: true, + EventID: strings.Clone(strings.TrimSpace(ojson.GetBytesNoCopy(payload, "event_id").String())), + } + } + return statusErr{ + code: http.StatusBadRequest, + msg: "local summary compaction requires full conversation input without previous_response_id", + } + } + if !helps.HasResponsesCompactionConversationInput(payload) { + return statusErr{ + code: http.StatusBadRequest, + msg: "local summary compaction requires non-empty conversation input", + } + } + return nil +} + +func (e *CodexExecutor) expandCodexResponsesCompaction(auth *cliproxyauth.Auth, req *cliproxyexecutor.Request, opts *cliproxyexecutor.Options, baseModel string) (bool, error) { + if req == nil || opts == nil { + return false, nil + } + isCompat := e.resolveCodexModelIsCompat(auth, *req, baseModel) + if isCompat && opts.SourceFormat == sdktranslator.FormatOpenAIResponse && opts.Alt != "responses/compact" { + return true, helps.ExpandResponsesCompactionCapsules(req, opts, e.Identifier()) + } + return isCompat, helps.ExpandRecognizedResponsesCompactionCapsules(req, opts) +} + +func (e *CodexExecutor) shouldCompactCompatResponsesTrigger(isCompat bool, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) bool { + return isCompat && opts.SourceFormat == sdktranslator.FormatOpenAIResponse && opts.Alt != "responses/compact" && helps.HasResponsesCompactionTriggerRequest(req, opts) +} + func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { ctx = helps.EnsureSessionContext(ctx, opts, req.Payload) ctx = helps.WithCodexCommentaryPolicy(ctx, e.cfg) - if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&req, &opts); errExpand != nil { - return resp, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} - } if opts.Alt == "responses/compact" { return e.executeCompact(ctx, auth, req, opts) } if isCodexOpenAIImageRequest(opts) { + if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&req, &opts); errExpand != nil { + return resp, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } return e.executeOpenAIImage(ctx, auth, req, opts) } baseModel := thinking.ParseSuffix(req.Model).ModelName + isCompat, errExpand := e.expandCodexResponsesCompaction(auth, &req, &opts, baseModel) + if errExpand != nil { + return resp, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } + if !codexCompactionSummaryFromContext(ctx) && e.shouldCompactCompatResponsesTrigger(isCompat, req, opts) { + return e.executeCodexResponsesCompaction(ctx, auth, req, opts) + } + if errPrev := rejectSyntheticCompactionPreviousResponseID(ctx, req.Payload); errPrev != nil { + return resp, errPrev + } apiKey, baseURL := codexCredsForRequest(ctx, auth, opts.Headers) if errSIWC := ensureCodexSIWCCredentialsForRequest(ctx, auth, apiKey, opts.Headers); errSIWC != nil { @@ -50,7 +141,6 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re originalPayloadSource = opts.OriginalRequest } originalPayload := originalPayloadSource - isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) targetModel := resolveResponsesSignatureTargetModel(baseModel, req, opts) originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntentContext(ctx, from, to, targetModel, originalPayload, req.Payload, false, isCompat) if err != nil { @@ -65,7 +155,7 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re return resp, err } - ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslated, req, opts)) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslated, req, opts, auth)) helps.SetStringIfDifferentDoc(doc, "model", baseModel) helps.SetBoolIfDifferentDoc(doc, "stream", true) _ = doc.Delete("previous_response_id") @@ -76,11 +166,18 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re useSIWC := codexUseSIWCForRequest(ctx, auth, opts.Headers) instructionsResult := ojson.GetBytesNoCopy(req.Payload, "instructions") hasExplicitInstructions := instructionsResult.Exists() && strings.TrimSpace(instructionsResult.String()) != "" - ensureWebSearchToolForHistoryDoc(doc, opts.Headers) + isCompactionSummary := codexCompactionSummaryFromContext(ctx) + if !isCompactionSummary { + ensureWebSearchToolForHistoryDoc(doc, opts.Headers) + } if !useSIWC { normalizeCodexInstructionsDoc(doc, helps.IsNativeCodexRequest(req.Payload, opts)) - if e.cfg == nil || e.cfg.DisableImageGeneration == config.DisableImageGenerationOff { - ensureImageGenerationToolDoc(doc, baseModel, auth, opts.Headers) + if !isCompactionSummary && (e.cfg == nil || e.cfg.DisableImageGeneration == config.DisableImageGenerationOff) { + checkModel := req.Model + if strings.TrimSpace(checkModel) == "" { + checkModel = baseModel + } + ensureImageGenerationToolDoc(doc, checkModel, auth, opts.Headers) if !codexAuthUsesAPIKey(auth) { normalizeCodexImageGenerationToolsDoc(doc) } @@ -149,11 +246,14 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } if errClearReplay := clearCodexReasoningReplayOnInvalidSignature(ctx, replayScope, httpResp.StatusCode, b); errClearReplay != nil { return resp, errClearReplay } - helps.AppendAPIResponseChunk(ctx, e.cfg, b) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) err = newCodexStatusErrWithHeadersAndCooling(httpResp.StatusCode, httpResp.Header, b, e.modelLevelCooling()) return resp, err @@ -182,9 +282,15 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re if streamErr, terminalBody, ok := codexTerminalFailureErrWithCooling(eventData, e.modelLevelCooling()); ok { if errClearReplay := clearCodexReasoningReplayOnInvalidSignature(ctx, replayScope, streamErr.StatusCode(), terminalBody); errClearReplay != nil { + if detail, hasDetail := helps.ParseCodexUsageWithOutputItems(eventData, outputItemsByIndex, outputItemsFallback); hasDetail { + reporter.PublishFailureWithDetail(ctx, detail, errClearReplay) + } return resp, errClearReplay } err = streamErr + if detail, hasDetail := helps.ParseCodexUsageWithOutputItems(eventData, outputItemsByIndex, outputItemsFallback); hasDetail { + reporter.PublishFailureWithDetail(ctx, detail, err) + } return resp, err } @@ -208,6 +314,9 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re if helps.IsCodexTerminalEmptyIncomplete(eventData, len(outputItemsByIndex)+len(outputItemsFallback), sawOutputDelta) { err = newCodexEmptyIncompleteStreamError() + if detail, hasDetail := helps.ParseCodexUsageWithOutputItems(eventData, outputItemsByIndex, outputItemsFallback); hasDetail { + reporter.PublishFailureWithDetail(ctx, detail, err) + } return resp, err } @@ -221,13 +330,43 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { return cliproxyexecutor.Response{}, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} } - if detail, ok := helps.ParseCodexUsageWithOutputItems(completedData, outputItemsByIndex, outputItemsFallback); ok { - reporter.Publish(ctx, detail) - } - publishCodexImageToolUsageWithOutputItems(ctx, reporter, body, completedData, outputItemsByIndex, outputItemsFallback) + detail, hasDetail := helps.ParseCodexUsageWithOutputItems(completedData, outputItemsByIndex, outputItemsFallback) if responseFormat == sdktranslator.FormatOpenAIResponse { out = helps.EnsureResponsesUsageDetails(out) } + if summaryState := codexCompactionSummaryStateFromContext(ctx); summaryState != nil { + if eventType == "response.incomplete" { + err = statusErr{code: http.StatusBadGateway, msg: "compaction summary response status is \"incomplete\", want \"completed\""} + if hasDetail { + reporter.PublishFailureWithDetail(ctx, detail, err) + } else { + reporter.PublishFailure(ctx, err) + } + return cliproxyexecutor.Response{}, err + } + compactedPayload, errBuild := helps.BuildResponsesCompactionResponseFromSummary(summaryState.baseModel, out) + if errBuild != nil { + err = statusErr{code: http.StatusBadGateway, msg: errBuild.Error()} + if hasDetail { + reporter.PublishFailureWithDetail(ctx, detail, err) + } else { + reporter.PublishFailure(ctx, err) + } + return cliproxyexecutor.Response{}, err + } + if hasDetail { + reporter.Publish(ctx, detail) + } else { + reporter.EnsurePublished(ctx) + } + publishCodexImageToolUsageWithOutputItems(ctx, reporter, body, completedData, outputItemsByIndex, outputItemsFallback) + resp = cliproxyexecutor.Response{Payload: compactedPayload, Headers: httpResp.Header.Clone()} + return resp, nil + } + if hasDetail { + reporter.Publish(ctx, detail) + } + publishCodexImageToolUsageWithOutputItems(ctx, reporter, body, completedData, outputItemsByIndex, outputItemsFallback) resp = cliproxyexecutor.Response{Payload: out, Incomplete: eventType == "response.incomplete", Headers: httpResp.Header.Clone()} return resp, nil } @@ -243,6 +382,51 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re return resp, err } +func (e *CodexExecutor) executeCodexResponsesCompaction(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + var resp cliproxyexecutor.Response + sourcePayload := helps.ResponsesCompactionSourcePayload(req, opts) + if errValidate := validateCodexLocalCompactionSource(ctx, sourcePayload); errValidate != nil { + return resp, errValidate + } + baseModel := thinking.ParseSuffix(req.Model).ModelName + summaryPayload := helps.PrepareAntigravityCompactionSummaryPayload(sourcePayload, baseModel) + summaryReq := req + summaryReq.Payload = summaryPayload + summaryOpts := opts + summaryOpts.Alt = "" + summaryOpts.Stream = false + summaryOpts.OriginalRequest = nil + summaryOpts.SourceFormat = sdktranslator.FormatOpenAIResponse + summaryOpts.ResponseFormat = sdktranslator.FormatOpenAIResponse + + return e.Execute(withCodexCompactionSummary(ctx, baseModel), auth, summaryReq, summaryOpts) +} + +func (e *CodexExecutor) executeCodexResponsesCompactionStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + cliproxyexecutor.MarkLocalWebsocketTurn(ctx) + baseModel := thinking.ParseSuffix(req.Model).ModelName + summaryResp, errSummary := e.executeCodexResponsesCompaction(ctx, auth, req, opts) + if errSummary != nil { + return nil, errSummary + } + chunks, errChunks := helps.BuildResponsesCompactionStreamChunksFromResponse(baseModel, summaryResp.Payload) + if errChunks != nil { + return nil, statusErr{code: http.StatusBadGateway, msg: errChunks.Error()} + } + out := make(chan cliproxyexecutor.StreamChunk, len(chunks)) + for _, chunk := range chunks { + out <- cliproxyexecutor.StreamChunk{Payload: chunk} + } + close(out) + + headers := summaryResp.Headers.Clone() + if headers == nil { + headers = make(http.Header) + } + headers.Set("Content-Type", "text/event-stream") + return &cliproxyexecutor.StreamResult{Headers: headers, Chunks: out}, nil +} + func (e *CodexExecutor) executeCompact(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&req, &opts); errExpand != nil { return resp, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} @@ -342,18 +526,21 @@ func (e *CodexExecutor) executeCompact(ctx context.Context, auth *cliproxyauth.A }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) err = newCodexStatusErrWithHeadersAndCooling(httpResp.StatusCode, httpResp.Header, b, e.modelLevelCooling()) return resp, err } data, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) upstreamData := helps.RestoreCodexMultiAgentV2Response(data, optimizeMultiAgentV2) var param any out := sdktranslator.TranslateNonStream(ctx, to, responseFormat, req.Model, originalPayload, body, upstreamData, ¶m) diff --git a/internal/runtime/executor/codex_executor_execute_usage_test.go b/internal/runtime/executor/codex_executor_execute_usage_test.go index 18fd2f1af27..b2910619926 100644 --- a/internal/runtime/executor/codex_executor_execute_usage_test.go +++ b/internal/runtime/executor/codex_executor_execute_usage_test.go @@ -6,10 +6,13 @@ import ( "io" "net/http" "net/http/httptest" + "strings" "testing" "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" @@ -265,3 +268,61 @@ func TestCodexExecutorExecuteCompactRecordsFinalizedPayloadOverrideReasoningEffo t.Fatalf("usage record ReasoningEffort = %q, want %q", record.ReasoningEffort, "high") } } + +func TestCodexExecutorPreservesPartialNon2xxBodyAndReadErrorWhenRequestLogDisabled(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, alt := range []string{"", "responses/compact"} { + name := "responses" + if alt != "" { + name = "compact" + } + t.Run(name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hijacker, ok := w.(http.Hijacker) + if !ok { + t.Error("response writer does not support hijacking") + return + } + conn, buf, errHijack := hijacker.Hijack() + if errHijack != nil { + t.Errorf("hijack: %v", errHijack) + return + } + _, _ = buf.WriteString("HTTP/1.1 502 Bad Gateway\r\nContent-Type: application/json\r\nContent-Length: 4096\r\n\r\n{\"error\":{\"message\":\"partial codex 502") + _ = buf.Flush() + _ = conn.Close() + })) + defer server.Close() + + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + executor := NewCodexExecutor(&config.Config{}) + _, errExec := executor.Execute(ctx, codexOAuthTestAuth(server.URL), cliproxyexecutor.Request{ + Model: "gpt-5.5", + Payload: []byte(`{"model":"gpt-5.5","input":[{"type":"message","role":"user","content":"hi"}]}`), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse, Alt: alt}) + if errExec == nil { + t.Fatal("expected Execute to fail on 502") + } + + value, exists := ginCtx.Get(logging.DeferredAPIResponseContextKey) + if !exists { + t.Fatal("deferred API response was not recorded") + } + deferred, ok := value.(logging.DeferredAPIResponse) + if !ok || deferred == nil { + t.Fatalf("deferred API response = %#v, want logging.DeferredAPIResponse", value) + } + rendered := string(deferred.RenderAPIResponse()) + for _, want := range []string{ + "Status: 502", + `{"error":{"message":"partial codex 502`, + "Error: unexpected EOF", + } { + if !strings.Contains(rendered, want) { + t.Fatalf("deferred API response missing %q:\n%s", want, rendered) + } + } + }) + } +} diff --git a/internal/runtime/executor/codex_executor_imagegen_test.go b/internal/runtime/executor/codex_executor_imagegen_test.go index 405a2d158db..a43243ee9bd 100644 --- a/internal/runtime/executor/codex_executor_imagegen_test.go +++ b/internal/runtime/executor/codex_executor_imagegen_test.go @@ -11,6 +11,8 @@ import ( "github.com/MoeForge/moego/ojson" "github.com/gorilla/websocket" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" @@ -152,8 +154,14 @@ func TestEnsureImageGenerationTool_ResponsesLiteFalseMetadataStillInjectsTool(t liteHeaders := make(http.Header) liteHeaders.Set(codexResponsesLiteHeader, "false") liteResult := ensureImageGenerationTool(liteBody, liteModel, nil, liteHeaders) - if ojson.GetBytes(liteResult, "tools").Exists() { - t.Fatalf("for %s: expected no auto-injected tools even when responses-lite is explicitly false, got %s", liteModel, liteResult) + if got := ojson.GetBytes(liteResult, "tools.0.type").String(); got != "image_generation" { + t.Fatalf("for %s: tools.0.type = %q, want image_generation when responses-lite is false and reasoning is absent; body=%s", liteModel, got, liteResult) + } + + reasoningBody := []byte(`{"model":"` + liteModel + `","reasoning":{"effort":"medium"},"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":"false"},"input":"hello"}`) + reasoningResult := ensureImageGenerationTool(reasoningBody, liteModel, nil, liteHeaders) + if ojson.GetBytes(reasoningResult, "tools").Exists() { + t.Fatalf("for %s: expected no auto-injected tools when reasoning.effort is present, got %s", liteModel, reasoningResult) } } } @@ -300,7 +308,7 @@ func TestEnsureImageGenerationTool_FreeCodexAuthDoesNotInjectTool(t *testing.T) } func TestEnsureImageGenerationTool_ResponsesLiteModelsDoNotInjectToolByDefault(t *testing.T) { - for _, model := range []string{ + liteModels := []string{ "gpt-6-astra", "gpt-6-sol", "gpt-6.1-sol", @@ -312,21 +320,56 @@ func TestEnsureImageGenerationTool_ResponsesLiteModelsDoNotInjectToolByDefault(t "gpt-5.6-luna", "gpt-reserve", "codex-auto-review", + } + + for _, model := range liteModels { + t.Run("standard_without_reasoning/"+model, func(t *testing.T) { + body := []byte(`{"model":"` + model + `","input":"hello"}`) + result := ensureImageGenerationTool(body, model, nil, nil) + if got := ojson.GetBytes(result, "tools.0.type").String(); got != "image_generation" { + t.Fatalf("for %s without reasoning: tools.0.type = %q, want image_generation; body=%s", model, got, result) + } + + withFunctionTool := []byte(`{"model":"` + model + `","input":"Generate a photorealistic image of a mountain lake at sunset.","tools":[{"type":"function","name":"get_weather","description":"Get current weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}`) + withFunctionResult := ensureImageGenerationTool(withFunctionTool, model, nil, nil) + if got := ojson.GetBytes(withFunctionResult, "tools.1.type").String(); got != "image_generation" { + t.Fatalf("for %s with function tool and no reasoning: tools.1.type = %q, want image_generation; body=%s", model, got, withFunctionResult) + } + }) + + t.Run("with_reasoning_effort/"+model, func(t *testing.T) { + body := []byte(`{"model":"` + model + `","reasoning":{"effort":"medium"},"input":"hello"}`) + result := ensureImageGenerationTool(body, model, nil, nil) + if ojson.GetBytes(result, "tools").Exists() { + t.Fatalf("expected no auto-injected tools for %s with reasoning.effort, got %s", model, result) + } + }) + + t.Run("with_configuration_update_reasoning/"+model, func(t *testing.T) { + body := []byte(`{"model":"` + model + `","input":[{"type":"configuration_update","reasoning":{"effort":"high"}},{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}]}`) + result := ensureImageGenerationTool(body, model, nil, nil) + if ojson.GetBytes(result, "tools").Exists() { + t.Fatalf("expected no auto-injected tools for %s with configuration_update reasoning, got %s", model, result) + } + }) + } + + for _, suffixedModel := range []string{ "codex/gpt-6-astra(medium)", "codex/gpt-5.6-sol(high)", } { - t.Run(model, func(t *testing.T) { - body := []byte(`{"model":"` + model + `","input":"hello"}`) - result := ensureImageGenerationTool(body, model, nil, nil) + t.Run("with_thinking_suffix/"+suffixedModel, func(t *testing.T) { + body := []byte(`{"model":"` + suffixedModel + `","input":"hello"}`) + result := ensureImageGenerationTool(body, suffixedModel, nil, nil) if ojson.GetBytes(result, "tools").Exists() { - t.Fatalf("expected no auto-injected tools for %s, got %s", model, result) + t.Fatalf("expected no auto-injected tools for %s, got %s", suffixedModel, result) } }) } for _, nonLiteModel := range []string{"gpt-5.5", "gpt-5.4"} { t.Run("non-lite/"+nonLiteModel, func(t *testing.T) { - body := []byte(`{"model":"` + nonLiteModel + `","input":"hello"}`) + body := []byte(`{"model":"` + nonLiteModel + `","reasoning":{"effort":"medium"},"input":"hello"}`) result := ensureImageGenerationTool(body, nonLiteModel, nil, nil) if got := ojson.GetBytes(result, "tools.0.type").String(); got != "image_generation" { t.Fatalf("for %s: tools.0.type = %q, want image_generation; body=%s", nonLiteModel, got, result) @@ -335,6 +378,473 @@ func TestEnsureImageGenerationTool_ResponsesLiteModelsDoNotInjectToolByDefault(t } } +func TestCodexExecutorStandardResponsesInjectsImageGenerationWithoutReasoningAndSkipsWithReasoning(t *testing.T) { + for _, transport := range []string{"http", "websocket"} { + for _, stream := range []bool{false, true} { + streamLabel := "false" + if stream { + streamLabel = "true" + } + for _, tc := range []struct { + name string + model string + sourceFmt sdktranslator.Format + payload string + reqMetadata map[string]any + reqHeaders http.Header + authAttrs map[string]string + cfg config.Config + overrideHeaders map[string]string + wantTools int + wantImgIdx string + wantToolType string + wantEffort string + }{ + { + name: "standard_responses_with_function_tool_no_reasoning", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"Generate a photorealistic image of a mountain lake at sunset.","tools":[{"type":"function","name":"get_weather","description":"Get current weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}`, + wantTools: 2, + wantImgIdx: "tools.1.type", + }, + { + name: "standard_responses_bare_no_reasoning", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"Generate a photorealistic image of a mountain lake at sunset."}`, + wantTools: 1, + wantImgIdx: "tools.0.type", + }, + { + name: "standard_responses_with_reasoning_effort", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","reasoning":{"effort":"medium"},"input":"Generate a photorealistic image of a mountain lake at sunset."}`, + wantTools: 0, + }, + { + name: "standard_responses_with_model_thinking_suffix", + model: "gpt-6-astra(medium)", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra(medium)","input":"Generate a photorealistic image of a mountain lake at sunset."}`, + wantTools: 0, + }, + { + name: "openai_chat_completions_defaults_reasoning_effort", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAI, + payload: `{"model":"gpt-6-astra","messages":[{"role":"user","content":"Generate a photorealistic image of a mountain lake at sunset."}]}`, + wantTools: 0, + }, + { + name: "payload_default_sets_reasoning_effort_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Default: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{"reasoning.effort": "medium"}, + }, + }, + }, + }, + wantTools: 0, + wantEffort: "medium", + }, + { + name: "payload_override_sets_reasoning_effort_with_function_tool_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello","tools":[{"type":"function","name":"get_weather","description":"Get current weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}]}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{"reasoning.effort": "high"}, + }, + }, + }, + }, + wantTools: 1, + wantImgIdx: "tools.0.type", + wantToolType: "function", + wantEffort: "high", + }, + { + name: "payload_conditional_exist_tools_sets_reasoning_effort_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra", Exist: []string{"tools"}}}, + Params: map[string]any{"reasoning.effort": "medium"}, + }, + }, + }, + }, + wantTools: 0, + wantEffort: "medium", + }, + { + name: "payload_conditional_exist_prompt_cache_key_sets_reasoning_effort_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + reqMetadata: map[string]any{cliproxyexecutor.ExecutionSessionMetadataKey: "sess-prompt-cache-7384"}, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra", Exist: []string{"prompt_cache_key"}}}, + Params: map[string]any{"reasoning.effort": "medium"}, + }, + }, + }, + }, + wantTools: 0, + wantEffort: "medium", + }, + { + name: "payload_override_switches_to_lite_model_with_reasoning_skips_auto_injection", + model: "gpt-5.4", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-5.4","reasoning":{"effort":"medium"},"input":"hello"}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-5.4"}}, + Params: map[string]any{"model": "gpt-6-astra"}, + }, + }, + }, + }, + wantTools: 0, + wantEffort: "medium", + }, + { + name: "model_override_header_enables_responses_lite_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + overrideHeaders: map[string]string{codexResponsesLiteHeader: "true"}, + wantTools: 0, + }, + { + name: "payload_override_sets_reasoning_effort_and_tool_choice_auto_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{ + "reasoning.effort": "medium", + "tool_choice": "auto", + }, + }, + }, + }, + }, + wantTools: 0, + wantEffort: "medium", + }, + { + name: "client_lite_header_overridden_false_by_auth_with_payload_rule_keeps_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + reqHeaders: http.Header{codexResponsesLiteHeader: []string{"true"}}, + authAttrs: map[string]string{"header:" + codexResponsesLiteHeader: "false"}, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{"service_tier": "default"}, + }, + }, + }, + }, + wantTools: 1, + wantImgIdx: "tools.0.type", + }, + { + name: "payload_default_image_tool_choice_overridden_to_auto_with_reasoning_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Default: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{"tool_choice": map[string]any{"type": "image_generation"}}, + }, + }, + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{ + "tool_choice": "auto", + "reasoning.effort": "medium", + }, + }, + }, + }, + }, + wantTools: 0, + wantEffort: "medium", + }, + { + name: "auth_lite_header_true_overridden_false_by_initial_model_then_switched_to_model_without_override_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + authAttrs: map[string]string{"header:" + codexResponsesLiteHeader: "true"}, + overrideHeaders: map[string]string{codexResponsesLiteHeader: "false"}, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{"model": "gpt-5.5"}, + }, + }, + }, + }, + wantTools: 0, + }, + { + name: "payload_override_function_tool_then_filter_deletes_it_with_reasoning_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello","tools":[{"type":"function","name":"get_weather","description":"Get current weather","parameters":{"type":"object"}}]}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{ + "tools.0.description": "Updated weather", + "reasoning.effort": "medium", + }, + }, + }, + Filter: []config.PayloadFilterRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: []string{"tools.0"}, + }, + }, + }, + }, + wantTools: 0, + wantEffort: "medium", + }, + { + name: "payload_override_image_tool_then_filter_deletes_earlier_tool_with_reasoning_keeps_configured_image_tool", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello","tools":[{"type":"function","name":"get_weather","description":"Get current weather","parameters":{"type":"object"}}]}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{ + "tools.1.output_format": "webp", + "reasoning.effort": "medium", + }, + }, + }, + Filter: []config.PayloadFilterRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: []string{"tools.0"}, + }, + }, + }, + }, + wantTools: 1, + wantImgIdx: "tools.0.type", + wantEffort: "medium", + }, + { + name: "payload_override_raw_escaped_configuration_update_reasoning_skips_auto_injection", + model: "gpt-6-astra", + sourceFmt: sdktranslator.FormatOpenAIResponse, + payload: `{"model":"gpt-6-astra","input":"hello"}`, + cfg: config.Config{ + Payload: config.PayloadConfig{ + OverrideRaw: []config.PayloadRule{ + { + Models: []config.PayloadModelRule{{Name: "gpt-6-astra"}}, + Params: map[string]any{ + "input.-1": `{"type":"\u0063onfiguration_update","reasoning":{"effort":"medium"}}`, + }, + }, + }, + }, + }, + wantTools: 0, + }, + } { + t.Run(tc.name+"/"+transport+"/stream="+streamLabel, func(t *testing.T) { + capturedBody := make(chan []byte, 1) + completedEvent := []byte(`{"type":"response.completed","response":{"id":"resp_7384","object":"response","status":"completed","model":"gpt-6-astra","output":[],"usage":{"input_tokens":10,"output_tokens":5,"total_tokens":15}}}`) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if transport == "websocket" { + upgrader := websocket.Upgrader{} + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + t.Errorf("upgrade websocket: %v", errUpgrade) + return + } + defer func() { + _ = conn.Close() + }() + _, msg, errRead := conn.ReadMessage() + if errRead != nil { + t.Errorf("read websocket message: %v", errRead) + return + } + capturedBody <- msg + if errWrite := conn.WriteMessage(websocket.TextMessage, completedEvent); errWrite != nil { + t.Errorf("write websocket message: %v", errWrite) + } + return + } + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read http body: %v", errRead) + return + } + capturedBody <- body + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write(append(append([]byte("data: "), completedEvent...), '\n', '\n')) + })) + defer server.Close() + + cfg := tc.cfg + var exec cliproxyauth.ProviderExecutor = NewCodexExecutor(&cfg) + if transport == "websocket" { + exec = NewCodexWebsocketsExecutor(&cfg) + } + if len(tc.overrideHeaders) > 0 { + reg := registry.GetGlobalRegistry() + clientID := t.Name() + "/override-header" + reg.RegisterClient(clientID, "codex", []*registry.ModelInfo{{ + ID: tc.model, + Type: "codex", + Config: ®istry.ModelConfig{OverrideHeader: tc.overrideHeaders}, + }}) + t.Cleanup(func() { reg.UnregisterClient(clientID) }) + } + attrs := map[string]string{ + "base_url": server.URL, + "plan_type": "pro", + } + for k, v := range tc.authAttrs { + attrs[k] = v + } + auth := &cliproxyauth.Auth{ + ID: t.Name(), + Provider: "codex", + Attributes: attrs, + Metadata: map[string]any{ + "access_token": "test-token", + "account_id": "acct-1", + }, + } + req := cliproxyexecutor.Request{ + Model: tc.model, + Payload: []byte(tc.payload), + Metadata: tc.reqMetadata, + } + finalized := 0 + var headers http.Header + if tc.reqHeaders != nil { + headers = make(http.Header, len(tc.reqHeaders)) + for k, vals := range tc.reqHeaders { + for _, v := range vals { + headers.Add(k, v) + } + } + } + opts := cliproxyexecutor.Options{ + SourceFormat: tc.sourceFmt, + Stream: stream, + Headers: headers, + Metadata: map[string]any{ + cliproxyexecutor.FinalizedResponseFormatCallbackMetadataKey: func(string) { finalized++ }, + }, + } + evalsBefore := helps.PayloadConfigEvaluationCount() + var errExec error + if stream { + var res *cliproxyexecutor.StreamResult + res, errExec = exec.ExecuteStream(context.Background(), auth, req, opts) + if res != nil { + for chunk := range res.Chunks { + if chunk.Err != nil { + errExec = chunk.Err + } + } + } + } else { + _, errExec = exec.Execute(context.Background(), auth, req, opts) + } + + if gotEvals := helps.PayloadConfigEvaluationCount() - evalsBefore; gotEvals != 1 { + t.Fatalf("payload rule engine evaluated %d times, want 1", gotEvals) + } + if finalized != 1 { + t.Fatalf("payload finalizer evaluated %d times, want 1", finalized) + } + if errExec != nil { + t.Fatalf("execute error = %v", errExec) + } + gotBody := <-capturedBody + if tc.wantEffort != "" { + if gotEffort := ojson.GetBytes(gotBody, "reasoning.effort").String(); gotEffort != tc.wantEffort { + t.Fatalf("reasoning.effort = %q, want %q; body=%s", gotEffort, tc.wantEffort, gotBody) + } + } + tools := ojson.GetBytes(gotBody, "tools") + if tc.wantTools == 0 { + if tools.Exists() { + t.Fatalf("expected no tools, got %s (body=%s)", tools.Raw, gotBody) + } + return + } + if !tools.IsArray() || len(tools.Array()) != tc.wantTools { + t.Fatalf("tools count = %d, want %d; body=%s", len(tools.Array()), tc.wantTools, gotBody) + } + wantType := tc.wantToolType + if wantType == "" { + wantType = "image_generation" + } + if gotType := ojson.GetBytes(gotBody, tc.wantImgIdx).String(); gotType != wantType { + t.Fatalf("%s = %q, want %s; body=%s", tc.wantImgIdx, gotType, wantType, gotBody) + } + }) + } + } + } +} + func TestCodexExecutorHostedImageGenerationSIWCAndAPIKeyPreserveUpstreamModelAndParams(t *testing.T) { for _, credKind := range []string{"api_key", "siwc"} { for _, transport := range []string{"http", "websocket"} { diff --git a/internal/runtime/executor/codex_executor_native_effort_test.go b/internal/runtime/executor/codex_executor_native_effort_test.go new file mode 100644 index 00000000000..89c96e16536 --- /dev/null +++ b/internal/runtime/executor/codex_executor_native_effort_test.go @@ -0,0 +1,142 @@ +package executor + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestCodexSIWCNormalizesNativeResponsesEffort(t *testing.T) { + const completed = `{"type":"response.completed","response":{"id":"resp_effort","object":"response","status":"completed","model":"gpt-6.1-sol","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + for _, mode := range []string{"http", "stream", "compact", "websocket", "websocket stream preparation"} { + for _, tc := range []struct { + name string + body string + override bool + wantEffort string + }{ + { + name: "baseline none uses minimum effort", + body: `{"model":"gpt-6.1-sol","reasoning":{"effort":"none","summary":"auto"},"input":[{"role":"user","content":"hi"}]}`, + wantEffort: "low", + }, + { + name: "collapsed update cannot restore none", + body: `{"model":"gpt-6.1-sol","reasoning":{"effort":"high","summary":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"none"}},{"role":"user","content":"hi"}]}`, + wantEffort: "low", + }, + { + name: "user payload override remains final", + body: `{"model":"gpt-6.1-sol","reasoning":{"effort":"high","summary":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"none"}},{"role":"user","content":"hi"}]}`, + override: true, + wantEffort: "none", + }, + } { + t.Run(mode+"/"+tc.name, func(t *testing.T) { + captured := make(chan []byte, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if websocket.IsWebSocketUpgrade(r) { + upgrader := websocket.Upgrader{} + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + t.Errorf("upgrade websocket: %v", errUpgrade) + return + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close websocket: %v", errClose) + } + }() + _, body, errRead := conn.ReadMessage() + if errRead != nil { + t.Errorf("read websocket: %v", errRead) + return + } + captured <- body + if errWrite := conn.WriteMessage(websocket.TextMessage, []byte(completed)); errWrite != nil { + t.Errorf("write websocket: %v", errWrite) + } + return + } + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read request: %v", errRead) + return + } + captured <- body + if strings.HasSuffix(r.URL.Path, "/compact") { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"resp_effort","object":"response.compaction","usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+completed+"\n\n") + })) + defer server.Close() + + cfg := &config.Config{SDKConfig: config.SDKConfig{DisableImageGeneration: config.DisableImageGenerationAll}} + if tc.override { + protocol := "codex" + if mode == "compact" { + protocol = "openai-response" + } + cfg.Payload.Override = []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "gpt-6.1-sol", Protocol: protocol}}, + Params: map[string]any{"reasoning.effort": "none"}, + }} + } + auth := codexSIWCAuthForUpdateTest(server.URL) + req := cliproxyexecutor.Request{Model: "gpt-6.1-sol", Payload: []byte(tc.body)} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString("openai-response")} + executor := NewCodexExecutor(cfg) + var err error + switch mode { + case "stream": + var result *cliproxyexecutor.StreamResult + result, err = executor.ExecuteStream(context.Background(), auth, req, opts) + if err == nil { + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Errorf("stream chunk: %v", chunk.Err) + } + } + } + case "compact": + opts.Alt = "responses/compact" + _, err = executor.Execute(context.Background(), auth, req, opts) + case "websocket": + _, err = NewCodexWebsocketsExecutor(cfg).Execute(context.Background(), auth, req, opts) + case "websocket stream preparation": + prepared, errPrepare := NewCodexWebsocketsExecutor(cfg).prepareCodexWebsocketStream(context.Background(), auth, req, opts) + err = errPrepare + if err == nil { + captured <- prepared.clientBody + } + default: + _, err = executor.Execute(context.Background(), auth, req, opts) + } + if err != nil { + t.Fatalf("execute request: %v", err) + } + select { + case body := <-captured: + assertCodexSIWCUpdateStripped(t, body, tc.wantEffort) + if summary := ojson.GetBytes(body, "reasoning.summary").String(); summary != "auto" { + t.Fatalf("reasoning.summary = %q, want auto; body=%s", summary, body) + } + default: + t.Fatal("upstream request was not captured") + } + }) + } + } +} diff --git a/internal/runtime/executor/codex_executor_request.go b/internal/runtime/executor/codex_executor_request.go index 17b140cdbab..1acd7d79495 100644 --- a/internal/runtime/executor/codex_executor_request.go +++ b/internal/runtime/executor/codex_executor_request.go @@ -808,29 +808,61 @@ func ensureImageGenerationTool(body []byte, baseModel string, auth *cliproxyauth return doc.Bytes() } -func ensureImageGenerationToolDoc(doc *ojson.Doc, baseModel string, auth *cliproxyauth.Auth, headers http.Header) bool { - if doc == nil || isCodexResponsesLiteRequestDoc(doc, headers) || isCodexResponsesLiteModel(baseModel) { +func codexRequestHasReasoningForHostedImageDoc(doc *ojson.Doc, model string) bool { + return helps.CodexRequestHasReasoningForHostedImageDoc(doc, model) +} + +func isCodexResponsesLiteRequestForAuthDoc(doc *ojson.Doc, modelName string, auth *cliproxyauth.Auth, headers http.Header) bool { + return helps.CodexResponsesLiteRequestForAuthDoc(doc, modelName, auth, headers) +} + +func codexToolsAlreadyContainImageGenDoc(doc *ojson.Doc) bool { + if doc == nil { return false } - if strings.HasSuffix(baseModel, "spark") { + tools := doc.Get("tools") + if !tools.Exists() || !tools.IsArray() { return false } - if isCodexFreePlanAuth(auth) { - return false + for _, t := range tools.Array() { + if t.Get("type").String() == "image_generation" || isImageGenerationFunctionTool(t) { + return true + } } + return false +} +func appendImageGenerationToolDoc(doc *ojson.Doc) bool { + if doc == nil { + return false + } tools := doc.Get("tools") if !tools.Exists() || !tools.IsArray() { return doc.SetRawBytes("tools", imageGenToolArrayJSON) == nil } - for _, t := range tools.Array() { - if t.Get("type").String() == "image_generation" || isImageGenerationFunctionTool(t) { - return false - } - } return doc.SetRawBytes("tools.-1", imageGenToolJSON) == nil } +func ensureImageGenerationToolDoc(doc *ojson.Doc, baseModel string, auth *cliproxyauth.Auth, headers http.Header) bool { + if doc == nil || isCodexFreePlanAuth(auth) || codexToolsAlreadyContainImageGenDoc(doc) { + return false + } + modelName := strings.TrimSpace(thinking.ParseSuffix(baseModel).ModelName) + if modelName == "" { + modelName = strings.TrimSpace(thinking.ParseSuffix(doc.Get("model").String()).ModelName) + } + if isCodexResponsesLiteRequestForAuthDoc(doc, modelName, auth, headers) { + return false + } + if isCodexResponsesLiteModel(modelName) && codexRequestHasReasoningForHostedImageDoc(doc, baseModel) { + return false + } + if strings.HasSuffix(strings.ToLower(modelName), "spark") { + return false + } + return appendImageGenerationToolDoc(doc) +} + func resolveCodexGPTImage2BaseModel(cfg *config.Config) string { if cfg == nil { return codexOpenAIImagesMainModel diff --git a/internal/runtime/executor/codex_executor_siwc_darwin_test.go b/internal/runtime/executor/codex_executor_siwc_darwin_test.go new file mode 100644 index 00000000000..cca10dabd1d --- /dev/null +++ b/internal/runtime/executor/codex_executor_siwc_darwin_test.go @@ -0,0 +1,16 @@ +package executor + +import ( + "context" + "os" + "testing" + + codexauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" +) + +func TestMain(m *testing.M) { + codexauth.ReadSIWCSystemState = func(context.Context) ([]byte, error) { + return []byte("Current System Capabilities are: CPU Graphics Audio Network\nCurrent Power State: 4\n"), nil + } + os.Exit(m.Run()) +} diff --git a/internal/runtime/executor/codex_executor_siwc_renewal_test.go b/internal/runtime/executor/codex_executor_siwc_renewal_test.go new file mode 100644 index 00000000000..114d3122b63 --- /dev/null +++ b/internal/runtime/executor/codex_executor_siwc_renewal_test.go @@ -0,0 +1,115 @@ +package executor + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + codexauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func TestCodexExecutorSIWCRetainsRotatedTokensWhenScopeIsOmitted(t *testing.T) { + previousTransport := http.DefaultTransport + t.Cleanup(func() { http.DefaultTransport = previousTransport }) + cycle := 0 + http.DefaultTransport = roundTripperFunc(func(req *http.Request) (*http.Response, error) { + if errParse := req.ParseForm(); errParse != nil { + t.Fatal(errParse) + } + if got, want := req.Form.Get("refresh_token"), fmt.Sprintf("refresh-%d", cycle); got != want { + t.Fatalf("submitted refresh token = %q, want saved replacement %q", got, want) + } + cycle++ + body := fmt.Sprintf(`{"access_token":"access-%d","refresh_token":"refresh-%d","expires_in":3600}`, cycle, cycle) + if cycle == 1 { + doc := ojson.NewDocString(body) + if errSet := doc.Set("earliest_refresh_at", 946684800); errSet != nil { + t.Fatal(errSet) + } + body = doc.String() + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil + }) + dir := t.TempDir() + path := filepath.Join(dir, "codex.json") + const grantedScope = "openid chatgpt.tokens.use.direct" + initial := map[string]any{ + "type": "codex", "use_siwc": true, + "siwc": map[string]any{ + "access_token": "access-0", "refresh_token": "refresh-0", "client_id": "oaiapp_test", + "scope": grantedScope, "scopes": strings.Fields(grantedScope), + "expires_at": time.Now().Add(-time.Hour).Format(time.RFC3339), + "earliest_refresh_at": "1999-01-01T00:00:00Z", + }, + } + if errWrite := codexauth.WriteJSONFileAtomic(path, initial); errWrite != nil { + t.Fatal(errWrite) + } + executor := NewCodexExecutor(&config.Config{AuthDir: dir}) + metadata := initial + for wantCycle := 1; wantCycle <= 2; wantCycle++ { + auth := &cliproxyauth.Auth{ID: "codex.json", FileName: "codex.json", Provider: "codex", Metadata: metadata} + if _, errRefresh := executor.Refresh(cliproxyauth.WithForceRefresh(context.Background()), auth); errRefresh != nil { + t.Fatalf("renewal %d: %v", wantCycle, errRefresh) + } + raw, errRead := os.ReadFile(path) + if errRead != nil { + t.Fatal(errRead) + } + saved := ojson.ParseBytes(raw) + if got, want := saved.Get("siwc.refresh_token").String(), fmt.Sprintf("refresh-%d", wantCycle); got != want { + t.Fatalf("persisted refresh token = %q, want %q", got, want) + } + if saved.Get("siwc.scope").String() != grantedScope || saved.Get("siwc.scopes.1").String() != codexauth.SIWCDirectTokenScope { + t.Fatal("previously granted permissions were lost") + } + window := saved.Get("siwc.earliest_refresh_at") + if wantCycle == 1 && (window.Type != ojson.Number || window.Int() != 946684800) { + t.Fatalf("new server renewal window was not persisted: %s", window.Raw) + } + if wantCycle == 2 && window.Exists() { + t.Fatalf("previous token's renewal window survived rotation: %s", window.Raw) + } + metadata = saved.Value().(map[string]any) + } +} + +func TestCodexExecutorSIWCExplicitRefreshHonorsServerWindow(t *testing.T) { + previousTransport := http.DefaultTransport + t.Cleanup(func() { http.DefaultTransport = previousTransport }) + calls := 0 + http.DefaultTransport = roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + return &http.Response{StatusCode: http.StatusBadRequest, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"error":"invalid_grant"}`))}, nil + }) + for _, force := range []bool{false, true} { + t.Run(fmt.Sprintf("force=%t", force), func(t *testing.T) { + ctx := context.Background() + if force { + ctx = cliproxyauth.WithForceRefresh(ctx) + } + auth := &cliproxyauth.Auth{Provider: "codex", Metadata: map[string]any{ + "siwc": map[string]any{ + "access_token": "access", "refresh_token": "refresh", "client_id": "oaiapp_window", + "expires_at": time.Now().Add(-time.Hour).Format(time.RFC3339), + "earliest_refresh_at": time.Now().Add(time.Hour).Format(time.RFC3339), + }, + }} + if _, errRefresh := NewCodexExecutor(&config.Config{}).Refresh(ctx, auth); errRefresh != nil { + t.Fatalf("refresh before the server window: %v", errRefresh) + } + if calls != 0 { + t.Fatalf("sent %d token requests before the server window", calls) + } + }) + } +} diff --git a/internal/runtime/executor/codex_executor_stream.go b/internal/runtime/executor/codex_executor_stream.go index 32244fd7cf9..3223e020a16 100644 --- a/internal/runtime/executor/codex_executor_stream.go +++ b/internal/runtime/executor/codex_executor_stream.go @@ -25,13 +25,23 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au if opts.Alt == "responses/compact" { return nil, statusErr{code: http.StatusBadRequest, msg: "streaming not supported for /responses/compact"} } - if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&req, &opts); errExpand != nil { - return nil, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} - } if isCodexOpenAIImageRequest(opts) { + if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&req, &opts); errExpand != nil { + return nil, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } return e.executeOpenAIImageStream(ctx, auth, req, opts) } baseModel := thinking.ParseSuffix(req.Model).ModelName + isCompat, errExpand := e.expandCodexResponsesCompaction(auth, &req, &opts, baseModel) + if errExpand != nil { + return nil, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } + if e.shouldCompactCompatResponsesTrigger(isCompat, req, opts) { + return e.executeCodexResponsesCompactionStream(ctx, auth, req, opts) + } + if errPrev := rejectSyntheticCompactionPreviousResponseID(ctx, req.Payload); errPrev != nil { + return nil, errPrev + } apiKey, baseURL := codexCredsForRequest(ctx, auth, opts.Headers) if errSIWC := ensureCodexSIWCCredentialsForRequest(ctx, auth, apiKey, opts.Headers); errSIWC != nil { @@ -54,7 +64,6 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au originalPayloadSource = opts.OriginalRequest } originalPayload := originalPayloadSource - isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) targetModel := resolveResponsesSignatureTargetModel(baseModel, req, opts) originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntentContext(ctx, from, to, targetModel, originalPayload, req.Payload, true, isCompat) if err != nil { @@ -69,7 +78,7 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au return nil, err } - ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslated, req, opts)) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, e.Identifier(), baseModel, to.String(), "", originalTranslated, req, opts, auth)) _ = doc.Delete("previous_response_id") _ = doc.Delete("generate") _ = doc.Delete("prompt_cache_retention") @@ -92,7 +101,11 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au if !useSIWC { normalizeCodexInstructionsDoc(doc, preserveNativeOutput) if e.cfg == nil || e.cfg.DisableImageGeneration == config.DisableImageGenerationOff { - ensureImageGenerationToolDoc(doc, baseModel, auth, opts.Headers) + checkModel := req.Model + if strings.TrimSpace(checkModel) == "" { + checkModel = baseModel + } + ensureImageGenerationToolDoc(doc, checkModel, auth, opts.Headers) if !codexAuthUsesAPIKey(auth) { normalizeCodexImageGenerationToolsDoc(doc) } @@ -173,6 +186,7 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("codex executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if readErr != nil { helps.RecordAPIResponseError(ctx, e.cfg, readErr) return nil, readErr @@ -180,7 +194,6 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au if errClearReplay := clearCodexReasoningReplayOnInvalidSignature(ctx, replayScope, httpResp.StatusCode, data); errClearReplay != nil { return nil, errClearReplay } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) err = newCodexStatusErrWithHeadersAndCooling(httpResp.StatusCode, httpResp.Header, data, e.modelLevelCooling()) return nil, err diff --git a/internal/runtime/executor/codex_executor_tokens.go b/internal/runtime/executor/codex_executor_tokens.go index 22c73eb72af..e65d9a18f58 100644 --- a/internal/runtime/executor/codex_executor_tokens.go +++ b/internal/runtime/executor/codex_executor_tokens.go @@ -18,10 +18,10 @@ import ( func (e *CodexExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { ctx = helps.WithCodexCommentaryPolicy(ctx, e.cfg) - if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&req, &opts); errExpand != nil { + baseModel := thinking.ParseSuffix(req.Model).ModelName + if _, errExpand := e.expandCodexResponsesCompaction(auth, &req, &opts, baseModel); errExpand != nil { return cliproxyexecutor.Response{}, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} } - baseModel := thinking.ParseSuffix(req.Model).ModelName from := opts.SourceFormat responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) diff --git a/internal/runtime/executor/codex_openai_images.go b/internal/runtime/executor/codex_openai_images.go index 11e60c3d96b..7f11a7cdaed 100644 --- a/internal/runtime/executor/codex_openai_images.go +++ b/internal/runtime/executor/codex_openai_images.go @@ -140,11 +140,11 @@ func (e *CodexExecutor) executeOpenAIImage(ctx context.Context, auth *cliproxyau helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) err = newCodexStatusErrWithHeadersAndCooling(httpResp.StatusCode, httpResp.Header, data, e.modelLevelCooling()) @@ -248,11 +248,11 @@ func (e *CodexExecutor) executeOpenAIImageStream(ctx context.Context, auth *clip if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("codex executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return nil, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) err = newCodexStatusErrWithHeadersAndCooling(httpResp.StatusCode, httpResp.Header, data, e.modelLevelCooling()) return nil, err @@ -399,11 +399,11 @@ func (e *CodexExecutor) executeDirectOpenAIImage(ctx context.Context, auth *clip helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) err = newCodexStatusErrWithHeadersAndCooling(httpResp.StatusCode, httpResp.Header, data, e.modelLevelCooling()) @@ -470,11 +470,11 @@ func (e *CodexExecutor) executeDirectOpenAIImageStream(ctx context.Context, auth if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("codex executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return nil, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) err = newCodexStatusErrWithHeadersAndCooling(httpResp.StatusCode, httpResp.Header, data, e.modelLevelCooling()) return nil, err diff --git a/internal/runtime/executor/codex_refresh_outcome_test.go b/internal/runtime/executor/codex_refresh_outcome_test.go index 66d2b3ecc35..7e6b36cc548 100644 --- a/internal/runtime/executor/codex_refresh_outcome_test.go +++ b/internal/runtime/executor/codex_refresh_outcome_test.go @@ -3,11 +3,16 @@ package executor import ( "context" "io" + "net" "net/http" + "net/http/httptest" + "net/url" "os" "path/filepath" "strings" + "sync/atomic" "testing" + "time" codexauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" @@ -50,3 +55,102 @@ func TestCodexUnknownRefreshSurvivesForcedRefreshAndFileAlias(t *testing.T) { t.Fatalf("force refresh or file alias replayed unresolved grant: calls=%d, want 1", calls) } } + +func TestCodexExecutorPreSendRefreshFailureRecoversOnLaterAttempt(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "codex.json") + now := time.Now().UTC().Truncate(time.Second) + expiry := now.Add(48 * time.Hour) + initialJSON := `{"type":"codex","access_token":"valid-access","refresh_token":"wake-ordinary-grant","expired":"` + expiry.Format(time.RFC3339) + `"}` + if errWrite := os.WriteFile(path, []byte(initialJSON), 0o600); errWrite != nil { + t.Fatal(errWrite) + } + + var serverCalls atomic.Int32 + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + serverCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"rotated-access","refresh_token":"rotated-grant","expires_in":86400}`) + })) + t.Cleanup(server.Close) + parsedServer, errParse := url.Parse(server.URL) + if errParse != nil { + t.Fatal(errParse) + } + + closedListener, errListen := net.Listen("tcp", "127.0.0.1:0") + if errListen != nil { + t.Fatal(errListen) + } + closedAddr := closedListener.Addr().String() + if errClose := closedListener.Close(); errClose != nil { + t.Fatal(errClose) + } + + var failDial atomic.Bool + failDial.Store(true) + baseTransport := server.Client().Transport.(*http.Transport).Clone() + baseTransport.TLSClientConfig = baseTransport.TLSClientConfig.Clone() + baseTransport.TLSClientConfig.ServerName = "127.0.0.1" + baseTransport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { + var dialer net.Dialer + if failDial.Load() { + return dialer.DialContext(ctx, network, closedAddr) + } + return dialer.DialContext(ctx, network, parsedServer.Host) + } + t.Cleanup(baseTransport.CloseIdleConnections) + + originalTransport := http.DefaultTransport + http.DefaultTransport = baseTransport + t.Cleanup(func() { http.DefaultTransport = originalTransport }) + + cfg := &config.Config{AuthDir: dir} + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(NewCodexExecutor(cfg)) + auth := &cliproxyauth.Auth{ + ID: "codex.json", + FileName: "codex.json", + Provider: "codex", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{cliproxyauth.AttributePath: path}, + Metadata: map[string]any{ + "type": "codex", + "access_token": "valid-access", + "refresh_token": "wake-ordinary-grant", + "expired": expiry.Format(time.RFC3339), + }, + } + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + + if _, errFirst := manager.ForceRefreshAuth(context.Background(), auth.ID); errFirst == nil { + t.Fatal("expected pre-send dial failure on first refresh") + } else if codexauth.IsRefreshOutcomeUnknown(errFirst) { + t.Fatalf("pre-send dial failure became permanent unknown outcome: %v", errFirst) + } + + afterFailure, _ := manager.GetByID(auth.ID) + if afterFailure.RequiresSignIn || afterFailure.RejectedRefreshToken != "" { + t.Fatalf("pre-send failure permanently rejected refresh token: RequiresSignIn=%v, RejectedRefreshToken=%q", afterFailure.RequiresSignIn, afterFailure.RejectedRefreshToken) + } + if afterFailure.NextRefreshAfter.IsZero() || !afterFailure.NextRefreshAfter.Before(now.Add(time.Hour)) { + t.Fatalf("NextRefreshAfter = %v, want short retry backoff rather than token expiry %v", afterFailure.NextRefreshAfter, expiry) + } + + failDial.Store(false) + refreshed, errSecond := manager.ForceRefreshAuth(context.Background(), auth.ID) + if errSecond != nil { + t.Fatalf("recovery refresh after network restored failed: %v", errSecond) + } + if got, _ := refreshed.Metadata["access_token"].(string); got != "rotated-access" { + t.Fatalf("refreshed access_token = %q, want rotated-access", got) + } + if got, _ := refreshed.Metadata["refresh_token"].(string); got != "rotated-grant" { + t.Fatalf("refreshed refresh_token = %q, want rotated-grant", got) + } + if serverCalls.Load() != 1 { + t.Fatalf("serverCalls = %d, want 1", serverCalls.Load()) + } +} diff --git a/internal/runtime/executor/codex_stream_bootstrap_buffering_test.go b/internal/runtime/executor/codex_stream_bootstrap_buffering_test.go index 965f5b0ad6f..6ab82d5fcf2 100644 --- a/internal/runtime/executor/codex_stream_bootstrap_buffering_test.go +++ b/internal/runtime/executor/codex_stream_bootstrap_buffering_test.go @@ -46,12 +46,12 @@ func codexTestAuth(baseURL string) *cliproxyauth.Auth { func codexTestRequest() (cliproxyexecutor.Request, cliproxyexecutor.Options) { return cliproxyexecutor.Request{ - Model: "gpt-5.6-terra", - Payload: []byte(`{"model":"gpt-5.6-terra","input":"hello"}`), - }, cliproxyexecutor.Options{ - SourceFormat: sdktranslator.FromString("openai-response"), - Stream: true, - } + Model: "gpt-5.6-terra", + Payload: []byte(`{"model":"gpt-5.6-terra","input":"hello"}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai-response"), + Stream: true, + } } // codexSSEServer streams the supplied event payloads as an HTTP 200 SSE response. @@ -92,11 +92,11 @@ func codexWebsocketServer(t *testing.T, frames ...string) *httptest.Server { func codexWebsocketRequest() (cliproxyexecutor.Request, cliproxyexecutor.Options) { return cliproxyexecutor.Request{ - Model: "gpt-5.6-terra", - Payload: []byte(`{"model":"gpt-5.6-terra","input":[{"type":"message","role":"user","content":"hello"}]}`), - }, cliproxyexecutor.Options{ - SourceFormat: sdktranslator.FromString("openai-response"), - } + Model: "gpt-5.6-terra", + Payload: []byte(`{"model":"gpt-5.6-terra","input":[{"type":"message","role":"user","content":"hello"}]}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString("openai-response"), + } } // drainChunks collects every payload and the first error from a stream result. diff --git a/internal/runtime/executor/codex_websockets_duplex.go b/internal/runtime/executor/codex_websockets_duplex.go index 41aa876a158..29cd1569f25 100644 --- a/internal/runtime/executor/codex_websockets_duplex.go +++ b/internal/runtime/executor/codex_websockets_duplex.go @@ -17,6 +17,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" log "github.com/sirupsen/logrus" ) @@ -42,10 +43,26 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( initialReporter *helps.UsageReporter, headers http.Header, unlock func(), ) *cliproxyexecutor.StreamResult { streamCtx, cancel := context.WithCancel(ctx) + // Duplex successors bypass dispatch, including automatic steering responses. + // Reader usage reporting uses ctx so post-cancel failure publishing still has + // request metadata; writer-side local HTTP calls derive from streamCtx so an + // upstream websocket disconnect cancels in-flight HTTP compaction immediately. + followupCtx := ctx + writerFollowupCtx := streamCtx + if selection := coreusage.HomeSelectionFromContext(ctx); selection != nil { + reusedSelection := *selection + reusedSelection.Reused = true + followupCtx = coreusage.WithHomeSelection(ctx, reusedSelection) + writerFollowupCtx = coreusage.WithHomeSelection(streamCtx, reusedSelection) + } out := make(chan cliproxyexecutor.StreamChunk) // This first frame was successfully written by ExecuteStream before handoff. log.Infof("codex websockets: request forwarded session=%s auth=%s url=%s event=response.create", sess.sessionID, auth.ID, initial.wsURL) - writeErrors := make(chan error, 1) + type writerFailure struct { + err error + preserveClassification bool + } + writeErrors := make(chan writerFailure, 1) // Explicit creates have their own request settings. Automatic successors // inherit the preceding response settings, just as they do upstream. var metadataMu sync.Mutex @@ -60,9 +77,27 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( acceptedSteers := make(map[string]codexAcceptedSteer) current := initial responseID := "" + latestTurnResponseID := "" responseSettings := make(map[string]*codexWebsocketPrepared) steeringSettings := make(map[string]*codexWebsocketPrepared) var responseOrder []string + firstResponse := true + responseActive := false + terminalDeliveryPending := false + localCompactionDeliveredAny := false + localCompactionItems := make(map[string]string) + var localCompactionOrder []string + storeResponseSettingsLocked := func(id string, snapshot *codexWebsocketPrepared) { + if id == "" || snapshot == nil { + return + } + responseSettings[id] = snapshot + responseOrder = append(responseOrder, id) + if len(responseOrder) > 16 { + delete(responseSettings, responseOrder[0]) + responseOrder = responseOrder[1:] + } + } releaseSteeringSettings := func(parent string) { for _, target := range unacknowledgedSteers { if target.parent == parent { @@ -128,17 +163,32 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } go func() { defer close(writerDone) - fail := func(err error) { + failWithClassification := func(err error, preserveClassification bool) { select { - case writeErrors <- err: + case writeErrors <- writerFailure{err: err, preserveClassification: preserveClassification}: default: } cancel() } - reject := func(message string) bool { + fail := func(err error) { failWithClassification(err, false) } + emitDuplexError := func(status int, errType, code, param, message, eventID string) bool { + errBody := map[string]string{ + "type": errType, + "message": message, + } + if code != "" { + errBody["code"] = code + } + if param != "" { + errBody["param"] = param + } + if eventID != "" { + errBody["event_id"] = eventID + } payload, _ := json.Marshal(map[string]any{ - "type": "error", "status": http.StatusBadRequest, - "error": map[string]string{"type": "invalid_request_error", "message": message}, + "type": "error", + "status": status, + "error": errBody, }) // Reader cleanup joins this writer before closing out. Cancellation must // also release a local error blocked behind a disconnected downstream. @@ -150,6 +200,19 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( return false } } + reject := func(message string) bool { + return emitDuplexError(http.StatusBadRequest, "invalid_request_error", "", "", message, "") + } + rejectPreviousResponseNotFound := func(eventID string) bool { + return emitDuplexError( + http.StatusConflict, + "invalid_request_error", + "previous_response_not_found", + "previous_response_id", + "Previous response is not available on this websocket; resend the full conversation input without previous_response_id", + eventID, + ) + } initialModel := "" if initial != nil { initialModel = strings.TrimSpace(ojson.GetBytesNoCopy(initial.originalPayload, "model").String()) @@ -298,13 +361,15 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( if allowed, keepOpen := authorizePayload(payload, false); !allowed { return keepOpen } + eventID := strings.Clone(strings.TrimSpace(ojson.GetBytesNoCopy(payload, "event_id").String())) metadataMu.Lock() isAppend := ojson.GetBytesNoCopy(payload, "type").String() == "response.append" prevID := strings.TrimSpace(ojson.GetBytesNoCopy(payload, "previous_response_id").String()) - if isAppend && prevID == "" && responseID != "" { - prevID = responseID + if isAppend && prevID == "" && latestTurnResponseID != "" { + prevID = latestTurnResponseID payload, _ = ojson.SetBytes(payload, "previous_response_id", prevID) } + localCompactionItem, hasLocalCompactionParent := localCompactionItems[prevID] wrongParent := false for _, accepted := range acceptedSteers { if accepted.successorID == "" && prevID != waitingParent { @@ -318,6 +383,9 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } return true } + if prevID != "" && !hasLocalCompactionParent && helps.RecognizedResponsesCompactionResponseID(prevID) { + return rejectPreviousResponseNotFound(eventID) + } model := strings.TrimSpace(ojson.GetBytesNoCopy(payload, "model").String()) if model != "" && model != req.Model && model != boundModel { fail(cliproxyexecutor.NewUpstreamWebsocketReplayRequiredError()) @@ -329,11 +397,9 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( if !allowed { return keepOpen } + model = req.Model if model == "" { - model = req.Model - if model == "" { - model = boundModel - } + model = boundModel } createDoc := ojson.NewDoc(payload) _ = createDoc.Set("model", model) @@ -362,11 +428,187 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( _ = createDoc.SetRawBytes("instructions", []byte(inst.Raw)) } } + if hasLocalCompactionParent { + if !createDoc.Get("instructions").Exists() { + metadataMu.Lock() + parentSettings := responseSettings[prevID] + metadataMu.Unlock() + targetSettings := parentSettings + if targetSettings == nil { + targetSettings = initial + } + var inst ojson.Result + if targetSettings != nil { + inst = ojson.GetBytesNoCopy(targetSettings.clientBody, "instructions") + if !inst.Exists() { + inst = ojson.GetBytesNoCopy(targetSettings.originalPayload, "instructions") + } + } + if !inst.Exists() && initial != nil { + inst = ojson.GetBytesNoCopy(initial.clientBody, "instructions") + if !inst.Exists() { + inst = ojson.GetBytesNoCopy(initial.originalPayload, "instructions") + } + } + if inst.Exists() { + _ = createDoc.SetRawBytes("instructions", []byte(inst.Raw)) + } + } + existingInput := createDoc.Get("input") + rebuiltItems := make([]string, 0, 2) + rebuiltItems = append(rebuiltItems, localCompactionItem) + switch { + case existingInput.IsArray(): + for _, item := range existingInput.Array() { + rebuiltItems = append(rebuiltItems, item.Raw) + } + case existingInput.Type == ojson.String: + message := ojson.NewDocString(`{"type":"message","role":"user"}`) + _ = message.Set("content", existingInput.String()) + rebuiltItems = append(rebuiltItems, message.String()) + case existingInput.Exists(): + return emitDuplexError(http.StatusBadRequest, "invalid_request_error", "", "input", "input must be a string or an array", eventID) + } + _ = createDoc.SetRaw("input", "["+strings.Join(rebuiltItems, ",")+"]") + _ = createDoc.Delete("previous_response_id") + _ = createDoc.Set("type", "response.create") + isAppend = false + prevID = "" + } payload = createDoc.Bytes() nextReq, nextOpts := req, opts + // Dispatch already resolved aliases to the bound upstream execution model. + // The client model above is only used for authorization and consistency. + nextReq.Model = req.Model nextReq.Payload = payload nextOpts.OriginalRequest = payload nextOpts.Headers = turnHeaders + turnBaseModel := thinking.ParseSuffix(nextReq.Model).ModelName + if turnIsCompat := e.resolveCodexModelIsCompat(auth, nextReq, turnBaseModel); e.shouldCompactCompatResponsesTrigger(turnIsCompat, nextReq, nextOpts) { + if _, errExpand := e.expandCodexResponsesCompaction(auth, &nextReq, &nextOpts, turnBaseModel); errExpand != nil { + return emitDuplexError(http.StatusBadRequest, "invalid_request_error", "", "", errExpand.Error(), eventID) + } + if prevID != "" || isAppend { + return rejectPreviousResponseNotFound(eventID) + } + if !helps.HasResponsesCompactionConversationInput(nextReq.Payload) { + return emitDuplexError(http.StatusBadRequest, "invalid_request_error", "", "", "local summary compaction requires non-empty conversation input", eventID) + } + if !waitFor(func() bool { + ready := !firstResponse && !responseActive && !terminalDeliveryPending && len(pending) == 0 && len(unacknowledgedSteers) == 0 && !automaticActive + if e.duplexStateObserver != nil { + e.duplexStateObserver("compaction_wait", ready) + } + return ready + }) { + return false + } + if !cliproxyexecutor.WebsocketAuthEnabled(streamCtx, auth.ID) { + fail(fmt.Errorf("websocket credential is no longer enabled")) + return false + } + // Build business settings snapshot from the turn request (before summary + // prompt preparation strips tools/fields) so subsequent response.append + // or synthetic-parent continuations inherit this turn's instructions. + snapshotDoc := ojson.NewDoc([]byte("{}")) + if reasoning := ojson.GetBytesNoCopy(nextReq.Payload, "reasoning"); reasoning.Exists() { + _ = snapshotDoc.SetRawBytes("reasoning", []byte(reasoning.Raw)) + } + if inst := ojson.GetBytesNoCopy(nextReq.Payload, "instructions"); inst.Exists() { + _ = snapshotDoc.SetRawBytes("instructions", []byte(inst.Raw)) + } else if initial != nil { + initInst := ojson.GetBytesNoCopy(initial.clientBody, "instructions") + if !initInst.Exists() { + initInst = ojson.GetBytesNoCopy(initial.originalPayload, "instructions") + } + if initInst.Exists() { + _ = snapshotDoc.SetRawBytes("instructions", []byte(initInst.Raw)) + } + } + if serviceTier := ojson.GetBytesNoCopy(nextReq.Payload, "service_tier"); serviceTier.Exists() { + _ = snapshotDoc.SetRawBytes("service_tier", []byte(serviceTier.Raw)) + } + compactionSettings := &codexWebsocketPrepared{ + to: sdktranslator.FromString("codex"), + clientBody: snapshotDoc.Bytes(), + } + metadataMu.Lock() + localCompactionDeliveredAny = false + metadataMu.Unlock() + compactionResp, errCompact := e.CodexExecutor.executeCodexResponsesCompaction(writerFollowupCtx, auth, nextReq, nextOpts) + if errCompact != nil { + if streamCtx.Err() != nil { + return false + } + var statusHolder interface{ StatusCode() int } + status := http.StatusBadGateway + if errors.As(errCompact, &statusHolder) && statusHolder.StatusCode() > 0 { + status = statusHolder.StatusCode() + } + if status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusTooManyRequests { + failWithClassification(errCompact, true) + return false + } + errType := "server_error" + if status >= 400 && status < 500 { + errType = "invalid_request_error" + } + return emitDuplexError(status, errType, "", "", errCompact.Error(), eventID) + } + chunks, errChunks := helps.BuildResponsesCompactionStreamChunksFromResponse(turnBaseModel, compactionResp.Payload) + if errChunks != nil { + return emitDuplexError(http.StatusBadGateway, "server_error", "", "", errChunks.Error(), eventID) + } + compactedRespID := "" + compactedItemRaw := "" + for i := len(chunks) - 1; i >= 0; i-- { + for _, line := range bytes.Split(chunks[i], []byte("\n")) { + trimmedLine := bytes.TrimSpace(line) + if !bytes.HasPrefix(trimmedLine, dataTag) { + continue + } + eventData := bytes.TrimSpace(trimmedLine[len(dataTag):]) + if ojson.GetBytesNoCopy(eventData, "type").String() == "response.completed" { + compactedRespID = strings.Clone(strings.TrimSpace(ojson.GetBytesNoCopy(eventData, "response.id").String())) + compactedItemRaw = strings.Clone(ojson.GetBytesNoCopy(eventData, "response.output.0").Raw) + break + } + } + if compactedRespID != "" { + break + } + } + if compactedRespID != "" && compactedItemRaw != "" { + metadataMu.Lock() + latestTurnResponseID = compactedRespID + waitingParent = "" + storeResponseSettingsLocked(compactedRespID, compactionSettings) + localCompactionItems[compactedRespID] = compactedItemRaw + localCompactionOrder = append(localCompactionOrder, compactedRespID) + if len(localCompactionOrder) > 16 { + delete(localCompactionItems, localCompactionOrder[0]) + localCompactionOrder = localCompactionOrder[1:] + } + metadataMu.Unlock() + } + for idx, chunk := range chunks { + select { + case out <- cliproxyexecutor.StreamChunk{Payload: chunk}: + if idx == 0 { + metadataMu.Lock() + localCompactionDeliveredAny = true + metadataMu.Unlock() + } + case <-streamCtx.Done(): + return false + } + } + metadataMu.Lock() + localCompactionDeliveredAny = false + metadataMu.Unlock() + consumedPayload = nil + return true + } prepared, errPrepare := e.prepareCodexWebsocketStream(streamCtx, auth, nextReq, nextOpts) if errPrepare != nil { fail(errPrepare) @@ -477,10 +719,19 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( steerOpts := opts steerOpts.OriginalRequest = payload steerOpts.Headers = steerHeaders - if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&steerReq, &steerOpts); errExpand != nil { + steerBaseModel := thinking.ParseSuffix(req.Model).ModelName + steerIsCompat, errExpand := e.expandCodexResponsesCompaction(auth, &steerReq, &steerOpts, steerBaseModel) + if errExpand != nil { fail(statusErr{code: http.StatusBadRequest, msg: errExpand.Error()}) return } + if steerIsCompat && helps.HasResponsesCompactionTrigger(steerReq.Payload) { + steerEventID := strings.Clone(strings.TrimSpace(ojson.GetBytesNoCopy(steerReq.Payload, "event_id").String())) + if !emitDuplexError(http.StatusBadRequest, "invalid_request_error", "", "", "compaction_trigger is not supported in response.steer", steerEventID) { + return + } + continue + } steerDoc := ojson.NewDoc(steerReq.Payload) if codexUseSIWCForRequest(ctx, auth, steerHeaders) { thinking.StripConfigurationUpdatesDoc(steerDoc) @@ -570,8 +821,6 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } } reporter := initialReporter - firstResponse := true - responseActive := false outputItems := make(map[int64][]byte) var outputFallback [][]byte // A business rejection followed by EOF with nothing outstanding stays terminal. @@ -579,14 +828,20 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( for { kind, payload, errRead := readCodexWebsocketMessage(streamCtx, sess, conn, readCh) if errRead != nil { + preserveClassification := false select { - case errWrite := <-writeErrors: - errRead = errWrite + case failure := <-writeErrors: + errRead = failure.err + preserveClassification = failure.preserveClassification default: } if ctx.Err() == nil { var connectionErr error = &codexDuplexConnectionError{cause: errRead} - if lost := codexWebsocketTurnTransportError(errRead); cliproxyexecutor.IsUpstreamWebsocketTurnError(lost) { + if preserveClassification { + // HTTP business failures must retain credential/cooldown policy. + connectionErr = errRead + } + if lost := codexWebsocketTurnTransportError(errRead); !preserveClassification && cliproxyexecutor.IsUpstreamWebsocketTurnError(lost) { // Stop and join the writer first: after that nothing else is sent // upstream and the outcome of every operation is known. cancel() @@ -625,7 +880,10 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( for _, queued := range pendingCreates { abandon(queued, true) } - abandon(consumedPayload, true) + abandon(consumedPayload, !localCompactionDeliveredAny) + if !firstResponse && !responseActive && len(consumedPayload) > 0 && len(turnErr.Abandoned) == 0 && !localCompactionDeliveredAny { + turnErr.NotSent = true + } if !firstResponse && !responseActive && len(turnErr.Abandoned) > 0 { // No running turn owns the loss: the correlated errors report it. turnErr.Idle = true @@ -653,7 +911,9 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } payload = bytes.TrimSpace(payload) eventType := ojson.GetBytesNoCopy(payload, "type").String() + metadataMu.Lock() establishing := firstResponse && eventType == "response.created" + metadataMu.Unlock() if eventType == "response.created" { metadataMu.Lock() parent := strings.Clone(ojson.GetBytesNoCopy(payload, "response.previous_response_id").String()) @@ -687,6 +947,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( current, pending = pending[0], pending[1:] } responseID = createdResponseID + latestTurnResponseID = createdResponseID // Retain response settings, not request history or authorization headers. // In-flight steering pins its parent's settings independently of this window. snapshot := *current @@ -702,22 +963,18 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( _ = snapshotDoc.SetRawBytes("service_tier", []byte(serviceTier.Raw)) } snapshot.clientBody = snapshotDoc.Bytes() - responseSettings[responseID] = &snapshot - responseOrder = append(responseOrder, responseID) - if len(responseOrder) > 16 { - delete(responseSettings, responseOrder[0]) - responseOrder = responseOrder[1:] - } + storeResponseSettingsLocked(responseID, &snapshot) + wasFirstResponse := firstResponse + firstResponse = false + responseActive = true releaseSteeringSettings(parent) metadataMu.Unlock() wakeWriter() - if !firstResponse { - reporter = helps.NewExecutorUsageReporter(ctx, e, req.Model, auth) + if !wasFirstResponse { + reporter = helps.NewExecutorUsageReporter(followupCtx, e, req.Model, auth) reporter.SetTranslatedReasoningEffort(current.clientBody, current.to.String()) reporter.StartResponseTTFT() } - firstResponse = false - responseActive = true outputItems = make(map[int64][]byte) outputFallback = nil } @@ -729,10 +986,10 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( if strings.HasPrefix(eventType, "response.steer.") { id := strings.Clone(ojson.GetBytesNoCopy(payload, "steer.id").String()) parent := strings.Clone(ojson.GetBytesNoCopy(payload, "steer.previous_response_id").String()) + metadataMu.Lock() if parent == "" { parent = responseID } - metadataMu.Lock() consumeSubmission := func() codexSteerSubmission { for i, target := range unacknowledgedSteers { if target.parent == parent || target.parent == "" { @@ -764,7 +1021,10 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } continue } - if !firstResponse && (eventType == "error" || eventType == "response.failed") { + metadataMu.Lock() + isInitialResponse := firstResponse + metadataMu.Unlock() + if !isInitialResponse && (eventType == "error" || eventType == "response.failed") { var credentialErr error if wsErr, ok := parseCodexWebsocketErrorWithCooling(payload, e.modelLevelCooling()); ok { credentialErr = wsErr @@ -784,7 +1044,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } } eventPrepared, eventReporter := current, reporter - if !firstResponse && (eventType == "response.failed" || eventType == "error") { + if !isInitialResponse && (eventType == "response.failed" || eventType == "error") { failedID := ojson.GetBytesNoCopy(payload, "response.id").String() if failedID == "" { failedID = ojson.GetBytesNoCopy(payload, "response_id").String() @@ -797,11 +1057,13 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( ambiguous := failedID == "" && ((len(pending) > 0 && responseActive) || len(unacknowledgedSteers) > 0) if len(pending) > 0 && !currentFailure && !ambiguous { eventPrepared, pending = pending[0], pending[1:] - eventReporter = helps.NewExecutorUsageReporter(ctx, e, req.Model, auth) + eventReporter = helps.NewExecutorUsageReporter(followupCtx, e, req.Model, auth) eventReporter.SetTranslatedReasoningEffort(eventPrepared.clientBody, eventPrepared.to.String()) + terminalDeliveryPending = true } else if !ambiguous { responseActive = false automaticActive = false + terminalDeliveryPending = true } metadataMu.Unlock() wakeWriter() @@ -841,7 +1103,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( terminalBusinessRejection = errors.As(terminalErr, &status) && status.StatusCode() == http.StatusBadRequest helps.RecordAPIWebsocketError(ctx, e.cfg, "upstream_error", terminalErr) eventReporter.PublishFailure(ctx, terminalErr) - if firstResponse { + if isInitialResponse { send(cliproxyexecutor.StreamChunk{Err: terminalErr}) return } @@ -854,11 +1116,11 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( if endedID == "" { endedID = ojson.GetBytesNoCopy(payload, "response_id").String() } + metadataMu.Lock() if endedID == "" && !responseActive { // An id-less failure that ended the running response. endedID = responseID } - metadataMu.Lock() // A steer is complete once the response that consumed it has ended. for id, accepted := range acceptedSteers { if endedID != "" && accepted.successorID == endedID { @@ -869,11 +1131,11 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } if eventType == "response.completed" || eventType == "response.done" || eventType == "response.incomplete" { terminalBusinessRejection = false - responseActive = false metadataMu.Lock() + responseActive = false automaticActive = false + terminalDeliveryPending = true metadataMu.Unlock() - wakeWriter() payload = normalizeCodexWebsocketCompletion(payload) if !current.preserveNativeOutput { payload = patchCodexCompletedOutput(payload, outputItems, outputFallback) @@ -887,10 +1149,19 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( reporter.EnsurePublished(ctx) } publishCodexImageToolUsageWithOutputItems(ctx, reporter, current.clientBody, payload, outputItems, outputFallback) + if e.duplexStateObserver != nil { + e.duplexStateObserver("terminal_pending", false) + } } if !send(cliproxyexecutor.StreamChunk{Payload: helps.EnsureResponsesUsageDetails(payload), Incomplete: eventType == "response.incomplete"}) { return } + if isCodexTerminalEventType(eventType) { + metadataMu.Lock() + terminalDeliveryPending = false + metadataMu.Unlock() + wakeWriter() + } if establishing { // Deliver response.created before any locally generated error so the // downstream handler also observes successful bootstrap first. diff --git a/internal/runtime/executor/codex_websockets_duplex_health_test.go b/internal/runtime/executor/codex_websockets_duplex_health_test.go index fdd09734574..41dffaa6b3c 100644 --- a/internal/runtime/executor/codex_websockets_duplex_health_test.go +++ b/internal/runtime/executor/codex_websockets_duplex_health_test.go @@ -87,3 +87,87 @@ func TestCodexDuplexConnectionTimeoutDoesNotCoolHealthyAccount(t *testing.T) { t.Fatalf("connection timeout cooled the model: %+v", state.LastError) } } + +func TestCodexDuplexSummaryCredentialFailuresThroughManager(t *testing.T) { + for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusTooManyRequests} { + t.Run(http.StatusText(status), func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !websocket.IsWebSocketUpgrade(r) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"error":{"message":"summary credential rejected"}}`)) + return + } + c, errUpgrade := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUpgrade != nil { + t.Error(errUpgrade) + return + } + defer func() { + if errClose := c.Close(); errClose != nil { + t.Errorf("close upstream websocket: %v", errClose) + } + }() + if _, _, errRead := c.ReadMessage(); errRead != nil { + t.Error(errRead) + return + } + for _, payload := range []string{`{"type":"response.created","response":{"id":"r1"}}`, `{"type":"response.completed","response":{"id":"r1","output":[]}}`} { + if errWrite := c.WriteMessage(websocket.TextMessage, []byte(payload)); errWrite != nil { + t.Error(errWrite) + return + } + } + _, _, _ = c.ReadMessage() + })) + defer upstream.Close() + const id, model = "duplex-summary-health-account", "duplex-summary-health-model" + cfg := &config.Config{CodexKey: []config.CodexKey{{APIKey: "test-key", BaseURL: upstream.URL, Models: []config.CodexModel{{Name: model, IsCompat: true}}}}} + cfg.Codex.ResponseSteering = true + cfg.CodexResponseSteering = true + manager := auth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + exec := NewCodexAutoExecutor(cfg) + manager.RegisterExecutor(exec) + defer exec.CloseExecutionSession("summary-health-session") + if _, errRegister := manager.Register(context.Background(), &auth.Auth{ID: id, Provider: "codex", Status: auth.StatusActive, Attributes: map[string]string{"api_key": "test-key", "base_url": upstream.URL, "websockets": "true"}}); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(id, "codex", []*registry.ModelInfo{{ID: model, IsCompat: true}}) + defer registry.GetGlobalRegistry().UnregisterClient(id) + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + input := make(chan core.WebsocketInput, 1) + ctx = core.WithWebsocketInput(core.WithDownstreamWebsocket(ctx), input) + stream, errStream := manager.ExecuteStream(ctx, []string{"codex"}, core.Request{Model: model, Payload: []byte(`{"model":"duplex-summary-health-model","input":[]}`)}, core.Options{SourceFormat: translator.FormatOpenAIResponse, Metadata: map[string]any{core.ExecutionSessionMetadataKey: "summary-health-session"}}) + if errStream != nil { + t.Fatal(errStream) + } + var terminal error + for chunk := range stream.Chunks { + if ojson.GetBytes(chunk.Payload, "type").String() == "response.completed" { + input <- core.WebsocketInput{Payload: []byte(`{"type":"response.create","input":[{"role":"user","content":"history"},{"type":"compaction_trigger"}]}`)} + } + if chunk.Err != nil { + terminal = chunk.Err + } + } + var statusHolder interface{ StatusCode() int } + if !errors.As(terminal, &statusHolder) || statusHolder.StatusCode() != status { + t.Fatalf("terminal error = %v, want HTTP %d", terminal, status) + } + var scoped interface{ IsRequestScoped() bool } + if errors.As(terminal, &scoped) && scoped.IsRequestScoped() { + t.Fatalf("credential failure incorrectly classified as request-scoped: %v", terminal) + } + current, ok := manager.GetByID(id) + if !ok { + t.Fatal("account disappeared") + } + state := current.ModelStates[model] + if state == nil || state.LastError == nil || state.LastError.HTTPStatus != status || state.LastError.IsRequestScoped() || !state.Unavailable || state.NextRetryAfter.IsZero() { + t.Fatalf("HTTP %d did not retain credential failure state: %+v", status, state) + } + }) + } +} diff --git a/internal/runtime/executor/codex_websockets_duplex_test.go b/internal/runtime/executor/codex_websockets_duplex_test.go index 4790bad0306..1366b1fa8e8 100644 --- a/internal/runtime/executor/codex_websockets_duplex_test.go +++ b/internal/runtime/executor/codex_websockets_duplex_test.go @@ -15,6 +15,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/config" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" core "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) @@ -95,6 +96,11 @@ func TestCodexDuplexSteeringLifecycle(t *testing.T) { defer cancel() input := make(chan core.WebsocketInput, 8) ctx = core.WithWebsocketInput(core.WithDownstreamWebsocket(ctx), input) + ctx = coreusage.WithRequestedModelAlias(ctx, t.Name()) + ctx = coreusage.WithHomeSelection(ctx, coreusage.HomeSelection{Model: "home-route"}) + capture := &codexResponseModelUsageCapture{alias: t.Name(), records: make(chan coreusage.Record, 8)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { coreusage.RegisterNamedPlugin(t.Name(), codexResponseModelNoopUsagePlugin{}) }) exec := NewCodexWebsocketsExecutor(&config.Config{Codex: config.CodexConfig{ResponseSteering: true}}) exec.store = &codexWebsocketSessionStore{sessions: make(map[string]*codexWebsocketSession)} auth := &cliproxyauth.Auth{ID: "A", Provider: "codex", Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL, "websockets": "true"}} @@ -161,6 +167,17 @@ func TestCodexDuplexSteeringLifecycle(t *testing.T) { if connections.Load() != 1 { t.Fatalf("connections=%d", connections.Load()) } + ids := make(map[string]bool) + for turn := range 3 { + record := capture.await(t) + if record.HomeSelection == nil || record.HomeSelection.Reused != (turn > 0) || record.HomeSelection.Model != "home-route" { + t.Fatalf("turn %d accounting=%+v", turn, record.HomeSelection) + } + if ids[record.RequestID] { + t.Fatal("duplex responses share an execution ID") + } + ids[record.RequestID] = true + } for _, key := range []string{"accepted", "boundary", "pending", "successor", "failed"} { if !seen[key] { t.Fatalf("missing %s", key) @@ -574,3 +591,67 @@ func TestCodexDuplexQueuedCreateDoesNotBlockSubsequentSteer(t *testing.T) { t.Fatal("server did not finish") } } + +func TestCodexDuplexNativeAliasContinuationUsesRealModel(t *testing.T) { + frames := make(chan []byte, 3) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, errUpgrade := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUpgrade != nil { + t.Error(errUpgrade) + return + } + defer func() { + if errClose := c.Close(); errClose != nil { + t.Errorf("close upstream websocket: %v", errClose) + } + }() + for i := 0; i < 3; i++ { + _, frame, errRead := c.ReadMessage() + if errRead != nil { + return + } + frames <- frame + for _, payload := range []string{`{"type":"response.created","response":{"id":"r1"}}`, `{"type":"response.completed","response":{"id":"r1","output":[]}}`} { + if errWrite := c.WriteMessage(websocket.TextMessage, []byte(payload)); errWrite != nil { + t.Error(errWrite) + return + } + } + } + _, _, _ = c.ReadMessage() + })) + defer upstream.Close() + cfg := &config.Config{CodexKey: []config.CodexKey{{APIKey: "test-key", BaseURL: upstream.URL, Models: []config.CodexModel{{Name: "real-model", IsCompat: false}}}}} + cfg.Codex.ResponseSteering = true + cfg.CodexResponseSteering = true + exec := NewCodexWebsocketsExecutor(cfg) + defer exec.CloseExecutionSession("native-alias-session") + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + input := make(chan core.WebsocketInput, 1) + ctx = core.WithWebsocketInput(core.WithDownstreamWebsocket(ctx), input) + stream, errStream := exec.ExecuteStream(ctx, &cliproxyauth.Auth{ID: "native-alias-account", Provider: "codex", Attributes: map[string]string{"api_key": "test-key", "base_url": upstream.URL, "websockets": "true"}}, core.Request{Model: "real-model", Payload: []byte(`{"model":"client-alias","input":[]}`)}, core.Options{SourceFormat: sdktranslator.FromString("codex"), Metadata: map[string]any{core.ExecutionSessionMetadataKey: "native-alias-session"}}) + if errStream != nil { + t.Fatal(errStream) + } + for turn := 0; turn < 3; turn++ { + for { + chunk, ok := <-stream.Chunks + if !ok || chunk.Err != nil { + t.Fatalf("turn %d stream closed or failed: %v", turn, chunk.Err) + } + if ojson.GetBytes(chunk.Payload, "type").String() == "response.completed" { + break + } + } + frame := <-frames + if got := ojson.GetBytes(frame, "model").String(); got != "real-model" { + t.Fatalf("turn %d model = %q, want real-model; frame=%s", turn, got, frame) + } + if turn == 0 { + input <- core.WebsocketInput{Payload: []byte(`{"type":"response.create","model":"client-alias","previous_response_id":"r1","input":"follow up"}`)} + } else if turn == 1 { + input <- core.WebsocketInput{Payload: []byte(`{"type":"response.create","previous_response_id":"r1","input":"follow up again"}`)} + } + } +} diff --git a/internal/runtime/executor/codex_websockets_errors.go b/internal/runtime/executor/codex_websockets_errors.go index 718d56b1523..0e30d980804 100644 --- a/internal/runtime/executor/codex_websockets_errors.go +++ b/internal/runtime/executor/codex_websockets_errors.go @@ -194,15 +194,50 @@ func recordAPIWebsocketHandshake(ctx context.Context, cfg *config.Config, resp * } func websocketHandshakeBody(resp *http.Response) []byte { + body, _ := websocketHandshakeBodyWithReadErr(resp) + return body +} + +func websocketHandshakeBodyWithReadErr(resp *http.Response) ([]byte, error) { if resp == nil || resp.Body == nil { - return nil + return nil, nil } - body, _ := io.ReadAll(resp.Body) + body, errRead := io.ReadAll(resp.Body) closeHTTPResponseBody(resp, "codex websockets executor: close handshake response body error") if len(body) == 0 { - return nil + return nil, errRead } - return body + return body, errRead +} + +func recordWebsocketUpgradeRejection(ctx context.Context, cfg *config.Config, wsReqLog helps.UpstreamRequestLog, resp *http.Response) []byte { + bodyErr, errRead := websocketHandshakeBodyWithReadErr(resp) + if resp != nil { + helps.RecordAPIWebsocketUpgradeRejection(ctx, cfg, websocketUpgradeRequestLog(wsReqLog), resp.StatusCode, resp.Header.Clone(), bodyErr) + if errRead != nil { + helps.RecordAPIResponseError(ctx, cfg, errRead) + } + } + return bodyErr +} + +func recordWebsocketDialFailure(ctx context.Context, cfg *config.Config, wsReqLog helps.UpstreamRequestLog, resp *http.Response, errDial error) []byte { + bodyErr := recordWebsocketUpgradeRejection(ctx, cfg, wsReqLog, resp) + helps.RecordAPIWebsocketError(ctx, cfg, "dial", errDial) + return bodyErr +} + +func recordWebsocketDialRetryFailure(ctx context.Context, cfg *config.Config, wsReqLog helps.UpstreamRequestLog, resp *http.Response, errDial error) []byte { + if resp != nil { + bodyErr := recordWebsocketUpgradeRejection(ctx, cfg, wsReqLog, resp) + helps.RecordAPIWebsocketError(ctx, cfg, "dial_retry", errDial) + return bodyErr + } + if cfg != nil && !cfg.CommercialMode && !cfg.RequestLog { + helps.RecordAPIRequest(ctx, cfg, websocketUpgradeRequestLog(wsReqLog)) + } + helps.RecordAPIWebsocketError(ctx, cfg, "dial_retry", errDial) + return nil } func closeHTTPResponseBody(resp *http.Response, logPrefix string) { diff --git a/internal/runtime/executor/codex_websockets_execute.go b/internal/runtime/executor/codex_websockets_execute.go index f56a5dd4d0d..e1b44ebbcd0 100644 --- a/internal/runtime/executor/codex_websockets_execute.go +++ b/internal/runtime/executor/codex_websockets_execute.go @@ -22,14 +22,21 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut ctx = context.Background() } ctx = helps.WithCodexCommentaryPolicy(ctx, e.cfg) - if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&req, &opts); errExpand != nil { - return resp, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} - } if opts.Alt == "responses/compact" { return e.CodexExecutor.executeCompact(ctx, auth, req, opts) } baseModel := thinking.ParseSuffix(req.Model).ModelName + isCompat, errExpand := e.expandCodexResponsesCompaction(auth, &req, &opts, baseModel) + if errExpand != nil { + return resp, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } + if e.shouldCompactCompatResponsesTrigger(isCompat, req, opts) { + return e.CodexExecutor.executeCodexResponsesCompaction(ctx, auth, req, opts) + } + if errPrev := rejectSyntheticCompactionPreviousResponseID(ctx, req.Payload); errPrev != nil { + return resp, errPrev + } apiKey, baseURL := codexCredsForRequest(ctx, auth, opts.Headers) if errSIWC := ensureCodexSIWCCredentialsForRequest(ctx, auth, apiKey, opts.Headers); errSIWC != nil { return resp, errSIWC @@ -55,7 +62,6 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut originalPayloadSource = opts.OriginalRequest } originalPayload := originalPayloadSource - isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) targetModel := resolveResponsesSignatureTargetModel(baseModel, req, opts) originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntentContext(ctx, from, to, targetModel, originalPayload, req.Payload, false, isCompat) if err != nil { @@ -72,7 +78,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut instructionsResult := ojson.GetBytesNoCopy(req.Payload, "instructions") hasExplicitInstructions := instructionsResult.Exists() && strings.TrimSpace(instructionsResult.String()) != "" - ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, "codex-websockets", baseModel, to.String(), "", originalTranslated, req, opts)) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, "codex-websockets", baseModel, to.String(), "", originalTranslated, req, opts, auth)) helps.SetStringIfDifferentDoc(doc, "model", baseModel) helps.SetBoolIfDifferentDoc(doc, "stream", true) _ = doc.Delete("prompt_cache_retention") @@ -81,7 +87,11 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut if !useSIWC { normalizeCodexInstructionsDoc(doc, nativeRequest) if e.cfg == nil || e.cfg.DisableImageGeneration == config.DisableImageGenerationOff { - ensureImageGenerationToolDoc(doc, baseModel, auth, opts.Headers) + checkModel := req.Model + if strings.TrimSpace(checkModel) == "" { + checkModel = baseModel + } + ensureImageGenerationToolDoc(doc, checkModel, auth, opts.Headers) if !codexAuthUsesAPIKey(auth) { normalizeCodexImageGenerationToolsDoc(doc) } @@ -181,10 +191,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut conn, closer, respHS, errDial = e.ensureUpstreamConnWithSIWC(dialCtx, auth, sess, authID, wsURL, wsHeaders, useSIWC) } if errDial != nil { - bodyErr := websocketHandshakeBody(respHS) - if respHS != nil { - helps.RecordAPIWebsocketUpgradeRejection(ctx, e.cfg, websocketUpgradeRequestLog(wsReqLog), respHS.StatusCode, respHS.Header.Clone(), bodyErr) - } + bodyErr := recordWebsocketDialFailure(ctx, e.cfg, wsReqLog, respHS, errDial) if respHS != nil && respHS.StatusCode == http.StatusUpgradeRequired { if opts.ExecutionLifecycle == nil && !cliproxyexecutor.DownstreamWebsocket(ctx) { return e.CodexExecutor.Execute(ctx, auth, req, opts) @@ -200,7 +207,6 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut if respHS != nil && respHS.StatusCode > 0 { return resp, newCodexStatusErrWithHeadersAndCooling(respHS.StatusCode, respHS.Header, bodyErr, e.modelLevelCooling()) } - helps.RecordAPIWebsocketError(ctx, e.cfg, "dial", errDial) return resp, errDial } if errBind := sess.bindExecutionLifecycle(opts, conn, closer, req.Model); errBind != nil { @@ -242,8 +248,8 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut return resp, cliproxyexecutor.NewUpstreamWebsocketReplayRequiredError() } e.invalidateUpstreamConn(sess, conn, "send_error", errSend) + helps.RecordAPIWebsocketError(ctx, e.cfg, "send", errSend) if !shouldRetryCodexWebsocketSend(errSend) { - helps.RecordAPIWebsocketError(ctx, e.cfg, "send", errSend) return resp, errSend } @@ -287,8 +293,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut return resp, errSendRetry } } else { - closeHTTPResponseBody(respHSRetry, "codex websockets executor: close handshake response body error") - helps.RecordAPIWebsocketError(ctx, e.cfg, "dial_retry", errDialRetry) + _ = recordWebsocketDialRetryFailure(ctx, e.cfg, wsReqLog, respHSRetry, errDialRetry) return resp, errDialRetry } } else { diff --git a/internal/runtime/executor/codex_websockets_executor.go b/internal/runtime/executor/codex_websockets_executor.go index a8114f9e865..199bb2d8f7a 100644 --- a/internal/runtime/executor/codex_websockets_executor.go +++ b/internal/runtime/executor/codex_websockets_executor.go @@ -24,6 +24,9 @@ type CodexWebsocketsExecutor struct { *CodexExecutor store *codexWebsocketSessionStore + + // Set before execution by concurrency tests; never mutated during a session. + duplexStateObserver func(event string, ready bool) } func NewCodexWebsocketsExecutor(cfg *config.Config) *CodexWebsocketsExecutor { diff --git a/internal/runtime/executor/codex_websockets_executor_test.go b/internal/runtime/executor/codex_websockets_executor_test.go index 2efdd414643..4d9d28fa730 100644 --- a/internal/runtime/executor/codex_websockets_executor_test.go +++ b/internal/runtime/executor/codex_websockets_executor_test.go @@ -9,6 +9,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync" "sync/atomic" "testing" "time" @@ -19,6 +20,7 @@ import ( "github.com/gorilla/websocket" internalcache "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" @@ -2641,15 +2643,18 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_WithSession(t *testing.T) { upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} serverPongCh := make(chan string, 1) inWriteHook := make(chan struct{}) + var inWriteHookOnce sync.Once pongDeliveredDuringWrite := make(chan struct{}) - requestSeen := make(chan struct{}) + var pongDeliveredOnce sync.Once + serverDone := make(chan struct{}) + defer close(serverDone) testWebsocketWritePayloadHook = func(conn *websocket.Conn) { - close(inWriteHook) + inWriteHookOnce.Do(func() { close(inWriteHook) }) // Wait until server confirms pong was received before allowing write to finish. select { case <-pongDeliveredDuringWrite: - case <-time.After(2 * time.Second): + case <-time.After(5 * time.Second): t.Error("timed out waiting for pong delivery while payload write was held in hook") } } @@ -2670,16 +2675,17 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_WithSession(t *testing.T) { // Start server reader loop so server processes control frames. readErrCh := make(chan error, 1) + payloadReceived := make(chan struct{}) go func() { - first := true + signaled := false for { if _, _, errRead := conn.ReadMessage(); errRead != nil { readErrCh <- errRead return } - if first { - first = false - close(requestSeen) + if !signaled { + signaled = true + close(payloadReceived) } } }() @@ -2687,13 +2693,13 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_WithSession(t *testing.T) { // Wait until client has entered writeMessage and is actively holding writeMu. select { case <-inWriteHook: - case <-time.After(2 * time.Second): + case <-time.After(5 * time.Second): t.Errorf("timed out waiting for client write hook") return } // Upstream sends Ping WHILE client payload write is in progress holding writeMu. - _ = conn.WriteControl(websocket.PingMessage, []byte("session-ping"), time.Now().Add(time.Second)) + _ = conn.WriteControl(websocket.PingMessage, []byte("session-ping"), time.Now().Add(5*time.Second)) // Server asserts Pong arrives while client write is still blocked in the hook. select { @@ -2701,25 +2707,25 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_WithSession(t *testing.T) { if got != "session-ping" { t.Errorf("unexpected pong payload: got %q, want session-ping", got) } - close(pongDeliveredDuringWrite) - case <-time.After(2 * time.Second): + pongDeliveredOnce.Do(func() { close(pongDeliveredDuringWrite) }) + case <-time.After(5 * time.Second): t.Errorf("pong was not received while payload write was in progress") return } - // The client payload write resumes once the pong is observed. Wait until the - // server has actually read that payload before sending the terminal event and - // closing the socket; otherwise the close races the in-flight client write. + // The held client write is released together with the pong. Wait until the + // request frame arrives before writing the terminal event and closing. select { - case <-requestSeen: - case <-time.After(2 * time.Second): - t.Errorf("timed out waiting for client request payload") + case <-payloadReceived: + case <-time.After(5 * time.Second): + t.Errorf("timed out waiting for client payload after pong") return } // Now send terminal response. respPayload := []byte(`{"type":"response.completed","response":{"id":"resp-1","status":"completed","output":[]}}`) _ = conn.WriteMessage(websocket.TextMessage, respPayload) + <-serverDone })) defer server.Close() @@ -2757,14 +2763,17 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_Sessionless(t *testing.T) { upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} serverPongCh := make(chan string, 1) inWriteHook := make(chan struct{}) + var inWriteHookOnce sync.Once pongDeliveredDuringWrite := make(chan struct{}) - requestSeen := make(chan struct{}) + var pongDeliveredOnce sync.Once + serverDone := make(chan struct{}) + defer close(serverDone) testWebsocketWritePayloadHook = func(conn *websocket.Conn) { - close(inWriteHook) + inWriteHookOnce.Do(func() { close(inWriteHook) }) select { case <-pongDeliveredDuringWrite: - case <-time.After(2 * time.Second): + case <-time.After(5 * time.Second): t.Error("timed out waiting for pong delivery while payload write was held in hook") } } @@ -2783,15 +2792,16 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_Sessionless(t *testing.T) { return nil }) + payloadReceived := make(chan struct{}) go func() { - first := true + signaled := false for { if _, _, errRead := conn.ReadMessage(); errRead != nil { return } - if first { - first = false - close(requestSeen) + if !signaled { + signaled = true + close(payloadReceived) } } }() @@ -2799,13 +2809,13 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_Sessionless(t *testing.T) { // Wait until client has entered writeMessage on sessionless path. select { case <-inWriteHook: - case <-time.After(2 * time.Second): + case <-time.After(5 * time.Second): t.Errorf("timed out waiting for client write hook") return } // Upstream sends Ping WHILE client payload write is in progress. - _ = conn.WriteControl(websocket.PingMessage, []byte("sessionless-ping"), time.Now().Add(time.Second)) + _ = conn.WriteControl(websocket.PingMessage, []byte("sessionless-ping"), time.Now().Add(5*time.Second)) // Server asserts Pong arrives while client write is still in progress. select { @@ -2813,24 +2823,22 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_Sessionless(t *testing.T) { if got != "sessionless-ping" { t.Errorf("unexpected pong payload: got %q, want sessionless-ping", got) } - close(pongDeliveredDuringWrite) - case <-time.After(2 * time.Second): + pongDeliveredOnce.Do(func() { close(pongDeliveredDuringWrite) }) + case <-time.After(5 * time.Second): t.Errorf("pong was not received while payload write was in progress on sessionless connection") return } - // The client payload write resumes once the pong is observed. Wait until the - // server has actually read that payload before sending the terminal event and - // closing the socket; otherwise the close races the in-flight client write. select { - case <-requestSeen: - case <-time.After(2 * time.Second): - t.Errorf("timed out waiting for client request payload") + case <-payloadReceived: + case <-time.After(5 * time.Second): + t.Errorf("timed out waiting for client payload after pong on sessionless connection") return } respPayload := []byte(`{"type":"response.completed","response":{"id":"resp-1","status":"completed","output":[]}}`) _ = conn.WriteMessage(websocket.TextMessage, respPayload) + <-serverDone })) defer server.Close() @@ -2865,14 +2873,17 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_NonstreamSessionless(t *testi upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} serverPongCh := make(chan string, 1) inWriteHook := make(chan struct{}) + var inWriteHookOnce sync.Once pongDeliveredDuringWrite := make(chan struct{}) - requestSeen := make(chan struct{}) + var pongDeliveredOnce sync.Once + serverDone := make(chan struct{}) + defer close(serverDone) testWebsocketWritePayloadHook = func(conn *websocket.Conn) { - close(inWriteHook) + inWriteHookOnce.Do(func() { close(inWriteHook) }) select { case <-pongDeliveredDuringWrite: - case <-time.After(2 * time.Second): + case <-time.After(5 * time.Second): t.Error("timed out waiting for pong delivery while nonstream payload write was held in hook") } } @@ -2891,15 +2902,16 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_NonstreamSessionless(t *testi return nil }) + payloadReceived := make(chan struct{}) go func() { - first := true + signaled := false for { if _, _, errRead := conn.ReadMessage(); errRead != nil { return } - if first { - first = false - close(requestSeen) + if !signaled { + signaled = true + close(payloadReceived) } } }() @@ -2907,13 +2919,13 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_NonstreamSessionless(t *testi // Wait until client has entered writeMessage on nonstream path. select { case <-inWriteHook: - case <-time.After(2 * time.Second): + case <-time.After(5 * time.Second): t.Errorf("timed out waiting for client write hook") return } // Upstream sends Ping WHILE client payload write is in progress. - _ = conn.WriteControl(websocket.PingMessage, []byte("nonstream-sessionless-ping"), time.Now().Add(time.Second)) + _ = conn.WriteControl(websocket.PingMessage, []byte("nonstream-sessionless-ping"), time.Now().Add(5*time.Second)) // Server asserts Pong arrives while client write is still in progress. select { @@ -2921,24 +2933,22 @@ func TestCodexWebsockets_KeepalivePingDuringUpload_NonstreamSessionless(t *testi if got != "nonstream-sessionless-ping" { t.Errorf("unexpected pong payload: got %q, want nonstream-sessionless-ping", got) } - close(pongDeliveredDuringWrite) - case <-time.After(2 * time.Second): + pongDeliveredOnce.Do(func() { close(pongDeliveredDuringWrite) }) + case <-time.After(5 * time.Second): t.Errorf("pong was not received while payload write was in progress on nonstream sessionless connection") return } - // The client payload write resumes once the pong is observed. Wait until the - // server has actually read that payload before sending the terminal event and - // closing the socket; otherwise the close races the in-flight client write. select { - case <-requestSeen: - case <-time.After(2 * time.Second): - t.Errorf("timed out waiting for client request payload") + case <-payloadReceived: + case <-time.After(5 * time.Second): + t.Errorf("timed out waiting for client payload after pong on nonstream sessionless connection") return } respPayload := []byte(`{"type":"response.completed","response":{"id":"resp-1","status":"completed","output":[]}}`) _ = conn.WriteMessage(websocket.TextMessage, respPayload) + <-serverDone })) defer server.Close() @@ -3338,3 +3348,208 @@ func TestCodexWebsockets_SendErrorLogsSessionObject(t *testing.T) { t.Fatalf("expected reason=send_error in log output, got: %s", logOutput) } } + +func TestCodexWebsocketReconnectUpgradeRejectionRecordedWhenRequestLogDisabled(t *testing.T) { + gin.SetMode(gin.TestMode) + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + + for _, stream := range []bool{false, true} { + name := "execute" + if stream { + name = "stream" + } + t.Run(name, func(t *testing.T) { + var dials atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if dials.Add(1) == 1 { + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + return + } + defer func() { _ = conn.Close() }() + for { + if _, _, errRead := conn.ReadMessage(); errRead != nil { + return + } + } + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Retry-After", "11") + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"error":{"message":"codex websocket reconnect forbidden"}}`)) + })) + defer server.Close() + + var writes atomic.Int32 + testWebsocketWritePayloadHook = func(conn *websocket.Conn) { + if writes.Add(1) == 1 { + _ = conn.SetWriteDeadline(time.Now().Add(-time.Second)) + } + } + defer func() { testWebsocketWritePayloadHook = nil }() + + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + exec := NewCodexWebsocketsExecutor(&config.Config{ + SDKConfig: config.SDKConfig{ + DisableImageGeneration: config.DisableImageGenerationAll, + }, + }) + auth := &cliproxyauth.Auth{ + ID: "codex-ws-reconnect", + Attributes: map[string]string{"api_key": "sk-test", "base_url": server.URL}, + } + req := cliproxyexecutor.Request{ + Model: "gpt-5.6-sol", + Payload: []byte(`{"model":"gpt-5.6-sol","input":[{"type":"message","role":"user","content":"reconnect"}]}`), + } + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Metadata: map[string]any{ + cliproxyexecutor.ExecutionSessionMetadataKey: "sess-codex-reconnect-" + name, + }, + } + + var errExec error + if stream { + _, errExec = exec.ExecuteStream(ctx, auth, req, opts) + } else { + _, errExec = exec.Execute(ctx, auth, req, opts) + } + if errExec == nil { + t.Fatal("expected reconnect upgrade rejection to fail") + } + + value, exists := ginCtx.Get(logging.DeferredAPIResponseContextKey) + if !exists { + t.Fatal("deferred API response was not recorded on codex websocket reconnect rejection") + } + deferred, ok := value.(logging.DeferredAPIResponse) + if !ok || deferred == nil { + t.Fatalf("deferred API response = %#v, want logging.DeferredAPIResponse", value) + } + rendered := string(deferred.RenderAPIResponse()) + for _, want := range []string{ + "=== API RESPONSE 1 ===", + "Status: 101", + "Error: send:", + "=== API RESPONSE 2 ===", + "Status: 403", + "Retry-After: 11", + `{"error":{"message":"codex websocket reconnect forbidden"}}`, + "Error: dial_retry:", + } { + if !strings.Contains(rendered, want) { + t.Fatalf("deferred API response missing %q:\n%s", want, rendered) + } + } + + var transportDials atomic.Int32 + transportServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if transportDials.Add(1) == 1 { + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + return + } + defer func() { _ = conn.Close() }() + for { + if _, _, errRead := conn.ReadMessage(); errRead != nil { + return + } + } + } + if hijacker, ok := w.(http.Hijacker); ok { + if rawConn, _, errHijack := hijacker.Hijack(); errHijack == nil { + _ = rawConn.Close() + } + } + })) + defer transportServer.Close() + + writes.Store(0) + subGinCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + subCtx := context.WithValue(context.Background(), "gin", subGinCtx) + subAuth := &cliproxyauth.Auth{ + ID: "codex-ws-transport-" + name, + Attributes: map[string]string{"api_key": "sk-test", "base_url": transportServer.URL}, + } + subOpts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + Metadata: map[string]any{ + cliproxyexecutor.ExecutionSessionMetadataKey: "sess-codex-transport-" + name, + }, + } + if stream { + _, errExec = exec.ExecuteStream(subCtx, subAuth, req, subOpts) + } else { + _, errExec = exec.Execute(subCtx, subAuth, req, subOpts) + } + if errExec == nil { + t.Fatal("expected transport reconnect failure") + } + subVal, ok := subGinCtx.Get(logging.DeferredAPIResponseContextKey) + if !ok { + t.Fatal("deferred API response missing on transport reconnect failure") + } + subRendered := string(subVal.(logging.DeferredAPIResponse).RenderAPIResponse()) + for _, want := range []string{ + "=== API RESPONSE 1 ===", + "Error: send:", + "=== API RESPONSE 2 ===", + "Error: dial_retry:", + } { + if !strings.Contains(subRendered, want) { + t.Fatalf("transport reconnect response missing %q:\n%s", want, subRendered) + } + } + + initServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hijacker, ok := w.(http.Hijacker) + if !ok { + t.Error("hijacker unsupported") + return + } + rawConn, rawBuf, errHijack := hijacker.Hijack() + if errHijack != nil { + t.Errorf("hijack: %v", errHijack) + return + } + _, _ = rawBuf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: invalid\r\n\r\n") + _ = rawBuf.Flush() + _ = rawConn.Close() + })) + defer initServer.Close() + + initGinCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + initCtx := context.WithValue(context.Background(), "gin", initGinCtx) + initAuth := &cliproxyauth.Auth{ + ID: "codex-ws-init-" + name, + Attributes: map[string]string{"api_key": "sk-test", "base_url": initServer.URL}, + } + initOpts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + } + if stream { + _, errExec = exec.ExecuteStream(initCtx, initAuth, req, initOpts) + } else { + _, errExec = exec.Execute(initCtx, initAuth, req, initOpts) + } + if errExec == nil { + t.Fatal("expected initial invalid-101 handshake to fail") + } + initVal, ok := initGinCtx.Get(logging.DeferredAPIResponseContextKey) + if !ok { + t.Fatal("deferred API response missing on initial invalid-101 handshake") + } + initRendered := string(initVal.(logging.DeferredAPIResponse).RenderAPIResponse()) + for _, want := range []string{"Status: 101", "Error: dial:"} { + if !strings.Contains(initRendered, want) { + t.Fatalf("initial handshake response missing %q:\n%s", want, initRendered) + } + } + }) + } +} diff --git a/internal/runtime/executor/codex_websockets_stream.go b/internal/runtime/executor/codex_websockets_stream.go index 540fb468363..e01dc786f66 100644 --- a/internal/runtime/executor/codex_websockets_stream.go +++ b/internal/runtime/executor/codex_websockets_stream.go @@ -30,6 +30,31 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr } baseModel := thinking.ParseSuffix(req.Model).ModelName + isCompat, errExpand := e.expandCodexResponsesCompaction(auth, &req, &opts, baseModel) + if errExpand != nil { + return nil, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } + if e.shouldCompactCompatResponsesTrigger(isCompat, req, opts) { + executionSessionID := executionSessionIDFromOptions(opts) + var sess *codexWebsocketSession + if executionSessionID != "" { + sess = e.getOrCreateSession(executionSessionID) + if sess != nil { + sess.reqMu.Lock() + defer sess.reqMu.Unlock() + } + } + res, errCompact := e.CodexExecutor.executeCodexResponsesCompactionStream(ctx, auth, req, opts) + if errCompact == nil && sess != nil { + sess.connMu.Lock() + existingConn := sess.conn + sess.connMu.Unlock() + if existingConn != nil { + e.invalidateUpstreamConnWithoutDisconnectNotify(sess, existingConn, "local_compaction", nil) + } + } + return res, errCompact + } reporter := helps.NewExecutorUsageReporter(ctx, e, baseModel, auth) defer reporter.TrackFailure(ctx, &err) @@ -133,10 +158,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr unlockStreamSession() return nil, codexWebsocketTurnEventID(errDial, originalPayload) } - bodyErr := websocketHandshakeBody(respHS) - if respHS != nil { - helps.RecordAPIWebsocketUpgradeRejection(ctx, e.cfg, websocketUpgradeRequestLog(wsReqLog), respHS.StatusCode, respHS.Header.Clone(), bodyErr) - } + bodyErr := recordWebsocketDialFailure(ctx, e.cfg, wsReqLog, respHS, errDial) if respHS != nil && respHS.StatusCode == http.StatusUpgradeRequired { unlockStreamSession() if opts.ExecutionLifecycle == nil && !cliproxyexecutor.DownstreamWebsocket(ctx) { @@ -154,7 +176,6 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr unlockStreamSession() return nil, newCodexStatusErrWithHeadersAndCooling(respHS.StatusCode, respHS.Header, bodyErr, e.modelLevelCooling()) } - helps.RecordAPIWebsocketError(ctx, e.cfg, "dial", errDial) unlockStreamSession() return nil, errDial } @@ -220,8 +241,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr // Retry once with a new websocket connection for the same execution session. connRetry, closerRetry, respHSRetry, errDialRetry := e.ensureUpstreamConnWithSIWC(ctx, auth, sess, authID, wsURL, wsHeaders, useSIWC) if errDialRetry != nil || connRetry == nil { - closeHTTPResponseBody(respHSRetry, "codex websockets executor: close handshake response body error") - helps.RecordAPIWebsocketError(ctx, e.cfg, "dial_retry", errDialRetry) + _ = recordWebsocketDialRetryFailure(ctx, e.cfg, wsReqLog, respHSRetry, errDialRetry) sess.clearActive(conn, readCh) sess.reqMu.Unlock() return nil, errDialRetry @@ -857,10 +877,14 @@ type codexWebsocketPrepared struct { } func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*codexWebsocketPrepared, error) { - if errExpand := helps.ExpandRecognizedResponsesCompactionCapsules(&req, &opts); errExpand != nil { - return nil, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + if errPrev := rejectSyntheticCompactionPreviousResponseID(ctx, req.Payload); errPrev != nil { + return nil, errPrev } baseModel := thinking.ParseSuffix(req.Model).ModelName + isCompat, errExpand := e.expandCodexResponsesCompaction(auth, &req, &opts, baseModel) + if errExpand != nil { + return nil, statusErr{code: http.StatusBadRequest, msg: errExpand.Error()} + } apiKey, baseURL := codexCredsForRequest(ctx, auth, opts.Headers) if errSIWC := ensureCodexSIWCCredentialsForRequest(ctx, auth, apiKey, opts.Headers); errSIWC != nil { return nil, errSIWC @@ -883,7 +907,6 @@ func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Contex originalPayloadSource = opts.OriginalRequest } originalPayload := originalPayloadSource - isCompat := e.resolveCodexModelIsCompat(auth, req, baseModel) targetModel := resolveResponsesSignatureTargetModel(baseModel, req, opts) originalTranslated, body, updatesChanged, err := translateCodexRequestPairWithUpdateIntentContext(ctx, from, to, targetModel, originalPayload, req.Payload, true, isCompat) if err != nil { @@ -900,13 +923,17 @@ func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Contex instructionsResult := ojson.GetBytesNoCopy(req.Payload, "instructions") hasExplicitInstructions := instructionsResult.Exists() && strings.TrimSpace(instructionsResult.String()) != "" - ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, "codex-websockets", baseModel, to.String(), "", originalTranslated, req, opts)) + ctx = helps.WithPayloadFinalizer(ctx, helps.NewPayloadFinalizer(e.cfg, "codex-websockets", baseModel, to.String(), "", originalTranslated, req, opts, auth)) helps.SetStringIfDifferentDoc(doc, "model", baseModel) ensureWebSearchToolForHistoryDoc(doc, opts.Headers) if !useSIWC { normalizeCodexInstructionsDoc(doc, preserveNativeOutput) if e.cfg == nil || e.cfg.DisableImageGeneration == config.DisableImageGenerationOff { - ensureImageGenerationToolDoc(doc, baseModel, auth, opts.Headers) + checkModel := req.Model + if strings.TrimSpace(checkModel) == "" { + checkModel = baseModel + } + ensureImageGenerationToolDoc(doc, checkModel, auth, opts.Headers) if !codexAuthUsesAPIKey(auth) { normalizeCodexImageGenerationToolsDoc(doc) } diff --git a/internal/runtime/executor/devin_executor.go b/internal/runtime/executor/devin_executor.go index 88209c5458d..7ff11219a41 100644 --- a/internal/runtime/executor/devin_executor.go +++ b/internal/runtime/executor/devin_executor.go @@ -275,13 +275,18 @@ func (e *DevinExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re return resp, errDo } defer func() { - _ = httpResp.Body.Close() + if errClose := httpResp.Body.Close(); errClose != nil { + log.Errorf("devin executor: close response body error: %v", errClose) + } }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - errData, _ := io.ReadAll(io.LimitReader(httpResp.Body, 1<<20)) + errData, errRead := io.ReadAll(io.LimitReader(httpResp.Body, 1<<20)) helps.AppendAPIResponseChunk(ctx, e.cfg, errData) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } return resp, newDevinStatusErrorForAuth(httpResp.StatusCode, httpResp.Header, errData, auth) } @@ -302,9 +307,28 @@ func (e *DevinExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re if helps.ApplyPatchRequested(original) { var patchErr statusErr if errors.As(errConsume, &patchErr) && patchErr.diagnostic != "" { + if respLog != nil && respLog.Usage != nil { + publishDevinUsageFailure(ctx, reporter, respLog.Usage, patchErr) + } return resp, patchErr } - return resp, devinApplyPatchStatusError(patchDiagnostics.Render(nil, devinApplyPatchConsumeReason(respLog, errConsume))) + if patchDiagnostics.HasPatchActivity() { + wrappedPatchErr := devinApplyPatchStatusError(patchDiagnostics.Render(nil, devinApplyPatchConsumeReason(respLog, errConsume))) + var truncErr cliproxyexecutor.StreamTruncatedError + if errors.As(errConsume, &truncErr) && truncErr.IsStreamTruncated() { + wrappedPatchErr.streamTruncated = true + } + if respLog != nil && respLog.Usage != nil { + publishDevinUsageFailure(ctx, reporter, respLog.Usage, wrappedPatchErr) + } + if ctx.Err() == nil { + helps.RecordAPIResponseError(ctx, e.cfg, wrappedPatchErr) + } + return resp, wrappedPatchErr + } + } + if respLog != nil && respLog.Usage != nil { + publishDevinUsageFailure(ctx, reporter, respLog.Usage, errConsume) } if ctx.Err() == nil { helps.RecordAPIResponseError(ctx, e.cfg, errConsume) @@ -320,7 +344,14 @@ func (e *DevinExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re var param any out := sdktranslator.TranslateNonStream(ctx, sdktranslator.FormatInteractions, targetFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), req.Payload, interactionsJSON, ¶m) if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { - return cliproxyexecutor.Response{}, devinApplyPatchStatusError(patchDiagnostics.Render(param, "")) + patchErr := devinApplyPatchStatusError(patchDiagnostics.Render(param, "")) + if respLog != nil && respLog.Usage != nil { + publishDevinUsageFailure(ctx, reporter, respLog.Usage, patchErr) + } + if ctx.Err() == nil { + helps.RecordAPIResponseError(ctx, e.cfg, patchErr) + } + return cliproxyexecutor.Response{}, patchErr } reporter.Publish(ctx, helps.ParseInteractionsUsage(interactionsJSON)) if targetFormat == sdktranslator.FormatOpenAIResponse { @@ -372,9 +403,12 @@ func (e *DevinExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au } helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - errData, _ := io.ReadAll(io.LimitReader(httpResp.Body, 1<<20)) + errData, errRead := io.ReadAll(io.LimitReader(httpResp.Body, 1<<20)) _ = httpResp.Body.Close() helps.AppendAPIResponseChunk(ctx, e.cfg, errData) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } return nil, newDevinStatusErrorForAuth(httpResp.StatusCode, httpResp.Header, errData, auth) } @@ -538,6 +572,7 @@ func (e *DevinExecutor) streamDevinFramesForAuth( out chan<- cliproxyexecutor.StreamChunk, auth *cliproxyauth.Auth, ) { + completedPublished := false if reporter != nil { if chatModelUID != "" { reporter.SetUpstreamModel(chatModelUID) @@ -584,6 +619,31 @@ func (e *DevinExecutor) streamDevinFramesForAuth( firstStreamEvent := true streamFrameCount := 0 createdSent := false + summaryWritten := false + appendStreamResponseSummary := func(status string) { + if summaryWritten { + return + } + summaryWritten = true + streamSummary := &helps.DevinUpstreamResponseLog{ + Status: status, + FramesCount: streamFrameCount, + Thinking: accumulatedThinking.String(), + Content: accumulatedContent.String(), + Signature: string(accumulatedSignature), + SignatureType: signatureType, + Usage: finalUsage, + } + if summaryJSON, errMarshal := json.MarshalIndent(streamSummary, "", " "); errMarshal == nil { + helps.AppendAPIResponseChunk(ctx, e.cfg, []byte("\n=== DEVIN UPSTREAM RESPONSE SUMMARY ===\n"+string(summaryJSON)+"\n")) + } + } + defer func() { + if !completedPublished && ctx.Err() != nil { + publishDevinUsageFailure(ctx, reporter, finalUsage, ctx.Err()) + appendStreamResponseSummary(fmt.Sprintf("read_error: %v", ctx.Err())) + } + }() var emitInteractionsEvent func(rawJSON []byte) bool emitInteractionsEvent = func(rawJSON []byte) bool { if translationFailed { @@ -597,6 +657,10 @@ func (e *DevinExecutor) streamDevinFramesForAuth( eventType := ojson.GetBytesNoCopy(trimmed, "event_type").String() isFailedEvent := eventType == "response.failed" || eventType == "interaction.failed" + if ctx.Err() != nil && !isFailedEvent { + return false + } + // If a failure occurs before any stream content has started, suppress the payload event // so the stream can cleanly fail at the bootstrap layer with an HTTP error status code. if isFailedEvent && !createdSent { @@ -647,7 +711,9 @@ func (e *DevinExecutor) streamDevinFramesForAuth( patchFailed := helps.ApplyPatchTranslationError(translateParam) != nil if patchFailed { patchErr = applyPatchErr("") + publishDevinUsageFailure(ctx, reporter, finalUsage, patchErr) helps.RecordApplyPatchStreamFailure(ctx, translateParam, reporter, patchErr) + appendStreamResponseSummary("apply_patch_error") } for _, line := range lines { select { @@ -896,14 +962,20 @@ func (e *DevinExecutor) streamDevinFramesForAuth( return true } - closeOpenSteps := func() { + closeOpenSteps := func() bool { for _, index := range deferredThoughtStops { - stopEvent, _ := ojson.SetBytes([]byte(`{"event_type":"step.stop","index":0}`), "index", index) - _ = emitInteractionsEvent(stopEvent) + stopDoc := ojson.NewDoc([]byte(`{"event_type":"step.stop","index":0}`)) + _ = stopDoc.Set("index", index) + if !emitInteractionsEvent(stopDoc.Bytes()) { + deferredThoughtStops = nil + return false + } } deferredThoughtStops = nil if len(pendingActions) > 0 || thoughtStarted { - _ = flushPendingActions() + if !flushPendingActions() { + return false + } } if len(activeToolSlots) > 0 { sortedIndices := make([]int, 0, len(activeToolSlots)) @@ -930,12 +1002,19 @@ func (e *DevinExecutor) streamDevinFramesForAuth( _ = deltaDoc.Set("delta.invalid_json_str", true) } if !emitInteractionsEvent(deltaDoc.Bytes()) { - break + clear(activeToolSlots) + clear(activeCallByID) + activeCallSlot = nil + return false } } - stopEvent, _ := ojson.SetBytes([]byte(`{"event_type":"step.stop","index":0}`), "index", sIdx) - if !emitInteractionsEvent(stopEvent) { - break + stopDoc := ojson.NewDoc([]byte(`{"event_type":"step.stop","index":0}`)) + _ = stopDoc.Set("index", sIdx) + if !emitInteractionsEvent(stopDoc.Bytes()) { + clear(activeToolSlots) + clear(activeCallByID) + activeCallSlot = nil + return false } } clear(activeToolSlots) @@ -943,22 +1022,33 @@ func (e *DevinExecutor) streamDevinFramesForAuth( activeCallSlot = nil } if len(postToolBufferedContent) > 0 { - startEvent, _ := ojson.SetBytes([]byte(`{"event_type":"step.start","index":0,"step":{"type":"model_output"}}`), "index", stepIndex) - _ = emitInteractionsEvent(startEvent) + startDoc := ojson.NewDoc([]byte(`{"event_type":"step.start","index":0,"step":{"type":"model_output"}}`)) + _ = startDoc.Set("index", stepIndex) + if !emitInteractionsEvent(startDoc.Bytes()) { + postToolBufferedContent = nil + return false + } contentStarted = true for _, chunk := range postToolBufferedContent { deltaDoc := ojson.NewDoc([]byte(`{"event_type":"step.delta","index":0,"delta":{"type":"text","text":""}}`)) _ = deltaDoc.Set("index", stepIndex) _ = deltaDoc.Set("delta.text", chunk) - _ = emitInteractionsEvent(deltaDoc.Bytes()) + if !emitInteractionsEvent(deltaDoc.Bytes()) { + postToolBufferedContent = nil + return false + } } postToolBufferedContent = nil } if contentStarted { - stopEvent, _ := ojson.SetBytes([]byte(`{"event_type":"step.stop","index":0}`), "index", stepIndex) - _ = emitInteractionsEvent(stopEvent) + stopDoc := ojson.NewDoc([]byte(`{"event_type":"step.stop","index":0}`)) + _ = stopDoc.Set("index", stepIndex) contentStarted = false + if !emitInteractionsEvent(stopDoc.Bytes()) { + return false + } } + return true } // 2. Consume streaming Connect-proto frames @@ -978,23 +1068,44 @@ func (e *DevinExecutor) streamDevinFramesForAuth( if flag&helps.ConnectFlagEndStream != 0 { code, errTrailer := helps.ParseDevinTrailerError(payload) if errTrailer != nil { - if helps.EndApplyPatchStream(ctx, translateParam, reporter, out, applyPatchErr("devin_trailer_error")) { - return - } - closeOpenSteps() - if translationFailed { - return + trailerStatus := fmt.Sprintf("trailer_error(%d): %s", code, errTrailer.Error()) + if patchDiagnostics.HasPatchActivity() { + patchErr := applyPatchErr("devin_trailer_error") + chunks := helps.FinalizeApplyPatchStream(translateParam) + if helps.ApplyPatchTranslationError(translateParam) != nil { + publishDevinUsageFailure(ctx, reporter, finalUsage, patchErr) + if ctx.Err() == nil { + helps.RecordAPIResponseError(ctx, e.cfg, patchErr) + } + appendStreamResponseSummary(trailerStatus) + for _, chunk := range chunks { + select { + case out <- cliproxyexecutor.StreamChunk{Payload: chunk}: + case <-ctx.Done(): + return + } + } + _ = helps.StopApplyPatchStream(ctx, translateParam, reporter, out, patchErr) + return + } } - if reporter != nil { - reporter.PublishFailure(ctx, errTrailer) + if !closeOpenSteps() { + if translationFailed || ctx.Err() != nil { + return + } } + trailerErr := devinTrailerStatusError(code, errTrailer.Error(), auth) + publishDevinUsageFailure(ctx, reporter, finalUsage, trailerErr) log.Warnf("devin executor: trailer error (%d): %v", code, errTrailer) - helps.RecordAPIResponseError(ctx, e.cfg, errTrailer) - failedDoc := ojson.NewDoc([]byte(`{"event_type":"response.failed","error":{"message":"","code":""}}`)) - _ = failedDoc.Set("error.message", errTrailer.Error()) - _ = failedDoc.Set("error.code", fmt.Sprintf("%d", code)) - _ = emitInteractionsEvent(failedDoc.Bytes()) - emitStreamError(devinTrailerStatusError(code, errTrailer.Error(), auth)) + helps.RecordAPIResponseError(ctx, e.cfg, trailerErr) + appendStreamResponseSummary(fmt.Sprintf("trailer_error(%d): %s", code, errTrailer.Error())) + if createdSent { + failedDoc := ojson.NewDoc([]byte(`{"event_type":"response.failed","error":{"message":"","code":""}}`)) + _ = failedDoc.Set("error.message", errTrailer.Error()) + _ = failedDoc.Set("error.code", fmt.Sprintf("%d", code)) + _ = emitInteractionsEvent(failedDoc.Bytes()) + } + emitStreamError(trailerErr) return } sawEOS = true @@ -1173,41 +1284,112 @@ func (e *DevinExecutor) streamDevinFramesForAuth( } } - if (!sawEOS || streamErr != nil) && ctx.Err() == nil { + // When caller context is canceled before EOS (e.g. client disconnect or downstream timeout on a hung stream), + // exit without synthesizing a fake interaction.completed event; the deferred cancel handler records failure usage and summary. + if ctx.Err() != nil && !sawEOS { + return + } + + if (!sawEOS || streamErr != nil) && ctx.Err() == nil && patchDiagnostics.HasPatchActivity() { reason := "devin_stream_ended_before_eos" + summaryStatus := "premature_eof_before_eos" if streamErr != nil { reason = "devin_stream_read_error" + summaryStatus = fmt.Sprintf("read_error: %v", streamErr) } - if helps.EndApplyPatchStream(ctx, translateParam, reporter, out, applyPatchErr(reason)) { + patchErr := applyPatchErr(reason) + patchErr.streamTruncated = true + chunks := helps.FinalizeApplyPatchStream(translateParam) + if helps.ApplyPatchTranslationError(translateParam) != nil { + publishDevinUsageFailure(ctx, reporter, finalUsage, patchErr) + helps.RecordAPIResponseError(ctx, e.cfg, patchErr) + appendStreamResponseSummary(summaryStatus) + for _, chunk := range chunks { + select { + case out <- cliproxyexecutor.StreamChunk{Payload: chunk}: + case <-ctx.Done(): + return + } + } + _ = helps.StopApplyPatchStream(ctx, translateParam, reporter, out, patchErr) return } } + + hasGeneratedOutput := accumulatedContent.Len() > 0 || + accumulatedThinking.Len() > 0 || + len(accumulatedSignature) > 0 || + toolCallCount > 0 + // 3. Close open steps - closeOpenSteps() - if translationFailed { + if !closeOpenSteps() || translationFailed || ctx.Err() != nil { return } // If stream encountered an abnormal read error mid-flight, record failure and emit response.failed if streamErr != nil && ctx.Err() == nil { - helps.RecordAPIResponseError(ctx, e.cfg, streamErr) - failedEvent, _ := ojson.SetBytes([]byte(`{"event_type":"response.failed","error":{"message":"","code":"stream_read_error"}}`), "error.message", streamErr.Error()) - _ = emitInteractionsEvent(failedEvent) - emitStreamError(streamErr) + var errOut error + if !createdSent && !hasGeneratedOutput && (finalUsage == nil || finalUsage.CompletionTokens == 0) { + errOut = newDevinTransientStreamError(fmt.Sprintf("devin upstream stream read error: %v", streamErr), streamErr) + } else { + errOut = newDevinTruncatedStreamError(fmt.Sprintf("devin upstream stream read error: %v", streamErr), streamErr) + } + publishDevinUsageFailure(ctx, reporter, finalUsage, errOut) + helps.RecordAPIResponseError(ctx, e.cfg, errOut) + appendStreamResponseSummary(fmt.Sprintf("read_error: %v", streamErr)) + if createdSent { + failedDoc := ojson.NewDoc([]byte(`{"event_type":"response.failed","error":{"message":"","code":"stream_read_error"}}`)) + _ = failedDoc.Set("error.message", streamErr.Error()) + _ = emitInteractionsEvent(failedDoc.Bytes()) + } + emitStreamError(errOut) return } // In Connect-RPC, the stream must cleanly terminate with an EOS trailer frame. - // If the upstream connection dropped before sending EOS without caller cancellation, reject as truncated. + // If the upstream connection dropped before sending EOS without caller cancellation, reject as truncated or retryable pre-output drop. if !sawEOS && ctx.Err() == nil { - truncErr := fmt.Errorf("devin stream terminated prematurely before EOS trailer") + const msg = "devin stream terminated prematurely before EOS trailer" + var truncErr error + if !createdSent && !hasGeneratedOutput && (finalUsage == nil || finalUsage.CompletionTokens == 0) { + truncErr = newDevinTransientStreamError(msg, nil) + } else { + truncErr = newDevinTruncatedStreamError(msg, nil) + } + publishDevinUsageFailure(ctx, reporter, finalUsage, truncErr) helps.RecordAPIResponseError(ctx, e.cfg, truncErr) - failedEvent, _ := ojson.SetBytes([]byte(`{"event_type":"response.failed","error":{"message":"devin stream terminated prematurely before EOS trailer","code":"stream_truncated"}}`), "error.message", truncErr.Error()) - _ = emitInteractionsEvent(failedEvent) + appendStreamResponseSummary("premature_eof_before_eos") + if createdSent { + failedDoc := ojson.NewDoc([]byte(`{"event_type":"response.failed","error":{"message":"","code":"stream_truncated"}}`)) + _ = failedDoc.Set("error.message", msg) + _ = emitInteractionsEvent(failedDoc.Bytes()) + } emitStreamError(truncErr) return } + // Reject a clean EOS stream that produced zero generated steps and zero output tokens + // so dead upstream slots fail over across credentials and fallback layers without cooling. + if isDevinEmptyCompletion(hasGeneratedOutput, lastStopReason, finalUsage) { + emptyErr := newDevinEmptyCompletionError() + publishDevinUsageFailure(ctx, reporter, finalUsage, emptyErr) + if ctx.Err() == nil { + helps.RecordAPIResponseError(ctx, e.cfg, emptyErr) + } + appendStreamResponseSummary("empty_completion") + if createdSent { + failedDoc := ojson.NewDoc([]byte(`{"event_type":"response.failed","error":{"message":"","code":"empty_completion"}}`)) + _ = failedDoc.Set("error.message", emptyErr.Error()) + _ = emitInteractionsEvent(failedDoc.Bytes()) + } + emitStreamError(emptyErr) + return + } + + if ctx.Err() != nil { + return + } + // 5. Emit interaction.completed with final usage completionStatus := "completed" var completionFinishReason string @@ -1231,7 +1413,7 @@ func (e *DevinExecutor) streamDevinFramesForAuth( _ = completedDoc.Set("interaction.finish_reason", completionFinishReason) } if finalUsage != nil { - totalInput := finalUsage.PromptTokens + finalUsage.CachedTokens + totalInput := devinTotalInputTokens(finalUsage) totalOutput := finalUsage.CompletionTokens totalTokens := totalInput + totalOutput @@ -1250,23 +1432,13 @@ func (e *DevinExecutor) streamDevinFramesForAuth( if !emitInteractionsEvent(completedEvent) { return } + completedPublished = true if detail, okUsage := helps.ParseInteractionsStreamUsage(completedEvent); okUsage && reporter != nil { reporter.Publish(ctx, detail) } if finalUsage != nil || len(accumulatedSignature) > 0 { - streamSummary := &helps.DevinUpstreamResponseLog{ - Status: "completed", - FramesCount: streamFrameCount, - Thinking: accumulatedThinking.String(), - Content: accumulatedContent.String(), - Signature: string(accumulatedSignature), - SignatureType: signatureType, - Usage: finalUsage, - } - if summaryJSON, err := json.MarshalIndent(streamSummary, "", " "); err == nil { - helps.AppendAPIResponseChunk(ctx, e.cfg, []byte("\n=== DEVIN UPSTREAM RESPONSE SUMMARY ===\n"+string(summaryJSON)+"\n")) - } + appendStreamResponseSummary("completed") } // 6. Terminate stream with [DONE] @@ -1373,6 +1545,7 @@ func consumeDevinFramesToInteractionsForAuth(body io.Reader, model, chatModelUID if errors.Is(errRead, io.EOF) { break } + toolCallsSoFar := getToolCalls() respLog := &helps.DevinUpstreamResponseLog{ Status: fmt.Sprintf("read_error: %v", errRead), FramesCount: framesCount, @@ -1380,12 +1553,19 @@ func consumeDevinFramesToInteractionsForAuth(body io.Reader, model, chatModelUID Thinking: strings.Join(thinkingParts, ""), Signature: string(accumulatedSignature), SignatureType: signatureType, - ToolCalls: getToolCalls(), + ToolCalls: toolCallsSoFar, Usage: finalUsage, UnknownFields: unknownFields, ApplyPatchDiagnostics: patchDiagnostics, } - return nil, respLog, errRead + if errors.Is(errRead, context.Canceled) || errors.Is(errRead, context.DeadlineExceeded) { + return nil, respLog, errRead + } + hasGenerated := len(preToolTextParts) > 0 || len(postToolTextParts) > 0 || len(thinkingParts) > 0 || len(accumulatedSignature) > 0 || len(toolCallsSoFar) > 0 + if !hasGenerated && (finalUsage == nil || finalUsage.CompletionTokens == 0) { + return nil, respLog, newDevinTransientStreamError(fmt.Sprintf("devin upstream stream read error: %v", errRead), errRead) + } + return nil, respLog, newDevinTruncatedStreamError(fmt.Sprintf("devin upstream stream read error: %v", errRead), errRead) } framesCount++ @@ -1546,7 +1726,7 @@ func consumeDevinFramesToInteractionsForAuth(body io.Reader, model, chatModelUID } if !sawEOS { - truncErr := fmt.Errorf("devin upstream stream terminated prematurely before EOS trailer") + toolCallsSoFar := getToolCalls() respLog := &helps.DevinUpstreamResponseLog{ Status: "premature_eof_before_eos", FramesCount: framesCount, @@ -1554,12 +1734,17 @@ func consumeDevinFramesToInteractionsForAuth(body io.Reader, model, chatModelUID Thinking: strings.Join(thinkingParts, ""), Signature: string(accumulatedSignature), SignatureType: signatureType, - ToolCalls: getToolCalls(), + ToolCalls: toolCallsSoFar, Usage: finalUsage, UnknownFields: unknownFields, ApplyPatchDiagnostics: patchDiagnostics, } - return nil, respLog, truncErr + const msg = "devin upstream stream terminated prematurely before EOS trailer" + hasGenerated := len(preToolTextParts) > 0 || len(postToolTextParts) > 0 || len(thinkingParts) > 0 || len(accumulatedSignature) > 0 || len(toolCallsSoFar) > 0 + if !hasGenerated && (finalUsage == nil || finalUsage.CompletionTokens == 0) { + return nil, respLog, newDevinTransientStreamError(msg, nil) + } + return nil, respLog, newDevinTruncatedStreamError(msg, nil) } if len(original) > 0 { @@ -1576,10 +1761,37 @@ func consumeDevinFramesToInteractionsForAuth(body io.Reader, model, chatModelUID continue } } - return nil, nil, devinApplyPatchStatusError(patchDiagnostics.Render(nil, "legacy_invalid_json_str")) + respLog := &helps.DevinUpstreamResponseLog{ + Status: "legacy_invalid_json_str", + FramesCount: framesCount, + Content: getAllContentText(), + Thinking: strings.Join(thinkingParts, ""), + Signature: string(accumulatedSignature), + SignatureType: signatureType, + ToolCalls: getToolCalls(), + Usage: finalUsage, + UnknownFields: unknownFields, + ApplyPatchDiagnostics: patchDiagnostics, + } + return nil, respLog, devinApplyPatchStatusError(patchDiagnostics.Render(nil, "legacy_invalid_json_str")) } } toolCalls := getToolCalls() + hasGeneratedOutput := len(preToolTextParts) > 0 || + len(postToolTextParts) > 0 || + len(thinkingParts) > 0 || + len(accumulatedSignature) > 0 || + len(toolCalls) > 0 + if isDevinEmptyCompletion(hasGeneratedOutput, lastStopReason, finalUsage) { + respLog := &helps.DevinUpstreamResponseLog{ + Status: "empty_completion", + FramesCount: framesCount, + Usage: finalUsage, + UnknownFields: unknownFields, + ApplyPatchDiagnostics: patchDiagnostics, + } + return nil, respLog, newDevinEmptyCompletionError() + } completionStatus := "completed" var completionFinishReason string @@ -1662,7 +1874,7 @@ func consumeDevinFramesToInteractionsForAuth(body io.Reader, model, chatModelUID } if finalUsage != nil { - totalInput := finalUsage.PromptTokens + finalUsage.CachedTokens + totalInput := devinTotalInputTokens(finalUsage) totalOutput := finalUsage.CompletionTokens totalTokens := totalInput + totalOutput @@ -2691,15 +2903,31 @@ func (e *DevinExecutor) getSensitiveWords() []string { return nil } +func (e *DevinExecutor) getSensitiveWordsReplace() map[string]string { + if e != nil && e.cfg != nil && len(e.cfg.Devin.SensitiveWordsReplace) > 0 { + return e.cfg.Devin.SensitiveWordsReplace + } + return nil +} + +func (e *DevinExecutor) getSensitivePatternsReplace() []config.SensitivePatternRule { + if e != nil && e.cfg != nil && len(e.cfg.Devin.SensitivePatternsReplace) > 0 { + return e.cfg.Devin.SensitivePatternsReplace + } + return nil +} + func (e *DevinExecutor) getSensitiveWordMatcher() *helps.SensitiveWordMatcher { if e == nil { return nil } words := e.getSensitiveWords() - if len(words) == 0 { + replacements := e.getSensitiveWordsReplace() + patterns := e.getSensitivePatternsReplace() + if len(words) == 0 && len(replacements) == 0 && len(patterns) == 0 { return nil } - key := strings.Join(words, "\x00") + key := helps.SensitiveWordConfigCacheKeyWithPatterns(words, replacements, patterns) e.matcherMu.RLock() if e.lastWordsKey == key { m := e.cachedMatcher @@ -2714,7 +2942,7 @@ func (e *DevinExecutor) getSensitiveWordMatcher() *helps.SensitiveWordMatcher { return e.cachedMatcher } e.lastWordsKey = key - e.cachedMatcher = helps.BuildSensitiveWordMatcher(words) + e.cachedMatcher = helps.BuildSensitiveWordMatcherWithPatterns(words, replacements, patterns) return e.cachedMatcher } @@ -2742,6 +2970,88 @@ func devinApplyPatchStatusError(diagnostic string) statusErr { return statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage, diagnostic: diagnostic} } +// devinTransientStreamError marks a pre-output Devin Connect stream failure +// (such as an empty 0-token completion or premature drop before any output) +// as HTTP 502 while carrying ErrorCodeTransientTransport so Conductor rotates +// across credentials and fallback layers without cooling healthy credentials. +type devinTransientStreamError struct { + statusErr + cause error +} + +func (devinTransientStreamError) ErrorCode() string { + return cliproxyauth.ErrorCodeTransientTransport +} + +func (e devinTransientStreamError) Unwrap() error { + return e.cause +} + +func newDevinTransientStreamError(msg string, cause error) devinTransientStreamError { + return devinTransientStreamError{ + statusErr: statusErr{code: http.StatusBadGateway, msg: msg}, + cause: cause, + } +} + +func newDevinEmptyCompletionError() devinTransientStreamError { + return newDevinTransientStreamError("devin upstream returned an empty completion (0 output tokens)", nil) +} + +// devinTruncatedStreamError marks a mid-generation Devin stream drop after +// partial output was already produced, skipping credential cooldown and +// preventing replay of an already-accepted generation. +type devinTruncatedStreamError struct { + statusErr + cause error +} + +func (devinTruncatedStreamError) IsStreamTruncated() bool { + return true +} + +func (e devinTruncatedStreamError) Unwrap() error { + return e.cause +} + +func newDevinTruncatedStreamError(msg string, cause error) devinTruncatedStreamError { + return devinTruncatedStreamError{ + statusErr: statusErr{code: http.StatusBadGateway, msg: msg, streamTruncated: true}, + cause: cause, + } +} + +func isDevinEmptyCompletion(hasGeneratedOutput bool, stopReason uint64, u *helps.DevinUsage) bool { + if hasGeneratedOutput || stopReason == 11 { + return false + } + return u == nil || u.CompletionTokens == 0 +} + +func publishDevinUsageFailure(ctx context.Context, reporter *helps.UsageReporter, u *helps.DevinUsage, err error) { + if reporter == nil || err == nil { + return + } + if u == nil { + reporter.PublishFailure(ctx, err) + return + } + if u.ModelName != "" { + reporter.SetResponseModel(u.ModelName) + } + usageDoc := ojson.NewDoc([]byte(`{"usage":{"total_input_tokens":0,"total_output_tokens":0,"total_cached_tokens":0,"total_tokens":0}}`)) + totalInput := devinTotalInputTokens(u) + totalOutput := u.CompletionTokens + _ = usageDoc.Set("usage.total_input_tokens", totalInput) + _ = usageDoc.Set("usage.total_output_tokens", totalOutput) + _ = usageDoc.Set("usage.total_cached_tokens", u.CachedTokens) + if u.CacheWriteTokens > 0 { + _ = usageDoc.Set("usage.cache_write_tokens", u.CacheWriteTokens) + } + _ = usageDoc.Set("usage.total_tokens", totalInput+totalOutput) + reporter.PublishFailureWithDetail(ctx, helps.ParseInteractionsUsage(usageDoc.Bytes()), err) +} + // devinTrailerStatusError builds the scheduling view of a Connect trailer // error. Explicit account-wide daily/weekly usage quota exhaustion (issue // #6690) is credential-scoped and, when auth carries a valid observed reset @@ -2875,6 +3185,17 @@ func resolveDevinSessionAndCascadeIDs(ctx context.Context, sessionID, cascadeID return sessionID, cascadeID } +// devinTotalInputTokens returns the full prompt size. Devin reports the prompt in +// three disjoint parts: uncached (field 2), cache write (field 4) and cache read +// (field 5). A cache miss on the GPT route is almost all cache write, so leaving +// it out reported a few tokens for a full prompt. +func devinTotalInputTokens(u *helps.DevinUsage) int64 { + if u == nil { + return 0 + } + return u.PromptTokens + u.CachedTokens + u.CacheWriteTokens +} + func normalizeDevinUUID(raw string) string { raw = strings.TrimSpace(raw) if raw == "" { diff --git a/internal/runtime/executor/devin_executor_test.go b/internal/runtime/executor/devin_executor_test.go index 2364a790ea0..69c5b579bf6 100644 --- a/internal/runtime/executor/devin_executor_test.go +++ b/internal/runtime/executor/devin_executor_test.go @@ -21,6 +21,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/util" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" log "github.com/sirupsen/logrus" logtest "github.com/sirupsen/logrus/hooks/test" @@ -141,6 +142,45 @@ func TestDevinExecutor_GetSensitiveWords(t *testing.T) { } } +func TestDevinSensitiveWordsReplaceFromYAML(t *testing.T) { + cfg, errParse := config.ParseConfigBytes([]byte(`devin: + sensitive-words: + - "Codex" + sensitive-words-replace: + "You are Codex, an agent based on GPT-5.": "You are a helpful coding assistant." +`)) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + e := NewDevinExecutor(cfg) + got := helps.SanitizeDevinSystemPrompt("You are Codex, an agent based on GPT-5.\nFollow project conventions.", e.getSensitiveWordMatcher()) + want := "You are a helpful coding assistant.\nFollow project conventions." + if got != want { + t.Fatalf("SanitizeDevinSystemPrompt() = %q, want %q", got, want) + } +} + +func TestDevinSensitivePatternsReplaceFromYAML(t *testing.T) { + cfg, errParse := config.ParseConfigBytes([]byte(`devin: + sensitive-words: + - "omp" + sensitive-patterns-replace: + - pattern: '(?m)^You are omp[^\n]*' + replacement: "You are a coding assistant." + - pattern: '(?s).*?\n?' + replacement: "" +`)) + if errParse != nil { + t.Fatalf("ParseConfigBytes() error = %v", errParse) + } + e := NewDevinExecutor(cfg) + got := helps.SanitizeDevinSystemPrompt("You are omp's assistant.\n\nRFC 2119.\n\nFollow project conventions.", e.getSensitiveWordMatcher()) + want := "You are a coding assistant.\nFollow project conventions." + if got != want { + t.Fatalf("SanitizeDevinSystemPrompt() = %q, want %q", got, want) + } +} + func TestParseInteractionsPayload(t *testing.T) { interactionsPayload := []byte(`{ "system_instruction": "You are a helpful coding assistant.", @@ -3196,8 +3236,9 @@ func TestRegressionIssue5910_UsageStatsCacheWriteTokensInResponses(t *testing.T) } root := ojson.ParseBytes(interactionsJSON) - if root.Get("usage.total_input_tokens").Int() != 53 { - t.Errorf("usage.total_input_tokens = %d, want 53", root.Get("usage.total_input_tokens").Int()) + // total input = uncached 3 + cache read 50 + cache write 14361 + if root.Get("usage.total_input_tokens").Int() != 14414 { + t.Errorf("usage.total_input_tokens = %d, want 14414", root.Get("usage.total_input_tokens").Int()) } if root.Get("usage.cache_write_tokens").Int() != 14361 { t.Errorf("usage.cache_write_tokens = %d, want 14361", root.Get("usage.cache_write_tokens").Int()) @@ -3206,8 +3247,11 @@ func TestRegressionIssue5910_UsageStatsCacheWriteTokensInResponses(t *testing.T) if detail.CacheCreationTokens != 14361 { t.Errorf("ParseInteractionsUsage CacheCreationTokens = %d, want 14361", detail.CacheCreationTokens) } - if detail.InputTokens != 53 { - t.Errorf("ParseInteractionsUsage InputTokens = %d, want 53", detail.InputTokens) + if detail.InputTokens != 14414 { + t.Errorf("ParseInteractionsUsage InputTokens = %d, want 14414", detail.InputTokens) + } + if detail.TokenBreakdown.Quality != usage.TokenAccountingQualityComplete || detail.TokenBreakdown.Input.UncachedTokens != 3 { + t.Errorf("token breakdown = %+v, want complete with 3 uncached", detail.TokenBreakdown) } // 2. Streaming test @@ -3265,8 +3309,11 @@ func TestRegressionIssue5910_UsageStatsCacheWriteTokensInResponses(t *testing.T) if sDetail.CacheCreationTokens != 14361 { t.Errorf("ParseInteractionsStreamUsage CacheCreationTokens = %d, want 14361", sDetail.CacheCreationTokens) } - if sDetail.InputTokens != 53 { - t.Errorf("ParseInteractionsStreamUsage InputTokens = %d, want 53", sDetail.InputTokens) + if sDetail.InputTokens != 14414 { + t.Errorf("ParseInteractionsStreamUsage InputTokens = %d, want 14414", sDetail.InputTokens) + } + if got := cRoot.Get("interaction.usage.total_input_tokens").Int(); got != 14414 { + t.Errorf("interaction.usage.total_input_tokens = %d, want 14414", got) } } diff --git a/internal/runtime/executor/devin_issue7442_test.go b/internal/runtime/executor/devin_issue7442_test.go new file mode 100644 index 00000000000..6a6fb81422c --- /dev/null +++ b/internal/runtime/executor/devin_issue7442_test.go @@ -0,0 +1,1341 @@ +package executor + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + "google.golang.org/protobuf/encoding/protowire" +) + +type issue7442UsageCapture struct { + prefix string + records chan coreusage.Record +} + +func (c *issue7442UsageCapture) HandleUsage(_ context.Context, record coreusage.Record) { + if strings.HasPrefix(record.AuthID, c.prefix) { + select { + case c.records <- record: + default: + } + } +} + +func buildIssue7442DevinUsageFrame(promptTokens, completionTokens, cachedTokens, cacheWriteTokens uint64) []byte { + var f7 []byte + f7 = protowire.AppendTag(f7, 2, protowire.VarintType) + f7 = protowire.AppendVarint(f7, promptTokens) + f7 = protowire.AppendTag(f7, 3, protowire.VarintType) + f7 = protowire.AppendVarint(f7, completionTokens) + if cacheWriteTokens > 0 { + f7 = protowire.AppendTag(f7, 4, protowire.VarintType) + f7 = protowire.AppendVarint(f7, cacheWriteTokens) + } + f7 = protowire.AppendTag(f7, 5, protowire.VarintType) + f7 = protowire.AppendVarint(f7, cachedTokens) + + var frame []byte + frame = protowire.AppendTag(frame, 7, protowire.BytesType) + frame = protowire.AppendBytes(frame, f7) + return helps.WrapConnectEnvelope(frame) +} + +func buildIssue7442DevinTextStream(text string, promptTokens, completionTokens uint64) []byte { + var textFrame []byte + textFrame = protowire.AppendTag(textFrame, 3, protowire.BytesType) + textFrame = protowire.AppendString(textFrame, text) + + var buf bytes.Buffer + buf.Write(helps.WrapConnectEnvelope(textFrame)) + buf.Write(buildIssue7442DevinUsageFrame(promptTokens, completionTokens, 0, 0)) + buf.Write(helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))) + return buf.Bytes() +} + +func TestIssue7442_DevinEmptyCompletionFailsOverWithoutCredentialCooldown(t *testing.T) { + var metadataFrame []byte + metadataFrame = protowire.AppendTag(metadataFrame, 1, protowire.BytesType) + metadataFrame = protowire.AppendString(metadataFrame, "out_dead_slot") + + cases := []struct { + name string + badFrames []byte + }{ + { + name: "zero_usage_clean_eos", + badFrames: append( + buildIssue7442DevinUsageFrame(0, 0, 0, 0), + helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))..., + ), + }, + { + name: "no_usage_metadata_only_clean_eos", + badFrames: append( + helps.WrapConnectEnvelope(metadataFrame), + helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))..., + ), + }, + { + name: "prompt_tokens_only_zero_output_clean_eos", + badFrames: append( + buildIssue7442DevinUsageFrame(420, 0, 120, 0), + helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))..., + ), + }, + { + name: "premature_eof_before_any_output", + badFrames: helps.WrapConnectEnvelope(metadataFrame), + }, + } + + type execMode struct { + name string + stream bool + format sdktranslator.Format + } + modes := []execMode{ + {name: "stream_openai", stream: true, format: sdktranslator.FormatOpenAI}, + {name: "stream_responses", stream: true, format: sdktranslator.FormatOpenAIResponse}, + {name: "stream_interactions", stream: true, format: sdktranslator.FormatInteractions}, + {name: "stream_claude", stream: true, format: sdktranslator.FormatClaude}, + {name: "stream_gemini", stream: true, format: sdktranslator.FormatGemini}, + {name: "nonstream_openai", stream: false, format: sdktranslator.FormatOpenAI}, + {name: "nonstream_responses", stream: false, format: sdktranslator.FormatOpenAIResponse}, + {name: "nonstream_interactions", stream: false, format: sdktranslator.FormatInteractions}, + {name: "nonstream_claude", stream: false, format: sdktranslator.FormatClaude}, + {name: "nonstream_gemini", stream: false, format: sdktranslator.FormatGemini}, + } + for _, tc := range cases { + for _, em := range modes { + stream := em.stream + clientFormat := em.format + t.Run(tc.name+"/"+em.name, func(t *testing.T) { + prefix := "issue7442-" + uuid.NewString() + capture := &issue7442UsageCapture{prefix: prefix, records: make(chan coreusage.Record, 8)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), multiProviderNoopUsagePlugin{}) + }) + + var badHits atomic.Int32 + var goodHits atomic.Int32 + goodFrames := buildIssue7442DevinTextStream("recovered-from-second-credential", 25, 6) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + w.Header().Set("Content-Type", "application/connect+proto") + authHeader := r.Header.Get("Authorization") + if strings.Contains(authHeader, "bad-token") { + badHits.Add(1) + _, _ = w.Write(tc.badFrames) + return + } + goodHits.Add(1) + _, _ = w.Write(goodFrames) + })) + defer server.Close() + + cfg := &config.Config{DisableCooling: false} + manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewDevinExecutor(cfg)) + + const model = "devin/swe-2" + badAuth := &cliproxyauth.Auth{ + ID: prefix + "-bad", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{ + "api_key": "bad-token", + "base_url": server.URL, + "priority": "10", + }, + } + goodAuth := &cliproxyauth.Auth{ + ID: prefix + "-good", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{ + "api_key": "good-token", + "base_url": server.URL, + "priority": "5", + }, + } + for _, candidate := range []*cliproxyauth.Auth{badAuth, goodAuth} { + registry.GetGlobalRegistry().RegisterClient(candidate.ID, "devin", []*registry.ModelInfo{{ID: model}}) + id := candidate.ID + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + if _, errRegister := manager.Register(context.Background(), candidate); errRegister != nil { + t.Fatalf("register %s: %v", candidate.ID, errRegister) + } + } + + var rawReq []byte + switch clientFormat { + case sdktranslator.FormatOpenAIResponse, sdktranslator.FormatInteractions: + rawReq = []byte(fmt.Sprintf(`{"model":%q,"stream":%t,"input":[{"role":"user","content":"hello"}]}`, model, stream)) + case sdktranslator.FormatClaude: + rawReq = []byte(fmt.Sprintf(`{"model":%q,"max_tokens":64,"stream":%t,"messages":[{"role":"user","content":"hello"}]}`, model, stream)) + case sdktranslator.FormatGemini: + rawReq = []byte(`{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}`) + default: + rawReq = []byte(fmt.Sprintf(`{"model":%q,"stream":%t,"messages":[{"role":"user","content":"hello"}]}`, model, stream)) + } + req := cliproxyexecutor.Request{Model: model, Payload: rawReq} + opts := cliproxyexecutor.Options{ + Stream: stream, + SourceFormat: clientFormat, + ResponseFormat: clientFormat, + OriginalRequest: rawReq, + } + + ctx := context.Background() + var combinedOut strings.Builder + if stream { + streamRes, errStream := manager.ExecuteStream(ctx, []string{"devin"}, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream failed: %v", errStream) + } + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected chunk error after failover: %v", chunk.Err) + } + combinedOut.Write(chunk.Payload) + } + } else { + resp, errExec := manager.Execute(ctx, []string{"devin"}, req, opts) + if errExec != nil { + t.Fatalf("Execute failed: %v", errExec) + } + combinedOut.Write(resp.Payload) + } + + if badHits.Load() != 1 || goodHits.Load() != 1 { + t.Fatalf("upstream hits bad=%d good=%d, want 1 and 1", badHits.Load(), goodHits.Load()) + } + if !strings.Contains(combinedOut.String(), "recovered-from-second-credential") { + t.Fatalf("expected failover response text, got: %s", combinedOut.String()) + } + + gotBad, okBad := manager.GetByID(badAuth.ID) + if !okBad || gotBad == nil { + t.Fatalf("missing registered auth %s", badAuth.ID) + } + now := time.Now() + if gotBad.Unavailable || !gotBad.NextRetryAfter.IsZero() || !cliproxyauth.IsAuthAvailableForModel(gotBad, model, now) { + t.Fatalf("dead-slot failure cooled healthy credential %s: unavailable=%v nextRetryAfter=%v modelStates=%+v", + badAuth.ID, gotBad.Unavailable, gotBad.NextRetryAfter, gotBad.ModelStates) + } + + sawBadFailureRecord := false + deadline := time.NewTimer(2 * time.Second) + defer deadline.Stop() + for i := 0; i < 2; i++ { + select { + case rec := <-capture.records: + if rec.AuthID == badAuth.ID { + if !rec.Failed { + t.Fatalf("bad auth usage record marked Failed=false on dead slot: %+v", rec) + } + sawBadFailureRecord = true + } + case <-deadline.C: + t.Fatal("timed out waiting for usage records") + } + } + if !sawBadFailureRecord { + t.Fatalf("did not observe failure usage record for %s", badAuth.ID) + } + }) + } + } +} + +func TestIssue7442_DevinAllDeadCredentialsFailOverToFallbackProviderLayerWithoutCoolingDevinPool(t *testing.T) { + deadDevinFrames := append( + buildIssue7442DevinUsageFrame(0, 0, 0, 0), + helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))..., + ) + + for _, stream := range []bool{true, false} { + mode := "nonstream" + if stream { + mode = "stream" + } + t.Run(mode, func(t *testing.T) { + var devinAttempts atomic.Int32 + devinServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + devinAttempts.Add(1) + w.Header().Set("Content-Type", "application/connect+proto") + _, _ = w.Write(deadDevinFrames) + })) + defer devinServer.Close() + + var fallbackAttempts atomic.Int32 + fallbackServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fallbackAttempts.Add(1) + if stream { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-fb\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"fallback-layer-ok\"}}]}\n\n")) + _, _ = w.Write([]byte("data: {\"id\":\"chatcmpl-fb\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":3,\"total_tokens\":11}}\n\n")) + _, _ = w.Write([]byte("data: [DONE]\n\n")) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"chatcmpl-fb","object":"chat.completion","model":"shared-swe-2","choices":[{"index":0,"message":{"role":"assistant","content":"fallback-layer-ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":8,"completion_tokens":3,"total_tokens":11}}`)) + })) + defer fallbackServer.Close() + + const routeModel = "shared-swe-2" + cfg := &config.Config{ + DisableCooling: false, + OAuthModelAlias: map[string][]config.OAuthModelAlias{ + "devin": { + {Name: "devin/swe-2", Alias: routeModel}, + }, + }, + OpenAICompatibility: []config.OpenAICompatibility{ + { + Name: "fallback-compat", + BaseURL: fallbackServer.URL, + APIKeyEntries: []config.OpenAICompatibilityAPIKey{ + {APIKey: "fb-key"}, + }, + Models: []config.OpenAICompatibilityModel{ + {Name: routeModel, Alias: routeModel}, + }, + }, + }, + } + + manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewDevinExecutor(cfg)) + manager.RegisterExecutor(NewOpenAICompatExecutor("openai-compatibility", cfg)) + + prefix := "issue7442-layer-" + uuid.NewString() + devinAuth1 := &cliproxyauth.Auth{ + ID: prefix + "-devin-1", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{ + "api_key": "d1", + "base_url": devinServer.URL, + "priority": "20", + }, + } + devinAuth2 := &cliproxyauth.Auth{ + ID: prefix + "-devin-2", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{ + "api_key": "d2", + "base_url": devinServer.URL, + "priority": "15", + }, + } + fallbackAuth := &cliproxyauth.Auth{ + ID: prefix + "-fb", + Provider: "openai-compatibility", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{ + "api_key": "fb-key", + "base_url": fallbackServer.URL, + "priority": "1", + }, + } + + for _, candidate := range []*cliproxyauth.Auth{devinAuth1, devinAuth2} { + registry.GetGlobalRegistry().RegisterClient(candidate.ID, "devin", []*registry.ModelInfo{{ID: "devin/swe-2"}, {ID: routeModel}}) + id := candidate.ID + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + if _, errRegister := manager.Register(context.Background(), candidate); errRegister != nil { + t.Fatalf("register %s: %v", candidate.ID, errRegister) + } + } + registry.GetGlobalRegistry().RegisterClient(fallbackAuth.ID, "openai-compatibility", []*registry.ModelInfo{{ID: routeModel}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(fallbackAuth.ID) }) + if _, errRegister := manager.Register(context.Background(), fallbackAuth); errRegister != nil { + t.Fatalf("register fallback: %v", errRegister) + } + + rawReq := []byte(fmt.Sprintf(`{"model":%q,"stream":%t,"messages":[{"role":"user","content":"hello"}]}`, routeModel, stream)) + req := cliproxyexecutor.Request{Model: routeModel, Payload: rawReq} + opts := cliproxyexecutor.Options{ + Stream: stream, + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: rawReq, + } + + var outText strings.Builder + if stream { + res, errStream := manager.ExecuteStream(context.Background(), []string{"devin", "openai-compatibility"}, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream failed: %v", errStream) + } + for chunk := range res.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected chunk error: %v", chunk.Err) + } + outText.Write(chunk.Payload) + } + } else { + resp, errExec := manager.Execute(context.Background(), []string{"devin", "openai-compatibility"}, req, opts) + if errExec != nil { + t.Fatalf("Execute failed: %v", errExec) + } + outText.Write(resp.Payload) + } + + if devinAttempts.Load() != 2 || fallbackAttempts.Load() != 1 { + t.Fatalf("attempts devin=%d fallback=%d, want 2 and 1", devinAttempts.Load(), fallbackAttempts.Load()) + } + if !strings.Contains(outText.String(), "fallback-layer-ok") { + t.Fatalf("expected fallback layer output, got: %s", outText.String()) + } + + now := time.Now() + for _, id := range []string{devinAuth1.ID, devinAuth2.ID} { + got, ok := manager.GetByID(id) + if !ok || got == nil { + t.Fatalf("missing auth %s", id) + } + if got.Unavailable || !got.NextRetryAfter.IsZero() || !cliproxyauth.IsAuthAvailableForModel(got, "devin/swe-2", now) { + t.Fatalf("Devin credential %s was cooled by dead upstream slot: unavailable=%v nextRetryAfter=%v modelStates=%+v", + id, got.Unavailable, got.NextRetryAfter, got.ModelStates) + } + } + }) + } +} + +func TestIssue7442_DevinDanglingStreamCanceledDoesNotEmitCompletedOrRecordSuccessUsage(t *testing.T) { + t.Run("before_any_frames", func(t *testing.T) { + gin.SetMode(gin.TestMode) + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + + prefix := "issue7442-cancel-" + uuid.NewString() + capture := &issue7442UsageCapture{prefix: prefix, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), multiProviderNoopUsagePlugin{}) + }) + + headersFlushed := make(chan struct{}) + releaseServer := make(chan struct{}) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + w.Header().Set("Content-Type", "application/connect+proto") + w.WriteHeader(http.StatusOK) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + close(headersFlushed) + select { + case <-r.Context().Done(): + case <-releaseServer: + } + })) + defer close(releaseServer) + defer server.Close() + + cfg := &config.Config{} + exec := NewDevinExecutor(cfg) + auth := &cliproxyauth.Auth{ + ID: prefix + "-auth", + Provider: "devin", + Attributes: map[string]string{ + "api_key": "dangling-token", + "base_url": server.URL, + }, + } + + baseCtx := context.WithValue(context.Background(), "gin", ginCtx) + ctx, cancel := context.WithCancel(baseCtx) + defer cancel() + + rawReq := []byte(`{"model":"devin/swe-2","stream":true,"messages":[{"role":"user","content":"hello"}]}`) + req := cliproxyexecutor.Request{Model: "devin/swe-2", Payload: rawReq} + opts := cliproxyexecutor.Options{ + Stream: true, + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: rawReq, + } + + streamRes, errStream := exec.ExecuteStream(ctx, auth, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream failed: %v", errStream) + } + + <-headersFlushed + cancel() + + for chunk := range streamRes.Chunks { + if len(chunk.Payload) > 0 && strings.Contains(string(chunk.Payload), "finish_reason") { + t.Fatalf("dangling canceled stream emitted completion chunk: %s", chunk.Payload) + } + } + + select { + case rec := <-capture.records: + if !rec.Failed { + t.Fatalf("dangling canceled stream published Failed=false usage record: %+v", rec) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for usage record on canceled dangling stream") + } + + if value, exists := ginCtx.Get(logging.DeferredAPIResponseContextKey); exists { + if deferred, ok := value.(logging.DeferredAPIResponse); ok && deferred != nil && deferred.HasPayload() { + rendered := string(deferred.RenderAPIResponse()) + if strings.Contains(rendered, `"event_type":"interaction.completed"`) || strings.Contains(rendered, `"event_type":"interaction.created"`) { + t.Fatalf("dangling canceled stream synthesized fake interaction lifecycle in log:\n%s", rendered) + } + } + } + }) + + t.Run("during_downstream_emit_with_partial_usage", func(t *testing.T) { + gin.SetMode(gin.TestMode) + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + + prefix := "issue7442-cancelemit-" + uuid.NewString() + capture := &issue7442UsageCapture{prefix: prefix, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), multiProviderNoopUsagePlugin{}) + }) + + var textFrame1, textFrame2 []byte + textFrame1 = protowire.AppendTag(textFrame1, 3, protowire.BytesType) + textFrame1 = protowire.AppendString(textFrame1, "chunk-one ") + textFrame2 = protowire.AppendTag(textFrame2, 3, protowire.BytesType) + textFrame2 = protowire.AppendString(textFrame2, "chunk-two") + + releaseServer := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + w.Header().Set("Content-Type", "application/connect+proto") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(buildIssue7442DevinUsageFrame(42, 7, 0, 0)) + _, _ = w.Write(helps.WrapConnectEnvelope(textFrame1)) + _, _ = w.Write(helps.WrapConnectEnvelope(textFrame2)) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + select { + case <-r.Context().Done(): + case <-releaseServer: + } + })) + defer close(releaseServer) + defer server.Close() + + cfg := &config.Config{} + exec := NewDevinExecutor(cfg) + auth := &cliproxyauth.Auth{ + ID: prefix + "-auth", + Provider: "devin", + Attributes: map[string]string{ + "api_key": "dangling-emit-token", + "base_url": server.URL, + }, + } + + baseCtx := context.WithValue(context.Background(), "gin", ginCtx) + ctx, cancel := context.WithCancel(baseCtx) + defer cancel() + + rawReq := []byte(`{"model":"devin/swe-2","stream":true,"input":[{"role":"user","content":"hello"}]}`) + req := cliproxyexecutor.Request{Model: "devin/swe-2", Payload: rawReq} + opts := cliproxyexecutor.Options{ + Stream: true, + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + OriginalRequest: rawReq, + } + + streamRes, errStream := exec.ExecuteStream(ctx, auth, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream failed: %v", errStream) + } + + // Read only the first SSE chunk so streamDevinFramesForAuth blocks inside + // emitInteractionsEvent on subsequent chunks, then cancel ctx mid-emit. + firstChunk, ok := <-streamRes.Chunks + if !ok || len(firstChunk.Payload) == 0 { + t.Fatalf("expected initial SSE chunk before cancel, got ok=%v chunk=%+v", ok, firstChunk) + } + cancel() + + for chunk := range streamRes.Chunks { + if bytes.Contains(chunk.Payload, []byte(`"event_type":"interaction.completed"`)) { + t.Fatalf("canceled mid-emit stream synthesized interaction.completed: %s", chunk.Payload) + } + } + + select { + case rec := <-capture.records: + if !rec.Failed { + t.Fatalf("mid-emit canceled stream published Failed=false usage record: %+v", rec) + } + if rec.Detail.InputTokens != 42 || rec.Detail.OutputTokens != 7 { + t.Fatalf("mid-emit canceled stream lost partial usage detail: got in=%d out=%d, want 42 and 7", + rec.Detail.InputTokens, rec.Detail.OutputTokens) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for usage record on mid-emit canceled stream") + } + }) + + t.Run("during_close_open_steps_after_eos_preserves_cached_usage_and_skips_completed", func(t *testing.T) { + gin.SetMode(gin.TestMode) + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + + prefix := "issue7442-cancelclose-" + uuid.NewString() + capture := &issue7442UsageCapture{prefix: prefix, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), multiProviderNoopUsagePlugin{}) + }) + + var thoughtFrame, textFrame []byte + thoughtFrame = protowire.AppendTag(thoughtFrame, 9, protowire.BytesType) + thoughtFrame = protowire.AppendString(thoughtFrame, "reasoning-step") + textFrame = protowire.AppendTag(textFrame, 3, protowire.BytesType) + textFrame = protowire.AppendString(textFrame, "final-answer") + + eosBody := append([]byte{}, buildIssue7442DevinUsageFrame(31, 6, 10, 4)...) + eosBody = append(eosBody, helps.WrapConnectEnvelope(thoughtFrame)...) + eosBody = append(eosBody, helps.WrapConnectEnvelope(textFrame)...) + eosBody = append(eosBody, helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))...) + + serverDone := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + w.Header().Set("Content-Type", "application/connect+proto") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(eosBody) + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } + close(serverDone) + })) + defer server.Close() + + cfg := &config.Config{} + exec := NewDevinExecutor(cfg) + auth := &cliproxyauth.Auth{ + ID: prefix + "-auth", + Provider: "devin", + Attributes: map[string]string{ + "api_key": "close-cancel-token", + "base_url": server.URL, + }, + } + + baseCtx := context.WithValue(context.Background(), "gin", ginCtx) + ctx, cancel := context.WithCancel(baseCtx) + defer cancel() + + rawReq := []byte(`{"model":"devin/swe-2","stream":true,"input":[{"role":"user","content":"hello"}]}`) + req := cliproxyexecutor.Request{Model: "devin/swe-2", Payload: rawReq} + opts := cliproxyexecutor.Options{ + Stream: true, + SourceFormat: sdktranslator.FormatInteractions, + ResponseFormat: sdktranslator.FormatInteractions, + OriginalRequest: rawReq, + } + + streamRes, errStream := exec.ExecuteStream(ctx, auth, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream failed: %v", errStream) + } + + // Wait until server wrote all frames including EOS, read only the first two + // chunks (interaction.created + thinking step.start + thinking step.delta so + // closeOpenSteps blocks emitting pending content after EOS), then cancel and drain. + <-serverDone + for i := 0; i < 3; i++ { + chunk, ok := <-streamRes.Chunks + if !ok || len(chunk.Payload) == 0 { + t.Fatalf("expected initial chunk %d before cancel, got ok=%v chunk=%+v", i, ok, chunk) + } + } + cancel() + + for chunk := range streamRes.Chunks { + if bytes.Contains(chunk.Payload, []byte(`"event_type":"interaction.completed"`)) { + t.Fatalf("post-EOS canceled closeOpenSteps still emitted interaction.completed: %s", chunk.Payload) + } + } + + select { + case rec := <-capture.records: + if !rec.Failed { + t.Fatalf("post-EOS canceled stream published Failed=false usage record: %+v", rec) + } + // Total input = 31 uncached + 10 cached + 4 cache_write = 45. + if rec.Detail.InputTokens != 45 || rec.Detail.OutputTokens != 6 || rec.Detail.CachedTokens != 10 || rec.Detail.CacheCreationTokens != 4 { + t.Fatalf("post-EOS canceled stream lost cached usage detail: %+v", rec.Detail) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for usage record on post-EOS canceled stream") + } + }) +} + +func TestIssue7442_DevinDeclaredApplyPatchPreservesEmptyCompletionAndQuotaErrorsWhenNoPatchActivity(t *testing.T) { + for _, badCase := range []struct { + name string + badFrames []byte + }{ + { + name: "empty_completion_rotates_instead_of_apply_patch_error", + badFrames: append( + buildIssue7442DevinUsageFrame(0, 0, 0, 0), + helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))..., + ), + }, + { + name: "premature_eof_rotates_instead_of_apply_patch_error", + badFrames: nil, + }, + { + name: "stream_read_error_rotates_instead_of_apply_patch_error", + badFrames: []byte{0, 0}, + }, + } { + for _, stream := range []bool{false, true} { + mode := "nonstream" + if stream { + mode = "stream" + } + t.Run(badCase.name+"/"+mode, func(t *testing.T) { + goodFrames := buildIssue7442DevinTextStream("patch-free-ok", 20, 4) + + var badHits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + w.Header().Set("Content-Type", "application/connect+proto") + if strings.Contains(r.Header.Get("Authorization"), "bad-patch") { + badHits.Add(1) + _, _ = w.Write(badCase.badFrames) + return + } + _, _ = w.Write(goodFrames) + })) + defer server.Close() + + cfg := &config.Config{DisableCooling: false} + manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewDevinExecutor(cfg)) + + const model = "devin/swe-2" + prefix := "issue7442-patch-" + uuid.NewString() + badAuth := &cliproxyauth.Auth{ + ID: prefix + "-bad", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"api_key": "bad-patch", "base_url": server.URL, "priority": "10"}, + } + goodAuth := &cliproxyauth.Auth{ + ID: prefix + "-good", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"api_key": "good-patch", "base_url": server.URL, "priority": "5"}, + } + for _, candidate := range []*cliproxyauth.Auth{badAuth, goodAuth} { + registry.GetGlobalRegistry().RegisterClient(candidate.ID, "devin", []*registry.ModelInfo{{ID: model}}) + id := candidate.ID + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + if _, errRegister := manager.Register(context.Background(), candidate); errRegister != nil { + t.Fatal(errRegister) + } + } + + req := cliproxyexecutor.Request{Model: model, Payload: []byte(task6PatchRequest)} + opts := cliproxyexecutor.Options{ + Stream: stream, + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: []byte(task6PatchRequest), + } + + var out strings.Builder + if stream { + res, errStream := manager.ExecuteStream(context.Background(), []string{"devin"}, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream failed: %v", errStream) + } + for chunk := range res.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected stream chunk error: %v", chunk.Err) + } + out.Write(chunk.Payload) + } + } else { + resp, errExec := manager.Execute(context.Background(), []string{"devin"}, req, opts) + if errExec != nil { + t.Fatalf("Execute failed: %v", errExec) + } + out.Write(resp.Payload) + } + if badHits.Load() != 1 || !strings.Contains(out.String(), "patch-free-ok") { + t.Fatalf("badHits=%d payload=%s", badHits.Load(), out.String()) + } + gotBad, _ := manager.GetByID(badAuth.ID) + if gotBad.Unavailable || !gotBad.NextRetryAfter.IsZero() { + t.Fatalf("badAuth was cooled on pre-output failure: unavailable=%v nextRetryAfter=%v", gotBad.Unavailable, gotBad.NextRetryAfter) + } + }) + } + } + + for _, stream := range []bool{false, true} { + mode := "nonstream" + if stream { + mode = "stream" + } + t.Run("trailer_rate_limit_not_masked_as_apply_patch_error/"+mode, func(t *testing.T) { + trailer429 := helps.WrapConnectEnvelopeWithFlag( + helps.ConnectFlagEndStream, + []byte(`{"error":{"code":"resource_exhausted","message":"rate limit"}}`), + ) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + w.Header().Set("Content-Type", "application/connect+proto") + _, _ = w.Write(trailer429) + })) + defer server.Close() + + exec := NewDevinExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + ID: "issue7442-patch-429-" + mode, + Provider: "devin", + Attributes: map[string]string{"api_key": "tok", "base_url": server.URL}, + } + req := cliproxyexecutor.Request{Model: "devin/swe-2", Payload: []byte(task6PatchRequest)} + opts := cliproxyexecutor.Options{ + Stream: stream, + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: []byte(task6PatchRequest), + } + + var gotErr error + if stream { + res, errStream := exec.ExecuteStream(context.Background(), auth, req, opts) + if errStream != nil { + gotErr = errStream + } else { + for chunk := range res.Chunks { + if chunk.Err != nil { + gotErr = chunk.Err + } else if len(chunk.Payload) > 0 { + t.Fatalf("unexpected SSE payload before trailer 429 error: %s", chunk.Payload) + } + } + } + } else { + _, gotErr = exec.Execute(context.Background(), auth, req, opts) + } + if gotErr == nil { + t.Fatal("expected 429 error, got nil") + } + if strings.Contains(gotErr.Error(), helps.ApplyPatchUpstreamErrorMessage) { + t.Fatalf("trailer 429 was masked as apply_patch error: %v", gotErr) + } + var status cliproxyexecutor.StatusError + if !errors.As(gotErr, &status) || status.StatusCode() != http.StatusTooManyRequests { + t.Fatalf("status error = %T (%v), want 429", gotErr, gotErr) + } + }) + } + + for _, stream := range []bool{false, true} { + mode := "nonstream" + if stream { + mode = "stream" + } + t.Run("truncated_active_apply_patch_preserves_stream_truncated_without_replay_or_cooldown/"+mode, func(t *testing.T) { + truncatedPatchFrames := task6DevinFrames(`{"input":"*** Begin Patch\n*** Add File: a.txt\n+ok\n*** End Patch"}`, false, "") + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + hits.Add(1) + w.Header().Set("Content-Type", "application/connect+proto") + _, _ = w.Write(truncatedPatchFrames) + })) + defer server.Close() + + cfg := &config.Config{DisableCooling: false} + manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewDevinExecutor(cfg)) + + const model = "devin/swe-2" + prefix := "issue7442-truncpatch-" + uuid.NewString() + auth1 := &cliproxyauth.Auth{ + ID: prefix + "-1", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"api_key": "tp1", "base_url": server.URL, "priority": "10"}, + } + auth2 := &cliproxyauth.Auth{ + ID: prefix + "-2", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"api_key": "tp2", "base_url": server.URL, "priority": "5"}, + } + for _, candidate := range []*cliproxyauth.Auth{auth1, auth2} { + registry.GetGlobalRegistry().RegisterClient(candidate.ID, "devin", []*registry.ModelInfo{{ID: model}}) + id := candidate.ID + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + if _, errRegister := manager.Register(context.Background(), candidate); errRegister != nil { + t.Fatal(errRegister) + } + } + + req := cliproxyexecutor.Request{Model: model, Payload: []byte(task6PatchRequest)} + opts := cliproxyexecutor.Options{ + Stream: stream, + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: []byte(task6PatchRequest), + } + + var gotErr error + if stream { + res, errStream := manager.ExecuteStream(context.Background(), []string{"devin"}, req, opts) + if errStream != nil { + gotErr = errStream + } else { + for chunk := range res.Chunks { + if chunk.Err != nil { + gotErr = chunk.Err + } + } + } + } else { + _, gotErr = manager.Execute(context.Background(), []string{"devin"}, req, opts) + } + assertTask6PatchError(t, gotErr) + var truncErr cliproxyexecutor.StreamTruncatedError + if !errors.As(gotErr, &truncErr) || !truncErr.IsStreamTruncated() { + t.Fatalf("gotErr = %T (%v), want IsStreamTruncated()==true", gotErr, gotErr) + } + if hits.Load() != 1 { + t.Fatalf("hits = %d, want 1 (active apply_patch truncation must not replay)", hits.Load()) + } + got1, _ := manager.GetByID(auth1.ID) + if got1.Unavailable || !got1.NextRetryAfter.IsZero() { + t.Fatalf("truncated apply_patch stream cooled credential %s: unavailable=%v nextRetryAfter=%v", + auth1.ID, got1.Unavailable, got1.NextRetryAfter) + } + }) + } + + for _, patchCase := range []struct { + name string + frames []byte + }{ + { + name: "invalid_patch_json_preserves_partial_usage", + frames: append( + buildIssue7442DevinUsageFrame(55, 9, 0, 0), + task6DevinFrames(`{"input":7}`, false, `{}`)..., + ), + }, + { + name: "truncated_patch_before_eos_preserves_partial_usage", + frames: append( + buildIssue7442DevinUsageFrame(55, 9, 0, 0), + task6DevinFrames(`{"input":"*** Begin Patch\n*** Add File: a.txt\n+ok\n*** End Patch"}`, false, "")..., + ), + }, + } { + for _, stream := range []bool{false, true} { + mode := "nonstream" + if stream { + mode = "stream" + } + t.Run(patchCase.name+"/"+mode, func(t *testing.T) { + prefix := "issue7442-patchusage-" + uuid.NewString() + capture := &issue7442UsageCapture{prefix: prefix, records: make(chan coreusage.Record, 4)} + coreusage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + coreusage.RegisterNamedPlugin(t.Name(), multiProviderNoopUsagePlugin{}) + }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + w.Header().Set("Content-Type", "application/connect+proto") + _, _ = w.Write(patchCase.frames) + })) + defer server.Close() + + exec := NewDevinExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + ID: prefix + "-auth", + Provider: "devin", + Attributes: map[string]string{"api_key": "pu", "base_url": server.URL}, + } + req := cliproxyexecutor.Request{Model: "devin/swe-2", Payload: []byte(task6PatchRequest)} + opts := cliproxyexecutor.Options{ + Stream: stream, + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: []byte(task6PatchRequest), + } + + if stream { + res, errStream := exec.ExecuteStream(context.Background(), auth, req, opts) + if errStream != nil { + t.Fatal(errStream) + } + for range res.Chunks { + } + } else { + _, errExec := exec.Execute(context.Background(), auth, req, opts) + assertTask6PatchError(t, errExec) + } + + select { + case rec := <-capture.records: + if !rec.Failed { + t.Fatalf("expected Failed=true usage record, got %+v", rec) + } + if rec.Detail.InputTokens != 55 || rec.Detail.OutputTokens != 9 { + t.Fatalf("patch failure lost partial usage: in=%d out=%d, want 55 and 9", + rec.Detail.InputTokens, rec.Detail.OutputTokens) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for patch failure usage record") + } + }) + } + } +} + +func TestIssue7442_DevinEmptyCompletionExhaustedReturns502AndSupportsRequestScopedStopRule(t *testing.T) { + deadFrames := append( + buildIssue7442DevinUsageFrame(0, 0, 0, 0), + helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))..., + ) + + t.Run("exhausted_returns_502_without_cooling", func(t *testing.T) { + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + hits.Add(1) + w.Header().Set("Content-Type", "application/connect+proto") + _, _ = w.Write(deadFrames) + })) + defer server.Close() + + cfg := &config.Config{DisableCooling: false} + manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewDevinExecutor(cfg)) + + const model = "devin/swe-2" + prefix := "issue7442-exhaust-" + uuid.NewString() + for i, prio := range []string{"10", "5"} { + candidate := &cliproxyauth.Auth{ + ID: fmt.Sprintf("%s-%d", prefix, i), + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"api_key": fmt.Sprintf("k%d", i), "base_url": server.URL, "priority": prio}, + } + registry.GetGlobalRegistry().RegisterClient(candidate.ID, "devin", []*registry.ModelInfo{{ID: model}}) + id := candidate.ID + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + if _, errRegister := manager.Register(context.Background(), candidate); errRegister != nil { + t.Fatal(errRegister) + } + } + + rawReq := []byte(`{"model":"devin/swe-2","stream":true,"messages":[{"role":"user","content":"hello"}]}`) + req := cliproxyexecutor.Request{Model: model, Payload: rawReq} + opts := cliproxyexecutor.Options{ + Stream: true, + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: rawReq, + } + res, errStream := manager.ExecuteStream(context.Background(), []string{"devin"}, req, opts) + var finalStreamErr error + if errStream != nil { + finalStreamErr = errStream + } else if res != nil { + for chunk := range res.Chunks { + if chunk.Err != nil { + finalStreamErr = chunk.Err + } else if len(chunk.Payload) > 0 { + t.Fatalf("expected no SSE payload before 502 bootstrap error, got %q", string(chunk.Payload)) + } + } + } + if finalStreamErr == nil { + t.Fatal("expected 502 error when all Devin credentials return empty completion, got nil") + } + var statusErr cliproxyexecutor.StatusError + if !errors.As(finalStreamErr, &statusErr) || statusErr.StatusCode() != http.StatusBadGateway { + t.Fatalf("finalStreamErr = %T (%v), want HTTP 502 StatusError", finalStreamErr, finalStreamErr) + } + if hits.Load() != 2 { + t.Fatalf("hits = %d, want 2", hits.Load()) + } + + // Also verify non-streaming returns HTTP 502 directly when exhausted. + opts.Stream = false + _, errExec := manager.Execute(context.Background(), []string{"devin"}, req, opts) + if !errors.As(errExec, &statusErr) || statusErr.StatusCode() != http.StatusBadGateway { + t.Fatalf("errExec = %T (%v), want HTTP 502 StatusError", errExec, errExec) + } + if hits.Load() != 4 { + t.Fatalf("hits after non-stream = %d, want 4", hits.Load()) + } + }) + + t.Run("request_scoped_errors_stop_rule_halts_dead_payload_retries", func(t *testing.T) { + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + hits.Add(1) + w.Header().Set("Content-Type", "application/connect+proto") + _, _ = w.Write(deadFrames) + })) + defer server.Close() + + cfg := &config.Config{ + DisableCooling: false, + OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{ + "devin": { + { + Status: http.StatusBadGateway, + Match: []string{"empty completion"}, + Action: "stop", + }, + }, + }, + } + manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewDevinExecutor(cfg)) + + const model = "devin/swe-2" + prefix := "issue7442-stoprule-" + uuid.NewString() + for i, prio := range []string{"10", "5"} { + candidate := &cliproxyauth.Auth{ + ID: fmt.Sprintf("%s-%d", prefix, i), + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{ + "auth_kind": "oauth", + "base_url": server.URL, + "priority": prio, + }, + Metadata: map[string]any{ + "session_token": fmt.Sprintf("oauth-tok-%d", i), + }, + } + registry.GetGlobalRegistry().RegisterClient(candidate.ID, "devin", []*registry.ModelInfo{{ID: model}}) + id := candidate.ID + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + if _, errRegister := manager.Register(context.Background(), candidate); errRegister != nil { + t.Fatal(errRegister) + } + } + + rawReq := []byte(`{"model":"devin/swe-2","stream":true,"messages":[{"role":"user","content":"hello"}]}`) + req := cliproxyexecutor.Request{Model: model, Payload: rawReq} + opts := cliproxyexecutor.Options{ + Stream: true, + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: rawReq, + } + _, errStream := manager.ExecuteStream(context.Background(), []string{"devin"}, req, opts) + if errStream == nil { + t.Fatal("expected error from stop rule, got nil") + } + if hits.Load() != 1 { + t.Fatalf("hits = %d, want 1 when oauth-request-scoped-errors action=stop matches empty completion", hits.Load()) + } + }) +} + +func TestIssue7442_DevinPartialOutputPrematureEOFIsStreamTruncatedWithoutReplayOrCooldown(t *testing.T) { + var partialTextFrame []byte + partialTextFrame = protowire.AppendTag(partialTextFrame, 3, protowire.BytesType) + partialTextFrame = protowire.AppendString(partialTextFrame, "partial-generated-text") + partialEOFFrames := helps.WrapConnectEnvelope(partialTextFrame) + partialReadErrFrames := append(append([]byte{}, partialEOFFrames...), 0, 0) + + var activeFrames atomic.Value + activeFrames.Store(partialEOFFrames) + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _, _ = helps.ReadConnectFrame(r.Body) + hits.Add(1) + w.Header().Set("Content-Type", "application/connect+proto") + _, _ = w.Write(activeFrames.Load().([]byte)) + })) + defer server.Close() + + cfg := &config.Config{DisableCooling: false} + manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(0, 0, 0) + manager.RegisterExecutor(NewDevinExecutor(cfg)) + + const model = "devin/swe-2" + prefix := "issue7442-partial-" + uuid.NewString() + auth1 := &cliproxyauth.Auth{ + ID: prefix + "-1", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"api_key": "p1", "base_url": server.URL, "priority": "10"}, + } + auth2 := &cliproxyauth.Auth{ + ID: prefix + "-2", + Provider: "devin", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"api_key": "p2", "base_url": server.URL, "priority": "5"}, + } + for _, candidate := range []*cliproxyauth.Auth{auth1, auth2} { + registry.GetGlobalRegistry().RegisterClient(candidate.ID, "devin", []*registry.ModelInfo{{ID: model}}) + id := candidate.ID + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + if _, errRegister := manager.Register(context.Background(), candidate); errRegister != nil { + t.Fatal(errRegister) + } + } + + for _, dropCase := range []struct { + name string + frames []byte + }{ + {name: "premature_eof", frames: partialEOFFrames}, + {name: "read_error", frames: partialReadErrFrames}, + } { + for _, clientFormat := range []sdktranslator.Format{ + sdktranslator.FormatOpenAI, + sdktranslator.FormatOpenAIResponse, + sdktranslator.FormatInteractions, + sdktranslator.FormatClaude, + sdktranslator.FormatGemini, + } { + for _, stream := range []bool{false, true} { + mode := "nonstream" + if stream { + mode = "stream" + } + t.Run(fmt.Sprintf("%s/%s/%s", dropCase.name, clientFormat.String(), mode), func(t *testing.T) { + activeFrames.Store(dropCase.frames) + hits.Store(0) + var rawReq []byte + switch clientFormat { + case sdktranslator.FormatOpenAIResponse, sdktranslator.FormatInteractions: + rawReq = []byte(fmt.Sprintf(`{"model":"devin/swe-2","stream":%t,"input":[{"role":"user","content":"hello"}]}`, stream)) + case sdktranslator.FormatClaude: + rawReq = []byte(fmt.Sprintf(`{"model":"devin/swe-2","max_tokens":64,"stream":%t,"messages":[{"role":"user","content":"hello"}]}`, stream)) + case sdktranslator.FormatGemini: + rawReq = []byte(`{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}`) + default: + rawReq = []byte(fmt.Sprintf(`{"model":"devin/swe-2","stream":%t,"messages":[{"role":"user","content":"hello"}]}`, stream)) + } + req := cliproxyexecutor.Request{Model: model, Payload: rawReq} + opts := cliproxyexecutor.Options{ + Stream: stream, + SourceFormat: clientFormat, + ResponseFormat: clientFormat, + OriginalRequest: rawReq, + } + + var gotErr error + if stream { + res, errStream := manager.ExecuteStream(context.Background(), []string{"devin"}, req, opts) + if errStream != nil { + gotErr = errStream + } else { + for chunk := range res.Chunks { + if chunk.Err != nil { + gotErr = chunk.Err + } + } + } + } else { + _, gotErr = manager.Execute(context.Background(), []string{"devin"}, req, opts) + } + if gotErr == nil { + t.Fatal("expected truncated error on premature EOF after partial output, got nil") + } + var truncErr cliproxyexecutor.StreamTruncatedError + if !errors.As(gotErr, &truncErr) || !truncErr.IsStreamTruncated() { + t.Fatalf("gotErr = %T (%v), want StreamTruncatedError", gotErr, gotErr) + } + if hits.Load() != 1 { + t.Fatalf("hits = %d, want 1 (partial accepted generation must not replay)", hits.Load()) + } + got1, _ := manager.GetByID(auth1.ID) + if got1.Unavailable || !got1.NextRetryAfter.IsZero() { + t.Fatalf("partial truncated stream cooled credential %s: unavailable=%v nextRetryAfter=%v", auth1.ID, got1.Unavailable, got1.NextRetryAfter) + } + }) + } + } + } +} + +func TestIssue7442_DevinContentFilterZeroTextPreservedAsIncomplete(t *testing.T) { + var stopFrame []byte + stopFrame = protowire.AppendTag(stopFrame, 5, protowire.VarintType) + stopFrame = protowire.AppendVarint(stopFrame, 11) // CONTENT_FILTER + + frames := append( + helps.WrapConnectEnvelope(stopFrame), + helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))..., + ) + + out, _, errConsume := consumeDevinFramesToInteractions(bytes.NewReader(frames), "devin/swe-2", "swe-2-high") + if errConsume != nil { + t.Fatalf("content_filter stop should not fail as empty completion: %v", errConsume) + } + parsed := ojson.ParseBytes(out) + if parsed.Get("status").String() != "incomplete" || parsed.Get("finish_reason").String() != "content_filter" { + t.Fatalf("unexpected content_filter output: %s", out) + } +} diff --git a/internal/runtime/executor/gemini_claude_signature_round_trip_test.go b/internal/runtime/executor/gemini_claude_signature_round_trip_test.go new file mode 100644 index 00000000000..4387482e282 --- /dev/null +++ b/internal/runtime/executor/gemini_claude_signature_round_trip_test.go @@ -0,0 +1,112 @@ +package executor + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + internalcache "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + internalsignature "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestGeminiClaudeCarrierExecutorReplay(t *testing.T) { + for _, backend := range []string{"vertex", "gemini"} { + for _, mode := range []string{"native", "override", "filter"} { + for _, stream := range []bool{false, true} { + name := backend + "/" + mode + "/nonstream" + if stream { + name = backend + "/" + mode + "/stream" + } + t.Run(name, func(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + t.Cleanup(internalcache.ClearAntigravityReasoningReplayCache) + signature := testVertexBareTinkSignature() + captured := make(chan []byte, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read request: %v", errRead) + w.WriteHeader(http.StatusBadRequest) + return + } + captured <- body + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+vertexBareTinkTestOKResponse+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, vertexBareTinkTestOKResponse) + })) + defer server.Close() + + cfg := &config.Config{} + models := []config.PayloadModelRule{{Name: "gemini-4-carbon"}} + signaturePath := "contents.1.parts.0.thoughtSignature" + if mode == "override" { + cfg.Payload.Override = []config.PayloadRule{{Models: models, Params: map[string]any{signaturePath: "configured-signature"}}} + } else if mode == "filter" { + cfg.Payload.Filter = []config.PayloadFilterRule{{Models: models, Params: []string{signaturePath}}} + } + gemini := NewGeminiExecutor(cfg) + execute, executeStream := gemini.Execute, gemini.ExecuteStream + if backend == "vertex" { + vertex := NewGeminiVertexExecutor(cfg) + execute, executeStream = vertex.Execute, vertex.ExecuteStream + } + auth := &cliproxyauth.Auth{ID: t.Name(), Provider: backend, Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL}} + request := ojson.NewDocString(`{"model":"gemini-4-carbon","max_tokens":1024,"messages":[{"role":"user","content":"lookup"},{"role":"assistant","content":[{"type":"thinking","thinking":"","signature":""},{"type":"tool_use","id":"call-1","name":"lookup","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call-1","content":"ok"}]}]}`) + _ = request.Set("messages.1.content.0.signature", signature) + req := cliproxyexecutor.Request{Model: "gemini-4-carbon", Payload: request.Bytes()} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude} + if stream { + response, errExecute := executeStream(context.Background(), auth, req, opts) + if errExecute != nil { + t.Fatal(errExecute) + } + for chunk := range response.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, errExecute := execute(context.Background(), auth, req, opts); errExecute != nil { + t.Fatal(errExecute) + } + var body []byte + select { + case body = <-captured: + default: + t.Fatal("upstream request was not captured") + } + part := ojson.GetBytes(body, "contents.1.parts.0") + if !part.Get("functionCall").Exists() || ojson.GetBytes(body, "contents.1.parts.#").Int() != 1 { + t.Fatalf("carrier was not consumed by functionCall: %s", body) + } + want := signature + if backend == "gemini" { + want = internalsignature.GeminiSkipThoughtSignatureValidator + } + if mode == "override" { + want = "configured-signature" + } else if mode == "filter" { + want = "" + if part.Get("thoughtSignature").Exists() { + t.Fatalf("payload filter was overwritten: %s", body) + } + } + if got := part.Get("thoughtSignature").String(); got != want { + t.Fatalf("upstream signature = %q, want %q; body=%s", got, want, body) + } + }) + } + } + } +} diff --git a/internal/runtime/executor/gemini_executor.go b/internal/runtime/executor/gemini_executor.go index f832fb54e79..2846a67c030 100644 --- a/internal/runtime/executor/gemini_executor.go +++ b/internal/runtime/executor/gemini_executor.go @@ -176,6 +176,19 @@ func (e *GeminiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r if action != "countTokens" { helps.EnsureGeminiTrailingUserContentDoc(doc, "contents") } + replayScope := antigravityReasoningReplayScope{} + var replayRequestPayload []byte + if antigravityUsesReasoningReplayCache(baseModel) { + var changedReplay bool + var errReplay error + replayScope, replayRequestPayload, changedReplay, errReplay = prepareGeminiTopLevelReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc) + if errReplay != nil { + return resp, errReplay + } + if changedReplay { + internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents") + } + } baseURL := resolveGeminiBaseURL(auth) url := fmt.Sprintf("%s/%s/models/%s:%s", baseURL, glAPIVersion, baseModel, action) if opts.Alt != "" && action != "countTokens" { @@ -228,18 +241,35 @@ func (e *GeminiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, replayScope, httpResp.StatusCode, b); errClear != nil { + logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) + } err = statusErr{code: httpResp.StatusCode, msg: string(b)} return resp, err } data, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) + if action != "countTokens" { + if _, zeroErrMsg, zeroOutput := helps.CheckGeminiZeroOutputNonStream(responseFormat, data, false); zeroOutput { + gemDetail := helps.ParseGeminiUsage(data) + helps.ApplyGeminiRequestImageConfig(&gemDetail, body) + err = statusErr{code: http.StatusBadGateway, msg: zeroErrMsg} + helps.RecordAPIResponseError(ctx, e.cfg, err) + reporter.PublishFailureWithDetail(ctx, gemDetail, err) + return cliproxyexecutor.Response{}, err + } + cacheAntigravityReasoningReplayFromResponse(ctx, replayScope, replayRequestPayload, data) + } reporter.ObserveResponseModel(data) if blockMsg, blocked := geminiPromptBlockErrorMessage(data); blocked { err = statusErr{code: http.StatusBadGateway, msg: blockMsg} @@ -309,6 +339,19 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A capGeminiMaxOutputTokensDoc(doc, baseModel) internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents") helps.EnsureGeminiBoundaryUserContentDoc(doc, "contents") + replayScope := antigravityReasoningReplayScope{} + var replayRequestPayload []byte + if antigravityUsesReasoningReplayCache(baseModel) { + var changedReplay bool + var errReplay error + replayScope, replayRequestPayload, changedReplay, errReplay = prepareGeminiTopLevelReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc) + if errReplay != nil { + return nil, errReplay + } + if changedReplay { + internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents") + } + } baseURL := resolveGeminiBaseURL(auth) url := fmt.Sprintf("%s/%s/models/%s:%s", baseURL, glAPIVersion, baseModel, "streamGenerateContent") @@ -359,15 +402,22 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("gemini executor: close response body error: %v", errClose) } + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, replayScope, httpResp.StatusCode, b); errClear != nil { + logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) + } err = statusErr{code: httpResp.StatusCode, msg: string(b)} return nil, err } + replayAccumulator := newAntigravityReasoningReplayAccumulator(replayScope, replayRequestPayload) out := make(chan cliproxyexecutor.StreamChunk, 1) go func() { defer close(out) @@ -396,8 +446,22 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A }() var param any var sawFinishReason bool + var replayCommitted bool + commitReplay := func() { + if !replayCommitted && replayAccumulator != nil && replayAccumulator.terminal && streamErr == nil && helps.ApplyPatchTranslationError(param) == nil { + replayAccumulator.Commit(ctx) + replayCommitted = true + } + } var pendingFilterPayload []byte var pendingFilterMsg string + zeroOutputGuard := helps.NewGeminiZeroOutputStreamGuard(false, responseFormat) + failZeroOutput := func(finishReason string) bool { + streamErr = statusErr{code: http.StatusBadGateway, msg: helps.GeminiZeroOutputErrorMessage(responseFormat, finishReason)} + helps.RecordAPIResponseError(ctx, e.cfg, streamErr) + _ = helps.StopTranslatedClaudeStream(ctx, &streamErr, reporter, &streamUsage, out) + return false + } helps.InitializeApplyPatchStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, ¶m) emitTranslatedPayload := func(payload []byte) bool { lines := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, bytes.Clone(payload), ¶m, claudeInputTokens) @@ -405,9 +469,15 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { return statusErr{code: http.StatusBadGateway, msg: msg} }) + if replayAccumulator != nil && replayAccumulator.terminal && !replayCommitted && antigravityStreamChunksHaveTerminalCommitEvent(lines) { + commitReplay() + } for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: + if len(lines[i]) > 0 { + zeroOutputGuard.MarkEmitted() + } if helps.IsGeminiTerminalStreamChunk(lines[i]) { terminalDelivered = true } @@ -417,16 +487,52 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A } return !helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) } + filterAndEmitPayload := func(raw []byte) bool { + filtered := helps.FilterSSEUsageMetadata(append([]byte("data: "), raw...)) + payload := helps.JSONPayload(filtered) + if len(payload) == 0 { + return true + } + return emitTranslatedPayload(payload) + } + guardAndEmitPayload := func(raw []byte) bool { + shells, action, finishReason := zeroOutputGuard.Observe(raw) + switch action { + case helps.GeminiZeroOutputContinue: + return true + case helps.GeminiZeroOutputFailNow: + return failZeroOutput(finishReason) + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = raw + } + if !filterAndEmitPayload(errFrame) { + return false + } + return failZeroOutput(finishReason) + default: + for _, shell := range shells { + if !filterAndEmitPayload(shell) { + return false + } + } + return filterAndEmitPayload(raw) + } + } for scanner.Scan() { line := scanner.Bytes() helps.AppendAPIResponseChunk(ctx, e.cfg, line) + if replayAccumulator != nil { + replayAccumulator.ObserveSSELine(line) + } reporter.ObserveResponseModel(line) rawPayload := helps.JSONPayload(line) if len(rawPayload) > 0 && len(pendingFilterPayload) > 0 { flushed := pendingFilterPayload pendingFilterPayload = nil pendingFilterMsg = "" - if !emitTranslatedPayload(flushed) { + if !guardAndEmitPayload(flushed) { return } } @@ -451,12 +557,10 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A pendingFilterMsg = filterMsg continue } - filtered := helps.FilterSSEUsageMetadata(line) - payload := helps.JSONPayload(filtered) - if len(payload) == 0 { + if len(rawPayload) == 0 { continue } - if !emitTranslatedPayload(payload) { + if !guardAndEmitPayload(rawPayload) { return } } @@ -473,12 +577,26 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A return } if len(pendingFilterPayload) > 0 { - if !emitTranslatedPayload(pendingFilterPayload) { + if !guardAndEmitPayload(pendingFilterPayload) { return } pendingFilterPayload = nil pendingFilterMsg = "" } + if scanner.Err() == nil && ctx.Err() == nil && zeroOutputGuard.HasAbnormalFinish() { + _, action, finishReason := zeroOutputGuard.Finalize() + if action == helps.GeminiZeroOutputEmitErrorThenFail { + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + if !filterAndEmitPayload(errFrame) { + return + } + } + failZeroOutput(finishReason) + return + } if helps.EndApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return } @@ -500,6 +618,28 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if ctx.Err() != nil { return } + shells, action, finishReason := zeroOutputGuard.Finalize() + switch action { + case helps.GeminiZeroOutputFailNow: + failZeroOutput(finishReason) + return + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + if !filterAndEmitPayload(errFrame) { + return + } + failZeroOutput(finishReason) + return + default: + for _, shell := range shells { + if !filterAndEmitPayload(shell) { + return + } + } + } if (responseFormat == sdktranslator.FormatClaude || responseFormat == sdktranslator.FormatOpenAI) && !sawFinishReason { truncErr := statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before finishReason", streamTruncated: true} helps.RecordAPIResponseError(ctx, e.cfg, truncErr) @@ -517,6 +657,7 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { return statusErr{code: http.StatusBadGateway, msg: msg} }) + commitReplay() for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: @@ -650,11 +791,11 @@ func (e *GeminiExecutor) executeInteractions(ctx context.Context, auth *cliproxy }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) err = statusErr{code: httpResp.StatusCode, msg: string(data)} @@ -737,11 +878,14 @@ func (e *GeminiExecutor) executeInteractionsStream(ctx context.Context, auth *cl } helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - data, _ := io.ReadAll(httpResp.Body) + data, errRead := io.ReadAll(httpResp.Body) if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("gemini executor: close interactions error response body error: %v", errClose) } helps.AppendAPIResponseChunk(ctx, e.cfg, data) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } return nil, statusErr{code: httpResp.StatusCode, msg: string(data)} } @@ -879,6 +1023,15 @@ func (e *GeminiExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut helps.SetStringIfDifferentDoc(doc, "model", baseModel) internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents") helps.EnsureGeminiLeadingUserContentDoc(doc, "contents") + if antigravityUsesReasoningReplayCache(baseModel) { + changedReplay, errReplay := prepareGeminiTopLevelCountTokensReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc) + if errReplay != nil { + return cliproxyexecutor.Response{}, errReplay + } + if changedReplay { + internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents") + } + } baseURL := resolveGeminiBaseURL(auth) url := fmt.Sprintf("%s/%s/models/%s:%s", baseURL, glAPIVersion, baseModel, "countTokens") @@ -930,11 +1083,11 @@ func (e *GeminiExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut helps.RecordAPIResponseMetadata(ctx, e.cfg, resp.StatusCode, resp.Header.Clone()) data, err := io.ReadAll(resp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return cliproxyexecutor.Response{}, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if resp.StatusCode < 200 || resp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", resp.StatusCode, helps.SummarizeErrorBody(resp.Header.Get("Content-Type"), data)) return cliproxyexecutor.Response{}, statusErr{code: resp.StatusCode, msg: string(data)} diff --git a/internal/runtime/executor/gemini_executor_test.go b/internal/runtime/executor/gemini_executor_test.go index 7f71dbebfe4..a3a9ca03d40 100644 --- a/internal/runtime/executor/gemini_executor_test.go +++ b/internal/runtime/executor/gemini_executor_test.go @@ -1513,11 +1513,11 @@ func TestGeminiExecutorClaudeMalformedFunctionCallReturnsRetryableError(t *testi t.Fatalf("ExecuteStream() chunk.Err = %T %v, want status 502", streamErr, streamErr) } streamText := combined.String() - if strings.Contains(streamText, `"stop_reason":"refusal"`) { - t.Fatalf("stream unexpectedly emitted stop_reason refusal:\n%s", streamText) + if strings.TrimSpace(streamText) != "" { + t.Fatalf("stream unexpectedly emitted payload before bootstrap retryable error:\n%s", streamText) } - if !strings.Contains(streamText, "event: error\n") || !strings.Contains(streamText, `"type":"api_error"`) { - t.Fatalf("stream missing retryable api_error event:\n%s", streamText) + if got := ojson.Get(streamErr.Error(), "error.type").String(); got != "api_error" { + t.Fatalf("ExecuteStream() chunk.Err error.type = %q, want api_error; err=%s", got, streamErr.Error()) } assertMalformedFunctionCallFailedUsage(t, capture.records) } diff --git a/internal/runtime/executor/gemini_vertex_executor.go b/internal/runtime/executor/gemini_vertex_executor.go index bcc774cfcf5..265c8fa85b0 100644 --- a/internal/runtime/executor/gemini_vertex_executor.go +++ b/internal/runtime/executor/gemini_vertex_executor.go @@ -456,7 +456,6 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au fixGeminiImageAspectRatioDoc(baseModel, doc) helps.SetStringIfDifferentDoc(doc, "model", baseModel) - helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents") } @@ -471,6 +470,18 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au helps.DropGeminiTrailingThoughtOnlyContentDoc(doc, "contents") helps.EnsureGeminiTrailingUserContentDoc(doc, "contents") } + replayScope := antigravityReasoningReplayScope{} + var replayRequestPayload []byte + if !isImagenModel(baseModel) && antigravityUsesReasoningReplayCache(baseModel) { + var errReplay error + replayScope, replayRequestPayload, _, errReplay = prepareGeminiTopLevelReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc) + if errReplay != nil { + return resp, errReplay + } + } + if !isImagenModel(baseModel) { + helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, opts.SourceFormat.String()) + } baseURL := vertexBaseURL(location) url := fmt.Sprintf("%s/%s/projects/%s/locations/%s/publishers/google/models/%s:%s", baseURL, vertexAPIVersion, projectID, location, baseModel, action) if opts.Alt != "" && action != "countTokens" { @@ -531,18 +542,24 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, replayScope, httpResp.StatusCode, b); errClear != nil { + logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) + } err = statusErr{code: httpResp.StatusCode, msg: string(b)} return resp, err } data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) reporter.ObserveResponseModel(data) // For Imagen models, convert response to Gemini format before translation @@ -560,6 +577,17 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au // Standard Gemini translation (works for both Gemini and converted Imagen responses) responseFormat := cliproxyexecutor.ResponseFormatOrSource(opts) + if action != "countTokens" && !isImagenModel(baseModel) { + if _, zeroErrMsg, zeroOutput := helps.CheckGeminiZeroOutputNonStream(responseFormat, data, false); zeroOutput { + gemDetail := helps.ParseGeminiUsage(data) + helps.ApplyGeminiRequestImageConfig(&gemDetail, body) + err = statusErr{code: http.StatusBadGateway, msg: zeroErrMsg} + helps.RecordAPIResponseError(ctx, e.cfg, err) + reporter.PublishFailureWithDetail(ctx, gemDetail, err) + return cliproxyexecutor.Response{}, err + } + cacheAntigravityReasoningReplayFromResponse(ctx, replayScope, replayRequestPayload, data) + } to := sdktranslator.FromString("gemini") var param any out := sdktranslator.TranslateNonStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, data, ¶m) @@ -612,7 +640,6 @@ func (e *GeminiVertexExecutor) executeWithAPIKey(ctx context.Context, auth *clip requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) helps.SetStringIfDifferentDoc(doc, "model", baseModel) - helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents") action := getVertexAction(baseModel, false) @@ -626,6 +653,16 @@ func (e *GeminiVertexExecutor) executeWithAPIKey(ctx context.Context, auth *clip helps.DropGeminiTrailingThoughtOnlyContentDoc(doc, "contents") helps.EnsureGeminiTrailingUserContentDoc(doc, "contents") } + replayScope := antigravityReasoningReplayScope{} + var replayRequestPayload []byte + if !isImagenModel(baseModel) && antigravityUsesReasoningReplayCache(baseModel) { + var errReplay error + replayScope, replayRequestPayload, _, errReplay = prepareGeminiTopLevelReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc) + if errReplay != nil { + return resp, errReplay + } + } + helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) // For API key auth, use simpler URL format without project/location. // The helper honors base URLs that already encode "/publishers/..." so @@ -687,18 +724,24 @@ func (e *GeminiVertexExecutor) executeWithAPIKey(ctx context.Context, auth *clip }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, replayScope, httpResp.StatusCode, b); errClear != nil { + logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) + } err = statusErr{code: httpResp.StatusCode, msg: string(b)} return resp, err } data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) reporter.ObserveResponseModel(data) if blockMsg, blocked := geminiPromptBlockErrorMessage(data); blocked { err = statusErr{code: http.StatusBadGateway, msg: blockMsg} @@ -706,6 +749,17 @@ func (e *GeminiVertexExecutor) executeWithAPIKey(ctx context.Context, auth *clip reporter.PublishFailureWithDetail(ctx, helps.ParseGeminiUsage(data), err) return cliproxyexecutor.Response{}, err } + if action != "countTokens" && !isImagenModel(baseModel) { + if _, zeroErrMsg, zeroOutput := helps.CheckGeminiZeroOutputNonStream(responseFormat, data, false); zeroOutput { + gemDetail := helps.ParseGeminiUsage(data) + helps.ApplyGeminiRequestImageConfig(&gemDetail, body) + err = statusErr{code: http.StatusBadGateway, msg: zeroErrMsg} + helps.RecordAPIResponseError(ctx, e.cfg, err) + reporter.PublishFailureWithDetail(ctx, gemDetail, err) + return cliproxyexecutor.Response{}, err + } + cacheAntigravityReasoningReplayFromResponse(ctx, replayScope, replayRequestPayload, data) + } var param any out := sdktranslator.TranslateNonStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, data, ¶m) if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { @@ -757,12 +811,21 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) helps.SetStringIfDifferentDoc(doc, "model", baseModel) - helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents") action := getVertexAction(baseModel, true) helps.DropGeminiTrailingThoughtOnlyContentDoc(doc, "contents") helps.EnsureGeminiBoundaryUserContentDoc(doc, "contents") + replayScope := antigravityReasoningReplayScope{} + var replayRequestPayload []byte + if !isImagenModel(baseModel) && antigravityUsesReasoningReplayCache(baseModel) { + var errReplay error + replayScope, replayRequestPayload, _, errReplay = prepareGeminiTopLevelReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc) + if errReplay != nil { + return nil, errReplay + } + } + helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) baseURL := vertexBaseURL(location) url := fmt.Sprintf("%s/%s/projects/%s/locations/%s/publishers/google/models/%s:%s", baseURL, vertexAPIVersion, projectID, location, baseModel, action) // Imagen models don't support streaming, skip SSE params @@ -823,15 +886,22 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte } helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("vertex executor: close response body error: %v", errClose) } + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, replayScope, httpResp.StatusCode, b); errClear != nil { + logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) + } return nil, statusErr{code: httpResp.StatusCode, msg: string(b)} } + replayAccumulator := newAntigravityReasoningReplayAccumulator(replayScope, replayRequestPayload) out := make(chan cliproxyexecutor.StreamChunk, 1) go func() { defer close(out) @@ -853,9 +923,23 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte }() var terminalDelivered bool var sawFinishReason bool + var replayCommitted bool var pendingFilterLine []byte var pendingFilterMsg string var param any + zeroOutputGuard := helps.NewGeminiZeroOutputStreamGuard(false, responseFormat) + failZeroOutput := func(finishReason string) bool { + streamErr = statusErr{code: http.StatusBadGateway, msg: helps.GeminiZeroOutputErrorMessage(responseFormat, finishReason)} + helps.RecordAPIResponseError(ctx, e.cfg, streamErr) + _ = helps.StopTranslatedClaudeStream(ctx, &streamErr, reporter, &streamUsage, out) + return false + } + commitReplay := func() { + if !replayCommitted && replayAccumulator != nil && replayAccumulator.terminal && streamErr == nil && helps.ApplyPatchTranslationError(param) == nil { + replayAccumulator.Commit(ctx) + replayCommitted = true + } + } helps.InitializeApplyPatchStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, ¶m) emitTranslatedLine := func(line []byte) bool { lines := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, bytes.Clone(line), ¶m, claudeInputTokens) @@ -863,9 +947,15 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { return statusErr{code: http.StatusBadGateway, msg: msg} }) + if replayAccumulator != nil && replayAccumulator.terminal && !replayCommitted && antigravityStreamChunksHaveTerminalCommitEvent(lines) { + commitReplay() + } for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: + if len(lines[i]) > 0 { + zeroOutputGuard.MarkEmitted() + } if helps.IsGeminiTerminalStreamChunk(lines[i]) { terminalDelivered = true } @@ -875,16 +965,44 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte } return !helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) } + guardAndEmitLine := func(line []byte) bool { + shells, action, finishReason := zeroOutputGuard.Observe(line) + switch action { + case helps.GeminiZeroOutputContinue: + return true + case helps.GeminiZeroOutputFailNow: + return failZeroOutput(finishReason) + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = line + } + if !emitTranslatedLine(errFrame) { + return false + } + return failZeroOutput(finishReason) + default: + for _, shell := range shells { + if !emitTranslatedLine(shell) { + return false + } + } + return emitTranslatedLine(line) + } + } for scanner.Scan() { line := scanner.Bytes() helps.AppendAPIResponseChunk(ctx, e.cfg, line) + if replayAccumulator != nil { + replayAccumulator.ObserveSSELine(line) + } reporter.ObserveResponseModel(line) rawPayload := helps.JSONPayload(line) if len(rawPayload) > 0 && len(pendingFilterLine) > 0 { flushed := pendingFilterLine pendingFilterLine = nil pendingFilterMsg = "" - if !emitTranslatedLine(flushed) { + if !guardAndEmitLine(flushed) { return } } @@ -909,7 +1027,10 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte pendingFilterMsg = filterMsg continue } - if !emitTranslatedLine(line) { + if len(rawPayload) == 0 { + continue + } + if !guardAndEmitLine(line) { return } } @@ -926,12 +1047,26 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte return } if len(pendingFilterLine) > 0 { - if !emitTranslatedLine(pendingFilterLine) { + if !guardAndEmitLine(pendingFilterLine) { return } pendingFilterLine = nil pendingFilterMsg = "" } + if scanner.Err() == nil && ctx.Err() == nil && zeroOutputGuard.HasAbnormalFinish() { + _, action, finishReason := zeroOutputGuard.Finalize() + if action == helps.GeminiZeroOutputEmitErrorThenFail { + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + if !emitTranslatedLine(errFrame) { + return + } + } + failZeroOutput(finishReason) + return + } if helps.EndApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return } @@ -953,6 +1088,28 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte if ctx.Err() != nil { return } + shells, action, finishReason := zeroOutputGuard.Finalize() + switch action { + case helps.GeminiZeroOutputFailNow: + failZeroOutput(finishReason) + return + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + if !emitTranslatedLine(errFrame) { + return + } + failZeroOutput(finishReason) + return + default: + for _, shell := range shells { + if !emitTranslatedLine(shell) { + return + } + } + } if (responseFormat == sdktranslator.FormatClaude || responseFormat == sdktranslator.FormatOpenAI) && !sawFinishReason { truncErr := statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before finishReason", streamTruncated: true} helps.RecordAPIResponseError(ctx, e.cfg, truncErr) @@ -970,6 +1127,7 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { return statusErr{code: http.StatusBadGateway, msg: msg} }) + commitReplay() for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: @@ -1018,12 +1176,21 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth requestedModel := helps.PayloadRequestedModel(opts, req.Model) requestPath := helps.PayloadRequestPath(opts) helps.SetStringIfDifferentDoc(doc, "model", baseModel) - helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents") action := getVertexAction(baseModel, true) helps.DropGeminiTrailingThoughtOnlyContentDoc(doc, "contents") helps.EnsureGeminiBoundaryUserContentDoc(doc, "contents") + replayScope := antigravityReasoningReplayScope{} + var replayRequestPayload []byte + if !isImagenModel(baseModel) && antigravityUsesReasoningReplayCache(baseModel) { + var errReplay error + replayScope, replayRequestPayload, _, errReplay = prepareGeminiTopLevelReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc) + if errReplay != nil { + return nil, errReplay + } + } + helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) // For API key auth, use simpler URL format without project/location url := vertexAPIKeyModelsURL(baseURL, baseModel, action) // Imagen models don't support streaming, skip SSE params @@ -1081,15 +1248,22 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth } helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("vertex executor: close response body error: %v", errClose) } + if errClear := clearAntigravityReasoningReplayOnInvalidSignature(ctx, replayScope, httpResp.StatusCode, b); errClear != nil { + logAntigravityReasoningReplayDegraded(replayScope, "invalidate", errClear) + } return nil, statusErr{code: httpResp.StatusCode, msg: string(b)} } + replayAccumulator := newAntigravityReasoningReplayAccumulator(replayScope, replayRequestPayload) out := make(chan cliproxyexecutor.StreamChunk, 1) go func() { defer close(out) @@ -1111,9 +1285,23 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth }() var terminalDelivered bool var sawFinishReason bool + var replayCommitted bool var pendingFilterLine []byte var pendingFilterMsg string var param any + zeroOutputGuard := helps.NewGeminiZeroOutputStreamGuard(false, responseFormat) + failZeroOutput := func(finishReason string) bool { + streamErr = statusErr{code: http.StatusBadGateway, msg: helps.GeminiZeroOutputErrorMessage(responseFormat, finishReason)} + helps.RecordAPIResponseError(ctx, e.cfg, streamErr) + _ = helps.StopTranslatedClaudeStream(ctx, &streamErr, reporter, &streamUsage, out) + return false + } + commitReplay := func() { + if !replayCommitted && replayAccumulator != nil && replayAccumulator.terminal && streamErr == nil && helps.ApplyPatchTranslationError(param) == nil { + replayAccumulator.Commit(ctx) + replayCommitted = true + } + } helps.InitializeApplyPatchStream(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, ¶m) emitTranslatedLine := func(line []byte) bool { lines := helps.TranslateStreamWithClaudeInputTokens(ctx, to, responseFormat, req.Model, helps.ApplyPatchOriginalRequest(req, opts), body, bytes.Clone(line), ¶m, claudeInputTokens) @@ -1121,9 +1309,15 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { return statusErr{code: http.StatusBadGateway, msg: msg} }) + if replayAccumulator != nil && replayAccumulator.terminal && !replayCommitted && antigravityStreamChunksHaveTerminalCommitEvent(lines) { + commitReplay() + } for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: + if len(lines[i]) > 0 { + zeroOutputGuard.MarkEmitted() + } if helps.IsGeminiTerminalStreamChunk(lines[i]) { terminalDelivered = true } @@ -1133,16 +1327,44 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth } return !helps.StopApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) } + guardAndEmitLine := func(line []byte) bool { + shells, action, finishReason := zeroOutputGuard.Observe(line) + switch action { + case helps.GeminiZeroOutputContinue: + return true + case helps.GeminiZeroOutputFailNow: + return failZeroOutput(finishReason) + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = line + } + if !emitTranslatedLine(errFrame) { + return false + } + return failZeroOutput(finishReason) + default: + for _, shell := range shells { + if !emitTranslatedLine(shell) { + return false + } + } + return emitTranslatedLine(line) + } + } for scanner.Scan() { line := scanner.Bytes() helps.AppendAPIResponseChunk(ctx, e.cfg, line) + if replayAccumulator != nil { + replayAccumulator.ObserveSSELine(line) + } reporter.ObserveResponseModel(line) rawPayload := helps.JSONPayload(line) if len(rawPayload) > 0 && len(pendingFilterLine) > 0 { flushed := pendingFilterLine pendingFilterLine = nil pendingFilterMsg = "" - if !emitTranslatedLine(flushed) { + if !guardAndEmitLine(flushed) { return } } @@ -1167,7 +1389,10 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth pendingFilterMsg = filterMsg continue } - if !emitTranslatedLine(line) { + if len(rawPayload) == 0 { + continue + } + if !guardAndEmitLine(line) { return } } @@ -1184,12 +1409,26 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth return } if len(pendingFilterLine) > 0 { - if !emitTranslatedLine(pendingFilterLine) { + if !guardAndEmitLine(pendingFilterLine) { return } pendingFilterLine = nil pendingFilterMsg = "" } + if scanner.Err() == nil && ctx.Err() == nil && zeroOutputGuard.HasAbnormalFinish() { + _, action, finishReason := zeroOutputGuard.Finalize() + if action == helps.GeminiZeroOutputEmitErrorThenFail { + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + if !emitTranslatedLine(errFrame) { + return + } + } + failZeroOutput(finishReason) + return + } if helps.EndApplyPatchStream(ctx, param, reporter, out, statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}) { return } @@ -1211,6 +1450,28 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth if ctx.Err() != nil { return } + shells, action, finishReason := zeroOutputGuard.Finalize() + switch action { + case helps.GeminiZeroOutputFailNow: + failZeroOutput(finishReason) + return + case helps.GeminiZeroOutputEmitErrorThenFail: + errFrame := zeroOutputGuard.AbnormalFrame() + if len(errFrame) == 0 { + errFrame = []byte("[DONE]") + } + if !emitTranslatedLine(errFrame) { + return + } + failZeroOutput(finishReason) + return + default: + for _, shell := range shells { + if !emitTranslatedLine(shell) { + return + } + } + } if (responseFormat == sdktranslator.FormatClaude || responseFormat == sdktranslator.FormatOpenAI) && !sawFinishReason { truncErr := statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before finishReason", streamTruncated: true} helps.RecordAPIResponseError(ctx, e.cfg, truncErr) @@ -1228,6 +1489,7 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth helps.CaptureTranslatedClaudeStreamError(responseFormat, lines, &streamErr, func(msg string) error { return statusErr{code: http.StatusBadGateway, msg: msg} }) + commitReplay() for i := range lines { select { case out <- cliproxyexecutor.StreamChunk{Payload: lines[i]}: @@ -1269,13 +1531,18 @@ func (e *GeminiVertexExecutor) countTokensWithServiceAccount(ctx context.Context fixGeminiImageAspectRatioDoc(baseModel, doc) _ = doc.Set("model", baseModel) - helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) respCtx := context.WithValue(ctx, "alt", opts.Alt) _ = doc.Delete("tools") _ = doc.Delete("generationConfig") _ = doc.Delete("safetySettings") internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents") helps.EnsureGeminiLeadingUserContentDoc(doc, "contents") + if !isImagenModel(baseModel) && antigravityUsesReasoningReplayCache(baseModel) { + if _, errReplay := prepareGeminiTopLevelCountTokensReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc); errReplay != nil { + return cliproxyexecutor.Response{}, errReplay + } + } + helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) baseURL := vertexBaseURL(location) url := fmt.Sprintf("%s/%s/projects/%s/locations/%s/publishers/google/models/%s:%s", baseURL, vertexAPIVersion, projectID, location, baseModel, "countTokens") @@ -1333,17 +1600,20 @@ func (e *GeminiVertexExecutor) countTokensWithServiceAccount(ctx context.Context }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) return cliproxyexecutor.Response{}, statusErr{code: httpResp.StatusCode, msg: string(b)} } data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return cliproxyexecutor.Response{}, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) count := ojson.GetBytesNoCopy(data, "totalTokens").Int() out := sdktranslator.TranslateTokenCount(ctx, to, responseFormat, count, data) return cliproxyexecutor.Response{Payload: out, Headers: httpResp.Header.Clone()}, nil @@ -1373,13 +1643,18 @@ func (e *GeminiVertexExecutor) countTokensWithAPIKey(ctx context.Context, auth * fixGeminiImageAspectRatioDoc(baseModel, doc) _ = doc.Set("model", baseModel) - helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) respCtx := context.WithValue(ctx, "alt", opts.Alt) _ = doc.Delete("tools") _ = doc.Delete("generationConfig") _ = doc.Delete("safetySettings") internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents") helps.EnsureGeminiLeadingUserContentDoc(doc, "contents") + if !isImagenModel(baseModel) && antigravityUsesReasoningReplayCache(baseModel) { + if _, errReplay := prepareGeminiTopLevelCountTokensReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc); errReplay != nil { + return cliproxyexecutor.Response{}, errReplay + } + } + helps.StripVertexOpenAIResponsesToolCallIDsDoc(doc, from.String()) // For API key auth, use simpler URL format without project/location url := vertexAPIKeyModelsURL(baseURL, baseModel, "countTokens") @@ -1434,17 +1709,20 @@ func (e *GeminiVertexExecutor) countTokensWithAPIKey(ctx context.Context, auth * }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) return cliproxyexecutor.Response{}, statusErr{code: httpResp.StatusCode, msg: string(b)} } data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return cliproxyexecutor.Response{}, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) count := ojson.GetBytesNoCopy(data, "totalTokens").Int() out := sdktranslator.TranslateTokenCount(ctx, to, responseFormat, count, data) return cliproxyexecutor.Response{Payload: out, Headers: httpResp.Header.Clone()}, nil @@ -1739,11 +2017,11 @@ func (e *GeminiVertexExecutor) executeInteractions(ctx context.Context, auth *cl }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) err = statusErr{code: httpResp.StatusCode, msg: string(data)} @@ -1864,11 +2142,14 @@ func (e *GeminiVertexExecutor) executeInteractionsStream(ctx context.Context, au } helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - data, _ := io.ReadAll(httpResp.Body) + data, errRead := io.ReadAll(httpResp.Body) if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("vertex executor: close interactions error response body error: %v", errClose) } helps.AppendAPIResponseChunk(ctx, e.cfg, data) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } return nil, statusErr{code: httpResp.StatusCode, msg: string(data)} } diff --git a/internal/runtime/executor/gemini_vertex_executor_test.go b/internal/runtime/executor/gemini_vertex_executor_test.go index c0157afc705..ae8ab1ec027 100644 --- a/internal/runtime/executor/gemini_vertex_executor_test.go +++ b/internal/runtime/executor/gemini_vertex_executor_test.go @@ -206,11 +206,15 @@ func TestGeminiVertexExecutorClaudeMalformedFunctionCallReturnsRetryableError(t t.Fatal("ExecuteStream() chunk.Err = nil, want 502 error propagated") } streamText := combined.String() - if strings.Contains(streamText, `"stop_reason":"refusal"`) { - t.Fatalf("stream unexpectedly emitted stop_reason refusal:\n%s", streamText) + if strings.TrimSpace(streamText) != "" { + t.Fatalf("stream unexpectedly emitted payload before bootstrap retryable error:\n%s", streamText) } - if !strings.Contains(streamText, "event: error\n") || !strings.Contains(streamText, `"type":"api_error"`) { - t.Fatalf("stream missing retryable api_error event:\n%s", streamText) + streamStatus, okStreamStatus := streamErr.(interface{ StatusCode() int }) + if !okStreamStatus || streamStatus.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want status 502", streamErr, streamErr) + } + if got := ojson.Get(streamErr.Error(), "error.type").String(); got != "api_error" { + t.Fatalf("ExecuteStream() chunk.Err error.type = %q, want api_error; err=%s", got, streamErr.Error()) } assertMalformedFunctionCallFailedUsage(t, capture.records) }) diff --git a/internal/runtime/executor/helps/antigravity_compaction.go b/internal/runtime/executor/helps/antigravity_compaction.go index eecdf8a6858..48da8e72f0f 100644 --- a/internal/runtime/executor/helps/antigravity_compaction.go +++ b/internal/runtime/executor/helps/antigravity_compaction.go @@ -20,9 +20,10 @@ import ( ) const ( - antigravityCompactionCapsulePrefix = "cpa-ag-compact-v1:" - antigravityCompactionItemIDPrefix = "cmp_ag_compact_" - fixedCompactionKeySecret = "CLIProxyAPI" + antigravityCompactionCapsulePrefix = "cpa-ag-compact-v1:" + antigravityCompactionItemIDPrefix = "cmp_ag_compact_" + antigravityCompactionResponseIDPrefix = "resp_ag_compact_" + fixedCompactionKeySecret = "CLIProxyAPI" ) type antigravityCompactionCapsuleData struct { @@ -36,6 +37,32 @@ func RecognizedAntigravityCompactionCapsule(encryptedContent string) bool { return strings.HasPrefix(strings.TrimSpace(encryptedContent), antigravityCompactionCapsulePrefix) } +// RecognizedResponsesCompactionResponseID reports whether responseID is a locally synthesized CPA compaction response ID. +func RecognizedResponsesCompactionResponseID(responseID string) bool { + return strings.HasPrefix(strings.TrimSpace(responseID), antigravityCompactionResponseIDPrefix) +} + +// HasResponsesCompactionConversationInput reports whether payload carries at least one +// non-control conversation item in input for local summary compaction. +func HasResponsesCompactionConversationInput(payload []byte) bool { + input := ojson.GetBytesNoCopy(payload, "input") + if input.Type == ojson.String { + return strings.TrimSpace(input.String()) != "" + } + if !input.IsArray() { + return false + } + for _, item := range input.Array() { + switch strings.TrimSpace(item.Get("type").String()) { + case "compaction_trigger", "additional_tools", "configuration_update": + continue + default: + return true + } + } + return false +} + func isRecognizedCPACompactionItem(item ojson.Result) bool { if item.Get("type").String() != "compaction" { return false @@ -222,8 +249,8 @@ func PrepareAntigravityCompactionSummaryPayloadDoc(doc *ojson.Doc, modelName str if input.IsArray() { var filtered []string for _, item := range input.Array() { - itemType := item.Get("type").String() - if itemType == "compaction_trigger" || itemType == "additional_tools" { + switch strings.TrimSpace(item.Get("type").String()) { + case "compaction_trigger", "additional_tools", "configuration_update": continue } filtered = append(filtered, item.Raw) @@ -242,6 +269,8 @@ func PrepareAntigravityCompactionSummaryPayloadDoc(doc *ojson.Doc, modelName str // Remove fields not needed or incompatible with summary generation for _, field := range []string{ + "type", + "event_id", "stream", "tools", "tool_choice", @@ -250,6 +279,7 @@ func PrepareAntigravityCompactionSummaryPayloadDoc(doc *ojson.Doc, modelName str "additional_tools", "truncation", "metadata", + "text", } { _ = util.DeleteJSONDocIfExists(doc, field) } diff --git a/internal/runtime/executor/helps/antigravity_compaction_test.go b/internal/runtime/executor/helps/antigravity_compaction_test.go index dc0db241b8b..c30b8ca727f 100644 --- a/internal/runtime/executor/helps/antigravity_compaction_test.go +++ b/internal/runtime/executor/helps/antigravity_compaction_test.go @@ -69,8 +69,17 @@ func TestPrepareAntigravityCompactionSummaryPayload(t *testing.T) { "tools": [{"type": "function", "name": "bash"}], "tool_choice": "auto", "previous_response_id": "resp-old", + "text": { + "format": { + "type": "json_schema", + "name": "strict_bool", + "strict": true, + "schema": {"type": "object", "properties": {"ok": {"type": "boolean"}}, "required": ["ok"], "additionalProperties": false} + } + }, "input": [ {"type": "additional_tools", "tools": [{"type": "function", "name": "exec_command"}]}, + {"type": "configuration_update", "instructions": "Be brief"}, {"type": "message", "role": "user", "content": "hi"}, {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "hello"}]}, {"type": "compaction_trigger"} @@ -94,6 +103,9 @@ func TestPrepareAntigravityCompactionSummaryPayload(t *testing.T) { if ojson.GetBytes(prepared, "previous_response_id").Exists() { t.Fatal("expected previous_response_id to be removed") } + if ojson.GetBytes(prepared, "text").Exists() { + t.Fatal("expected text format constraints to be removed") + } input := ojson.GetBytes(prepared, "input").Array() if len(input) != 3 { @@ -107,6 +119,9 @@ func TestPrepareAntigravityCompactionSummaryPayload(t *testing.T) { if item.Get("type").String() == "additional_tools" { t.Fatal("additional_tools must be removed from summary payload") } + if item.Get("type").String() == "configuration_update" { + t.Fatal("configuration_update must be removed from summary payload") + } } lastItem := input[len(input)-1] diff --git a/internal/runtime/executor/helps/apply_patch_responses.go b/internal/runtime/executor/helps/apply_patch_responses.go index 0f074023c12..2a81c7b2c5b 100644 --- a/internal/runtime/executor/helps/apply_patch_responses.go +++ b/internal/runtime/executor/helps/apply_patch_responses.go @@ -161,6 +161,7 @@ type ApplyPatchResponsesState struct { upstream []byte eventLine []byte active, failed, closed bool + sawPatch bool transportDone bool } @@ -681,10 +682,22 @@ func (s *ApplyPatchResponsesState) Transform(event []byte) ([][]byte, error) { } var out [][]byte for _, e := range events { + if s.isCustomPatchEvent(e) { + s.sawPatch = true + } converted, errTransform := s.Bridge.Transform(e) + if !s.sawPatch && !strings.HasPrefix(ojson.GetBytesNoCopy(e, "type").String(), "response.custom_tool_call_input.") { + for _, c := range converted { + if strings.HasPrefix(ojson.GetBytesNoCopy(c, "type").String(), "response.custom_tool_call_input.") { + s.sawPatch = true + break + } + } + } out = append(out, converted...) if errTransform != nil { s.failed = true + s.sawPatch = true s.byDispatcherKey, s.records, s.upstream = nil, nil, nil return out, errTransform } @@ -696,6 +709,37 @@ func (s *ApplyPatchResponsesState) Transform(event []byte) ([][]byte, error) { return out, nil } +func (s *ApplyPatchResponsesState) isCustomPatchEvent(event []byte) bool { + if s == nil || !s.active { + return false + } + root := util.ParseGJSONBytesNoCopy(event) + if item := root.Get("item"); item.Exists() { + if item.Get("type").String() == "custom_tool_call" { + return false + } + d, ok := s.tools[util.QualifyResponsesNamespaceToolName(item.Get("namespace").String(), item.Get("name").String())] + return ok && applypatch.IsCustomTool(d.Tool) + } + if name := root.Get("name").String(); name != "" { + d, ok := s.tools[util.QualifyResponsesNamespaceToolName(root.Get("namespace").String(), name)] + return ok && applypatch.IsCustomTool(d.Tool) + } + return false +} + +// HasPatchActivity reports whether upstream emitted any custom apply_patch call +// or unfinished patch namespace dispatcher before closing the response. +func (s *ApplyPatchResponsesState) HasPatchActivity() bool { + if s == nil || !s.active { + return false + } + if s.failed || s.sawPatch || s.unfinishedDispatcher() { + return true + } + return s.Bridge != nil && s.Bridge.Finish() != nil +} + // Finish validates source response closure independently of completed tool input. // Common Finish remains argument-only because it also runs inside terminal conversion. func (s *ApplyPatchResponsesState) Finish() error { diff --git a/internal/runtime/executor/helps/claude_client_detection.go b/internal/runtime/executor/helps/claude_client_detection.go index 14475c560f8..52506d58f10 100644 --- a/internal/runtime/executor/helps/claude_client_detection.go +++ b/internal/runtime/executor/helps/claude_client_detection.go @@ -26,11 +26,7 @@ const ( claudeDefaultStainlessTimeout = "600" ) -var ( - claudeCodeUserAgentPattern = regexp.MustCompile(`(?i)^claude-cli/`) - claudeCodeUserAgentDetailsPattern = regexp.MustCompile(`(?i)^claude-cli/\S+\s+\(external,\s*([^,)]+)(?:,\s*agent-sdk/([^,)]+))?`) - claudeCodeNativeUserAgentPattern = regexp.MustCompile(`(?i)^claude-cli/[0-9]+\.[0-9]+\.[0-9]+\s+\(external,\s*[^,)]+(?:,\s*agent-sdk/[0-9]+\.[0-9]+\.[0-9]+)?\)$`) -) +var claudeCodeUserAgentPattern = regexp.MustCompile(`(?i)^claude-cli/`) var claudeCodeSubclientByEntrypoint = map[string]string{ "cli": "claude-code-cli", @@ -174,16 +170,16 @@ func DetectClaudeCodeRequest(headers http.Header, payload []byte, countTokens bo if len(configs) > 0 { cfg = configs[0] } - userAgent := headerValue(headers, "User-Agent") - entrypoint, agentSDKVersion := parseClaudeCodeUserAgentDetails(userAgent) + userAgent, validUserAgent := parseClaudeCodeUserAgent(headerValue(headers, "User-Agent")) + entrypoint := userAgent.entrypoint subclient := claudeSubclientForEntrypoint(entrypoint, cfg) detection := ClaudeCodeRequestDetection{ - XAppCLI: headerValue(headers, "X-App") == "cli", - UserAgent: plausibleClaudeCodeUserAgent(userAgent, cfg), + XAppCLI: isNativeClaudeXApp(headerValue(headers, "X-App")), + UserAgent: validUserAgent && plausibleClaudeCodeVersion(userAgent.version, cfg), BetasPresent: headerContainsClaudeCodeBeta(headers), Entrypoint: entrypoint, Subclient: subclient, - AgentSDKVersion: agentSDKVersion, + AgentSDKVersion: userAgent.agentSDKVersion, } metadataUserID := ojson.GetBytesNoCopy(payload, "metadata.user_id") @@ -201,6 +197,15 @@ func DetectClaudeCodeRequest(headers http.Header, payload []byte, countTokens bo return detection } +func isNativeClaudeXApp(value string) bool { + switch value { + case "cli", "cli-bg": + return true + default: + return false + } +} + func claudeCodeHelperBetaProfile(redactThinking bool, trailing ...string) string { betas := []string{"oauth-2025-04-20", "interleaved-thinking-2025-05-14"} if redactThinking { @@ -690,26 +695,19 @@ func IsClaudeCodeUserAgent(userAgent string) bool { } func plausibleClaudeCodeUserAgent(userAgent string, cfg *config.Config) bool { - userAgent = strings.TrimSpace(userAgent) - if !claudeCodeUserAgentPattern.MatchString(userAgent) || !claudeCodeNativeUserAgentPattern.MatchString(userAgent) { - return false - } - candidate, okCandidate := parseClaudeCLIVersion(userAgent) + parsed, ok := parseClaudeCodeUserAgent(userAgent) + return ok && plausibleClaudeCodeVersion(parsed.version, cfg) +} + +func plausibleClaudeCodeVersion(candidate claudeCLIVersion, cfg *config.Config) bool { baseline, okBaseline := parseClaudeCLIVersion(defaultClaudeDeviceProfile(cfg).UserAgent) // Patch releases (>= baseline.patch) within the release line preserve native passthrough. - return okCandidate && okBaseline && plausibleClaudeCLIVersion(candidate, baseline) + return okBaseline && plausibleClaudeCLIVersion(candidate, baseline) } func parseClaudeCodeUserAgentDetails(userAgent string) (entrypoint, agentSDKVersion string) { - matches := claudeCodeUserAgentDetailsPattern.FindStringSubmatch(strings.TrimSpace(userAgent)) - if len(matches) < 2 { - return "", "" - } - entrypoint = strings.ToLower(strings.TrimSpace(matches[1])) - if len(matches) >= 3 { - agentSDKVersion = strings.TrimSpace(matches[2]) - } - return entrypoint, agentSDKVersion + parsed, _ := parseClaudeCodeUserAgent(userAgent) + return parsed.entrypoint, parsed.agentSDKVersion } func headerValue(headers http.Header, name string) string { diff --git a/internal/runtime/executor/helps/claude_client_detection_test.go b/internal/runtime/executor/helps/claude_client_detection_test.go index 7e0c91566a1..1acbaf3d220 100644 --- a/internal/runtime/executor/helps/claude_client_detection_test.go +++ b/internal/runtime/executor/helps/claude_client_detection_test.go @@ -18,7 +18,7 @@ func claudeCodeDetectionPayload(userID string) []byte { func confirmedClaudeCodeHeaders() http.Header { return http.Header{ - "User-Agent": {"claude-cli/2.1.280 (external, cli)"}, + "User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219,interleaved-thinking-2025-05-14"}, } @@ -84,7 +84,7 @@ func TestDetectClaudeCodeRequestRequiresAllFourMessageSignals(t *testing.T) { func TestDetectClaudeCodeRequestAcceptsNewerPatchInMeasuredReleaseLine(t *testing.T) { headers := confirmedClaudeCodeHeaders() - headers.Set("User-Agent", "claude-cli/2.1.281 (external, cli)") + headers.Set("User-Agent", "claude-cli/2.1.322 (external, cli)") payload := claudeCodeDetectionPayload(validClaudeCodeMetadataUserID) detection := DetectClaudeCodeRequest(headers, payload, false) @@ -118,9 +118,9 @@ func TestDetectClaudeCodeRequestRejectsEachMissingMessageSignal(t *testing.T) { headers http.Header body []byte }{ - {name: "x-app", headers: http.Header{"User-Agent": {"claude-cli/2.1.280 (external, cli)"}, "Anthropic-Beta": {"claude-code-20250219"}}, body: payload}, + {name: "x-app", headers: http.Header{"User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "Anthropic-Beta": {"claude-code-20250219"}}, body: payload}, {name: "user-agent", headers: http.Header{"User-Agent": {"curl/8.7.1"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}}, body: payload}, - {name: "betas", headers: http.Header{"User-Agent": {"claude-cli/2.1.280 (external, cli)"}, "X-App": {"cli"}}, body: payload}, + {name: "betas", headers: http.Header{"User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}}, body: payload}, {name: "metadata", headers: confirmedClaudeCodeHeaders(), body: []byte(`{"messages":[]}`)}, } { t.Run(test.name, func(t *testing.T) { @@ -141,16 +141,16 @@ func TestDetectClaudeCodeRequestClassifiesEntrypoints(t *testing.T) { agentSDKVersion string native bool }{ - {name: "cli", userAgent: "claude-cli/2.1.280 (external, cli)", entrypoint: "cli", subclient: "claude-code-cli", native: true}, - {name: "vscode-agent-sdk", userAgent: "claude-cli/2.1.280 (external, claude-vscode, agent-sdk/0.3.220)", entrypoint: "claude-vscode", subclient: "claude-code-vscode", agentSDKVersion: "0.3.220", native: true}, - {name: "sdk-cli", userAgent: "claude-cli/2.1.280 (external, sdk-cli)", entrypoint: "sdk-cli", subclient: "claude-code-cli-sdk", native: true}, - {name: "sdk-ts", userAgent: "claude-cli/2.1.280 (external, sdk-ts, agent-sdk/0.3.220)", entrypoint: "sdk-ts", subclient: "claude-code-sdk-ts", agentSDKVersion: "0.3.220", native: true}, - {name: "sdk-py", userAgent: "claude-cli/2.1.280 (external, sdk-py, agent-sdk/0.1.0)", entrypoint: "sdk-py", subclient: "claude-code-sdk-py", agentSDKVersion: "0.1.0"}, - {name: "desktop", userAgent: "claude-cli/2.1.280 (external, claude-desktop)", entrypoint: "claude-desktop", subclient: "claude-desktop"}, - {name: "desktop-third-party-inference", userAgent: "claude-cli/2.1.280 (external, claude-desktop-3p)", entrypoint: "claude-desktop-3p", subclient: "claude-desktop-3p"}, - {name: "remote", userAgent: "claude-cli/2.1.280 (external, remote)", entrypoint: "remote", subclient: "claude-remote"}, - {name: "github-action", userAgent: "claude-cli/2.1.280 (external, claude-code-github-action)", entrypoint: "claude-code-github-action", subclient: "claude-code-gh-action"}, - {name: "unknown", userAgent: "claude-cli/2.1.280 (external, copied-client)", entrypoint: "copied-client"}, + {name: "cli", userAgent: "claude-cli/2.1.321 (external, cli)", entrypoint: "cli", subclient: "claude-code-cli", native: true}, + {name: "vscode-agent-sdk", userAgent: "claude-cli/2.1.321 (external, claude-vscode, agent-sdk/0.3.220)", entrypoint: "claude-vscode", subclient: "claude-code-vscode", agentSDKVersion: "0.3.220", native: true}, + {name: "sdk-cli", userAgent: "claude-cli/2.1.321 (external, sdk-cli)", entrypoint: "sdk-cli", subclient: "claude-code-cli-sdk", native: true}, + {name: "sdk-ts", userAgent: "claude-cli/2.1.321 (external, sdk-ts, agent-sdk/0.3.220)", entrypoint: "sdk-ts", subclient: "claude-code-sdk-ts", agentSDKVersion: "0.3.220", native: true}, + {name: "sdk-py", userAgent: "claude-cli/2.1.321 (external, sdk-py, agent-sdk/0.1.0)", entrypoint: "sdk-py", subclient: "claude-code-sdk-py", agentSDKVersion: "0.1.0"}, + {name: "desktop", userAgent: "claude-cli/2.1.321 (external, claude-desktop)", entrypoint: "claude-desktop", subclient: "claude-desktop"}, + {name: "desktop-third-party-inference", userAgent: "claude-cli/2.1.321 (external, claude-desktop-3p)", entrypoint: "claude-desktop-3p", subclient: "claude-desktop-3p"}, + {name: "remote", userAgent: "claude-cli/2.1.321 (external, remote)", entrypoint: "remote", subclient: "claude-remote"}, + {name: "github-action", userAgent: "claude-cli/2.1.321 (external, claude-code-github-action)", entrypoint: "claude-code-github-action", subclient: "claude-code-gh-action"}, + {name: "unknown", userAgent: "claude-cli/2.1.321 (external, copied-client)", entrypoint: "copied-client"}, } { t.Run(test.name, func(t *testing.T) { headers := confirmedClaudeCodeHeaders() @@ -171,7 +171,7 @@ func TestDetectClaudeCodeRequestClassifiesEntrypoints(t *testing.T) { func TestDetectClaudeCodeCountTokensAllowsMissingMetadata(t *testing.T) { headers := confirmedClaudeCodeHeaders() - headers.Set("User-Agent", "claude-cli/2.1.280 (external, claude-vscode, agent-sdk/0.3.220)") + headers.Set("User-Agent", "claude-cli/2.1.321 (external, claude-vscode, agent-sdk/0.3.220)") detection := DetectClaudeCodeRequest(headers, []byte(`{"messages":[]}`), true) if !detection.Confirmed { t.Fatalf("detection = %#v, want confirmed", detection) @@ -412,7 +412,7 @@ func TestDetectClaudeCodeRequestRejectsMalformedNativeSignals(t *testing.T) { {name: "older patch user agent", headers: http.Header{"User-Agent": {"claude-cli/2.1.257 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}}, userID: validClaudeCodeMetadataUserID}, {name: "unmeasured next-minor user agent", headers: http.Header{"User-Agent": {"claude-cli/2.2.0 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}}, userID: validClaudeCodeMetadataUserID}, {name: "implausible future user agent", headers: http.Header{"User-Agent": {"claude-cli/999.0.0 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"claude-code-20250219"}}, userID: validClaudeCodeMetadataUserID}, - {name: "unrelated beta", headers: http.Header{"User-Agent": {"claude-cli/2.1.280 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"anything"}}, userID: validClaudeCodeMetadataUserID}, + {name: "unrelated beta", headers: http.Header{"User-Agent": {"claude-cli/2.1.321 (external, cli)"}, "X-App": {"cli"}, "Anthropic-Beta": {"anything"}}, userID: validClaudeCodeMetadataUserID}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -607,11 +607,11 @@ func TestDetectClaudeCodeRequestRecognizesAgentSDKHaiku55Helpers(t *testing.T) { payload []byte cfg *config.Config }{ - {name: "sdk-ts title helper", userAgent: "claude-cli/2.1.304 (external, sdk-ts, agent-sdk/0.3.276)", entrypoint: "sdk-ts", subclient: "claude-code-sdk-ts", betas: titleBetas, payload: titlePayload}, - {name: "sdk-ts web_search helper", userAgent: "claude-cli/2.1.304 (external, sdk-ts, agent-sdk/0.3.276)", entrypoint: "sdk-ts", subclient: "claude-code-sdk-ts", betas: webSearchBetas, payload: webSearchPayload}, + {name: "sdk-ts title helper", userAgent: "claude-cli/2.1.345 (external, sdk-ts, agent-sdk/0.3.276)", entrypoint: "sdk-ts", subclient: "claude-code-sdk-ts", betas: titleBetas, payload: titlePayload}, + {name: "sdk-ts web_search helper", userAgent: "claude-cli/2.1.345 (external, sdk-ts, agent-sdk/0.3.276)", entrypoint: "sdk-ts", subclient: "claude-code-sdk-ts", betas: webSearchBetas, payload: webSearchPayload}, { name: "configured t3-code title helper", - userAgent: "claude-cli/2.1.316 (external, t3-code, agent-sdk/0.3.276)", + userAgent: "claude-cli/2.1.357 (external, t3-code, agent-sdk/0.3.276)", entrypoint: "t3-code", subclient: "claude-code-t3-code", betas: titleBetas, @@ -639,7 +639,7 @@ func TestDetectClaudeCodeRequestRecognizesAgentSDKHaiku55Helpers(t *testing.T) { func TestDetectClaudeCodeRequestAcceptsConfiguredNativeEntrypoints(t *testing.T) { payload := claudeCodeDetectionPayload(validClaudeCodeMetadataUserID) headers := confirmedClaudeCodeHeaders() - headers.Set("User-Agent", "claude-cli/2.1.316 (external, t3-code, agent-sdk/0.3.276)") + headers.Set("User-Agent", "claude-cli/2.1.357 (external, t3-code, agent-sdk/0.3.276)") if detection := DetectClaudeCodeRequest(headers, payload, false); detection.Confirmed || detection.NativeClient { t.Fatalf("default detection = %#v, want unconfirmed without native-entrypoints config", detection) @@ -659,9 +659,50 @@ func TestDetectClaudeCodeRequestAcceptsConfiguredNativeEntrypoints(t *testing.T) } missingBetaHeaders := confirmedClaudeCodeHeaders() - missingBetaHeaders.Set("User-Agent", "claude-cli/2.1.316 (external, t3-code, agent-sdk/0.3.276)") + missingBetaHeaders.Set("User-Agent", "claude-cli/2.1.357 (external, t3-code, agent-sdk/0.3.276)") missingBetaHeaders.Del("Anthropic-Beta") if unconfirmed := DetectClaudeCodeRequest(missingBetaHeaders, payload, false, cfg); unconfirmed.Confirmed || unconfirmed.StrongSignals { t.Fatalf("configured entrypoint without strong signals = %#v, want unconfirmed", unconfirmed) } } + +func TestDetectClaudeCodeRequestAcceptsBackgroundSessionXApp(t *testing.T) { + payload := claudeCodeDetectionPayload(validClaudeCodeMetadataUserID) + + t.Run("messages", func(t *testing.T) { + headers := confirmedClaudeCodeHeaders() + headers.Set("X-App", "cli-bg") + detection := DetectClaudeCodeRequest(headers, payload, false) + if !detection.Confirmed || !detection.StrongSignals || !detection.NativeClient || !detection.XAppCLI { + t.Fatalf("detection = %#v, want confirmed native CLI for X-App: cli-bg", detection) + } + }) + + t.Run("count_tokens", func(t *testing.T) { + headers := confirmedClaudeCodeHeaders() + headers.Set("X-App", "cli-bg") + detection := DetectClaudeCodeRequest(headers, []byte(`{"messages":[]}`), true) + if !detection.Confirmed || !detection.StrongSignals || !detection.NativeClient || !detection.XAppCLI { + t.Fatalf("detection = %#v, want confirmed count_tokens for X-App: cli-bg", detection) + } + }) + + t.Run("measured_helper", func(t *testing.T) { + headers := measuredClaudeCodeHelperHeaders(claudeCodeHelperBetaProfile(true)) + headers.Set("X-App", "cli-bg") + detection := DetectClaudeCodeRequest(headers, measuredClaudeCodeMinimalHelperPayload(), false) + if !detection.Confirmed || !detection.StrongSignals || !detection.NativeClient || !detection.HelperProfile || !detection.XAppCLI { + t.Fatalf("detection = %#v, want confirmed measured helper for X-App: cli-bg", detection) + } + }) + + t.Run("rejects_unknown_x_app", func(t *testing.T) { + for _, unknownApp := range []string{"cli-other", "web", "sdk"} { + headers := confirmedClaudeCodeHeaders() + headers.Set("X-App", unknownApp) + if detection := DetectClaudeCodeRequest(headers, payload, false); detection.Confirmed || detection.XAppCLI { + t.Fatalf("X-App %q detection = %#v, want unconfirmed", unknownApp, detection) + } + } + }) +} diff --git a/internal/runtime/executor/helps/claude_code_user_agent.go b/internal/runtime/executor/helps/claude_code_user_agent.go new file mode 100644 index 00000000000..2d88eb082c5 --- /dev/null +++ b/internal/runtime/executor/helps/claude_code_user_agent.go @@ -0,0 +1,92 @@ +package helps + +import "strings" + +type claudeCodeUserAgent struct { + version claudeCLIVersion + entrypoint string + agentSDKVersion string + profileUserAgent string + requestFields []string +} + +// parseClaudeCodeUserAgent separates client identity from opaque request fields. +// Parsing a valid UA does not establish native-client eligibility. +func parseClaudeCodeUserAgent(userAgent string) (claudeCodeUserAgent, bool) { + for _, char := range userAgent { + if (char < ' ' && char != '\t') || char == '\x7f' { + return claudeCodeUserAgent{}, false + } + } + userAgent = strings.TrimSpace(userAgent) + prefix, comment, ok := strings.Cut(userAgent, "(") + if !ok || !strings.HasSuffix(comment, ")") || prefix == strings.TrimSpace(prefix) { + return claudeCodeUserAgent{}, false + } + product := strings.TrimSpace(prefix) + versionText, okVersion := strings.CutPrefix(product, "claude-cli/") + if !okVersion || !claudePackageVersionPattern.MatchString(versionText) { + return claudeCodeUserAgent{}, false + } + version, okVersion := parseClaudeCLIVersion(product) + if !okVersion { + return claudeCodeUserAgent{}, false + } + comment = strings.TrimSuffix(comment, ")") + if strings.ContainsAny(comment, "()") { + return claudeCodeUserAgent{}, false + } + fields := strings.Split(comment, ",") + if len(fields) < 2 || !strings.EqualFold(fields[0], "external") { + return claudeCodeUserAgent{}, false + } + entrypoint := strings.ToLower(strings.TrimSpace(fields[1])) + if entrypoint == "" { + return claudeCodeUserAgent{}, false + } + parsed := claudeCodeUserAgent{ + version: version, entrypoint: entrypoint, profileUserAgent: userAgent, + } + stableFields := []string{fields[0], fields[1]} + seen := make(map[string]struct{}) + for _, field := range fields[2:] { + name, value, okField := strings.Cut(strings.TrimSpace(field), "/") + if !okField || !validClaudeCodeUserAgentFieldName(name) || strings.TrimSpace(value) == "" { + return claudeCodeUserAgent{}, false + } + name = strings.ToLower(name) + if _, duplicate := seen[name]; duplicate { + return claudeCodeUserAgent{}, false + } + seen[name] = struct{}{} + if name == "agent-sdk" { + if !claudePackageVersionPattern.MatchString(value) { + return claudeCodeUserAgent{}, false + } + parsed.agentSDKVersion = value + stableFields = append(stableFields, field) + } else { + parsed.requestFields = append(parsed.requestFields, field) + } + } + if len(parsed.requestFields) > 0 { + // Request fields must never become a credential's stored device identity. + parsed.profileUserAgent = prefix + "(" + strings.Join(stableFields, ",") + ")" + } + return parsed, true +} + +func validClaudeCodeUserAgentFieldName(name string) bool { + if name == "" { + return false + } + // Extension names use HTTP token syntax; values remain opaque. + for _, char := range name { + if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') || + strings.ContainsRune("!#$%&'*+-.^_`|~", char) { + continue + } + return false + } + return true +} diff --git a/internal/runtime/executor/helps/claude_code_user_agent_test.go b/internal/runtime/executor/helps/claude_code_user_agent_test.go new file mode 100644 index 00000000000..a531f036b89 --- /dev/null +++ b/internal/runtime/executor/helps/claude_code_user_agent_test.go @@ -0,0 +1,226 @@ +package helps + +import ( + "context" + "net/http/httptest" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func TestDetectClaudeCodeRequestAcceptsUserAgentFields(t *testing.T) { + for _, testCase := range []struct { + name, userAgent, sdkVersion string + }{ + {name: "cron", userAgent: "claude-cli/2.1.353 (external, cli, workload/cron)"}, + {name: "field before SDK", userAgent: "claude-cli/2.1.353 (external, cli, workload/cron, agent-sdk/0.2.133)", sdkVersion: "0.2.133"}, + {name: "field after SDK", userAgent: "claude-cli/2.1.353 (external, cli, agent-sdk/0.2.133, workload/cron)", sdkVersion: "0.2.133"}, + {name: "unknown fields", userAgent: "claude-cli/2.1.353 (external, cli, future-feature/value, workload/background)"}, + } { + for _, countTokens := range []bool{false, true} { + path := "messages" + if countTokens { + path = "count_tokens" + } + t.Run(testCase.name+"/"+path, func(t *testing.T) { + headers := confirmedClaudeCodeHeaders() + headers.Set("User-Agent", testCase.userAgent) + payload := []byte(`{}`) + if !countTokens { + payload = claudeCodeDetectionPayload(validClaudeCodeMetadataUserID) + } + detection := DetectClaudeCodeRequest(headers, payload, countTokens) + if !detection.Confirmed || !detection.StrongSignals || !detection.NativeClient { + t.Fatalf("detection = %+v, want confirmed native CLI", detection) + } + if detection.Entrypoint != "cli" || detection.AgentSDKVersion != testCase.sdkVersion { + t.Fatalf("identity = %q/%q, want cli/%q", detection.Entrypoint, detection.AgentSDKVersion, testCase.sdkVersion) + } + }) + } + } +} + +func TestParseClaudeCodeUserAgent(t *testing.T) { + for _, testCase := range []struct { + name, userAgent, entrypoint, sdkVersion, profile string + }{ + {name: "plain", userAgent: "claude-cli/2.1.353 (external, cli)", entrypoint: "cli"}, + {name: "SDK", userAgent: "claude-cli/2.1.353 (external, sdk-ts, agent-sdk/0.2.133)", entrypoint: "sdk-ts", sdkVersion: "0.2.133"}, + {name: "cron", userAgent: "claude-cli/2.1.353 (external, cli, workload/cron)", entrypoint: "cli", profile: "claude-cli/2.1.353 (external, cli)"}, + {name: "SDK after metadata", userAgent: "claude-cli/2.1.353 (external, sdk-ts, workload/cron, agent-sdk/0.2.133, future-feature/value)", entrypoint: "sdk-ts", sdkVersion: "0.2.133", profile: "claude-cli/2.1.353 (external, sdk-ts, agent-sdk/0.2.133)"}, + {name: "token field name", userAgent: "claude-cli/2.1.353 (external, cli, future_field.v2/value/path)", entrypoint: "cli", profile: "claude-cli/2.1.353 (external, cli)"}, + } { + t.Run(testCase.name, func(t *testing.T) { + parsed, ok := parseClaudeCodeUserAgent(testCase.userAgent) + if !ok || parsed.version != (claudeCLIVersion{major: 2, minor: 1, patch: 353}) || parsed.entrypoint != testCase.entrypoint || parsed.agentSDKVersion != testCase.sdkVersion { + t.Fatalf("parsed = %+v, valid = %v", parsed, ok) + } + profile := testCase.profile + if profile == "" { + profile = testCase.userAgent + } + if parsed.profileUserAgent != profile { + t.Fatalf("profile UA = %q, want %q", parsed.profileUserAgent, profile) + } + }) + } +} + +func TestParseClaudeCodeUserAgentRejectsMalformedFields(t *testing.T) { + for _, userAgent := range []string{ + "claude-cli/2.1.353(external, cli)", + "claude-cli/2.1.353-extra (external, cli)", + "claude-cli/999999999999999999999999.1.0 (external, cli)", + "claude-cli/2.1.353 (external, )", + "claude-cli/2.1.353 (external, cli, foo)", + "claude-cli/2.1.353 (external, cli, /cron)", + "claude-cli/2.1.353 (external, cli, workload/)", + "claude-cli/2.1.353 (external, cli, bad name/value)", + "claude-cli/2.1.353 (external, cli, workload/(cron))", + "claude-cli/2.1.353 (external, cli, workload/cron, WORKLOAD/background)", + "claude-cli/2.1.353 (external, cli, agent-sdk/dev)", + "claude-cli/2.1.353 (external, cli, agent-sdk/0.2.133, agent-sdk/0.2.134)", + "claude-cli/2.1.353 (external, cli, workload/cron) trailing", + "claude-cli/2.1.353 (external, cli, workload/cr\non)", + "claude-cli/2.1.353 (external, cli)\r\n", + } { + t.Run(userAgent, func(t *testing.T) { + if parsed, ok := parseClaudeCodeUserAgent(userAgent); ok { + t.Fatalf("accepted malformed UA: %+v", parsed) + } + }) + } +} + +func TestDetectClaudeCodeRequestUserAgentFieldsKeepNativeGuards(t *testing.T) { + for _, testCase := range []struct { + name, userAgent, missingHeader string + missingMetadata, allowEntrypoint, wantConfirmed bool + }{ + {name: "old patch", userAgent: "claude-cli/2.1.320 (external, cli, workload/cron)"}, + {name: "unknown release line", userAgent: "claude-cli/2.2.0 (external, cli, workload/cron)"}, + {name: "unknown entrypoint", userAgent: "claude-cli/2.1.353 (external, other-client, workload/cron)"}, + {name: "missing app", missingHeader: "X-App"}, + {name: "missing beta", missingHeader: "Anthropic-Beta"}, + {name: "missing metadata", missingMetadata: true}, + {name: "configured entrypoint", userAgent: "claude-cli/2.1.353 (external, other-client, workload/cron)", allowEntrypoint: true, wantConfirmed: true}, + } { + t.Run(testCase.name, func(t *testing.T) { + headers := confirmedClaudeCodeHeaders() + userAgent := testCase.userAgent + if userAgent == "" { + userAgent = "claude-cli/2.1.353 (external, cli, workload/cron)" + } + headers.Set("User-Agent", userAgent) + headers.Del(testCase.missingHeader) + payload := claudeCodeDetectionPayload(validClaudeCodeMetadataUserID) + if testCase.missingMetadata { + payload = []byte(`{}`) + } + cfg := &config.Config{} + if testCase.allowEntrypoint { + cfg.ClaudeHeaderDefaults.NativeEntrypoints = []string{"other-client"} + } + detection := DetectClaudeCodeRequest(headers, payload, false, cfg) + if detection.Confirmed != testCase.wantConfirmed { + t.Fatalf("detection = %+v, want confirmed = %v", detection, testCase.wantConfirmed) + } + }) + } +} + +func TestClaudeDeviceProfileUserAgentFieldsStayRequestScoped(t *testing.T) { + for _, homeMode := range []bool{false, true} { + name := "local" + if homeMode { + name = "home" + } + t.Run(name, func(t *testing.T) { + ResetClaudeDeviceProfileCache() + t.Cleanup(ResetClaudeDeviceProfileCache) + client := newFakeClaudeDeviceProfileKVClient() + useFakeClaudeDeviceProfileKVClient(t, client, homeMode, nil) + auth := &cliproxyauth.Auth{ID: "request-fields-" + name} + baseUA := "claude-cli/2.1.321 (external, cli, agent-sdk/0.2.133)" + cronUA := "claude-cli/2.1.321 (external, cli, workload/cron, agent-sdk/0.2.133, future-feature/value)" + for _, testCase := range []struct{ userAgent, want string }{ + {userAgent: cronUA, want: "claude-cli/2.1.321 (external, cli, agent-sdk/0.2.133, workload/cron, future-feature/value)"}, + {userAgent: baseUA, want: baseUA}, + {userAgent: "claude-cli/2.1.321 (external, cli, future-feature/next)", want: "claude-cli/2.1.321 (external, cli, agent-sdk/0.2.133, future-feature/next)"}, + {want: baseUA}, + } { + headers := claudeDeviceHeaders(testCase.userAgent) + profile, errProfile := ResolveClaudeDeviceProfileRequired(context.Background(), auth, "dummy-key", headers, nil) + if errProfile != nil { + t.Fatal(errProfile) + } + if profile.UserAgent != baseUA { + t.Fatalf("profile UA = %q after %q, want %q", profile.UserAgent, testCase.userAgent, baseUA) + } + request := httptest.NewRequest("POST", "https://example.invalid/messages", nil) + ApplyClaudeDeviceProfileHeaders(request, profile, testCase.userAgent) + if got := request.Header.Get("User-Agent"); got != testCase.want { + t.Fatalf("request UA = %q, want only current fields in %q", got, testCase.want) + } + } + if homeMode && client.setCount != 1 { + t.Fatalf("stored %d profiles, want one shared stable identity", client.setCount) + } + }) + } +} + +func TestApplyClaudeDeviceProfileHeadersKeepsCurrentUserAgentFields(t *testing.T) { + profile := defaultClaudeDeviceProfile(nil) + profile.UserAgent = "claude-cli/2.1.321 (external, cli, agent-sdk/0.3.220)" + for _, testCase := range []struct { + name, userAgent, want string + }{ + {name: "current fields", userAgent: "claude-cli/2.1.353 (external, cli, workload/cron, agent-sdk/0.2.133, future-feature/value)", want: "claude-cli/2.1.321 (external, cli, agent-sdk/0.3.220, workload/cron, future-feature/value)"}, + {name: "next request fields", userAgent: "claude-cli/2.1.353 (external, cli, future-feature/next)", want: "claude-cli/2.1.321 (external, cli, agent-sdk/0.3.220, future-feature/next)"}, + {name: "ordinary request", userAgent: "claude-cli/2.1.353 (external, cli)", want: profile.UserAgent}, + {name: "malformed request", userAgent: "claude-cli/2.1.353 (external, cli, foo)", want: profile.UserAgent}, + {name: "no request", want: profile.UserAgent}, + } { + t.Run(testCase.name, func(t *testing.T) { + request := httptest.NewRequest("POST", "https://example.invalid/messages", nil) + ApplyClaudeDeviceProfileHeaders(request, profile, testCase.userAgent) + if got := request.Header.Get("User-Agent"); got != testCase.want { + t.Fatalf("upstream UA = %q, want %q", got, testCase.want) + } + for name, want := range map[string]string{ + "X-Stainless-Package-Version": profile.PackageVersion, + "X-Stainless-Runtime-Version": profile.RuntimeVersion, + "X-Stainless-Os": profile.OS, + "X-Stainless-Arch": profile.Arch, + } { + if got := request.Header.Get(name); got != want { + t.Fatalf("%s = %q, want stabilized %q", name, got, want) + } + } + }) + } +} + +func FuzzParseClaudeCodeUserAgent(f *testing.F) { + for _, seed := range []string{ + "claude-cli/2.1.353 (external, cli)", + "claude-cli/2.1.353 (external, cli, workload/cron, agent-sdk/0.2.133)", + "claude-cli/2.1.353 (external, cli, agent-sdk/dev)", + "", + } { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, userAgent string) { + parsed, ok := parseClaudeCodeUserAgent(userAgent) + if !ok { + return + } + stable, okStable := parseClaudeCodeUserAgent(parsed.profileUserAgent) + if !okStable || stable.version != parsed.version || stable.entrypoint != parsed.entrypoint || stable.agentSDKVersion != parsed.agentSDKVersion || stable.profileUserAgent != parsed.profileUserAgent || len(stable.requestFields) != 0 { + t.Fatalf("unstable parsed identity: %+v -> %+v (valid = %v)", parsed, stable, okStable) + } + }) +} diff --git a/internal/runtime/executor/helps/claude_device_profile.go b/internal/runtime/executor/helps/claude_device_profile.go index b203836f121..e77968e913b 100644 --- a/internal/runtime/executor/helps/claude_device_profile.go +++ b/internal/runtime/executor/helps/claude_device_profile.go @@ -20,9 +20,9 @@ import ( ) const ( - defaultClaudeFingerprintUserAgent = "claude-cli/2.1.280 (external, cli)" - defaultClaudeFingerprintPackageVersion = "0.112.1" - defaultClaudeFingerprintRuntimeVersion = "v26.3.0" + defaultClaudeFingerprintUserAgent = "claude-cli/2.1.321 (external, cli)" + defaultClaudeFingerprintPackageVersion = "0.128.0" + defaultClaudeFingerprintRuntimeVersion = "v26.12.1" defaultClaudeFingerprintOS = "MacOS" defaultClaudeFingerprintArch = "arm64" claudeDeviceProfileTTL = 7 * 24 * time.Hour @@ -304,9 +304,8 @@ func extractClaudeDeviceProfile(headers http.Header, cfg *config.Config) (Claude return ClaudeDeviceProfile{}, false } - userAgent := strings.TrimSpace(headers.Get("User-Agent")) - version, ok := parseClaudeCLIVersion(userAgent) - if !ok || !claudeCodeNativeUserAgentPattern.MatchString(userAgent) { + userAgent, ok := parseClaudeCodeUserAgent(headers.Get("User-Agent")) + if !ok { return ClaudeDeviceProfile{}, false } @@ -320,12 +319,12 @@ func extractClaudeDeviceProfile(headers http.Header, cfg *config.Config) (Claude runtimeVersion = baseline.RuntimeVersion } profile := ClaudeDeviceProfile{ - UserAgent: userAgent, + UserAgent: userAgent.profileUserAgent, PackageVersion: packageVersion, RuntimeVersion: runtimeVersion, OS: firstNonEmptyHeader(headers, "X-Stainless-Os", baseline.OS), Arch: firstNonEmptyHeader(headers, "X-Stainless-Arch", baseline.Arch), - version: version, + version: userAgent.version, hasVersion: true, } return profile, true @@ -618,10 +617,23 @@ func (value claudeDeviceProfileKVValue) ToProfile() ClaudeDeviceProfile { return profile } -func ApplyClaudeDeviceProfileHeaders(r *http.Request, profile ClaudeDeviceProfile) { +// ApplyClaudeDeviceProfileHeaders applies a stable software identity. An optional +// UA from a confirmed native caller supplies only this request's extension fields. +func ApplyClaudeDeviceProfileHeaders(r *http.Request, profile ClaudeDeviceProfile, requestUserAgent ...string) { if r == nil { return } + userAgent := profile.UserAgent + if len(requestUserAgent) > 0 { + stable, validStable := parseClaudeCodeUserAgent(profile.UserAgent) + current, validCurrent := parseClaudeCodeUserAgent(requestUserAgent[0]) + if validStable && validCurrent { + userAgent = stable.profileUserAgent + if len(current.requestFields) > 0 { + userAgent = strings.TrimSuffix(userAgent, ")") + "," + strings.Join(current.requestFields, ",") + ")" + } + } + } for _, headerName := range []string{ "User-Agent", "X-Stainless-Package-Version", @@ -631,21 +643,21 @@ func ApplyClaudeDeviceProfileHeaders(r *http.Request, profile ClaudeDeviceProfil } { r.Header.Del(headerName) } - r.Header.Set("User-Agent", profile.UserAgent) + r.Header.Set("User-Agent", userAgent) r.Header.Set("X-Stainless-Package-Version", profile.PackageVersion) r.Header.Set("X-Stainless-Runtime-Version", profile.RuntimeVersion) r.Header.Set("X-Stainless-Os", profile.OS) r.Header.Set("X-Stainless-Arch", profile.Arch) } -// DefaultClaudeVersion returns the version string (e.g. "2.1.280") from the +// DefaultClaudeVersion returns the version string (e.g. "2.1.321") from the // current baseline device profile. It extracts the version from the User-Agent. func DefaultClaudeVersion(cfg *config.Config) string { profile := defaultClaudeDeviceProfile(cfg) if version, ok := parseClaudeCLIVersion(profile.UserAgent); ok { return strconv.Itoa(version.major) + "." + strconv.Itoa(version.minor) + "." + strconv.Itoa(version.patch) } - return "2.1.280" + return "2.1.321" } func ApplyClaudeDefaultDeviceProfileHeaders(r *http.Request, cfg *config.Config) { diff --git a/internal/runtime/executor/helps/claude_device_profile_test.go b/internal/runtime/executor/helps/claude_device_profile_test.go index d1b2777e717..1ab910173d4 100644 --- a/internal/runtime/executor/helps/claude_device_profile_test.go +++ b/internal/runtime/executor/helps/claude_device_profile_test.go @@ -130,7 +130,7 @@ func TestResolveClaudeDeviceProfileLocalUsesBaselineForInvalidSignals(t *testing func TestResolveClaudeDeviceProfileLocalKeepsExactMeasuredSoftwareBaseline(t *testing.T) { ResetClaudeDeviceProfileCache() auth := &cliproxyauth.Auth{ID: "auth-newer-patch-signals"} - headers := claudeDeviceHeaders("claude-cli/2.1.281 (external, cli)") + headers := claudeDeviceHeaders("claude-cli/2.1.322 (external, cli)") profile := resolveClaudeDeviceProfileLocal(auth, "api-key", headers, nil) baseline := defaultClaudeDeviceProfile(nil) @@ -280,7 +280,7 @@ func TestResolveClaudeDeviceProfileRequiredHomeSeparatesVSCodeAgentSDKFromCLI(t if errCLI != nil { t.Fatalf("ResolveClaudeDeviceProfileRequired() CLI error = %v", errCLI) } - vscodeUA := "claude-cli/2.1.280 (external, claude-vscode, agent-sdk/0.3.220)" + vscodeUA := "claude-cli/2.1.321 (external, claude-vscode, agent-sdk/0.3.220)" vscodeProfile, errVSCode := ResolveClaudeDeviceProfileRequired(context.Background(), auth, "api-key", claudeDeviceHeaders(vscodeUA), nil) if errVSCode != nil { t.Fatalf("ResolveClaudeDeviceProfileRequired() VSCode error = %v", errVSCode) @@ -362,19 +362,19 @@ func TestResolveClaudeDeviceProfilePreservesConfirmedClientAtBaselineVersion(t * client := newFakeClaudeDeviceProfileKVClient() useFakeClaudeDeviceProfileKVClient(t, client, false, nil) auth := &cliproxyauth.Auth{ID: "auth-baseline-entrypoint"} - headers := claudeDeviceHeaders("claude-cli/2.1.280 (external, cli)") - headers.Set("X-Stainless-Package-Version", "0.112.1") - headers.Set("X-Stainless-Runtime-Version", "v26.3.0") + headers := claudeDeviceHeaders("claude-cli/2.1.321 (external, cli)") + headers.Set("X-Stainless-Package-Version", "0.128.0") + headers.Set("X-Stainless-Runtime-Version", "v26.12.1") profile, errProfile := ResolveClaudeDeviceProfileRequired(context.Background(), auth, "api-key", headers, nil) if errProfile != nil { t.Fatalf("ResolveClaudeDeviceProfileRequired() error = %v", errProfile) } - if profile.UserAgent != "claude-cli/2.1.280 (external, cli)" { + if profile.UserAgent != "claude-cli/2.1.321 (external, cli)" { t.Fatalf("UserAgent = %q, want confirmed cli entrypoint preserved", profile.UserAgent) } - if profile.PackageVersion != "0.112.1" || profile.RuntimeVersion != "v26.3.0" { - t.Fatalf("software profile = %s/%s, want 0.112.1/v26.3.0", profile.PackageVersion, profile.RuntimeVersion) + if profile.PackageVersion != "0.128.0" || profile.RuntimeVersion != "v26.12.1" { + t.Fatalf("software profile = %s/%s, want 0.128.0/v26.12.1", profile.PackageVersion, profile.RuntimeVersion) } } @@ -384,27 +384,27 @@ func TestResolveClaudeDeviceProfileSeparatesVSCodeAgentSDKFromCLI(t *testing.T) useFakeClaudeDeviceProfileKVClient(t, client, false, nil) auth := &cliproxyauth.Auth{ID: "auth-subclient-isolation"} - cliHeaders := claudeDeviceHeaders("claude-cli/2.1.280 (external, cli)") - cliHeaders.Set("X-Stainless-Package-Version", "0.112.1") - cliHeaders.Set("X-Stainless-Runtime-Version", "v26.3.0") + cliHeaders := claudeDeviceHeaders("claude-cli/2.1.321 (external, cli)") + cliHeaders.Set("X-Stainless-Package-Version", "0.128.0") + cliHeaders.Set("X-Stainless-Runtime-Version", "v26.12.1") cliProfile, errCLI := ResolveClaudeDeviceProfileRequired(context.Background(), auth, "api-key", cliHeaders, nil) if errCLI != nil { t.Fatalf("ResolveClaudeDeviceProfileRequired() CLI error = %v", errCLI) } - vscodeUA := "claude-cli/2.1.280 (external, claude-vscode, agent-sdk/0.3.220)" + vscodeUA := "claude-cli/2.1.321 (external, claude-vscode, agent-sdk/0.3.220)" vscodeHeaders := claudeDeviceHeaders(vscodeUA) - vscodeHeaders.Set("X-Stainless-Package-Version", "0.112.1") - vscodeHeaders.Set("X-Stainless-Runtime-Version", "v26.3.0") + vscodeHeaders.Set("X-Stainless-Package-Version", "0.128.0") + vscodeHeaders.Set("X-Stainless-Runtime-Version", "v26.12.1") vscodeProfile, errVSCode := ResolveClaudeDeviceProfileRequired(context.Background(), auth, "api-key", vscodeHeaders, nil) if errVSCode != nil { t.Fatalf("ResolveClaudeDeviceProfileRequired() VSCode error = %v", errVSCode) } - sdkTSUA := "claude-cli/2.1.280 (external, sdk-ts, agent-sdk/0.3.220)" + sdkTSUA := "claude-cli/2.1.321 (external, sdk-ts, agent-sdk/0.3.220)" sdkTSHeaders := claudeDeviceHeaders(sdkTSUA) - sdkTSHeaders.Set("X-Stainless-Package-Version", "0.112.1") - sdkTSHeaders.Set("X-Stainless-Runtime-Version", "v26.3.0") + sdkTSHeaders.Set("X-Stainless-Package-Version", "0.128.0") + sdkTSHeaders.Set("X-Stainless-Runtime-Version", "v26.12.1") sdkTSProfile, errSDKTS := ResolveClaudeDeviceProfileRequired(context.Background(), auth, "api-key", sdkTSHeaders, nil) if errSDKTS != nil { t.Fatalf("ResolveClaudeDeviceProfileRequired() sdk-ts error = %v", errSDKTS) @@ -415,25 +415,25 @@ func TestResolveClaudeDeviceProfileSeparatesVSCodeAgentSDKFromCLI(t *testing.T) NativeEntrypoints: []string{"t3-code", "custom-ide"}, }, } - t3CodeUA := "claude-cli/2.1.280 (external, t3-code, agent-sdk/0.3.276)" + t3CodeUA := "claude-cli/2.1.321 (external, t3-code, agent-sdk/0.3.276)" t3CodeHeaders := claudeDeviceHeaders(t3CodeUA) - t3CodeHeaders.Set("X-Stainless-Package-Version", "0.112.1") - t3CodeHeaders.Set("X-Stainless-Runtime-Version", "v26.3.0") + t3CodeHeaders.Set("X-Stainless-Package-Version", "0.128.0") + t3CodeHeaders.Set("X-Stainless-Runtime-Version", "v26.12.1") t3CodeProfile, errT3Code := ResolveClaudeDeviceProfileRequired(context.Background(), auth, "api-key", t3CodeHeaders, cfg) if errT3Code != nil { t.Fatalf("ResolveClaudeDeviceProfileRequired() t3-code error = %v", errT3Code) } - customIDEUA := "claude-cli/2.1.280 (external, custom-ide, agent-sdk/0.3.276)" + customIDEUA := "claude-cli/2.1.321 (external, custom-ide, agent-sdk/0.3.276)" customIDEHeaders := claudeDeviceHeaders(customIDEUA) - customIDEHeaders.Set("X-Stainless-Package-Version", "0.112.1") - customIDEHeaders.Set("X-Stainless-Runtime-Version", "v26.3.0") + customIDEHeaders.Set("X-Stainless-Package-Version", "0.128.0") + customIDEHeaders.Set("X-Stainless-Runtime-Version", "v26.12.1") customIDEProfile, errCustomIDE := ResolveClaudeDeviceProfileRequired(context.Background(), auth, "api-key", customIDEHeaders, cfg) if errCustomIDE != nil { t.Fatalf("ResolveClaudeDeviceProfileRequired() custom-ide error = %v", errCustomIDE) } - if cliProfile.UserAgent != "claude-cli/2.1.280 (external, cli)" { + if cliProfile.UserAgent != "claude-cli/2.1.321 (external, cli)" { t.Fatalf("CLI UserAgent = %q, want CLI profile", cliProfile.UserAgent) } if vscodeProfile.UserAgent != vscodeUA { diff --git a/internal/runtime/executor/helps/claude_diagnostics.go b/internal/runtime/executor/helps/claude_diagnostics.go index 25ca3718894..194c12c46a4 100644 --- a/internal/runtime/executor/helps/claude_diagnostics.go +++ b/internal/runtime/executor/helps/claude_diagnostics.go @@ -796,6 +796,12 @@ func IsClaudeProbeOrHelperRequest(body []byte) bool { return isClaudeProbeRequest(body) || isClaudeTitleHelperRequest(body) } +// IsClaudeQuotaProbeRequest reports the max_tokens=1 quota probe alone, +// excluding the session-title helper that IsClaudeProbeOrHelperRequest also covers. +func IsClaudeQuotaProbeRequest(body []byte) bool { + return isClaudeProbeRequest(body) +} + // IsClaudeSubagentRequest reports whether the incoming request originates from // or represents a Claude Code subagent. func IsClaudeSubagentRequest(headers http.Header, body []byte) bool { @@ -833,6 +839,9 @@ func ClaudePayloadHas1hTTL(payload []byte) bool { if len(payload) == 0 || !jsonMayContainASCII(payload, `"1h"`) || !ojson.ValidBytes(payload) { return false } + if topCC := ojson.GetBytesNoCopy(payload, "cache_control"); topCC.IsObject() && topCC.Get("ttl").String() == "1h" { + return true + } has1h := false checkBlock := func(item ojson.Result) bool { cc := item.Get("cache_control") diff --git a/internal/runtime/executor/helps/claude_json_prefilter_fuzz_test.go b/internal/runtime/executor/helps/claude_json_prefilter_fuzz_test.go index bb206afa3c5..2cc2328e976 100644 --- a/internal/runtime/executor/helps/claude_json_prefilter_fuzz_test.go +++ b/internal/runtime/executor/helps/claude_json_prefilter_fuzz_test.go @@ -58,6 +58,9 @@ func referenceClaudePayloadHas1hTTL(payload []byte) bool { if len(payload) == 0 || !ojson.ValidBytes(payload) { return false } + if topCC := ojson.GetBytes(payload, "cache_control"); topCC.IsObject() && topCC.Get("ttl").String() == "1h" { + return true + } has1h := false checkBlock := func(item ojson.Result) bool { cc := item.Get("cache_control") diff --git a/internal/runtime/executor/helps/claude_thread.go b/internal/runtime/executor/helps/claude_thread.go new file mode 100644 index 00000000000..b8fd84c039d --- /dev/null +++ b/internal/runtime/executor/helps/claude_thread.go @@ -0,0 +1,308 @@ +package helps + +import ( + "bufio" + "bytes" + "context" + "errors" + "io" + "net/http" + "strings" + "sync" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" + cliproxysession "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" + log "github.com/sirupsen/logrus" +) + +const ( + claudeThreadBetaLimit = 1024 + claudeThreadBetaTTL = cliproxysession.ClaudeThreadStateTTL + claudeThreadEventLimit = 52_428_800 +) + +type claudeThreadBetaKey struct { + scope string + messageID string +} + +type claudeThreadBetaProfile struct { + betas string + policy string + bodyBetas string +} + +// ClaudeThreadBetaPolicy separates explicit payload rules from caller declarations. +type ClaudeThreadBetaPolicy struct { + Fingerprint string + BodyBetas string + PayloadConfigured bool +} + +// ClaudeThreadBetaConflictError requires replay when a fixed Thread profile +// cannot satisfy the current explicit policy or declared protocol capabilities. +type ClaudeThreadBetaConflictError struct{} + +func (ClaudeThreadBetaConflictError) Error() string { + return "The Thread beta profile conflicts with the current header policy or cannot be reconstructed. Replay the full conversation with thread create." +} + +func (ClaudeThreadBetaConflictError) StatusCode() int { return http.StatusConflict } + +func (ClaudeThreadBetaConflictError) IsRequestScoped() bool { return true } + +// ClaudeThreadBetaStore keeps successful Thread wire profiles bounded and shared +// across credential-scoped executor copies. Empty profiles are valid entries. +type ClaudeThreadBetaStore struct { + mu sync.Mutex + entries map[claudeThreadBetaKey]claudeThreadBetaProfile + order []claudeThreadBetaKey +} + +// ClaudeThreadBetaRequest binds a request to the profile sent to its upstream. +type ClaudeThreadBetaRequest struct { + store *ClaudeThreadBetaStore + scope string + betas string + policy string + bodyBetas string + onCommit func(string) +} + +// OnCommit registers routing state that must be visible before completion. +func (r *ClaudeThreadBetaRequest) OnCommit(commit func(string)) { + if r != nil { + r.onCommit = commit + } +} + +// Bind restores only an actual successful profile, recovering it from the +// configured KV store after memory eviction or restart. Unknown profiles are +// never guessed from the current turn's potentially different capabilities. +func (s *ClaudeThreadBetaStore) Bind(scope, previousMessageID string, header http.Header, policy ClaudeThreadBetaPolicy) (*ClaudeThreadBetaRequest, bool, error) { + betas := strings.Join(HeaderValuesCaseInsensitive(header, "Anthropic-Beta"), ",") + bodyBetas := policy.BodyBetas + if previousMessageID != "" { + key := claudeThreadBetaKey{scope: scope, messageID: previousMessageID} + s.mu.Lock() + previous, ok := s.entries[key] + s.mu.Unlock() + if !ok { + client, kvMode, errClient := kvstore.CurrentKVClient() + if errClient != nil { + log.WithError(errClient).Warn("Claude Thread beta store unavailable") + return nil, false, ClaudeThreadBetaConflictError{} + } + if !kvMode || client == nil { + return nil, false, nil + } + raw, found, errGet := client.KVGet(context.Background(), claudeThreadBetaKVKey(key)) + if errGet != nil { + log.WithError(errGet).Warn("Claude Thread beta profile load failed") + return nil, false, ClaudeThreadBetaConflictError{} + } + if !found { + return nil, false, nil + } + storedPolicy, rest, validPolicy := strings.Cut(string(raw), "\n") + storedBodyBetas, storedBetas, validBetas := strings.Cut(rest, "\n") + if !validPolicy || !validBetas || strings.ContainsAny(storedBetas+storedBodyBetas, "\r\n") { + return nil, false, ClaudeThreadBetaConflictError{} + } + previous = claudeThreadBetaProfile{betas: storedBetas, policy: storedPolicy, bodyBetas: storedBodyBetas} + s.save(key, previous) + } + payloadConflict := false + if policy.PayloadConfigured { + current := claudeThreadBetaNames(betas) + frozen := claudeThreadBetaNames(previous.betas) + for beta := range claudeThreadBetaNames(previous.bodyBetas) { + payloadConflict = payloadConflict || !current[beta] + } + for beta := range claudeThreadBetaNames(policy.BodyBetas) { + payloadConflict = payloadConflict || !frozen[beta] + } + } + if (previous.policy != policy.Fingerprint && previous.betas != betas) || payloadConflict { + return nil, true, ClaudeThreadBetaConflictError{} + } + betas = previous.betas + bodyBetas = previous.bodyBetas + for name := range header { + if strings.EqualFold(name, "Anthropic-Beta") { + delete(header, name) + } + } + if betas != "" { + header.Set("Anthropic-Beta", betas) + } + } + return &ClaudeThreadBetaRequest{store: s, scope: scope, betas: betas, policy: policy.Fingerprint, bodyBetas: bodyBetas}, true, nil +} + +// Commit publishes only a successful response ID. The existing KV store keeps +// exact snapshots recoverable across cache eviction and ordinary server restarts. +func (r *ClaudeThreadBetaRequest) Commit(messageID string) { + if r == nil || messageID == "" { + return + } + key := claudeThreadBetaKey{scope: r.scope, messageID: messageID} + if r.store.save(key, claudeThreadBetaProfile{betas: r.betas, policy: r.policy, bodyBetas: r.bodyBetas}) { + // Policy is hex; the delimiters cannot occur in HTTP header values. + kvstore.KVSetNXBestEffort(context.Background(), claudeThreadBetaKVKey(key), []byte(r.policy+"\n"+r.bodyBetas+"\n"+r.betas), claudeThreadBetaTTL) + } + if r.onCommit != nil { + r.onCommit(messageID) + } +} + +func (s *ClaudeThreadBetaStore) save(key claudeThreadBetaKey, profile claudeThreadBetaProfile) bool { + key.messageID = strings.Clone(key.messageID) + s.mu.Lock() + defer s.mu.Unlock() + if s.entries == nil { + s.entries = make(map[claudeThreadBetaKey]claudeThreadBetaProfile) + } + if _, exists := s.entries[key]; exists { + return false + } + s.entries[key] = profile + s.order = append(s.order, key) + if len(s.order) > claudeThreadBetaLimit { + delete(s.entries, s.order[0]) + s.order = s.order[1:] + } + return true +} + +func claudeThreadBetaNames(betas string) map[string]bool { + names := make(map[string]bool) + for _, beta := range strings.Split(betas, ",") { + if beta = strings.TrimSpace(beta); beta != "" { + names[beta] = true + } + } + return names +} + +func claudeThreadBetaKVKey(key claudeThreadBetaKey) string { + return "claude:thread-beta:v1:" + kvstore.HashKeyPart(key.scope) + ":" + kvstore.HashKeyPart(key.messageID) +} + +// StreamReader withholds terminal events until message_stop confirms success. +// This is before translation, so even translators that finish on message_delta +// cannot expose completion before the next turn can load its Thread profile. +func (r *ClaudeThreadBetaRequest) StreamReader(body io.Reader, beforeComplete func(string)) io.Reader { + if r == nil { + return body + } + scanner := bufio.NewScanner(body) + scanner.Buffer(nil, claudeThreadEventLimit) + return &claudeThreadStreamReader{scanner: scanner, commit: func(messageID string) { + if beforeComplete != nil { + beforeComplete(messageID) + } + r.Commit(messageID) + }} +} + +type claudeThreadStreamReader struct { + scanner *bufio.Scanner + commit func(string) + ready bytes.Buffer + pending bytes.Buffer + messageID string + failed bool + finished bool +} + +func (r *claudeThreadStreamReader) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + for r.ready.Len() == 0 { + if r.finished { + return 0, io.EOF + } + var event bytes.Buffer + for r.scanner.Scan() { + line := r.scanner.Bytes() + event.Write(line) + event.WriteByte('\n') + if event.Len() > claudeThreadEventLimit { + return 0, errors.New("Claude Thread event exceeds buffer limit") + } + if len(bytes.TrimSpace(line)) == 0 { + break + } + } + if event.Len() == 0 { + if errScan := r.scanner.Err(); errScan != nil { + return 0, errScan + } + // Never release a completion signal from a truncated Thread turn. + return 0, io.ErrUnexpectedEOF + } + payload := claudeThreadEventPayload(event.Bytes()) + if bytes.HasPrefix(payload, []byte("{")) && !ojson.ValidBytes(payload) { + return 0, errors.New("malformed Claude Thread stream event") + } + if r.pending.Len()+event.Len() > claudeThreadEventLimit { + return 0, errors.New("Claude Thread completion exceeds buffer limit") + } + root := ojson.ParseBytes(payload) + typ := root.Get("type").String() + terminal := false + if _, blocked := clienterror.ClaudePolicyRefusalMessage(payload); blocked { + r.failed = true + } + switch typ { + case "message_start": + r.messageID = strings.Clone(root.Get("message.id").String()) + case "message_delta": + terminal = root.Get("delta.stop_reason").String() != "" + case "error": + r.failed = true + // Drop any speculative completion and let the executor report the error. + r.pending.Reset() + case "message_stop": + r.finished = true + if !r.failed && r.messageID != "" { + r.commit(r.messageID) + } + case "message": + if root.Get("stop_reason").String() != "" { + r.finished = true + if !r.failed { + r.commit(root.Get("id").String()) + } + } + } + if terminal || r.pending.Len() > 0 { + r.pending.Write(event.Bytes()) + if r.finished { + r.ready.Write(r.pending.Bytes()) + r.pending.Reset() + } + } else { + r.ready.Write(event.Bytes()) + } + } + return r.ready.Read(p) +} + +func claudeThreadEventPayload(event []byte) []byte { + var lines [][]byte + for _, line := range bytes.Split(event, []byte("\n")) { + line = bytes.TrimSpace(line) + if bytes.HasPrefix(line, []byte("data:")) { + lines = append(lines, bytes.TrimSpace(line[len("data:"):])) + } + } + if len(lines) == 0 { + return bytes.TrimSpace(event) + } + return bytes.Join(lines, []byte("\n")) +} diff --git a/internal/runtime/executor/helps/claude_thread_test.go b/internal/runtime/executor/helps/claude_thread_test.go new file mode 100644 index 00000000000..7125380d94d --- /dev/null +++ b/internal/runtime/executor/helps/claude_thread_test.go @@ -0,0 +1,128 @@ +package helps + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "testing" + "testing/iotest" +) + +func TestClaudeThreadBetaStoreRestoresWireProfile(t *testing.T) { + for _, betas := range []string{"", "message-threads-2026-08-12,effort-2025-11-24"} { + t.Run(betas, func(t *testing.T) { + store := &ClaudeThreadBetaStore{} + first, ok, _ := store.Bind("caller-a", "", http.Header{"Anthropic-Beta": []string{betas}}, ClaudeThreadBetaPolicy{}) + if !ok { + t.Fatal("create was rejected") + } + first.Commit("message-a") + for _, scope := range []string{"caller-b", "other-credential"} { + if _, found, _ := store.Bind(scope, "message-a", http.Header{}, ClaudeThreadBetaPolicy{}); found { + t.Fatalf("profile leaked into scope %q", scope) + } + } + header := http.Header{"Anthropic-Beta": []string{"derived-beta"}, "anthropic-beta": []string{"custom-beta"}} + second, found, _ := store.Bind("caller-a", "message-a", header, ClaudeThreadBetaPolicy{}) + if !found || header.Get("Anthropic-Beta") != betas { + t.Fatalf("restored header = %v, found=%v, want %q", header, found, betas) + } + if _, duplicate := header["anthropic-beta"]; duplicate { + t.Fatal("restoring retained a duplicate wire-cased header") + } + second.Commit("message-b") + thirdHeader := http.Header{"Anthropic-Beta": []string{"new-body-beta"}} + if _, foundThird, _ := store.Bind("caller-a", "message-b", thirdHeader, ClaudeThreadBetaPolicy{}); !foundThird || thirdHeader.Get("Anthropic-Beta") != betas { + t.Fatalf("third-turn profile = %v, found=%v", thirdHeader, foundThird) + } + }) + } +} + +func TestClaudeThreadBetaStoreEvictsOldestMessage(t *testing.T) { + store := &ClaudeThreadBetaStore{} + for i := range claudeThreadBetaLimit + 1 { + request, _, _ := store.Bind("scope", "", http.Header{"Anthropic-Beta": []string{"stable-beta"}}, ClaudeThreadBetaPolicy{}) + request.Commit(fmt.Sprintf("message-%d", i)) + } + if _, found, _ := store.Bind("scope", "message-0", http.Header{}, ClaudeThreadBetaPolicy{}); found { + t.Fatal("oldest profile was not evicted") + } + if _, found, _ := store.Bind("scope", fmt.Sprintf("message-%d", claudeThreadBetaLimit), http.Header{}, ClaudeThreadBetaPolicy{}); !found { + t.Fatal("newest profile was evicted") + } +} + +func TestClaudeThreadBetaStoreConcurrentCallers(t *testing.T) { + store := &ClaudeThreadBetaStore{} + var wg sync.WaitGroup + for caller := range 16 { + wg.Go(func() { + scope := fmt.Sprintf("caller-%d", caller) + request, _, _ := store.Bind(scope, "", http.Header{"Anthropic-Beta": []string{scope}}, ClaudeThreadBetaPolicy{}) + request.Commit("shared-message-id") + for range 10 { + header := http.Header{} + if _, found, _ := store.Bind(scope, "shared-message-id", header, ClaudeThreadBetaPolicy{}); !found || header.Get("Anthropic-Beta") != scope { + t.Errorf("profile crossed callers: %v, scope=%s", header, scope) + } + } + }) + } + wg.Wait() +} + +func TestClaudeThreadOversizedCompletionDoesNotPublishState(t *testing.T) { + const start = "data: {\"type\":\"message_start\",\"message\":{\"id\":\"message-a\"}}\n\n" + const terminal = "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"}}\n\n" + const stop = "data: {\"type\":\"message_stop\"}\n\n" + const pingPrefix = "data: {\"type\":\"ping\",\"padding\":\"" + const pingSuffix = "\"}\n\n" + // Each event fits, but message_stop pushes the pending completion over its cap. + pingSize := (claudeThreadEventLimit - 1 - len(terminal)) / 2 + ping := pingPrefix + strings.Repeat("x", pingSize-len(pingPrefix)-len(pingSuffix)) + pingSuffix + body := io.MultiReader(strings.NewReader(start+terminal), strings.NewReader(ping), strings.NewReader(ping), strings.NewReader(stop)) + store := &ClaudeThreadBetaStore{} + request, _, _ := store.Bind("scope", "", http.Header{"Anthropic-Beta": []string{"profile"}}, ClaudeThreadBetaPolicy{}) + if _, errRead := io.Copy(io.Discard, request.StreamReader(body, nil)); errRead == nil { + t.Fatal("oversized completion was accepted") + } + if _, found, _ := store.Bind("scope", "message-a", http.Header{}, ClaudeThreadBetaPolicy{}); found { + t.Fatal("rejected oversized completion published Thread state") + } +} + +func TestClaudeThreadStreamNeverCommitsFailedTurn(t *testing.T) { + const start = "data: {\"type\":\"message_start\",\"message\":{\"id\":\"message-a\"}}\n\n" + const terminal = "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"}}\n\n" + const stop = "data: {\"type\":\"message_stop\"}\n\n" + for _, test := range []struct { + name string + body io.Reader + }{ + {name: "truncated", body: strings.NewReader(start + terminal)}, + {name: "malformed stop", body: strings.NewReader(start + terminal + "data: {\"type\":\"message_stop\",broken}\n\n")}, + {name: "error after terminal", body: strings.NewReader(start + terminal + "data: {\"type\":\"error\",\"error\":{\"message\":\"failed\"}}\n\n")}, + {name: "policy refusal", body: strings.NewReader(start + "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"refusal\",\"stop_details\":{\"type\":\"refusal\",\"category\":\"cyber\"}}}\n\n" + stop)}, + {name: "canceled", body: io.MultiReader(strings.NewReader(start), iotest.ErrReader(context.Canceled))}, + } { + t.Run(test.name, func(t *testing.T) { + store := &ClaudeThreadBetaStore{} + request, _, _ := store.Bind("scope", "", http.Header{"Anthropic-Beta": []string{"profile"}}, ClaudeThreadBetaPolicy{}) + data, errRead := io.ReadAll(request.StreamReader(test.body, nil)) + if test.name == "canceled" && !errors.Is(errRead, context.Canceled) { + t.Fatalf("cancellation error = %v", errRead) + } + if test.name == "truncated" && (errRead == nil || strings.Contains(string(data), "message_delta")) { + t.Fatalf("truncated turn released completion: data=%s, error=%v", data, errRead) + } + if _, found, _ := store.Bind("scope", "message-a", http.Header{}, ClaudeThreadBetaPolicy{}); found { + t.Fatal("failed turn published continuation state") + } + }) + } +} diff --git a/internal/runtime/executor/helps/claude_tool_property_names.go b/internal/runtime/executor/helps/claude_tool_property_names.go new file mode 100644 index 00000000000..adb99d8e2cf --- /dev/null +++ b/internal/runtime/executor/helps/claude_tool_property_names.go @@ -0,0 +1,175 @@ +package helps + +import ( + "fmt" + "strings" + + "github.com/MoeForge/moego/ojson" + log "github.com/sirupsen/logrus" +) + +// Claude rejects a request whose tools declare an input_schema property key +// outside ^[a-zA-Z0-9_.-]{1,64}$, while OpenAI-compatible clients and MCP +// servers commonly use parameter names such as "not[labels]". Because clients +// resend their tools on every turn, one such tool fails the whole conversation. +// +// Claude presents tool schemas to the model as part of its prompt, so such a +// tool is sent with an open object input_schema and its original schema +// embedded verbatim in the description. No parameter is renamed or dropped: +// the model sees every original name and constraint and calls the tool with +// the original names, so neither historical tool_use inputs nor tool calls in +// responses need any rewriting. Claude no longer enforces the embedded schema +// structurally, so strict is removed as structured outputs cannot apply it. +const ( + claudePropertyKeyMaxLength = 64 + claudeToolSchemaMaxInspectDepth = 256 + claudeToolSchemaFallbackPrefix = "The input object must conform to the following JSON Schema. Use its property names exactly as written, including any characters such as brackets:\n" + claudeToolSchemaFallbackSchema = `{"type":"object"}` +) + +// claudePropertyKeyAccepted reports whether Claude accepts name as an +// input_schema property key. +func claudePropertyKeyAccepted(name string) bool { + if len(name) == 0 || len(name) > claudePropertyKeyMaxLength { + return false + } + for i := 0; i < len(name); i++ { + c := name[i] + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '-' { + continue + } + return false + } + return true +} + +// claudeSchemaHasRejectedPropertyKey reports whether schema, or any subschema +// reachable through JSON Schema applicator and definition keywords, declares a +// properties key Claude rejects. Keyword names are only interpreted at schema +// positions, so a definition or property named like a keyword is handled by +// its role. Values of other keywords, such as const, default, enum, examples +// and unknown annotations, are data and are not inspected. Schemas nested +// beyond the inspection depth are reported as rejected so they take the +// fallback, which still carries the full schema text. +func claudeSchemaHasRejectedPropertyKey(schema ojson.Result, depth int) bool { + if !schema.IsObject() { + return false + } + if depth > claudeToolSchemaMaxInspectDepth { + return true + } + found := false + subschema := func(value ojson.Result) bool { + found = claudeSchemaHasRejectedPropertyKey(value, depth+1) + return !found + } + subschemas := func(value ojson.Result) { + value.ForEach(func(_, item ojson.Result) bool { return subschema(item) }) + } + schema.ForEach(func(key, value ojson.Result) bool { + switch key.String() { + case "properties": + if !value.IsObject() { + return true + } + value.ForEach(func(name, item ojson.Result) bool { + if !claudePropertyKeyAccepted(name.String()) { + found = true + return false + } + return subschema(item) + }) + case "$defs", "definitions", "patternProperties", "dependentSchemas", "dependencies": + // Maps of named subschemas; dependencies may also hold name arrays, + // which are not objects and are skipped by subschema. + if value.IsObject() { + subschemas(value) + } + case "allOf", "anyOf", "oneOf", "prefixItems": + if value.IsArray() { + subschemas(value) + } + case "items": + if value.IsArray() { + subschemas(value) + } else { + subschema(value) + } + case "additionalProperties", "unevaluatedProperties", "additionalItems", "unevaluatedItems", + "contains", "propertyNames", "not", "if", "then", "else", "contentSchema": + subschema(value) + } + return !found + }) + return found +} + +// claudeToolNeedsSchemaFallback reports whether a Claude client tool +// declaration has an input_schema that Claude would reject. +func claudeToolNeedsSchemaFallback(tool ojson.Result) bool { + if IsClaudeServerToolType(tool.Get("type").String()) { + return false + } + schema := tool.Get("input_schema") + return schema.IsObject() && claudeSchemaHasRejectedPropertyKey(schema, 0) +} + +// NormalizeClaudeToolPropertyNamesDoc applies the schema fallback to every +// client tool declared in tools[] or in an inline tool_addition definition +// whose input_schema has a property key Claude rejects. Tools Claude accepts +// are left unchanged. It must run before user payload rules. +func NormalizeClaudeToolPropertyNamesDoc(doc *ojson.Doc) { + if doc == nil || doc.Len() == 0 { + return + } + var paths []string + doc.Get("tools").ForEach(func(index, tool ojson.Result) bool { + if claudeToolNeedsSchemaFallback(tool) { + paths = append(paths, fmt.Sprintf("tools.%d", index.Int())) + } + return true + }) + doc.Get("messages").ForEach(func(messageIndex, message ojson.Result) bool { + message.Get("content").ForEach(func(partIndex, part ojson.Result) bool { + if part.Get("type").String() != "tool_addition" || part.Get("tool.type").String() != "tool_definition" { + return true + } + if claudeToolNeedsSchemaFallback(part.Get("tool.definition")) { + paths = append(paths, fmt.Sprintf("messages.%d.content.%d.tool.definition", messageIndex.Int(), partIndex.Int())) + } + return true + }) + return true + }) + for _, path := range paths { + applyClaudeToolSchemaFallbackDoc(doc, path) + } +} + +func applyClaudeToolSchemaFallbackDoc(doc *ojson.Doc, path string) { + tool := doc.Get(path) + name := strings.Clone(tool.Get("name").String()) + var description strings.Builder + if existing := tool.Get("description").String(); strings.TrimSpace(existing) != "" { + description.WriteString(existing) + description.WriteString("\n\n") + } + description.WriteString(claudeToolSchemaFallbackPrefix) + description.WriteString(tool.Get("input_schema").Raw) + hasStrict := tool.Get("strict").Exists() + + if errSet := doc.Set(path+".description", description.String()); errSet != nil { + log.Warnf("claude tool %q: failed to embed input_schema in description: %v", name, errSet) + return + } + if errSet := doc.SetRaw(path+".input_schema", claudeToolSchemaFallbackSchema); errSet != nil { + log.Warnf("claude tool %q: failed to replace input_schema: %v", name, errSet) + return + } + if hasStrict { + if errDelete := doc.Delete(path + ".strict"); errDelete != nil { + log.Warnf("claude tool %q: failed to remove strict: %v", name, errDelete) + } + } + log.Debugf("claude tool %q: input_schema has property names Claude rejects; embedded the schema in the description", name) +} diff --git a/internal/runtime/executor/helps/claude_tool_property_names_test.go b/internal/runtime/executor/helps/claude_tool_property_names_test.go new file mode 100644 index 00000000000..0bbaa11f816 --- /dev/null +++ b/internal/runtime/executor/helps/claude_tool_property_names_test.go @@ -0,0 +1,134 @@ +package helps + +import ( + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" +) + +func TestClaudePropertyKeyAccepted(t *testing.T) { + for name, want := range map[string]bool{ + "state": true, + "user.name": true, + "a-b_c": true, + strings.Repeat("x", 64): true, + strings.Repeat("x", 65): false, + "": false, + "not[labels]": false, + "$schema": false, + "a b": false, + "名": false, + } { + if got := claudePropertyKeyAccepted(name); got != want { + t.Errorf("claudePropertyKeyAccepted(%q) = %v, want %v", name, got, want) + } + } +} + +func TestNormalizeClaudeToolPropertyNamesDocEmbedsRejectedSchemas(t *testing.T) { + rejectedSchema := `{"type":"object","properties":{"not[labels]":{"type":"string"},"state":{"type":"string"}},"required":["not[labels]"]}` + nestedSchema := `{"type":"object","$defs":{"f":{"type":"object","properties":{"$schema":{"type":"string"}}}},"properties":{"filter":{"$ref":"#/$defs/f"}}}` + inlineSchema := `{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"id[]":{"type":"string"}}}}}}` + propertyNamedDefault := `{"type":"object","properties":{"default":{"type":"object","properties":{"a b":{"type":"string"}}}}}` + instanceOnly := `{"type":"object","properties":{"q":{"type":"object","default":{"properties":{"a b":1}},"examples":[{"properties":{"c d":2}}],"const":{"properties":{"e f":3}},"enum":[{"properties":{"g h":4}}]}}}` + validSchema := `{"type":"object","properties":{"user.name":{"type":"string"}}}` + body := `{"tools":[` + + `{"name":"list_merge_requests","description":"List merge requests.","strict":true,"cache_control":{"type":"ephemeral"},"input_schema":` + rejectedSchema + `,"input_examples":[{"not[labels]":"bug"}]},` + + `{"name":"nested","input_schema":` + nestedSchema + `},` + + `{"name":"property_named_default","description":"Default.","input_schema":` + propertyNamedDefault + `},` + + `{"name":"instance_only","description":"Data.","input_schema":` + instanceOnly + `},` + + `{"name":"valid","description":"Valid.","strict":true,"input_schema":` + validSchema + `},` + + `{"type":"web_search_20250305","name":"web_search","max_uses":1}],` + + `"messages":[` + + `{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"list_merge_requests","input":{"not[labels]":"bug"}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"[]"}]},` + + `{"role":"system","content":[{"type":"tool_addition","tool":{"type":"tool_definition","definition":{"name":"inline_tool","description":"Inline.","input_schema":` + inlineSchema + `}}}]}]}` + doc := ojson.NewDocString(body) + NormalizeClaudeToolPropertyNamesDoc(doc) + out := doc.Bytes() + + fallbacks := map[string]string{ + "tools.0": "List merge requests.\n\n" + claudeToolSchemaFallbackPrefix + rejectedSchema, + "tools.1": claudeToolSchemaFallbackPrefix + nestedSchema, + "tools.2": "Default.\n\n" + claudeToolSchemaFallbackPrefix + propertyNamedDefault, + "messages.2.content.0.tool.definition": "Inline.\n\n" + claudeToolSchemaFallbackPrefix + inlineSchema, + } + for path, description := range fallbacks { + if got := ojson.GetBytes(out, path+".input_schema").Raw; got != claudeToolSchemaFallbackSchema { + t.Errorf("%s.input_schema = %s, want %s", path, got, claudeToolSchemaFallbackSchema) + } + if got := ojson.GetBytes(out, path+".description").String(); got != description { + t.Errorf("%s.description = %q, want %q", path, got, description) + } + if ojson.GetBytes(out, path+".strict").Exists() { + t.Errorf("%s.strict must be removed", path) + } + } + unchanged := map[string]string{ + "tools.0.cache_control": `{"type":"ephemeral"}`, + "tools.0.input_examples": `[{"not[labels]":"bug"}]`, + "tools.3": `{"name":"instance_only","description":"Data.","input_schema":` + instanceOnly + `}`, + "tools.4": `{"name":"valid","description":"Valid.","strict":true,"input_schema":` + validSchema + `}`, + "tools.5": `{"type":"web_search_20250305","name":"web_search","max_uses":1}`, + "messages.0.content.0.input": `{"not[labels]":"bug"}`, + } + for path, want := range unchanged { + if got := ojson.GetBytes(out, path).Raw; got != want { + t.Errorf("%s = %s, want %s", path, got, want) + } + } +} + +func TestNormalizeClaudeToolPropertyNamesDocLeavesAcceptedRequestsUnchanged(t *testing.T) { + body := `{"tools":[{"name":"t","description":"d","input_schema":{"type":"object","$defs":{"a[b]":{"type":"string"}},"patternProperties":{"^x\\[":{}},"properties":{"file.xml":{"$ref":"#/$defs/a[b]"}}}}],"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"t","input":{"x[1]":2}}]}]}` + doc := ojson.NewDocString(body) + NormalizeClaudeToolPropertyNamesDoc(doc) + if got := doc.String(); got != body { + t.Fatalf("body changed:\n got: %s\nwant: %s", got, body) + } +} + +func TestNormalizeClaudeToolPropertyNamesDocFallsBackForDeepSchemas(t *testing.T) { + depth := claudeToolSchemaMaxInspectDepth + 10 + schema := strings.Repeat(`{"not":`, depth) + `{}` + strings.Repeat(`}`, depth) + doc := ojson.NewDocString(`{"tools":[{"name":"deep","input_schema":` + schema + `}]}`) + NormalizeClaudeToolPropertyNamesDoc(doc) + if got := doc.Get("tools.0.input_schema").Raw; got != claudeToolSchemaFallbackSchema { + t.Fatalf("deep input_schema = %.80s, want the fallback", got) + } + if !strings.HasSuffix(doc.Get("tools.0.description").String(), schema) { + t.Fatal("deep schema must be embedded verbatim in the description") + } +} + +// Keyword names are only interpreted at schema positions; named definitions, +// dependent schemas, patterns and properties are classified by their role. +func TestClaudeSchemaHasRejectedPropertyKeyFollowsSchemaPositions(t *testing.T) { + rejected := `{"type":"object","properties":{"not[labels]":{"type":"string"}}}` + accepted := `{"type":"object","properties":{"value":{"type":"string"}}}` + cases := map[string]struct { + schema string + want bool + }{ + "defs named default": {schema: `{"$defs":{"default":` + rejected + `},"properties":{"f":{"$ref":"#/$defs/default"}}}`, want: true}, + "definitions named enum": {schema: `{"definitions":{"enum":` + rejected + `}}`, want: true}, + "dependent schema named const": {schema: `{"dependentSchemas":{"const":` + rejected + `}}`, want: true}, + "dependencies schema named const": {schema: `{"dependencies":{"const":` + rejected + `,"a":["b"]}}`, want: true}, + "pattern named examples": {schema: `{"patternProperties":{"examples":` + rejected + `}}`, want: true}, + "property named default": {schema: `{"properties":{"default":` + rejected + `}}`, want: true}, + "property named properties": {schema: `{"properties":{"properties":` + rejected + `}}`, want: true}, + "nested applicators": {schema: `{"anyOf":[{"items":[{"not":{"if":{"then":{"contains":` + rejected + `}}}}]}]}`, want: true}, + "tuple items and prefix items": {schema: `{"prefixItems":[true,{"additionalProperties":` + rejected + `}]}`, want: true}, + "defs named properties": {schema: `{"$defs":{"text":{"type":"string"},"properties":{"$ref":"#/$defs/text"}},"properties":{"value":{"$ref":"#/$defs/properties"}},"additionalProperties":false}`, want: false}, + "property named properties valid": {schema: `{"properties":{"properties":` + accepted + `}}`, want: false}, + "defs with rejected definition key": {schema: `{"$defs":{"a[b]":` + accepted + `}}`, want: false}, + "data keywords": {schema: `{"default":{"properties":{"a b":1}},"const":{"properties":{"c d":2}},"enum":[{"properties":{"e f":3}}],"examples":[{"properties":{"g h":4}}]}`, want: false}, + "unknown annotation": {schema: `{"x-ui":{"properties":{"a b":{}}}}`, want: false}, + } + for name, tc := range cases { + if got := claudeSchemaHasRejectedPropertyKey(ojson.Parse(tc.schema), 0); got != tc.want { + t.Errorf("%s: claudeSchemaHasRejectedPropertyKey = %v, want %v", name, got, tc.want) + } + } +} diff --git a/internal/runtime/executor/helps/cloak_obfuscate.go b/internal/runtime/executor/helps/cloak_obfuscate.go index 10c6b5388ae..0e3ab071e3e 100644 --- a/internal/runtime/executor/helps/cloak_obfuscate.go +++ b/internal/runtime/executor/helps/cloak_obfuscate.go @@ -3,58 +3,323 @@ package helps import ( "regexp" "sort" + "strconv" "strings" + "unicode" "unicode/utf8" "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + log "github.com/sirupsen/logrus" ) // zeroWidthSpace is the Unicode zero-width space character used for obfuscation. const zeroWidthSpace = "\u200B" -// SensitiveWordMatcher holds the compiled regex for matching sensitive words. +// combiningGraphemeJoiner is the Unicode combining grapheme joiner (U+034F) +// used for Antigravity system-instruction obfuscation where U+200B obfuscation +// remains rejected by the upstream endpoint. +const combiningGraphemeJoiner = "\u034F" + +type sensitiveWordRule struct { + target string + lowerTarget string + replacement string + isReplacement bool +} + +type compiledPatternRule struct { + regex *regexp.Regexp + replacement string +} + +type patternMatchSpan struct { + start int + end int + replacement string +} + +// SensitiveWordMatcher holds the compiled regex and replacement state for matching sensitive words. type SensitiveWordMatcher struct { - regex *regexp.Regexp + regex *regexp.Regexp + replaceFn func(string) string + lookupReplacement func(string) (string, bool) + patternRules []compiledPatternRule +} + +func (m *SensitiveWordMatcher) hasRules() bool { + return m != nil && (m.regex != nil || len(m.patternRules) > 0) +} + +// SensitiveWordConfigCacheKey builds a deterministic, collision-free cache key +// for a (words, replacements) configuration pair. +func SensitiveWordConfigCacheKey(words []string, replacements map[string]string) string { + return SensitiveWordConfigCacheKeyWithPatterns(words, replacements, nil) +} + +// SensitiveWordConfigCacheKeyWithPatterns builds a deterministic, collision-free +// cache key for (words, replacements, patterns). +func SensitiveWordConfigCacheKeyWithPatterns( + words []string, + replacements map[string]string, + patterns []config.SensitivePatternRule, +) string { + var b strings.Builder + b.WriteString("w:") + b.WriteString(strconv.Itoa(len(words))) + b.WriteByte(';') + for _, w := range words { + b.WriteString(strconv.Itoa(len(w))) + b.WriteByte(':') + b.WriteString(w) + b.WriteByte(';') + } + b.WriteString("|r:") + b.WriteString(strconv.Itoa(len(replacements))) + b.WriteByte(';') + if len(replacements) > 0 { + keys := make([]string, 0, len(replacements)) + for k := range replacements { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + v := replacements[k] + b.WriteString(strconv.Itoa(len(k))) + b.WriteByte(':') + b.WriteString(k) + b.WriteByte('=') + b.WriteString(strconv.Itoa(len(v))) + b.WriteByte(':') + b.WriteString(v) + b.WriteByte(';') + } + } + b.WriteString("|p:") + b.WriteString(strconv.Itoa(len(patterns))) + b.WriteByte(';') + for _, p := range patterns { + b.WriteString(strconv.Itoa(len(p.Pattern))) + b.WriteByte(':') + b.WriteString(p.Pattern) + b.WriteByte('=') + b.WriteString(strconv.Itoa(len(p.Replacement))) + b.WriteByte(':') + b.WriteString(p.Replacement) + b.WriteByte(';') + } + return b.String() } -// BuildSensitiveWordMatcher compiles a regex from the word list. +// BuildSensitiveWordMatcher compiles a regex from the word list using U+200B. // Words are sorted by length (longest first) for proper matching. func BuildSensitiveWordMatcher(words []string) *SensitiveWordMatcher { - if len(words) == 0 { + return BuildSensitiveWordMatcherWithPatterns(words, nil, nil) +} + +// BuildSensitiveWordMatcherWithReplacements compiles a matcher combining literal +// replacements and U+200B sensitive-word obfuscation. +func BuildSensitiveWordMatcherWithReplacements(words []string, replacements map[string]string) *SensitiveWordMatcher { + return BuildSensitiveWordMatcherWithPatterns(words, replacements, nil) +} + +// BuildSensitiveWordMatcherWithPatterns compiles a matcher combining ordered RE2 +// regex replacements, literal replacements, and U+200B sensitive-word obfuscation. +func BuildSensitiveWordMatcherWithPatterns( + words []string, + replacements map[string]string, + patterns []config.SensitivePatternRule, +) *SensitiveWordMatcher { + return buildSensitiveWordMatcher(words, replacements, patterns, obfuscateWord, zeroWidthSpace) +} + +// BuildAntigravitySensitiveWordMatcher compiles a matcher for Antigravity system +// instructions combining literal replacements and per-subword U+034F obfuscation. +func BuildAntigravitySensitiveWordMatcher(words []string, replacements map[string]string) *SensitiveWordMatcher { + return BuildAntigravitySensitiveWordMatcherWithPatterns(words, replacements, nil) +} + +// BuildAntigravitySensitiveWordMatcherWithPatterns compiles a matcher for Antigravity +// system instructions combining ordered RE2 regex replacements, literal replacements, +// and per-subword U+034F obfuscation. +func BuildAntigravitySensitiveWordMatcherWithPatterns( + words []string, + replacements map[string]string, + patterns []config.SensitivePatternRule, +) *SensitiveWordMatcher { + return buildSensitiveWordMatcher(words, replacements, patterns, obfuscateAntigravityPhrase, combiningGraphemeJoiner) +} + +func buildSensitiveWordMatcher( + words []string, + replacements map[string]string, + patterns []config.SensitivePatternRule, + obfuscateFn func(string) string, + marker string, +) *SensitiveWordMatcher { + if len(words) == 0 && len(replacements) == 0 && len(patterns) == 0 { return nil } - // Filter and normalize words - var validWords []string - for _, w := range words { - w = strings.TrimSpace(w) - if utf8.RuneCountInString(w) >= 2 && !strings.Contains(w, zeroWidthSpace) { - validWords = append(validWords, w) + var compiledPatterns []compiledPatternRule + if len(patterns) > 0 { + compiledPatterns = make([]compiledPatternRule, 0, len(patterns)) + for i, p := range patterns { + if strings.TrimSpace(p.Pattern) == "" { + continue + } + compiled, errCompile := regexp.Compile(p.Pattern) + if errCompile != nil { + log.WithFields(log.Fields{ + "rule_index": i + 1, + "pattern": p.Pattern, + "error": errCompile, + }).Warn("sensitive-patterns-replace rule skipped: invalid regex") + continue + } + compiledPatterns = append(compiledPatterns, compiledPatternRule{ + regex: compiled, + replacement: p.Replacement, + }) + } + } + + var rules []sensitiveWordRule + var replacementRules []sensitiveWordRule + var exactReplacements map[string]string + var lowerReplacements map[string]string + seenLower := make(map[string]struct{}, len(words)+len(replacements)) + + if len(replacements) > 0 { + rawKeys := make([]string, 0, len(replacements)) + for k := range replacements { + rawKeys = append(rawKeys, k) + } + sort.Strings(rawKeys) + + for _, rawKey := range rawKeys { + target := strings.TrimSpace(rawKey) + if target == "" { + continue + } + if exactReplacements == nil { + exactReplacements = make(map[string]string, len(rawKeys)) + lowerReplacements = make(map[string]string, len(rawKeys)) + } + if _, exists := exactReplacements[target]; !exists || rawKey == target { + exactReplacements[target] = replacements[rawKey] + } + lower := strings.ToLower(target) + if _, exists := lowerReplacements[lower]; !exists { + lowerReplacements[lower] = replacements[rawKey] + } + if _, exists := seenLower[lower]; exists { + continue + } + seenLower[lower] = struct{}{} + rule := sensitiveWordRule{ + target: target, + lowerTarget: lower, + replacement: replacements[rawKey], + isReplacement: true, + } + rules = append(rules, rule) + replacementRules = append(replacementRules, rule) + } + } + + for _, rawWord := range words { + w := strings.TrimSpace(rawWord) + if utf8.RuneCountInString(w) < 2 || strings.Contains(w, marker) { + continue + } + if obfuscateFn(w) == w { + continue } + lower := strings.ToLower(w) + if _, exists := seenLower[lower]; exists { + continue + } + seenLower[lower] = struct{}{} + rules = append(rules, sensitiveWordRule{ + target: w, + lowerTarget: lower, + }) } - if len(validWords) == 0 { + if len(rules) == 0 && len(compiledPatterns) == 0 { return nil } - // Sort by length (longest first) for proper matching - sort.Slice(validWords, func(i, j int) bool { - return len(validWords[i]) > len(validWords[j]) - }) + var re *regexp.Regexp + var lookupReplacement func(string) (string, bool) + var replaceFn func(string) string + if len(rules) > 0 { + sortRulesLongestFirst(rules) + sortRulesLongestFirst(replacementRules) - // Escape and join - escaped := make([]string, len(validWords)) - for i, w := range validWords { - escaped[i] = regexp.QuoteMeta(w) + escaped := make([]string, len(rules)) + for i, r := range rules { + escaped[i] = regexp.QuoteMeta(r.target) + } + + pattern := "(?i:" + strings.Join(escaped, "|") + ")" + compiledLiteral, errCompile := regexp.Compile(pattern) + if errCompile != nil { + if len(compiledPatterns) == 0 { + return nil + } + } else { + re = compiledLiteral + replaceFn = obfuscateFn + if len(exactReplacements) > 0 { + lookupReplacement = func(matched string) (string, bool) { + if repl, ok := exactReplacements[matched]; ok { + return repl, true + } + if repl, ok := lowerReplacements[strings.ToLower(matched)]; ok { + return repl, true + } + for _, r := range replacementRules { + if strings.EqualFold(matched, r.target) { + return r.replacement, true + } + } + return "", false + } + replaceFn = func(matched string) string { + if repl, ok := lookupReplacement(matched); ok { + return repl + } + return obfuscateFn(matched) + } + } + } } - pattern := "(?i)" + strings.Join(escaped, "|") - re, err := regexp.Compile(pattern) - if err != nil { - return nil + return &SensitiveWordMatcher{ + regex: re, + replaceFn: replaceFn, + lookupReplacement: lookupReplacement, + patternRules: compiledPatterns, } +} - return &SensitiveWordMatcher{regex: re} +func sortRulesLongestFirst(rules []sensitiveWordRule) { + sort.SliceStable(rules, func(i, j int) bool { + ri := utf8.RuneCountInString(rules[i].target) + rj := utf8.RuneCountInString(rules[j].target) + if ri != rj { + return ri > rj + } + if len(rules[i].target) != len(rules[j].target) { + return len(rules[i].target) > len(rules[j].target) + } + if rules[i].isReplacement != rules[j].isReplacement { + return rules[i].isReplacement + } + return rules[i].lowerTarget < rules[j].lowerTarget + }) } // obfuscateWord inserts a zero-width space after the first grapheme. @@ -63,7 +328,6 @@ func obfuscateWord(word string) string { return word } - // Get first rune r, size := utf8.DecodeRuneInString(word) if r == utf8.RuneError || size >= len(word) { return word @@ -72,23 +336,414 @@ func obfuscateWord(word string) string { return string(r) + zeroWidthSpace + word[size:] } -// obfuscateText replaces all sensitive words in the text. -func (m *SensitiveWordMatcher) obfuscateText(text string) string { - if m == nil || m.regex == nil { +func isAntigravitySubwordRune(r rune) bool { + return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '\u034F' || r == '\u200B' +} + +func obfuscateSingleSubwordCGJ(subword string) (string, bool) { + if strings.Contains(subword, combiningGraphemeJoiner) { + return subword, true + } + r, size := utf8.DecodeRuneInString(subword) + if r == utf8.RuneError || size >= len(subword) { + return subword, false + } + return string(r) + combiningGraphemeJoiner + subword[size:], true +} + +// obfuscateAntigravityPhrase inserts U+034F after the first rune of every +// alphanumeric subword (>= 2 runes) within phrase, preserving punctuation and whitespace. +func obfuscateAntigravityPhrase(phrase string) string { + if phrase == "" || strings.Contains(phrase, combiningGraphemeJoiner) { + return phrase + } + + var b strings.Builder + b.Grow(len(phrase) + len(combiningGraphemeJoiner)*2) + subwordStart := -1 + inserted := false + + for i, r := range phrase { + if isAntigravitySubwordRune(r) { + if subwordStart < 0 { + subwordStart = i + } + continue + } + if subwordStart >= 0 { + obf, did := obfuscateSingleSubwordCGJ(phrase[subwordStart:i]) + b.WriteString(obf) + if did { + inserted = true + } + subwordStart = -1 + } + b.WriteRune(r) + } + if subwordStart >= 0 { + obf, did := obfuscateSingleSubwordCGJ(phrase[subwordStart:]) + b.WriteString(obf) + if did { + inserted = true + } + } + + if inserted { + return b.String() + } + + r, size := utf8.DecodeRuneInString(phrase) + if r == utf8.RuneError || size >= len(phrase) { + return phrase + } + return string(r) + combiningGraphemeJoiner + phrase[size:] +} + +func (m *SensitiveWordMatcher) collectPatternSpans(text string) []patternMatchSpan { + if m == nil || len(m.patternRules) == 0 || text == "" { + return nil + } + var spans []patternMatchSpan + spansOverlap := func(aStart, aEnd, bStart, bEnd int) bool { + if aStart == aEnd { + return bStart <= aStart && aStart <= bEnd + } + if bStart == bEnd { + return aStart <= bStart && bStart <= aEnd + } + return aStart < bEnd && bStart < aEnd + } + + for _, rule := range m.patternRules { + if rule.regex == nil { + continue + } + matches := rule.regex.FindAllStringSubmatchIndex(text, -1) + if len(matches) == 0 { + continue + } + if len(spans) == 0 { + spans = make([]patternMatchSpan, 0, len(matches)) + for _, submatch := range matches { + if len(submatch) < 2 { + continue + } + start, end := submatch[0], submatch[1] + repl := string(rule.regex.ExpandString(nil, rule.replacement, text, submatch)) + if start == end && repl == "" { + continue + } + spans = append(spans, patternMatchSpan{ + start: start, + end: end, + replacement: repl, + }) + } + continue + } + + var accepted []patternMatchSpan + var subsumed []bool + ci := 0 + for _, submatch := range matches { + if len(submatch) < 2 { + continue + } + start, end := submatch[0], submatch[1] + repl := string(rule.regex.ExpandString(nil, rule.replacement, text, submatch)) + if start == end && repl == "" { + continue + } + + for ci < len(spans) { + c := spans[ci] + if c.end < start || (c.end == start && c.start < c.end && start < end) { + ci++ + continue + } + break + } + + conflict := false + var localSubsumed []int + for j := ci; j < len(spans); j++ { + if subsumed != nil && subsumed[j] { + continue + } + c := spans[j] + if c.start > end || (c.start == end && c.start < c.end && start < end) { + break + } + if !spansOverlap(start, end, c.start, c.end) { + continue + } + if repl == "" && c.replacement == "" && start <= c.start && c.end <= end { + localSubsumed = append(localSubsumed, j) + continue + } + conflict = true + break + } + if conflict { + continue + } + if len(localSubsumed) > 0 { + if subsumed == nil { + subsumed = make([]bool, len(spans)) + } + for _, j := range localSubsumed { + subsumed[j] = true + } + } + accepted = append(accepted, patternMatchSpan{ + start: start, + end: end, + replacement: repl, + }) + } + + if len(accepted) == 0 { + continue + } + merged := make([]patternMatchSpan, 0, len(spans)+len(accepted)) + si, ai := 0, 0 + for si < len(spans) && ai < len(accepted) { + if subsumed != nil && subsumed[si] { + si++ + continue + } + if spans[si].start < accepted[ai].start || (spans[si].start == accepted[ai].start && spans[si].end <= accepted[ai].end) { + merged = append(merged, spans[si]) + si++ + } else { + merged = append(merged, accepted[ai]) + ai++ + } + } + for ; si < len(spans); si++ { + if subsumed != nil && subsumed[si] { + continue + } + merged = append(merged, spans[si]) + } + for ; ai < len(accepted); ai++ { + merged = append(merged, accepted[ai]) + } + spans = merged + } + return spans +} + +func (m *SensitiveWordMatcher) obfuscateLiterals(text string) string { + if m == nil || m.regex == nil || text == "" { return text } + if m.replaceFn != nil { + return m.regex.ReplaceAllStringFunc(text, m.replaceFn) + } return m.regex.ReplaceAllStringFunc(text, obfuscateWord) } -// Matches reports whether the text contains any of the configured sensitive words. +// obfuscateText replaces or obfuscates all sensitive words in the text. +func (m *SensitiveWordMatcher) obfuscateText(text string) string { + if !m.hasRules() || text == "" { + return text + } + spans := m.collectPatternSpans(text) + if len(spans) == 0 { + return m.obfuscateLiterals(text) + } + + var b strings.Builder + b.Grow(len(text)) + last := 0 + for _, span := range spans { + if span.start > last { + b.WriteString(m.obfuscateLiterals(text[last:span.start])) + } + b.WriteString(span.replacement) + last = span.end + } + if last < len(text) { + b.WriteString(m.obfuscateLiterals(text[last:])) + } + return b.String() +} + +// Matches reports whether the text contains any configured sensitive word, literal replacement, or pattern rule match. func (m *SensitiveWordMatcher) Matches(text string) bool { - if m == nil || m.regex == nil { + if !m.hasRules() { return false } - return m.regex.MatchString(text) + if m.regex != nil && m.regex.MatchString(text) { + return true + } + for _, rule := range m.patternRules { + if rule.regex != nil && rule.regex.MatchString(text) { + return true + } + } + return false +} + +// SanitizeDevinText applies configured pattern/literal replacements and Devin +// line-level sensitive-word filtering in a single non-cascading pass: +// - matches handled by sensitive-patterns-replace or sensitive-words-replace emit +// their replacement verbatim without re-scanning or triggering line deletion; +// - original lines containing an unreplaced sensitive-words match are dropped. +func (m *SensitiveWordMatcher) SanitizeDevinText(text string) string { + if !m.hasRules() || text == "" { + return text + } + + type devinOpKind uint8 + const ( + opLiteralText devinOpKind = iota + opReplacement + opSensitiveWord + ) + type devinOp struct { + start int + end int + kind devinOpKind + repl string + } + + var ops []devinOp + appendLiteralGapOps := func(gapStart, gapEnd int) { + if gapStart >= gapEnd { + return + } + if m.regex == nil { + ops = append(ops, devinOp{start: gapStart, end: gapEnd, kind: opLiteralText}) + return + } + seg := text[gapStart:gapEnd] + indices := m.regex.FindAllStringIndex(seg, -1) + if len(indices) == 0 { + ops = append(ops, devinOp{start: gapStart, end: gapEnd, kind: opLiteralText}) + return + } + last := 0 + for _, pair := range indices { + s, e := pair[0], pair[1] + if s > last { + ops = append(ops, devinOp{start: gapStart + last, end: gapStart + s, kind: opLiteralText}) + } + matched := seg[s:e] + if m.lookupReplacement != nil { + if repl, ok := m.lookupReplacement(matched); ok { + ops = append(ops, devinOp{start: gapStart + s, end: gapStart + e, kind: opReplacement, repl: repl}) + last = e + continue + } + } + ops = append(ops, devinOp{start: gapStart + s, end: gapStart + e, kind: opSensitiveWord}) + last = e + } + if last < len(seg) { + ops = append(ops, devinOp{start: gapStart + last, end: gapEnd, kind: opLiteralText}) + } + } + + spans := m.collectPatternSpans(text) + last := 0 + for _, span := range spans { + if span.start > last { + appendLiteralGapOps(last, span.start) + } + ops = append(ops, devinOp{ + start: span.start, + end: span.end, + kind: opReplacement, + repl: span.replacement, + }) + last = span.end + } + if last < len(text) { + appendLiteralGapOps(last, len(text)) + } + + // Build original line boundaries so replacement text never synthesizes fake + // newlines and line-drop state stays strictly anchored to original lines. + lineStarts := []int{0} + for i := 0; i < len(text); i++ { + if text[i] == '\n' { + lineStarts = append(lineStarts, i+1) + } + } + lineOf := func(pos int) int { + if pos <= 0 { + return 0 + } + // Find largest line index whose start <= pos. + idx := sort.Search(len(lineStarts), func(i int) bool { + return lineStarts[i] > pos + }) + return idx - 1 + } + + droppedLine := make([]bool, len(lineStarts)) + for _, op := range ops { + if op.kind != opSensitiveWord || op.end <= op.start { + continue + } + firstLine := lineOf(op.start) + lastLine := lineOf(op.end - 1) + for l := firstLine; l <= lastLine; l++ { + droppedLine[l] = true + } + } + + var b strings.Builder + b.Grow(len(text)) + for _, op := range ops { + switch op.kind { + case opSensitiveWord: + continue + case opReplacement: + if op.repl == "" { + continue + } + firstLine := lineOf(op.start) + lastLine := firstLine + if op.end > op.start { + lastLine = lineOf(op.end - 1) + } + dropped := false + for l := firstLine; l <= lastLine; l++ { + if droppedLine[l] { + dropped = true + break + } + } + if !dropped { + b.WriteString(op.repl) + } + case opLiteralText: + seg := text[op.start:op.end] + curLine := lineOf(op.start) + for len(seg) > 0 { + nl := strings.IndexByte(seg, '\n') + if nl < 0 { + if !droppedLine[curLine] { + b.WriteString(seg) + } + break + } + if !droppedLine[curLine] { + b.WriteString(seg[:nl+1]) + } + seg = seg[nl+1:] + curLine++ + } + } + } + + return strings.TrimSpace(b.String()) } -// ObfuscateText replaces all sensitive words in the text. +// ObfuscateText replaces or obfuscates all sensitive words in the text. func (m *SensitiveWordMatcher) ObfuscateText(text string) string { return m.obfuscateText(text) } @@ -96,7 +751,7 @@ func (m *SensitiveWordMatcher) ObfuscateText(text string) string { // ObfuscateSensitiveWords processes the payload and obfuscates sensitive words // in system blocks and message content. func ObfuscateSensitiveWords(payload []byte, matcher *SensitiveWordMatcher) []byte { - if matcher == nil || matcher.regex == nil || len(payload) == 0 { + if !matcher.hasRules() || len(payload) == 0 { return payload } doc := ojson.NewDoc(payload) @@ -109,7 +764,7 @@ func ObfuscateSensitiveWords(payload []byte, matcher *SensitiveWordMatcher) []by // ObfuscateSensitiveWordsDoc processes doc in place and obfuscates sensitive words // in system blocks and message content. func ObfuscateSensitiveWordsDoc(doc *ojson.Doc, matcher *SensitiveWordMatcher) bool { - if matcher == nil || matcher.regex == nil || doc == nil || doc.Len() == 0 { + if !matcher.hasRules() || doc == nil || doc.Len() == 0 { return false } modified := obfuscateSystemBlocksDoc(doc, matcher) @@ -121,7 +776,7 @@ func ObfuscateSensitiveWordsDoc(doc *ojson.Doc, matcher *SensitiveWordMatcher) b // ObfuscateSensitiveWordsInSystemInstruction obfuscates sensitive words in an Antigravity system instruction. func ObfuscateSensitiveWordsInSystemInstruction(payload []byte, matcher *SensitiveWordMatcher) []byte { - if matcher == nil || matcher.regex == nil || len(payload) == 0 { + if !matcher.hasRules() || len(payload) == 0 { return payload } doc := ojson.NewDoc(payload) @@ -133,7 +788,7 @@ func ObfuscateSensitiveWordsInSystemInstruction(payload []byte, matcher *Sensiti // ObfuscateSensitiveWordsInSystemInstructionDoc obfuscates sensitive words in an Antigravity system instruction in place on doc. func ObfuscateSensitiveWordsInSystemInstructionDoc(doc *ojson.Doc, matcher *SensitiveWordMatcher) bool { - if matcher == nil || matcher.regex == nil || doc == nil || doc.Len() == 0 { + if !matcher.hasRules() || doc == nil || doc.Len() == 0 { return false } diff --git a/internal/runtime/executor/helps/cloak_obfuscate_test.go b/internal/runtime/executor/helps/cloak_obfuscate_test.go new file mode 100644 index 00000000000..34aa8c48080 --- /dev/null +++ b/internal/runtime/executor/helps/cloak_obfuscate_test.go @@ -0,0 +1,369 @@ +package helps + +import ( + "fmt" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" +) + +func TestBuildSensitiveWordMatcherPreservesZeroWidthSpaceDefault(t *testing.T) { + matcher := BuildSensitiveWordMatcher([]string{"proxy", "Claude Code"}) + if matcher == nil { + t.Fatal("expected non-nil matcher") + } + + got := matcher.ObfuscateText("Use proxy with Claude Code.") + want := "Use p\u200Broxy with C\u200Blaude Code." + if got != want { + t.Fatalf("ObfuscateText() = %q, want %q", got, want) + } +} + +func TestBuildAntigravitySensitiveWordMatcherSubwordsAndPunctuation(t *testing.T) { + matcher := BuildAntigravitySensitiveWordMatcher([]string{ + "Codex", + "GPT-5", + "Claude Code", + "", + "claude-code", + "Agent X", + }, nil) + if matcher == nil { + t.Fatal("expected non-nil matcher") + } + + input := "You are Codex, an agent based on GPT-5. Follow in Claude Code / claude-code with Agent X." + got := matcher.ObfuscateText(input) + want := "You are C\u034Fodex, an agent based on G\u034FPT-5. Follow in C\u034Flaude C\u034Fode / c\u034Flaude-c\u034Fode with A\u034Fgent X." + if got != want { + t.Fatalf("ObfuscateText() = %q, want %q", got, want) + } + if strings.Contains(got, "\u200B") { + t.Fatalf("ObfuscateText() = %q, must not contain U+200B", got) + } + if secondPass := matcher.ObfuscateText(got); secondPass != got { + t.Fatalf("second obfuscation pass = %q, want idempotent %q", secondPass, got) + } +} + +func TestSensitiveWordMatcherReplacementsPrecedenceAndEmptyDeletion(t *testing.T) { + matcher := BuildAntigravitySensitiveWordMatcher( + []string{"Claude", "Codex", "GPT-5"}, + map[string]string{ + "You are Codex, an agent based on GPT-5.": "You are a helpful coding assistant.", + "Claude Code": "Claude", + "Codex": "Assistant", + "RemoveMe ": "", + }, + ) + if matcher == nil { + t.Fatal("expected non-nil matcher") + } + + input := "you are codex, an agent based on gpt-5. Built for Claude Code, standalone Claude, Codex, and RemoveMe ." + got := matcher.ObfuscateText(input) + want := "You are a helpful coding assistant. Built for Claude, standalone C\u034Flaude, Assistant, and ." + if got != want { + t.Fatalf("ObfuscateText() = %q, want %q", got, want) + } +} + +func TestObfuscateSensitiveWordsDocReplacementsOnlyAndBillingHeaderSkip(t *testing.T) { + matcher := BuildSensitiveWordMatcherWithReplacements(nil, map[string]string{ + "anthropic": "provider", + "secret": "", + }) + if matcher == nil { + t.Fatal("expected non-nil matcher when only replacements are configured") + } + + doc := ojson.NewDocString(`{ + "system": [ + {"type": "text", "text": "x-anthropic-billing-header: cc_version=2.1.321; cc_entrypoint=cli;"}, + {"type": "text", "text": "Keep anthropic rules and drop secret"} + ], + "messages": [ + {"role": "user", "content": "Ask anthropic about secret"} + ] + }`) + if !ObfuscateSensitiveWordsDoc(doc, matcher) { + t.Fatal("expected ObfuscateSensitiveWordsDoc to modify document") + } + if gotBilling := doc.Get("system.0.text").String(); gotBilling != "x-anthropic-billing-header: cc_version=2.1.321; cc_entrypoint=cli;" { + t.Fatalf("billing header = %q, want untouched", gotBilling) + } + if gotSys := doc.Get("system.1.text").String(); gotSys != "Keep provider rules and drop " { + t.Fatalf("system.1.text = %q, want %q", gotSys, "Keep provider rules and drop ") + } + if gotMsg := doc.Get("messages.0.content").String(); gotMsg != "Ask provider about " { + t.Fatalf("messages.0.content = %q, want %q", gotMsg, "Ask provider about ") + } +} + +func TestSensitiveWordConfigCacheKeyCollisionFree(t *testing.T) { + k1 := SensitiveWordConfigCacheKey([]string{"a", "b"}, map[string]string{"x": "1=2"}) + k2 := SensitiveWordConfigCacheKey([]string{"a;1:b"}, map[string]string{"x": "1=2"}) + k3 := SensitiveWordConfigCacheKey([]string{"a", "b"}, map[string]string{"x=2:1": "2"}) + if k1 == k2 || k1 == k3 || k2 == k3 { + t.Fatalf("expected distinct cache keys, got %q, %q, %q", k1, k2, k3) + } + p1 := SensitiveWordConfigCacheKeyWithPatterns([]string{"a"}, map[string]string{"x": "1"}, []config.SensitivePatternRule{ + {Pattern: "foo", Replacement: "bar"}, + }) + p2 := SensitiveWordConfigCacheKeyWithPatterns([]string{"a"}, map[string]string{"x": "1"}, []config.SensitivePatternRule{ + {Pattern: "foo", Replacement: "baz"}, + }) + p3 := SensitiveWordConfigCacheKeyWithPatterns([]string{"a"}, map[string]string{"x": "1"}, []config.SensitivePatternRule{ + {Pattern: "foo=bar;1:x", Replacement: "baz"}, + }) + if p1 == p2 || p1 == p3 || p2 == p3 { + t.Fatalf("expected distinct pattern cache keys, got %q, %q, %q", p1, p2, p3) + } +} + +func TestSensitivePatternRulesOnlyNonCascadingAndDevin(t *testing.T) { + matcher := BuildAntigravitySensitiveWordMatcherWithPatterns( + []string{"Claude", "omp"}, + map[string]string{"Codex": "Assistant"}, + []config.SensitivePatternRule{ + {Pattern: `[invalid`, Replacement: "skip"}, + {Pattern: `(?m)^You are (omp|Codex)[^\n]*\n?`, Replacement: "You are Claude ($1).\n"}, + {Pattern: `(?s).*?\n?`, Replacement: ""}, + }, + ) + if matcher == nil { + t.Fatal("expected non-nil matcher") + } + if !matcher.Matches("hello") { + t.Fatal("Matches() = false, want true for pattern-only match") + } + + input := "You are omp's assistant.\n\nRFC 2119\n\nKeep Codex and omp." + got := matcher.ObfuscateText(input) + want := "You are Claude (omp).\nKeep Assistant and o\u034Fmp." + if got != want { + t.Fatalf("ObfuscateText() = %q, want %q", got, want) + } + + // Pattern-only matcher (no words, no literal replacements) must still run on docs. + patternOnly := BuildSensitiveWordMatcherWithPatterns(nil, nil, []config.SensitivePatternRule{ + {Pattern: `(?m)^RFC 2119[^\n]*\n?`, Replacement: ""}, + {Pattern: `secret-\d+`, Replacement: "[redacted]"}, + }) + if patternOnly == nil { + t.Fatal("expected non-nil pattern-only matcher") + } + doc := ojson.NewDocString(`{ + "system": [ + {"type": "text", "text": "x-anthropic-billing-header: secret-123"}, + {"type": "text", "text": "RFC 2119 applies.\nKeep secret-42."} + ], + "messages": [ + {"role": "user", "content": "Check secret-99"} + ] + }`) + if !ObfuscateSensitiveWordsDoc(doc, patternOnly) { + t.Fatal("expected ObfuscateSensitiveWordsDoc to modify document") + } + if gotBilling := doc.Get("system.0.text").String(); gotBilling != "x-anthropic-billing-header: secret-123" { + t.Fatalf("billing header = %q, want untouched", gotBilling) + } + if gotSys := doc.Get("system.1.text").String(); gotSys != "Keep [redacted]." { + t.Fatalf("system.1.text = %q, want %q", gotSys, "Keep [redacted].") + } + if gotMsg := doc.Get("messages.0.content").String(); gotMsg != "Check [redacted]" { + t.Fatalf("messages.0.content = %q, want %q", gotMsg, "Check [redacted]") + } + + // Devin: pattern match emits replacement verbatim (even containing a sensitive word) without dropping the line. + devinMatcher := BuildSensitiveWordMatcherWithPatterns( + []string{"Claude", "DropMe"}, + nil, + []config.SensitivePatternRule{ + {Pattern: `You are omp\.`, Replacement: "You are Claude."}, + }, + ) + devinInput := "You are omp.\nRemove DropMe line.\nKeep final line." + if gotDevin := devinMatcher.SanitizeDevinText(devinInput); gotDevin != "You are Claude.\nKeep final line." { + t.Fatalf("SanitizeDevinText() = %q, want %q", gotDevin, "You are Claude.\nKeep final line.") + } + + // Multi-line literal and pattern replacements must not reset dropCurrentLine + // when the same original line contains an unreplaced sensitive word. + multilineLiteral := BuildSensitiveWordMatcherWithReplacements( + []string{"DROP_ME"}, + map[string]string{"alias": "safe\ncontinued"}, + ) + if got := multilineLiteral.SanitizeDevinText("DROP_ME alias\nKeep"); got != "Keep" { + t.Fatalf("SanitizeDevinText(DROP_ME before multiline literal) = %q, want %q", got, "Keep") + } + if got := multilineLiteral.SanitizeDevinText("alias DROP_ME\nKeep"); got != "Keep" { + t.Fatalf("SanitizeDevinText(DROP_ME after multiline literal) = %q, want %q", got, "Keep") + } + if got := multilineLiteral.SanitizeDevinText("alias\nKeep"); got != "safe\ncontinued\nKeep" { + t.Fatalf("SanitizeDevinText(multiline literal kept) = %q, want %q", got, "safe\ncontinued\nKeep") + } + + multilinePattern := BuildSensitiveWordMatcherWithPatterns( + []string{"DROP_ME"}, + nil, + []config.SensitivePatternRule{{Pattern: `alias-\d+`, Replacement: "safe\ncontinued"}}, + ) + if got := multilinePattern.SanitizeDevinText("DROP_ME alias-1\nKeep"); got != "Keep" { + t.Fatalf("SanitizeDevinText(DROP_ME before multiline pattern) = %q, want %q", got, "Keep") + } + if got := multilinePattern.SanitizeDevinText("alias-1 DROP_ME\nKeep"); got != "Keep" { + t.Fatalf("SanitizeDevinText(DROP_ME after multiline pattern) = %q, want %q", got, "Keep") + } + + // Pattern match consuming an original newline must flush/drop the finished line + // and reset dropCurrentLine so subsequent lines remain intact. + newlineConsumingPattern := BuildSensitiveWordMatcherWithPatterns( + []string{"DROP_ME"}, + nil, + []config.SensitivePatternRule{ + {Pattern: `alias-\d+\n`, Replacement: ""}, + {Pattern: `(?s).*?\n?`, Replacement: ""}, + }, + ) + if got := newlineConsumingPattern.SanitizeDevinText("DROP_ME alias-1\nKeep"); got != "Keep" { + t.Fatalf("SanitizeDevinText(DROP_ME + alias-1\\n) = %q, want %q", got, "Keep") + } + if got := newlineConsumingPattern.SanitizeDevinText("DROP_ME \nRFC\n\nKeep"); got != "Keep" { + t.Fatalf("SanitizeDevinText(DROP_ME + multiline block) = %q, want %q", got, "Keep") + } + if got := newlineConsumingPattern.SanitizeDevinText("KeepPrefix alias-1\nDROP_ME\nKeepAfter"); got != "KeepPrefix KeepAfter" { + t.Fatalf("SanitizeDevinText(KeepPrefix + alias-1\\n + DROP_ME) = %q, want %q", got, "KeepPrefix KeepAfter") + } + + // Multi-line match with non-empty replacement must not inject synthetic newlines + // and must preserve original-line drop ownership on both DROP_ME directions. + multilineMatchRepl := BuildSensitiveWordMatcherWithPatterns( + []string{"DROP_ME"}, + map[string]string{"L1\nL2": "M"}, + []config.SensitivePatternRule{ + {Pattern: `A\nB`, Replacement: "X"}, + {Pattern: `alias\n`, Replacement: "safe\n"}, + {Pattern: `lead\n`, Replacement: "safe"}, + }, + ) + if got := multilineMatchRepl.SanitizeDevinText("prefix A\nB suffix"); got != "prefix X suffix" { + t.Fatalf("SanitizeDevinText(prefix A\\nB suffix) = %q, want %q", got, "prefix X suffix") + } + if got := multilineMatchRepl.SanitizeDevinText("prefix L1\nL2 suffix"); got != "prefix M suffix" { + t.Fatalf("SanitizeDevinText(prefix L1\\nL2 suffix) = %q, want %q", got, "prefix M suffix") + } + if got := multilineMatchRepl.SanitizeDevinText("DROP_ME alias\nKeep"); got != "Keep" { + t.Fatalf("SanitizeDevinText(DROP_ME alias\\nKeep) = %q, want %q", got, "Keep") + } + if got := multilineMatchRepl.SanitizeDevinText("lead\nDROP_ME\nKeep"); got != "safeKeep" { + t.Fatalf("SanitizeDevinText(lead\\nDROP_ME\\nKeep) = %q, want %q", got, "safeKeep") + } +} + +func TestSensitivePatternRulesPreserveOriginalAnchorsAndNonCascadingDeletion(t *testing.T) { + // Original-text anchor preservation: earlier matches must not synthesize ^ or $ + // anchors for subsequent pattern rules. + prefixAnchorMatcher := BuildSensitiveWordMatcherWithPatterns(nil, nil, []config.SensitivePatternRule{ + {Pattern: `prefix`, Replacement: "safe"}, + {Pattern: `(?m)^KEEP`, Replacement: ""}, + }) + if got := prefixAnchorMatcher.ObfuscateText("prefixKEEP"); got != "safeKEEP" { + t.Fatalf("ObfuscateText(prefixKEEP) = %q, want %q", got, "safeKEEP") + } + suffixAnchorMatcher := BuildSensitiveWordMatcherWithPatterns(nil, nil, []config.SensitivePatternRule{ + {Pattern: `suffix`, Replacement: "safe"}, + {Pattern: `(?m)KEEP$`, Replacement: ""}, + }) + if got := suffixAnchorMatcher.ObfuscateText("KEEPsuffix"); got != "KEEPsafe" { + t.Fatalf("ObfuscateText(KEEPsuffix) = %q, want %q", got, "KEEPsafe") + } + + // Non-cascading across empty deletion: deleting "DELETE" from "fooDELETEbar" + // must not let subsequent regex/literal/sensitive-word rules match "foobar". + nonCascade := BuildSensitiveWordMatcherWithPatterns( + []string{"foobar"}, + map[string]string{"foobar": "LITERAL_CHANGED"}, + []config.SensitivePatternRule{ + {Pattern: `DELETE`, Replacement: ""}, + {Pattern: `foobar`, Replacement: "REGEX_CHANGED"}, + }, + ) + if got := nonCascade.ObfuscateText("fooDELETEbar"); got != "foobar" { + t.Fatalf("ObfuscateText(fooDELETEbar) = %q, want %q", got, "foobar") + } + if gotDevin := nonCascade.SanitizeDevinText("fooDELETEbar\nkeep"); gotDevin != "foobar\nkeep" { + t.Fatalf("SanitizeDevinText(fooDELETEbar) = %q, want %q", gotDevin, "foobar\nkeep") + } + + // Superset deletion subsumes enclosed empty deletions (e.g. inner line deleted + // before outer tag rule) without overwriting non-empty replacements. + nestedDeletion := BuildAntigravitySensitiveWordMatcherWithPatterns( + []string{"RFC 2119"}, + nil, + []config.SensitivePatternRule{ + {Pattern: `(?m)^RFC 2119[^\n]*\n?`, Replacement: ""}, + {Pattern: `(?s).*?\n?`, Replacement: ""}, + }, + ) + nestedInput := "\nRFC 2119 applies.\n\nKeep me." + if got := nestedDeletion.ObfuscateText(nestedInput); got != "Keep me." { + t.Fatalf("ObfuscateText(nestedInput) = %q, want %q", got, "Keep me.") + } +} + +func TestSensitivePatternRulesHighDensityLinearScaling(t *testing.T) { + matcher := BuildSensitiveWordMatcherWithPatterns( + []string{"omp"}, + nil, + []config.SensitivePatternRule{ + {Pattern: `secret-\d+`, Replacement: "[redacted]"}, + {Pattern: `token-[a-z]+`, Replacement: ""}, + }, + ) + if matcher == nil { + t.Fatal("expected non-nil matcher") + } + + const repeats = 25000 + var inBuilder strings.Builder + var wantBuilder strings.Builder + inBuilder.Grow(repeats * 24) + wantBuilder.Grow(repeats * 24) + for i := 0; i < repeats; i++ { + inBuilder.WriteString("secret-1 token-abc omp ") + wantBuilder.WriteString("[redacted] o\u200Bmp ") + } + got := matcher.ObfuscateText(inBuilder.String()) + if got != wantBuilder.String() { + t.Fatalf("high-density ObfuscateText mismatch (got len=%d, want len=%d)", len(got), wantBuilder.Len()) + } +} + +func BenchmarkObfuscateTextPatternsScaling(b *testing.B) { + matcher := BuildSensitiveWordMatcherWithPatterns( + []string{"omp"}, + nil, + []config.SensitivePatternRule{ + {Pattern: `(?m)^RFC 2119[^\n]*\n?`, Replacement: ""}, + {Pattern: `secret-\d+`, Replacement: "[redacted]"}, + {Pattern: `(?s).*?\n?`, Replacement: ""}, + }, + ) + for _, count := range []int{100, 1000, 10000} { + var sb strings.Builder + for i := 0; i < count; i++ { + sb.WriteString("\nRFC 2119 applies.\n\nsecret-42 omp ") + } + input := sb.String() + b.Run(fmt.Sprintf("n=%d", count), func(b *testing.B) { + b.SetBytes(int64(len(input))) + for i := 0; i < b.N; i++ { + _ = matcher.ObfuscateText(input) + } + }) + } +} diff --git a/internal/runtime/executor/helps/codex_hosted_images.go b/internal/runtime/executor/helps/codex_hosted_images.go index 48318e7d2dd..1e9f924276f 100644 --- a/internal/runtime/executor/helps/codex_hosted_images.go +++ b/internal/runtime/executor/helps/codex_hosted_images.go @@ -1,6 +1,7 @@ package helps import ( + "context" "net/http" "strings" @@ -8,9 +9,12 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" + "github.com/router-for-me/CLIProxyAPI/v8/internal/util" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" ) +const codexResponsesLiteHeaderName = "X-OpenAI-Internal-Codex-Responses-Lite" + // CodexModelUsesResponsesLite identifies models whose native Codex route uses Responses Lite. func CodexModelUsesResponsesLite(model string) bool { slug := strings.ToLower(strings.TrimSpace(thinking.ParseSuffix(model).ModelName)) @@ -22,7 +26,7 @@ func CodexModelUsesResponsesLite(model string) bool { // CodexResponsesLiteRequestDoc reads the route hints without changing the payload. func CodexResponsesLiteRequestDoc(doc *ojson.Doc, headers http.Header) bool { - if strings.EqualFold(strings.TrimSpace(headers.Get("X-OpenAI-Internal-Codex-Responses-Lite")), "true") { + if strings.EqualFold(strings.TrimSpace(headers.Get(codexResponsesLiteHeaderName)), "true") { return true } if doc == nil { @@ -32,15 +36,82 @@ func CodexResponsesLiteRequestDoc(doc *ojson.Doc, headers http.Header) bool { return value.Type == ojson.True || (value.Type == ojson.String && strings.EqualFold(strings.TrimSpace(value.String()), "true")) } +// CodexResponsesLiteRequestForAuthDoc reports whether the request uses the +// Codex Responses-Lite protocol after resolving client_metadata, client +// headers, credential header: attributes, and models.json override_header. +func CodexResponsesLiteRequestForAuthDoc(doc *ojson.Doc, modelName string, auth *cliproxyauth.Auth, headers http.Header) bool { + if CodexResponsesLiteRequestDoc(doc, nil) { + return true + } + var effective string + if headers != nil { + effective = strings.TrimSpace(headers.Get(codexResponsesLiteHeaderName)) + } + if auth != nil && len(auth.Attributes) > 0 { + resolved := (&http.Request{Header: http.Header{}}).WithContext(context.Background()) + util.ApplyCustomHeadersFromAttrs(resolved, auth.Attributes, headers) + if opLite := strings.TrimSpace(resolved.Header.Get(codexResponsesLiteHeaderName)); opLite != "" { + effective = opLite + } + } + if overrides := registry.ModelOverrideHeaders(modelName); len(overrides) > 0 { + for key, value := range overrides { + if strings.EqualFold(strings.TrimSpace(key), codexResponsesLiteHeaderName) { + effective = strings.TrimSpace(value) + } + } + } + return strings.EqualFold(effective, "true") +} + +// CodexRequestHasReasoningForHostedImageDoc reports whether the request carries +// a reasoning configuration (top-level reasoning.effort, configuration_update +// input item, or model thinking suffix). Upstream Codex /responses binds hosted +// image_generation to gpt-image-2-codex, which rejects complexity whenever +// reasoning effort is present on Responses-Lite models (#7270), whereas +// standard Responses requests without reasoning effort succeed (#7384). +func CodexRequestHasReasoningForHostedImageDoc(doc *ojson.Doc, model string) bool { + if thinking.HasThinkingSuffix(model) { + return true + } + if doc == nil { + return false + } + if thinking.HasThinkingSuffix(doc.Get("model").String()) { + return true + } + if reasoning := doc.Get("reasoning"); reasoning.Exists() && reasoning.Type != ojson.Null { + if reasoning.IsObject() { + if effort := reasoning.Get("effort"); effort.Exists() && effort.Type != ojson.Null && strings.TrimSpace(effort.String()) != "" { + return true + } + } else if strings.TrimSpace(reasoning.String()) != "" { + return true + } + } + if input := doc.Get("input"); input.IsArray() { + for _, item := range input.Array() { + if strings.TrimSpace(item.Get("type").String()) != "configuration_update" { + continue + } + if effort := item.Get("reasoning.effort"); effort.Exists() && effort.Type != ojson.Null && strings.TrimSpace(effort.String()) != "" { + return true + } + } + } + return false +} + // ValidateCodexHostedImageGenerationDoc checks the final, configured Responses payload // after all outbound headers, including credential and model overrides, are resolved. -// Native Codex Responses Lite cannot serve forced hosted images. API-key, SIWC, +// Native Codex Responses Lite cannot serve forced hosted images, while API-key, SIWC, // explicit passthrough, and standalone Images API requests retain their own contracts. func ValidateCodexHostedImageGenerationDoc(doc *ojson.Doc, upstreamHeaders http.Header, cfg *config.Config, nativeCodex bool) error { if !nativeCodex || doc == nil || (cfg != nil && cfg.DisableImageGeneration == config.DisableImageGenerationPassthrough) { return nil } - if !CodexModelUsesResponsesLite(doc.Get("model").String()) && !CodexResponsesLiteRequestDoc(doc, upstreamHeaders) { + model := doc.Get("model").String() + if !CodexModelUsesResponsesLite(model) && !CodexResponsesLiteRequestDoc(doc, upstreamHeaders) { return nil } if !codexRequestForcesImageGenerationDoc(doc) { diff --git a/internal/runtime/executor/helps/detachable_context.go b/internal/runtime/executor/helps/detachable_context.go deleted file mode 100644 index cc458b901c5..00000000000 --- a/internal/runtime/executor/helps/detachable_context.go +++ /dev/null @@ -1,59 +0,0 @@ -package helps - -import "context" - -// NewDetachableContext returns a context that carries parent's values and -// follows parent's cancellation until detach is called. -// -// It is meant for upstream requests whose response body should outlive the -// downstream request once the response is semantically complete. Before -// detach, when parent is cancelled, the returned context is cancelled with -// parent's cause, so errors surfaced through it keep parent's identity. -// After a successful detach, parent's cancellation no longer reaches it; it -// only ends with release. -// -// A parent with a deadline is returned unchanged and never detaches: a -// cancelled context cannot report context.DeadlineExceeded from Err(), and -// some transports (for example HTTP/2) report Err() rather than the cause, so -// forwarding the deadline as a cancellation would change the error callers -// see. Such requests keep their existing semantics and simply skip whatever -// the caller would do after a successful detach. -// -// detach reports whether the returned context was still live when it was -// detached; it returns false if parent was already done, if parent has a -// deadline, or if detach was called before. release stops propagation and -// cancels the returned context; it must always be called once the context is -// no longer needed. -func NewDetachableContext(parent context.Context) (ctx context.Context, detach func() bool, release func()) { - if parent == nil { - parent = context.Background() - } - if _, hasDeadline := parent.Deadline(); hasDeadline { - return parent, func() bool { return false }, func() {} - } - ctx, cancel := context.WithCancelCause(context.WithoutCancel(parent)) - forward := func() { cancel(context.Cause(parent)) } - stop := context.AfterFunc(parent, forward) - if parent.Err() != nil { - // AfterFunc runs forward in its own goroutine when parent is already - // done; run it synchronously so callers never get a live context. - forward() - } - detach = func() bool { - if !stop() { - return false - } - if parent.Err() != nil { - // For parents the context package cannot watch directly, - // AfterFunc waits in a goroutine that may not have run yet. - forward() - return false - } - return ctx.Err() == nil - } - release = func() { - stop() - cancel(nil) - } - return ctx, detach, release -} diff --git a/internal/runtime/executor/helps/detachable_context_test.go b/internal/runtime/executor/helps/detachable_context_test.go deleted file mode 100644 index 42fef515a17..00000000000 --- a/internal/runtime/executor/helps/detachable_context_test.go +++ /dev/null @@ -1,295 +0,0 @@ -package helps - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "sync" - "testing" - "time" -) - -type detachableContextKey struct{} - -func TestNewDetachableContext_FollowsParentUntilDetached(t *testing.T) { - parent, cancel := context.WithCancel(context.WithValue(context.Background(), detachableContextKey{}, "v")) - ctx, _, release := NewDetachableContext(parent) - defer release() - - if got := ctx.Value(detachableContextKey{}); got != "v" { - t.Fatalf("value = %v, want v", got) - } - cancel() - select { - case <-ctx.Done(): - case <-time.After(5 * time.Second): - t.Fatal("parent cancellation did not propagate before detach") - } -} - -func TestNewDetachableContext_DetachStopsPropagation(t *testing.T) { - parent, cancel := context.WithCancel(context.Background()) - ctx, detach, release := NewDetachableContext(parent) - - if !detach() { - t.Fatal("detach() = false on a live context") - } - if detach() { - t.Fatal("second detach() = true, want false") - } - cancel() - if err := ctx.Err(); err != nil { - t.Fatalf("detached context cancelled by parent: %v", err) - } - release() - if ctx.Err() == nil { - t.Fatal("release() did not cancel the context") - } -} - -func TestNewDetachableContext_DetachAfterParentCancelReportsFalse(t *testing.T) { - parent, cancel := context.WithCancel(context.Background()) - ctx, detach, release := NewDetachableContext(parent) - defer release() - - cancel() - <-ctx.Done() - if detach() { - t.Fatal("detach() = true after parent cancellation propagated") - } -} - -func TestNewDetachableContext_AlreadyCanceledParentCancelsImmediately(t *testing.T) { - parent, cancel := context.WithCancel(context.Background()) - cancel() - ctx, detach, release := NewDetachableContext(parent) - defer release() - - if ctx.Err() == nil { - t.Fatal("context still live for an already-cancelled parent") - } - if detach() { - t.Fatal("detach() = true for an already-cancelled parent") - } -} - -// pendingPropagationContext is a valid context the context package cannot -// see through, so AfterFunc watches it from its own goroutine. The first Err -// call after cancellation (made by that goroutine) blocks until gate is -// closed, which holds propagation pending while the test calls detach. -type pendingPropagationContext struct { - context.Context - once sync.Once - entered chan struct{} - gate chan struct{} -} - -func (c *pendingPropagationContext) Err() error { - err := c.Context.Err() - if err != nil { - first := false - c.once.Do(func() { first = true }) - if first { - close(c.entered) - <-c.gate - } - } - return err -} - -func (c *pendingPropagationContext) Value(any) any { return nil } - -func TestNewDetachableContext_DetachAfterParentCancelBeforePropagationReportsFalse(t *testing.T) { - inner, cancel := context.WithCancel(context.Background()) - parent := &pendingPropagationContext{Context: inner, entered: make(chan struct{}), gate: make(chan struct{})} - ctx, detach, release := NewDetachableContext(parent) - defer release() - defer close(parent.gate) - - cancel() - <-parent.entered - if detach() { - t.Fatal("detach() = true after parent cancellation") - } - if !errors.Is(context.Cause(ctx), context.Canceled) { - t.Fatalf("Cause() = %v, want context.Canceled", context.Cause(ctx)) - } -} - -var errDetachableCustomCause = errors.New("custom cause") - -func TestNewDetachableContext_ForwardsParentCause(t *testing.T) { - parent, cancel := context.WithCancelCause(context.Background()) - ctx, _, release := NewDetachableContext(parent) - defer release() - - cancel(errDetachableCustomCause) - select { - case <-ctx.Done(): - case <-time.After(5 * time.Second): - t.Fatal("parent cancellation did not propagate") - } - if got := context.Cause(ctx); !errors.Is(got, errDetachableCustomCause) { - t.Fatalf("Cause() = %v, want custom cause", got) - } -} - -func TestNewDetachableContext_AlreadyDoneParentKeepsCause(t *testing.T) { - parent, cancel := context.WithCancelCause(context.Background()) - cancel(errDetachableCustomCause) - ctx, _, release := NewDetachableContext(parent) - defer release() - - if got := context.Cause(ctx); !errors.Is(got, errDetachableCustomCause) { - t.Fatalf("Cause() = %v, want custom cause", got) - } -} - -// A parent with a deadline is used as-is and never detaches, so its deadline -// and error identity are untouched and the caller keeps its old behaviour. -func TestNewDetachableContext_DeadlineParentIsReturnedUnchanged(t *testing.T) { - parent, cancel := context.WithTimeout(context.WithValue(context.Background(), detachableContextKey{}, "v"), time.Hour) - defer cancel() - ctx, detach, release := NewDetachableContext(parent) - defer release() - - if ctx != parent { - t.Fatal("deadline parent was wrapped, want it returned unchanged") - } - if detach() { - t.Fatal("detach() = true for a deadline parent") - } - release() - if err := parent.Err(); err != nil { - t.Fatalf("release() cancelled the parent: %v", err) - } -} - -// Errors that net/http surfaces through the detachable context must keep the -// identity they have with the parent context itself, both while the request -// is sent and while the body is read. -func TestNewDetachableContext_HTTPErrorsMatchParent(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - _, _ = w.Write([]byte("data: x\n\n")) - w.(http.Flusher).Flush() - <-r.Context().Done() - })) - defer server.Close() - transport := &http.Transport{} - defer transport.CloseIdleConnections() - - parents := map[string]func() (context.Context, func()){ - "cancel": func() (context.Context, func()) { - return context.WithCancel(context.Background()) - }, - "cancel cause": func() (context.Context, func()) { - ctx, cancel := context.WithCancelCause(context.Background()) - return ctx, func() { cancel(errDetachableCustomCause) } - }, - } - run := func(t *testing.T, newParent func() (context.Context, func()), detachable, inBody bool) error { - t.Helper() - parent, end := newParent() - ctx := parent - if detachable { - var release func() - ctx, _, release = NewDetachableContext(parent) - defer release() - } - req, errReq := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil) - if errReq != nil { - t.Fatal(errReq) - } - if !inBody { - end() - resp, errRoundTrip := transport.RoundTrip(req) - if errRoundTrip == nil { - _ = resp.Body.Close() - } - return errRoundTrip - } - resp, errRoundTrip := transport.RoundTrip(req) - if errRoundTrip != nil { - t.Fatalf("RoundTrip() error = %v", errRoundTrip) - } - defer func() { _ = resp.Body.Close() }() - buf := make([]byte, 64) - _, _ = resp.Body.Read(buf) - end() - for { - if _, errRead := resp.Body.Read(buf); errRead != nil { - return errRead - } - } - } - identity := func(err error) [3]bool { - return [3]bool{errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded), errors.Is(err, errDetachableCustomCause)} - } - for name, newParent := range parents { - for _, inBody := range []bool{false, true} { - phase := "request" - if inBody { - phase = "body" - } - t.Run(name+"/"+phase, func(t *testing.T) { - want := identity(run(t, newParent, false, inBody)) - got := identity(run(t, newParent, true, inBody)) - if want == [3]bool{} { - t.Fatal("parent context produced no context error") - } - if got != want { - t.Fatalf("error identity [canceled deadline custom] = %v, want %v", got, want) - } - }) - } - } -} - -// HTTP/2 reports ctx.Err() directly on some paths, so a deadline must not be -// turned into a cancellation by the detachable context. -func TestNewDetachableContext_HTTP2DeadlineErrorMatchesParent(t *testing.T) { - server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) - server.EnableHTTP2 = true - server.StartTLS() - defer server.Close() - client := server.Client() - defer client.CloseIdleConnections() - - warm, errWarm := client.Get(server.URL) - if errWarm != nil { - t.Fatalf("warm-up request error = %v", errWarm) - } - _ = warm.Body.Close() - if warm.ProtoMajor != 2 { - t.Fatalf("warm-up protocol = %s, want HTTP/2", warm.Proto) - } - - do := func(detachable bool) error { - parent, cancel := context.WithDeadline(context.Background(), time.Unix(0, 0)) - defer cancel() - ctx := parent - if detachable { - var release func() - ctx, _, release = NewDetachableContext(parent) - defer release() - } - req, errReq := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil) - if errReq != nil { - t.Fatal(errReq) - } - resp, errDo := client.Do(req) - if errDo == nil { - _ = resp.Body.Close() - } - return errDo - } - want, got := do(false), do(true) - if !errors.Is(want, context.DeadlineExceeded) { - t.Fatalf("parent error = %v, want context.DeadlineExceeded", want) - } - if !errors.Is(got, context.DeadlineExceeded) || errors.Is(got, context.Canceled) { - t.Fatalf("detachable error = %v, want context.DeadlineExceeded like parent (%v)", got, want) - } -} diff --git a/internal/runtime/executor/helps/devin_apply_patch_diagnostic.go b/internal/runtime/executor/helps/devin_apply_patch_diagnostic.go index 7088d95d39e..fa611d93e82 100644 --- a/internal/runtime/executor/helps/devin_apply_patch_diagnostic.go +++ b/internal/runtime/executor/helps/devin_apply_patch_diagnostic.go @@ -82,6 +82,20 @@ func (d *DevinApplyPatchDiagnostics) ObserveDelta(tc DevinToolCallDelta) int { return key } +// HasPatchActivity reports whether any unnamed or apply_patch tool-call delta +// was observed during the upstream response. +func (d *DevinApplyPatchDiagnostics) HasPatchActivity() bool { + if d == nil { + return false + } + for _, call := range d.calls { + if call != nil && (call.name == "" || IsApplyPatchUpstreamTool(d.original, call.name)) { + return true + } + } + return false +} + // MarkRecovered marks the call identified by key as recovered from a complete // bare patch in invalid_json_str so subsequent failures on later calls report // the actually failing call. diff --git a/internal/runtime/executor/helps/devin_apply_patch_diagnostic_test.go b/internal/runtime/executor/helps/devin_apply_patch_diagnostic_test.go index 72441febf87..5a4178052a0 100644 --- a/internal/runtime/executor/helps/devin_apply_patch_diagnostic_test.go +++ b/internal/runtime/executor/helps/devin_apply_patch_diagnostic_test.go @@ -278,3 +278,30 @@ func TestRecoverDevinBareApplyPatch(t *testing.T) { }) } } + +func TestDevinApplyPatchDiagnosticsHasPatchActivity(t *testing.T) { + if (*DevinApplyPatchDiagnostics)(nil).HasPatchActivity() { + t.Fatal("nil diagnostics reported patch activity") + } + + d := NewDevinApplyPatchDiagnostics([]byte(devinDiagnosticPatchRequest)) + if d.HasPatchActivity() { + t.Fatal("empty diagnostics reported patch activity") + } + + d.Observe(0, DevinToolCallDelta{Name: "shell", Arguments: `{"cmd":"ls"}`}) + if d.HasPatchActivity() { + t.Fatal("non-patch tool call reported patch activity") + } + + d.Observe(1, DevinToolCallDelta{Name: "apply_patch", Arguments: `{"input":"*** Begin Patch"}`}) + if !d.HasPatchActivity() { + t.Fatal("apply_patch tool call did not report patch activity") + } + + dUnnamed := NewDevinApplyPatchDiagnostics([]byte(devinDiagnosticPatchRequest)) + dUnnamed.Observe(0, DevinToolCallDelta{InvalidJSONStr: "*** Begin Patch"}) + if !dUnnamed.HasPatchActivity() { + t.Fatal("unnamed tool call did not report patch activity") + } +} diff --git a/internal/runtime/executor/helps/devin_wire.go b/internal/runtime/executor/helps/devin_wire.go index ecebd412d22..a85a67e2223 100644 --- a/internal/runtime/executor/helps/devin_wire.go +++ b/internal/runtime/executor/helps/devin_wire.go @@ -617,7 +617,7 @@ func ParseDevinFrame(payload []byte) (DevinFrameResult, error) { } // SanitizeDevinSystemPrompt strips Claude Code attribution and CLI identity headers -// (referencing Antigravity conventions), and applies zero-width obfuscation for configured sensitive words. +// (referencing Antigravity conventions), and applies configured sensitive-word replacements and obfuscation. func SanitizeDevinSystemPrompt(prompt string, matcher *SensitiveWordMatcher) string { if prompt == "" { return "" @@ -648,16 +648,13 @@ func SanitizeDevinSystemPrompt(prompt string, matcher *SensitiveWordMatcher) str if strings.Contains(trimmed, "- Don’t output ANSI escape codes directly — the CLI renderer applies them.") { continue } - if matcher != nil && matcher.Matches(trimmed) { - continue - } kept = append(kept, line) } - res := strings.TrimSpace(strings.Join(kept, "\n")) + res := strings.Join(kept, "\n") if matcher != nil && res != "" { - res = matcher.ObfuscateText(res) + return matcher.SanitizeDevinText(res) } - return res + return strings.TrimSpace(res) } func parseDevinToolCallDelta(data []byte) (DevinToolCallDelta, error) { diff --git a/internal/runtime/executor/helps/devin_wire_test.go b/internal/runtime/executor/helps/devin_wire_test.go index 176f884bc34..fe0c647e03b 100644 --- a/internal/runtime/executor/helps/devin_wire_test.go +++ b/internal/runtime/executor/helps/devin_wire_test.go @@ -159,6 +159,39 @@ func TestSanitizeDevinSystemPrompt_AndSensitiveWords(t *testing.T) { } } +func TestSanitizeDevinSystemPrompt_ReplacementsAndMultiline(t *testing.T) { + matcher := BuildSensitiveWordMatcherWithReplacements( + []string{"Claude", "DROP_LINE_TOKEN"}, + map[string]string{ + "Claude Code": "Claude", + "First Header\nSecond Line": "Merged Header", + }, + ) + rawPrompt := "First Header\r\nSecond Line\r\nUse Claude Code safely.\r\nLine with DROP_LINE_TOKEN should be dropped." + sanitized := SanitizeDevinSystemPrompt(rawPrompt, matcher) + want := "Merged Header\nUse Claude safely." + if sanitized != want { + t.Fatalf("SanitizeDevinSystemPrompt() = %q, want %q", sanitized, want) + } +} + +func TestSanitizeDevinSystemPrompt_MultilineReplacementSinglePassNoDropOrCascade(t *testing.T) { + matcher := BuildSensitiveWordMatcherWithReplacements( + []string{"Claude"}, + map[string]string{ + "First\nSecond": "Claude", + "Multi\nLine": "Alias", + "Alias": "Final", + }, + ) + rawPrompt := "First\r\nSecond\r\nMulti\r\nLine" + sanitized := SanitizeDevinSystemPrompt(rawPrompt, matcher) + want := "Claude\nAlias" + if sanitized != want { + t.Fatalf("SanitizeDevinSystemPrompt() = %q, want %q", sanitized, want) + } +} + func TestBuildDevinGetChatMessageRequest_WithImages(t *testing.T) { prompts := []DevinPrompt{ { diff --git a/internal/runtime/executor/helps/gemini_zero_output.go b/internal/runtime/executor/helps/gemini_zero_output.go new file mode 100644 index 00000000000..4c9b9230b13 --- /dev/null +++ b/internal/runtime/executor/helps/gemini_zero_output.go @@ -0,0 +1,316 @@ +package helps + +import ( + "bytes" + "fmt" + "strings" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/util" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +// GeminiPayloadInspection summarizes output semantics of a Gemini or Antigravity response frame. +type GeminiPayloadInspection struct { + FinishReason string + HasCandidate bool + HasVisibleOutput bool + HasThoughtOutput bool + HasUsageMetadata bool + HasPromptBlock bool +} + +// GeminiZeroOutputStreamAction instructs stream executors how to process the current frame. +type GeminiZeroOutputStreamAction int + +const ( + // GeminiZeroOutputContinue absorbs the current frame (either buffered as a shell or waiting for trailing usage). + GeminiZeroOutputContinue GeminiZeroOutputStreamAction = iota + // GeminiZeroOutputEmit flushes any buffered shell frames and processes the current frame normally. + GeminiZeroOutputEmit + // GeminiZeroOutputFailNow terminates the stream with a retryable 502 error without emitting completion frames. + GeminiZeroOutputFailNow + // GeminiZeroOutputEmitErrorThenFail emits a post-commit Claude error event before failing with 502. + GeminiZeroOutputEmitErrorThenFail +) + +// IsGeminiZeroOutputAbnormalFinishReason reports whether finishReason indicates an abnormal +// function-call or malformed response termination that yields no answer when output is empty. +func IsGeminiZeroOutputAbnormalFinishReason(reason string) bool { + switch strings.ToUpper(strings.TrimSpace(reason)) { + case "MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "MALFORMED_RESPONSE": + return true + default: + return false + } +} + +// GeminiZeroOutputErrorMessage formats a 502 error message consistent with the downstream format. +func GeminiZeroOutputErrorMessage(responseFormat sdktranslator.Format, finishReason string) string { + reason := strings.ToUpper(strings.TrimSpace(finishReason)) + if responseFormat == sdktranslator.FormatClaude { + doc := ojson.NewDocString(`{"type":"error","error":{"type":"api_error","message":""}}`) + if reason == "" { + _ = doc.Set("error.message", "Gemini stream closed with zero output") + } else { + _ = doc.Set("error.message", fmt.Sprintf("Gemini response finished with %s", reason)) + } + return doc.String() + } + if reason == "" { + return "upstream stream closed with zero output" + } + return fmt.Sprintf("upstream returned zero output with finishReason %s", reason) +} + +func isValidGeminiFunctionCallPart(fc ojson.Result) bool { + if !fc.IsObject() { + return false + } + if strings.TrimSpace(fc.Get("name").String()) != "" || strings.TrimSpace(fc.Get("id").String()) != "" { + return true + } + if partial := fc.Get("partialArgs"); partial.IsArray() && len(partial.Array()) > 0 { + return true + } + if partial := fc.Get("partial_args"); partial.IsArray() && len(partial.Array()) > 0 { + return true + } + if args := fc.Get("args"); args.IsObject() && len(args.Map()) > 0 { + return true + } + return false +} + +func isValidGeminiInlineDataPart(d ojson.Result) bool { + return d.IsObject() && strings.TrimSpace(d.Get("data").String()) != "" +} + +func isValidGeminiFileDataPart(fd ojson.Result) bool { + return fd.IsObject() && (strings.TrimSpace(fd.Get("fileUri").String()) != "" || strings.TrimSpace(fd.Get("file_uri").String()) != "") +} + +func isValidGeminiExecutableCodePart(ec ojson.Result) bool { + return ec.IsObject() && strings.TrimSpace(ec.Get("code").String()) != "" +} + +func isValidGeminiCodeExecutionResultPart(cer ojson.Result) bool { + return cer.IsObject() && (strings.TrimSpace(cer.Get("output").String()) != "" || strings.TrimSpace(cer.Get("outcome").String()) != "") +} + +// InspectGeminiZeroOutputPayload inspects a Gemini or Antigravity JSON/SSE payload without modifying it. +func InspectGeminiZeroOutputPayload(payload []byte, allowResponseWrapper bool) GeminiPayloadInspection { + var out GeminiPayloadInspection + jsonBytes := JSONPayload(payload) + if len(jsonBytes) == 0 { + trimmed := bytes.TrimSpace(payload) + if len(trimmed) > 0 && trimmed[0] == '{' { + jsonBytes = trimmed + } else { + return out + } + } + if !ojson.ValidBytes(jsonBytes) { + return out + } + + root := util.ParseGJSONBytesNoCopy(jsonBytes) + usageRes := root.Get("usageMetadata") + if !usageRes.Exists() { + usageRes = root.Get("usage_metadata") + } + if !usageRes.Exists() && allowResponseWrapper { + usageRes = root.Get("response.usageMetadata") + if !usageRes.Exists() { + usageRes = root.Get("response.usage_metadata") + } + } + out.HasUsageMetadata = usageRes.Exists() + + promptRes := root.Get("promptFeedback") + if !promptRes.Exists() && allowResponseWrapper { + promptRes = root.Get("response.promptFeedback") + } + if promptRes.Exists() && strings.TrimSpace(promptRes.Get("blockReason").String()) != "" { + out.HasPromptBlock = true + } + + candidates := root.Get("candidates") + if !candidates.Exists() && allowResponseWrapper { + candidates = root.Get("response.candidates") + } + if !candidates.IsArray() { + return out + } + + candList := candidates.Array() + if len(candList) > 0 { + out.HasCandidate = true + } + + for _, cand := range candList { + if fr := strings.TrimSpace(cand.Get("finishReason").String()); fr != "" && out.FinishReason == "" { + out.FinishReason = strings.Clone(fr) + } + if chunks := cand.Get("groundingMetadata.groundingChunks"); chunks.IsArray() && len(chunks.Array()) > 0 { + out.HasVisibleOutput = true + } + parts := cand.Get("content.parts") + if !parts.IsArray() { + continue + } + for _, part := range parts.Array() { + hasMediaOrTool := isValidGeminiFunctionCallPart(part.Get("functionCall")) || isValidGeminiFunctionCallPart(part.Get("function_call")) || + isValidGeminiInlineDataPart(part.Get("inlineData")) || isValidGeminiInlineDataPart(part.Get("inline_data")) || + isValidGeminiFileDataPart(part.Get("fileData")) || isValidGeminiFileDataPart(part.Get("file_data")) || + isValidGeminiExecutableCodePart(part.Get("executableCode")) || isValidGeminiExecutableCodePart(part.Get("executable_code")) || + isValidGeminiCodeExecutionResultPart(part.Get("codeExecutionResult")) || isValidGeminiCodeExecutionResultPart(part.Get("code_execution_result")) + text := part.Get("text").String() + if part.Get("thought").Bool() { + if text != "" || hasMediaOrTool { + out.HasThoughtOutput = true + } + continue + } + if hasMediaOrTool || strings.TrimSpace(text) != "" { + out.HasVisibleOutput = true + continue + } + } + } + + return out +} + +// CheckGeminiZeroOutputNonStream reports whether a complete non-streaming response ended abnormally +// with zero visible output. +func CheckGeminiZeroOutputNonStream(responseFormat sdktranslator.Format, rawPayload []byte, allowResponseWrapper bool) (finishReason, errMsg string, zeroOutput bool) { + insp := InspectGeminiZeroOutputPayload(rawPayload, allowResponseWrapper) + if IsGeminiZeroOutputAbnormalFinishReason(insp.FinishReason) && !insp.HasVisibleOutput { + return insp.FinishReason, GeminiZeroOutputErrorMessage(responseFormat, insp.FinishReason), true + } + return "", "", false +} + +// GeminiZeroOutputStreamGuard tracks visible output across streaming frames, withholds leading +// contentless shell frames until meaningful content arrives, and intercepts abnormal zero-output +// terminations before HTTP 200 can be committed by readStreamBootstrap. +type GeminiZeroOutputStreamGuard struct { + allowResponseWrapper bool + responseFormat sdktranslator.Format + pendingShells [][]byte + sawCandidateShell bool + sawVisibleOutput bool + emittedToOut bool + abnormalFinishReason string + abnormalFrame []byte +} + +// NewGeminiZeroOutputStreamGuard creates a stream guard for Gemini-family response streams. +func NewGeminiZeroOutputStreamGuard(allowResponseWrapper bool, responseFormat sdktranslator.Format) *GeminiZeroOutputStreamGuard { + return &GeminiZeroOutputStreamGuard{ + allowResponseWrapper: allowResponseWrapper, + responseFormat: responseFormat, + } +} + +// MarkEmitted records that at least one non-empty payload chunk has been delivered downstream. +func (g *GeminiZeroOutputStreamGuard) MarkEmitted() { + if g != nil { + g.emittedToOut = true + } +} + +// Emitted reports whether any non-empty payload chunk has been delivered downstream. +func (g *GeminiZeroOutputStreamGuard) Emitted() bool { + return g != nil && g.emittedToOut +} + +// HasVisibleOutput reports whether any non-thought visible output has been observed so far. +func (g *GeminiZeroOutputStreamGuard) HasVisibleOutput() bool { + return g != nil && g.sawVisibleOutput +} + +// HasAbnormalFinish reports whether an abnormal zero-output termination was latched. +func (g *GeminiZeroOutputStreamGuard) HasAbnormalFinish() bool { + return g != nil && g.abnormalFinishReason != "" +} + +// AbnormalFrame returns the cloned abnormal finish frame retained while awaiting trailing usage. +func (g *GeminiZeroOutputStreamGuard) AbnormalFrame() []byte { + if g == nil || len(g.abnormalFrame) == 0 { + return nil + } + return bytes.Clone(g.abnormalFrame) +} + +func (g *GeminiZeroOutputStreamGuard) postCommitErrorAction() GeminiZeroOutputStreamAction { + if g.emittedToOut && g.responseFormat == sdktranslator.FormatClaude && strings.EqualFold(g.abnormalFinishReason, "MALFORMED_FUNCTION_CALL") { + return GeminiZeroOutputEmitErrorThenFail + } + return GeminiZeroOutputFailNow +} + +// Observe inspects a raw upstream payload (before usage-metadata filtering) and decides +// whether to buffer, flush/emit, or abort with a zero-output failure. +func (g *GeminiZeroOutputStreamGuard) Observe(rawPayload []byte) ([][]byte, GeminiZeroOutputStreamAction, string) { + if g == nil { + return nil, GeminiZeroOutputEmit, "" + } + insp := InspectGeminiZeroOutputPayload(rawPayload, g.allowResponseWrapper) + if insp.HasVisibleOutput { + g.sawVisibleOutput = true + } + + if g.abnormalFinishReason != "" { + if insp.HasUsageMetadata { + return nil, g.postCommitErrorAction(), g.abnormalFinishReason + } + return nil, GeminiZeroOutputContinue, g.abnormalFinishReason + } + + if IsGeminiZeroOutputAbnormalFinishReason(insp.FinishReason) && !g.sawVisibleOutput { + g.abnormalFinishReason = insp.FinishReason + g.abnormalFrame = bytes.Clone(rawPayload) + g.pendingShells = nil + if insp.HasUsageMetadata { + return nil, g.postCommitErrorAction(), g.abnormalFinishReason + } + return nil, GeminiZeroOutputContinue, g.abnormalFinishReason + } + + if !g.emittedToOut && insp.FinishReason == "" && !insp.HasVisibleOutput && !insp.HasThoughtOutput && !insp.HasPromptBlock { + if insp.HasCandidate || insp.HasUsageMetadata { + g.sawCandidateShell = true + } + g.pendingShells = append(g.pendingShells, bytes.Clone(rawPayload)) + return nil, GeminiZeroOutputContinue, "" + } + + var flush [][]byte + if len(g.pendingShells) > 0 { + flush = g.pendingShells + g.pendingShells = nil + } + return flush, GeminiZeroOutputEmit, "" +} + +// Finalize resolves any pending abnormal termination or buffered shell frames at upstream EOF. +func (g *GeminiZeroOutputStreamGuard) Finalize() ([][]byte, GeminiZeroOutputStreamAction, string) { + if g == nil { + return nil, GeminiZeroOutputEmit, "" + } + if g.abnormalFinishReason != "" { + return nil, g.postCommitErrorAction(), g.abnormalFinishReason + } + if len(g.pendingShells) > 0 { + if !g.emittedToOut && g.sawCandidateShell { + g.pendingShells = nil + return nil, GeminiZeroOutputFailNow, "" + } + flush := g.pendingShells + g.pendingShells = nil + return flush, GeminiZeroOutputEmit, "" + } + return nil, GeminiZeroOutputEmit, "" +} diff --git a/internal/runtime/executor/helps/gemini_zero_output_test.go b/internal/runtime/executor/helps/gemini_zero_output_test.go new file mode 100644 index 00000000000..8ec840f99e0 --- /dev/null +++ b/internal/runtime/executor/helps/gemini_zero_output_test.go @@ -0,0 +1,233 @@ +package helps + +import ( + "testing" + + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestInspectGeminiZeroOutputPayload(t *testing.T) { + tests := []struct { + name string + payload string + allowResponseWrapper bool + wantReason string + wantVisible bool + wantThought bool + wantUsage bool + }{ + { + name: "antigravity partless malformed", + payload: `{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":10}}}`, + allowResponseWrapper: true, + wantReason: "MALFORMED_FUNCTION_CALL", + wantUsage: true, + }, + { + name: "gemini whitespace and empty parts unexpected tool call", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"text":" "},{"thought":true,"text":"thinking"}]},"finishReason":"UNEXPECTED_TOOL_CALL"}]}`, + wantReason: "UNEXPECTED_TOOL_CALL", + wantThought: true, + }, + { + name: "gemini valid functionCall with malformed finish reason keeps visible output", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"bash","args":{}}}]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`, + wantReason: "MALFORMED_FUNCTION_CALL", + wantVisible: true, + }, + { + name: "gemini inlineData media keeps visible output", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"inlineData":{"mimeType":"image/png","data":"AA=="}}]},"finishReason":"MALFORMED_RESPONSE"}]}`, + wantReason: "MALFORMED_RESPONSE", + wantVisible: true, + }, + { + name: "cpaUsageMetadata does not count as upstream usageMetadata", + payload: `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":""}]}}],"cpaUsageMetadata":{"promptTokenCount":12}}}`, + allowResponseWrapper: true, + wantUsage: false, + }, + { + name: "empty functionCall placeholder is not visible output", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{}}]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`, + wantReason: "MALFORMED_FUNCTION_CALL", + wantVisible: false, + }, + { + name: "empty inlineData and fileData placeholders are not visible output", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"inlineData":{"mimeType":"image/png","data":""}},{"fileData":{}},{"executableCode":{}},{"codeExecutionResult":{}}]},"finishReason":"MALFORMED_RESPONSE"}]}`, + wantReason: "MALFORMED_RESPONSE", + wantVisible: false, + }, + { + name: "vertex streaming partialArgs functionCall counts as visible output", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"partialArgs":[{"jsonPath":"$.cmd","stringValue":"ls"}]}}]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`, + wantReason: "MALFORMED_FUNCTION_CALL", + wantVisible: true, + }, + { + name: "partial non-whitespace text counts as visible output", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`, + wantReason: "MALFORMED_FUNCTION_CALL", + wantVisible: true, + }, + { + name: "valid fileData executableCode and codeExecutionResult keep visible output", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"executableCode":{"code":"print(1)"}}]},"finishReason":"UNEXPECTED_TOOL_CALL"}]}`, + wantReason: "UNEXPECTED_TOOL_CALL", + wantVisible: true, + }, + { + name: "thought inlineData counts as thought only, not visible output", + payload: `{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"inlineData":{"mimeType":"image/png","data":"AA=="}}]},"finishReason":"MALFORMED_RESPONSE"}]}`, + wantReason: "MALFORMED_RESPONSE", + wantVisible: false, + wantThought: true, + }, + { + name: "antigravity non-thought thoughtSignature with empty text does not count as thought or visible output", + payload: `{"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"opaque-sig","text":""}]}}],"usageMetadata":{"promptTokenCount":378515,"cachedContentTokenCount":376466,"totalTokenCount":378515}}}`, + allowResponseWrapper: true, + wantVisible: false, + wantThought: false, + wantUsage: true, + }, + { + name: "antigravity thought flag with thoughtSignature and empty text does not count as thought or visible output", + payload: `{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"thoughtSignature":"opaque-sig","text":""}]}}]}}`, + allowResponseWrapper: true, + wantVisible: false, + wantThought: false, + wantUsage: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := InspectGeminiZeroOutputPayload([]byte(tc.payload), tc.allowResponseWrapper) + if got.FinishReason != tc.wantReason || got.HasVisibleOutput != tc.wantVisible || got.HasThoughtOutput != tc.wantThought || got.HasUsageMetadata != tc.wantUsage { + t.Fatalf("InspectGeminiZeroOutputPayload() = %+v, want reason=%q visible=%v thought=%v usage=%v", + got, tc.wantReason, tc.wantVisible, tc.wantThought, tc.wantUsage) + } + }) + } +} + +func TestGeminiZeroOutputStreamGuard_ShellBufferingAndSplitUsage(t *testing.T) { + t.Run("buffers leading shells then flushes when real content arrives", func(t *testing.T) { + guard := NewGeminiZeroOutputStreamGuard(true, sdktranslator.FormatGemini) + shell := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[]}}]}}`) + if flush, action, _ := guard.Observe(shell); action != GeminiZeroOutputContinue || len(flush) != 0 { + t.Fatalf("shell observe = (%d, %v), want (0, Continue)", len(flush), action) + } + textFrame := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]}}]}}`) + flush, action, _ := guard.Observe(textFrame) + if action != GeminiZeroOutputEmit || len(flush) != 1 { + t.Fatalf("content observe = (%d, %v), want (1, Emit)", len(flush), action) + } + guard.MarkEmitted() + if !guard.Emitted() { + t.Fatal("expected Emitted() = true after MarkEmitted()") + } + if !guard.HasVisibleOutput() { + t.Fatal("expected HasVisibleOutput() = true after real text chunk") + } + if guard.HasAbnormalFinish() { + t.Fatal("expected HasAbnormalFinish() = false for normal text chunk") + } + if finFlush, finAction, _ := guard.Finalize(); finAction != GeminiZeroOutputEmit || len(finFlush) != 0 { + t.Fatalf("Finalize() = (%d, %v), want (0, Emit)", len(finFlush), finAction) + } + }) + + t.Run("discards leading shells and waits for trailing usage on zero-output abnormal finish", func(t *testing.T) { + guard := NewGeminiZeroOutputStreamGuard(false, sdktranslator.FormatOpenAI) + shell := []byte(`{"candidates":[{"content":{"role":"model","parts":[{"text":""}]}}]}`) + if _, action, _ := guard.Observe(shell); action != GeminiZeroOutputContinue { + t.Fatalf("shell action = %v, want Continue", action) + } + abnormal := []byte(`{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_RESPONSE"}]}`) + if flush, action, reason := guard.Observe(abnormal); action != GeminiZeroOutputContinue || len(flush) != 0 || reason != "MALFORMED_RESPONSE" { + t.Fatalf("abnormal without usage = (%d, %v, %q), want (0, Continue, MALFORMED_RESPONSE)", len(flush), action, reason) + } + usageOnly := []byte(`{"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"totalTokenCount":130}}`) + if flush, action, reason := guard.Observe(usageOnly); action != GeminiZeroOutputFailNow || len(flush) != 0 || reason != "MALFORMED_RESPONSE" { + t.Fatalf("usage after abnormal = (%d, %v, %q), want (0, FailNow, MALFORMED_RESPONSE)", len(flush), action, reason) + } + if guard.Emitted() { + t.Fatal("expected Emitted() = false when pre-bootstrap zero-output fails") + } + }) + + t.Run("thought chunk is unbuffered and post-thought malformed claude emits error then fails", func(t *testing.T) { + guard := NewGeminiZeroOutputStreamGuard(false, sdktranslator.FormatClaude) + thought := []byte(`{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"hmm"}]}}]}`) + flush, action, _ := guard.Observe(thought) + if action != GeminiZeroOutputEmit || len(flush) != 0 { + t.Fatalf("thought chunk must emit immediately without buffering: (%d, %v)", len(flush), action) + } + guard.MarkEmitted() + abnormalNoUsage := []byte(`{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`) + if _, action, _ := guard.Observe(abnormalNoUsage); action != GeminiZeroOutputContinue { + t.Fatalf("post-thought abnormal without usage = %v, want Continue awaiting usage", action) + } + if !guard.HasAbnormalFinish() { + t.Fatal("expected HasAbnormalFinish() = true while awaiting trailing usage") + } + if guard.HasVisibleOutput() { + t.Fatal("expected HasVisibleOutput() = false after thought-only chunk") + } + usageOnly := []byte(`{"usageMetadata":{"promptTokenCount":10,"totalTokenCount":10}}`) + _, action, reason := guard.Observe(usageOnly) + if action != GeminiZeroOutputEmitErrorThenFail || reason != "MALFORMED_FUNCTION_CALL" { + t.Fatalf("post-thought claude usage action = (%v, %q), want (EmitErrorThenFail, MALFORMED_FUNCTION_CALL)", action, reason) + } + if len(guard.AbnormalFrame()) == 0 { + t.Fatal("expected retained abnormal frame for split post-thought Claude error emission") + } + }) + + t.Run("preliminary usage on early frame does not short-circuit final usage after abnormal finish", func(t *testing.T) { + guard := NewGeminiZeroOutputStreamGuard(true, sdktranslator.FormatGemini) + earlyShellWithPrelimUsage := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[]}}],"usageMetadata":{"promptTokenCount":120,"totalTokenCount":120}}}`) + if _, action, _ := guard.Observe(earlyShellWithPrelimUsage); action != GeminiZeroOutputContinue { + t.Fatalf("early shell action = %v, want Continue", action) + } + abnormalNoUsage := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}}`) + if _, action, _ := guard.Observe(abnormalNoUsage); action != GeminiZeroOutputContinue { + t.Fatalf("abnormal without usage after preliminary usage = %v, want Continue awaiting final usage", action) + } + finalUsage := []byte(`{"response":{"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443}}}`) + if _, action, reason := guard.Observe(finalUsage); action != GeminiZeroOutputFailNow || reason != "MALFORMED_FUNCTION_CALL" { + t.Fatalf("final usage observe = (%v, %q), want (FailNow, MALFORMED_FUNCTION_CALL)", action, reason) + } + }) + + t.Run("leading thoughtSignature-only empty-text frame buffers and fails on EOF without finishReason", func(t *testing.T) { + guard := NewGeminiZeroOutputStreamGuard(true, sdktranslator.FormatOpenAI) + sigOnly := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"opaque-sig","text":""}]}}],"usageMetadata":{"promptTokenCount":378515,"totalTokenCount":378515},"modelVersion":"gemini-4-hydrogen","responseId":"resp-7536"}}`) + if flush, action, _ := guard.Observe(sigOnly); action != GeminiZeroOutputContinue || len(flush) != 0 { + t.Fatalf("sig-only observe = (%d, %v), want (0, Continue)", len(flush), action) + } + if finFlush, finAction, _ := guard.Finalize(); finAction != GeminiZeroOutputFailNow || len(finFlush) != 0 { + t.Fatalf("Finalize() = (%d, %v), want (0, FailNow)", len(finFlush), finAction) + } + }) + + t.Run("leading thoughtSignature-only empty-text frame flushes when real content follows", func(t *testing.T) { + guard := NewGeminiZeroOutputStreamGuard(true, sdktranslator.FormatOpenAI) + sigOnly := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"opaque-sig","text":""}]}}]}}`) + if flush, action, _ := guard.Observe(sigOnly); action != GeminiZeroOutputContinue || len(flush) != 0 { + t.Fatalf("sig-only observe = (%d, %v), want (0, Continue)", len(flush), action) + } + textFrame := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]}}]}}`) + flush, action, _ := guard.Observe(textFrame) + if action != GeminiZeroOutputEmit || len(flush) != 1 { + t.Fatalf("content observe = (%d, %v), want (1, Emit)", len(flush), action) + } + guard.MarkEmitted() + if finFlush, finAction, _ := guard.Finalize(); finAction != GeminiZeroOutputEmit || len(finFlush) != 0 { + t.Fatalf("Finalize() = (%d, %v), want (0, Emit)", len(finFlush), finAction) + } + }) +} diff --git a/internal/runtime/executor/helps/home_usage_test.go b/internal/runtime/executor/helps/home_usage_test.go new file mode 100644 index 00000000000..acf5ca9b189 --- /dev/null +++ b/internal/runtime/executor/helps/home_usage_test.go @@ -0,0 +1,50 @@ +package helps + +import ( + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" +) + +func TestUsageReporterHomeAdditionalModelAccounting(t *testing.T) { + for _, mode := range []string{"local", "initial", "reused"} { + t.Run(mode, func(t *testing.T) { + ctx := t.Context() + if mode != "local" { + ctx = usage.WithHomeSelection(ctx, usage.HomeSelection{ + Reused: mode == "reused", Model: "route-model", CredentialPolicy: "codex-alpha-search-v1", + }) + } + reporter := NewUsageReporter(ctx, "codex", "text-model", nil) + primary := reporter.buildRecord(usage.Detail{TotalTokens: 12}, false) + image, ok := reporter.buildAdditionalModelRecord("image-model", usage.Detail{TotalTokens: 5}) + if !ok { + t.Fatal("missing image usage") + } + if image.RequestID == "" || image.RequestID == primary.RequestID { + t.Fatal("primary and image usage must retain independent execution IDs") + } + if image.Model != "image-model" || image.Detail.TotalTokens != 5 || primary.Detail.TotalTokens != 12 { + t.Fatal("scheduling metadata changed billable usage") + } + if mode == "local" { + if primary.HomeSelection != nil || image.HomeSelection != nil { + t.Fatal("local execution acquired Home accounting metadata") + } + return + } + if image.HomeSelection == nil || !image.HomeSelection.Additional || image.HomeSelection.Reused != (mode == "reused") { + t.Fatalf("image accounting metadata=%+v", image.HomeSelection) + } + if image.HomeSelection.Model != "route-model" || image.HomeSelection.CredentialPolicy != "codex-alpha-search-v1" { + t.Fatalf("image lost dispatch scope: %+v", image.HomeSelection) + } + if primary.HomeSelection == nil || primary.HomeSelection.Additional || primary.HomeSelection.Reused != (mode == "reused") { + t.Fatalf("image changed primary accounting: %+v", primary.HomeSelection) + } + if usage.HomeSelectionFromContext(ctx).Additional || reporter.buildRecord(usage.Detail{}, false).HomeSelection.Additional { + t.Fatal("image mutated context or reporter metadata") + } + }) + } +} diff --git a/internal/runtime/executor/helps/logging_helpers.go b/internal/runtime/executor/helps/logging_helpers.go index 298d4276bdb..07388988b29 100644 --- a/internal/runtime/executor/helps/logging_helpers.go +++ b/internal/runtime/executor/helps/logging_helpers.go @@ -20,13 +20,15 @@ import ( ) const ( - apiAttemptsKey = "API_UPSTREAM_ATTEMPTS" - apiRequestKey = "API_REQUEST" - apiResponseKey = "API_RESPONSE" - apiWebsocketTimelineKey = "API_WEBSOCKET_TIMELINE" - deferredAPIRequestBytesKey = "DEFERRED_API_REQUEST_BYTES" - creditsUsedKey = "__antigravity_credits_used__" - maxDeferredAPIRequestBodyBytes = 32 << 20 // 32 MiB + apiAttemptsKey = "API_UPSTREAM_ATTEMPTS" + apiRequestKey = "API_REQUEST" + apiResponseKey = "API_RESPONSE" + apiWebsocketTimelineKey = "API_WEBSOCKET_TIMELINE" + deferredAPIRequestBytesKey = "DEFERRED_API_REQUEST_BYTES" + creditsUsedKey = "__antigravity_credits_used__" + maxDeferredAPIRequestBodyBytes = logging.MaxDeferredAPIRequestBodyBytes + maxDeferredAPIResponseBodyBytes = logging.MaxDeferredAPIResponseBodyBytes + maxTotalDeferredAPIResponseBodyBytes = logging.MaxTotalDeferredAPIResponseBodyBytes ) // UpstreamRequestLog captures the outbound upstream request details for logging. @@ -66,18 +68,26 @@ func RecordAPIRequest(ctx context.Context, cfg *config.Config, info UpstreamRequ if cfg == nil || cfg.CommercialMode { return } - // Check the immutable policy before accessing the pooled request context. - if !cfg.RequestLog && logging.DeferredAPIRequestCaptureDisabled(ctx) { + // Check the immutable policy and request-scoped capture before accessing the pooled Gin context. + if !cfg.RequestLog { + if logging.DeferredAPIRequestCaptureDisabled(ctx) { + return + } + if capture := logging.DeferredAPICaptureFromContext(ctx); capture != nil { + deferAPIRequestToCapture(capture, info) + return + } + ginCtx := ginContextFrom(ctx) + if ginCtx == nil { + return + } + deferAPIRequest(ginCtx, info) return } ginCtx := ginContextFrom(ctx) if ginCtx == nil { return } - if !cfg.RequestLog { - deferAPIRequest(ginCtx, info) - return - } attempts := getAttempts(ginCtx) index := len(attempts) + 1 @@ -129,47 +139,135 @@ func RecordAPIRequest(ctx context.Context, cfg *config.Config, info UpstreamRequ } } -func deferAPIRequest(ginCtx *gin.Context, info UpstreamRequestLog) { - if ginCtx == nil { - return - } - var requests []logging.DeferredAPIRequest - if value, exists := ginCtx.Get(logging.DeferredAPIRequestContextKey); exists { - requests, _ = value.([]logging.DeferredAPIRequest) - } - index := len(requests) + 1 - capturedInfo := info - capturedAt := time.Now() - capturedBytes, _ := ginCtx.Get(deferredAPIRequestBytesKey) - bytesUsed, _ := capturedBytes.(int) - remaining := maxDeferredAPIRequestBodyBytes - bytesUsed - if remaining < 0 { - remaining = 0 - } - captureLength := len(info.Body) - if captureLength > remaining { - captureLength = remaining - } - capturedInfo.Body = bytes.Clone(info.Body[:captureLength]) - bodyEmpty := len(info.Body) == 0 - bodyTruncated := captureLength < len(info.Body) - ginCtx.Set(deferredAPIRequestBytesKey, bytesUsed+captureLength) - requests = append(requests, func() []byte { - builder := newAPIRequestLogBuilder(index, capturedInfo, capturedAt) +func buildDeferredAPIRequestCallback(capturedInfo UpstreamRequestLog, index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) logging.DeferredAPIRequest { + reqInfo := capturedInfo + reqInfo.Body = capturedBody + return func() []byte { + builder := newAPIRequestLogBuilder(index, reqInfo, capturedAt) if bodyEmpty { builder.WriteString("") } else { - builder.Write(capturedInfo.Body) + builder.Write(reqInfo.Body) if bodyTruncated { - builder.WriteString(fmt.Sprintf("\n[API REQUEST BODY TRUNCATED: captured first %d bytes]", captureLength)) + builder.WriteString(fmt.Sprintf("\n[API REQUEST BODY TRUNCATED: captured first %d bytes]", len(reqInfo.Body))) } } builder.WriteString("\n\n") return []byte(builder.String()) + } +} + +func deferAPIRequestToCapture(capture *logging.DeferredAPICapture, info UpstreamRequestLog) (logging.DeferredAPIRequest, int, bool) { + capturedInfo := info + return capture.RecordRequest(info.Body, func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) logging.DeferredAPIRequest { + return buildDeferredAPIRequestCallback(capturedInfo, index, capturedAt, capturedBody, bodyEmpty, bodyTruncated) + }) +} + +func deferOrReplacePendingAPIRequest(ctx context.Context, cfg *config.Config, info UpstreamRequestLog) { + if !deferredResponseCaptureEnabled(ctx, cfg) { + return + } + capturedInfo := info + if capture := logging.DeferredAPICaptureFromContext(ctx); capture != nil { + capture.RecordOrReplacePendingRequest(info.Body, func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) logging.DeferredAPIRequest { + return buildDeferredAPIRequestCallback(capturedInfo, index, capturedAt, capturedBody, bodyEmpty, bodyTruncated) + }) + return + } + ginCtx := ginContextFrom(ctx) + if ginCtx == nil { + return + } + capture := deferredResponseCaptureFrom(ginCtx) + fn, bytesUsed, replaced, ok := capture.RecordOrReplacePendingRequest(info.Body, func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) logging.DeferredAPIRequest { + return buildDeferredAPIRequestCallback(capturedInfo, index, capturedAt, capturedBody, bodyEmpty, bodyTruncated) }) + if !ok { + return + } + var requests []logging.DeferredAPIRequest + if value, exists := ginCtx.Get(logging.DeferredAPIRequestContextKey); exists { + requests, _ = value.([]logging.DeferredAPIRequest) + } + if replaced && len(requests) > 0 { + requests[len(requests)-1] = fn + } else { + requests = append(requests, fn) + } + ginCtx.Set(deferredAPIRequestBytesKey, bytesUsed) + ginCtx.Set(logging.DeferredAPIRequestContextKey, requests) +} + +func deferAPIRequest(ginCtx *gin.Context, info UpstreamRequestLog) { + if ginCtx == nil { + return + } + capture := deferredResponseCaptureFrom(ginCtx) + fn, bytesUsed, ok := deferAPIRequestToCapture(capture, info) + if !ok { + return + } + var requests []logging.DeferredAPIRequest + if value, exists := ginCtx.Get(logging.DeferredAPIRequestContextKey); exists { + requests, _ = value.([]logging.DeferredAPIRequest) + } + requests = append(requests, fn) + ginCtx.Set(deferredAPIRequestBytesKey, bytesUsed) ginCtx.Set(logging.DeferredAPIRequestContextKey, requests) } +func deferredResponseCaptureEnabled(ctx context.Context, cfg *config.Config) bool { + if cfg == nil || cfg.CommercialMode || cfg.RequestLog { + return false + } + return !logging.DeferredAPIRequestCaptureDisabled(ctx) +} + +func resolveDeferredAPICapture(ctx context.Context, cfg *config.Config) *logging.DeferredAPICapture { + // Check the immutable policy and request-scoped capture before accessing the pooled Gin context. + if !deferredResponseCaptureEnabled(ctx, cfg) { + return nil + } + if capture := logging.DeferredAPICaptureFromContext(ctx); capture != nil { + return capture + } + ginCtx := ginContextFrom(ctx) + if ginCtx == nil { + return nil + } + return deferredResponseCaptureFrom(ginCtx) +} + +func deferredResponseCaptureFrom(ginCtx *gin.Context) *logging.DeferredAPICapture { + if value, exists := ginCtx.Get(logging.DeferredAPIResponseContextKey); exists { + if capture, ok := value.(*logging.DeferredAPICapture); ok && capture != nil { + return capture + } + } + capture := logging.NewDeferredAPICapture() + ginCtx.Set(logging.DeferredAPIResponseContextKey, capture) + return capture +} + +func recordDeferredResponseMetadata(ctx context.Context, cfg *config.Config, status int, headers http.Header) { + if capture := resolveDeferredAPICapture(ctx, cfg); capture != nil { + capture.RecordResponseMetadata(status, headers) + } +} + +func recordDeferredResponseError(ctx context.Context, cfg *config.Config, err error) { + if capture := resolveDeferredAPICapture(ctx, cfg); capture != nil { + capture.RecordResponseError(err) + } +} + +func appendDeferredResponseChunk(ctx context.Context, cfg *config.Config, chunk []byte) { + if capture := resolveDeferredAPICapture(ctx, cfg); capture != nil { + capture.AppendResponseChunk(chunk) + } +} + func newAPIRequestLogBuilder(index int, info UpstreamRequestLog, timestamp time.Time) *strings.Builder { builder := &strings.Builder{} builder.WriteString(fmt.Sprintf("=== API REQUEST %d ===\n", index)) @@ -195,6 +293,7 @@ func newAPIRequestLogBuilder(index int, info UpstreamRequestLog, timestamp time. func RecordAPIResponseMetadata(ctx context.Context, cfg *config.Config, status int, headers http.Header) { logging.SetResponseHeaders(ctx, headers) if !requestLogCaptureEnabled(cfg) { + recordDeferredResponseMetadata(ctx, cfg, status, headers) return } ginCtx := ginContextFrom(ctx) @@ -222,7 +321,11 @@ func RecordAPIResponseMetadata(ctx context.Context, cfg *config.Config, status i // RecordAPIResponseError adds an error entry for the latest attempt when no HTTP response is available. func RecordAPIResponseError(ctx context.Context, cfg *config.Config, err error) { - if !requestLogCaptureEnabled(cfg) || err == nil { + if err == nil { + return + } + if !requestLogCaptureEnabled(cfg) { + recordDeferredResponseError(ctx, cfg, err) return } ginCtx := ginContextFrom(ctx) @@ -248,6 +351,7 @@ func RecordAPIResponseError(ctx context.Context, cfg *config.Config, err error) // AppendAPIResponseChunk appends an upstream response chunk to Gin context for request logging. func AppendAPIResponseChunk(ctx context.Context, cfg *config.Config, chunk []byte) { if !requestLogCaptureEnabled(cfg) { + appendDeferredResponseChunk(ctx, cfg, chunk) return } data := bytes.TrimSpace(chunk) @@ -291,7 +395,11 @@ func AppendAPIResponseChunk(ctx context.Context, cfg *config.Config, chunk []byt // RecordAPIWebsocketRequest stores an upstream websocket request event in Gin context. func RecordAPIWebsocketRequest(ctx context.Context, cfg *config.Config, info UpstreamRequestLog) { - if !requestLogCaptureEnabled(cfg) { + if cfg == nil || cfg.CommercialMode { + return + } + if !cfg.RequestLog { + RecordAPIRequest(ctx, cfg, info) return } ginCtx := ginContextFrom(ctx) @@ -325,6 +433,7 @@ func RecordAPIWebsocketRequest(ctx context.Context, cfg *config.Config, info Ups func RecordAPIWebsocketHandshake(ctx context.Context, cfg *config.Config, status int, headers http.Header) { logging.SetResponseHeaders(ctx, headers) if !requestLogCaptureEnabled(cfg) { + recordDeferredResponseMetadata(ctx, cfg, status, headers) return } ginCtx := ginContextFrom(ctx) @@ -348,7 +457,17 @@ func RecordAPIWebsocketHandshake(ctx context.Context, cfg *config.Config, status // RecordAPIWebsocketUpgradeRejection stores a rejected websocket upgrade as an HTTP attempt. func RecordAPIWebsocketUpgradeRejection(ctx context.Context, cfg *config.Config, info UpstreamRequestLog, status int, headers http.Header, body []byte) { logging.SetResponseHeaders(ctx, headers) - if !requestLogCaptureEnabled(cfg) { + if cfg == nil || cfg.CommercialMode { + return + } + // Check the immutable policy and request-scoped capture before accessing the pooled Gin context. + if !cfg.RequestLog { + if logging.DeferredAPIRequestCaptureDisabled(ctx) { + return + } + deferOrReplacePendingAPIRequest(ctx, cfg, info) + RecordAPIResponseMetadata(ctx, cfg, status, headers) + AppendAPIResponseChunk(ctx, cfg, body) return } ginCtx := ginContextFrom(ctx) @@ -383,6 +502,7 @@ func WebsocketUpgradeRequestURL(rawURL string) string { // AppendAPIWebsocketResponse stores an upstream websocket response frame in Gin context. func AppendAPIWebsocketResponse(ctx context.Context, cfg *config.Config, payload []byte) { if !requestLogCaptureEnabled(cfg) { + appendDeferredResponseChunk(ctx, cfg, payload) return } data := bytes.TrimSpace(payload) @@ -413,7 +533,15 @@ func AppendCodexAPIWebsocketResponse(ctx context.Context, cfg *config.Config, pa // RecordAPIWebsocketError stores an upstream websocket error event in Gin context. func RecordAPIWebsocketError(ctx context.Context, cfg *config.Config, stage string, err error) { - if !requestLogCaptureEnabled(cfg) || err == nil { + if err == nil { + return + } + if !requestLogCaptureEnabled(cfg) { + stageErr := err + if trimmed := strings.TrimSpace(stage); trimmed != "" { + stageErr = fmt.Errorf("%s: %w", trimmed, err) + } + recordDeferredResponseError(ctx, cfg, stageErr) return } ginCtx := ginContextFrom(ctx) diff --git a/internal/runtime/executor/helps/logging_helpers_test.go b/internal/runtime/executor/helps/logging_helpers_test.go index 607ecea9cd0..78506199ae9 100644 --- a/internal/runtime/executor/helps/logging_helpers_test.go +++ b/internal/runtime/executor/helps/logging_helpers_test.go @@ -1,10 +1,13 @@ package helps import ( + "bytes" "context" "errors" + "fmt" "net/http" "net/http/httptest" + "runtime" "strings" "sync" "testing" @@ -171,6 +174,281 @@ func TestRecordAPIResponseMetadataStoresHeadersWhenRequestLogDisabled(t *testing } } +func TestDeferredAPIResponseCapturedAndAlignedAcrossAttempts(t *testing.T) { + gin.SetMode(gin.TestMode) + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + cfg := &config.Config{} + + // Attempt 1: request recorded, then aborted before any upstream response arrives. + RecordAPIRequest(ctx, cfg, UpstreamRequestLog{ + URL: "https://api.example.com/v1/responses", + Method: http.MethodPost, + Body: []byte(`{"attempt":1}`), + }) + capture := deferredResponseCaptureFrom(ginCtx) + if capture.AttemptCount() != 1 || !capture.AttemptCapturedAt(0).IsZero() { + t.Fatalf("attempt 1 capturedAt = %v, want zero before response arrives", capture.AttemptCapturedAt(0)) + } + if capture.HasPayload() { + t.Fatal("HasPayload = true before any response details were recorded") + } + + // Attempt 2: response metadata, SSE chunks, and read error recorded. + RecordAPIRequest(ctx, cfg, UpstreamRequestLog{ + URL: "https://api.example.com/v1/responses", + Method: http.MethodPost, + Body: []byte(`{"attempt":2}`), + }) + if !capture.AttemptCapturedAt(1).IsZero() { + t.Fatalf("attempt 2 capturedAt = %v, want zero before response event", capture.AttemptCapturedAt(1)) + } + headers := http.Header{ + "Content-Type": []string{"text/event-stream"}, + "Authorization": []string{"Bearer super-secret-upstream-token"}, + "Set-Cookie": []string{"__cf_bm=super-secret-cf-cookie"}, + } + RecordAPIResponseMetadata(ctx, cfg, http.StatusBadGateway, headers) + headers.Set("Content-Type", "text/mutated") + if capture.AttemptCapturedAt(1).IsZero() { + t.Fatal("attempt 2 capturedAt was not stamped on first response event") + } + AppendAPIResponseChunk(ctx, cfg, []byte("event: response.created")) + AppendAPIResponseChunk(ctx, cfg, []byte(`data: {"type":"response.created"}`)) + RecordAPIResponseError(ctx, cfg, errors.New("stream disconnected")) + + // Attempt 3: transport dial error with no HTTP response metadata. + RecordAPIRequest(ctx, cfg, UpstreamRequestLog{ + URL: "https://api.example.com/v1/responses", + Method: http.MethodPost, + Body: []byte(`{"attempt":3}`), + }) + RecordAPIResponseError(ctx, cfg, errors.New("dial tcp timeout")) + + value, exists := ginCtx.Get(logging.DeferredAPIResponseContextKey) + if !exists { + t.Fatal("deferred API response was not stored in Gin context") + } + deferred, ok := value.(logging.DeferredAPIResponse) + if !ok || deferred == nil || !deferred.HasPayload() { + t.Fatalf("deferred API response = %#v, want populated DeferredAPIResponse", value) + } + + rendered := string(deferred.RenderAPIResponse()) + if strings.Contains(rendered, "=== API RESPONSE 1 ===") { + t.Fatalf("attempt 1 had no response content and should not render:\n%s", rendered) + } + for _, want := range []string{ + "=== API RESPONSE 2 ===", + "Status: 502", + "Authorization: Bearer supe...oken", + "Content-Type: text/event-stream", + "event: response.created\ndata: {\"type\":\"response.created\"}", + "Error: stream disconnected\n\n=== API RESPONSE 3 ===", + "Error: dial tcp timeout", + } { + if !strings.Contains(rendered, want) { + t.Fatalf("rendered deferred response missing %q:\n%s", want, rendered) + } + } + for _, secret := range []string{"super-secret-upstream-token", "super-secret-cf-cookie"} { + if strings.Contains(rendered, secret) { + t.Fatalf("rendered deferred response leaked secret %q:\n%s", secret, rendered) + } + } + attempt3Section := rendered[strings.Index(rendered, "=== API RESPONSE 3 ==="):] + if strings.Contains(attempt3Section, "Headers:") { + t.Fatalf("dial error without HTTP response should not fabricate Headers section:\n%s", attempt3Section) + } +} + +func TestDeferredAPIResponseBodyTruncatedAndBoundedAcrossAttempts(t *testing.T) { + gin.SetMode(gin.TestMode) + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + cfg := &config.Config{} + + // Pass a 2 MiB slice to verify truncation copies into a bounded buffer rather + // than retaining the multi-megabyte backing array. + largePayload := bytes.Repeat([]byte("a"), 2<<20) + RecordAPIRequest(ctx, cfg, UpstreamRequestLog{Method: http.MethodPost}) + RecordAPIResponseMetadata(ctx, cfg, http.StatusOK, nil) + AppendAPIResponseChunk(ctx, cfg, largePayload) + + capture := deferredResponseCaptureFrom(ginCtx) + attempt1Len, attempt1Cap, attempt1Truncated := capture.AttemptBodyStats(0) + if attempt1Len != maxDeferredAPIResponseBodyBytes { + t.Fatalf("attempt 1 body len = %d, want %d", attempt1Len, maxDeferredAPIResponseBodyBytes) + } + if attempt1Cap > maxDeferredAPIResponseBodyBytes*2 { + t.Fatalf("attempt 1 body cap = %d, retained oversized backing array", attempt1Cap) + } + if !attempt1Truncated { + t.Fatal("attempt 1 bodyTruncated = false, want true") + } + + maxAttempts := maxTotalDeferredAPIResponseBodyBytes/maxDeferredAPIResponseBodyBytes + 2 + for i := 1; i < maxAttempts; i++ { + RecordAPIRequest(ctx, cfg, UpstreamRequestLog{Method: http.MethodPost}) + RecordAPIResponseMetadata(ctx, cfg, http.StatusOK, nil) + AppendAPIResponseChunk(ctx, cfg, largePayload) + } + if capture.TotalResponseBodyBytes() > maxTotalDeferredAPIResponseBodyBytes { + t.Fatalf("total deferred response bytes = %d, want <= %d", capture.TotalResponseBodyBytes(), maxTotalDeferredAPIResponseBodyBytes) + } + lastLen, _, lastTruncated := capture.AttemptBodyStats(capture.AttemptCount() - 1) + if lastLen != 0 || !lastTruncated { + t.Fatalf("exhausted budget attempt len=%d truncated=%t, want len=0 truncated=true", lastLen, lastTruncated) + } + + rendered := string(capture.RenderAPIResponse()) + wantMarker := fmt.Sprintf("[API RESPONSE BODY TRUNCATED: captured first %d bytes]", maxDeferredAPIResponseBodyBytes) + if !strings.Contains(rendered, wantMarker) { + t.Fatalf("rendered response missing truncation marker %q", wantMarker) + } +} + +func TestDeferredAPIResponseBoundsLargeErrorsHeadersAndRetries(t *testing.T) { + gin.SetMode(gin.TestMode) + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + cfg := &config.Config{} + + giantErr := errors.New(strings.Repeat("e", 2<<20)) + giantHeaders := http.Header{ + "X-Giant-Header": []string{strings.Repeat("h", 256<<10)}, + } + + for range 24 { + RecordAPIRequest(ctx, cfg, UpstreamRequestLog{Method: http.MethodPost}) + RecordAPIResponseMetadata(ctx, cfg, http.StatusBadGateway, giantHeaders) + RecordAPIResponseError(ctx, cfg, giantErr) + } + + capture := deferredResponseCaptureFrom(ginCtx) + rendered := string(capture.RenderAPIResponse()) + if len(rendered) > maxTotalDeferredAPIResponseBodyBytes+(128<<10) { + t.Fatalf("rendered deferred response len = %d, exceeded bounded budget", len(rendered)) + } + if !strings.Contains(rendered, "[API RESPONSE ERROR TRUNCATED:") { + t.Fatalf("rendered deferred response missing error truncation marker:\n%.512s", rendered) + } + + t.Run("hundred thousand short headers do not allocate unbounded header map", func(t *testing.T) { + manyHeaders := make(http.Header, 100_000) + for i := range 100_000 { + manyHeaders[fmt.Sprintf("X-Short-%06d", i)] = []string{"1"} + } + hdrGinCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + hdrCtx := context.WithValue(context.Background(), "gin", hdrGinCtx) + RecordAPIRequest(hdrCtx, cfg, UpstreamRequestLog{Method: http.MethodPost}) + + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + RecordAPIResponseMetadata(hdrCtx, cfg, http.StatusBadGateway, manyHeaders) + runtime.ReadMemStats(&after) + + allocated := after.TotalAlloc - before.TotalAlloc + if allocated > 512<<10 { + t.Fatalf("RecordAPIResponseMetadata allocated %d bytes for 100k short headers, want <= %d", allocated, 512<<10) + } + hdrRendered := string(deferredResponseCaptureFrom(hdrGinCtx).RenderAPIResponse()) + if !strings.Contains(hdrRendered, "[API RESPONSE HEADERS TRUNCATED]") { + t.Fatalf("expected header truncation marker:\n%s", hdrRendered) + } + }) + + t.Run("sixty-five short headers retain first sixty-four sorted entries", func(t *testing.T) { + sixtyFive := make(http.Header, 65) + for i := range 65 { + sixtyFive[fmt.Sprintf("X-Cap-%02d", i)] = []string{fmt.Sprintf("val-%02d", i)} + } + capGinCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + capCtx := context.WithValue(context.Background(), "gin", capGinCtx) + RecordAPIRequest(capCtx, cfg, UpstreamRequestLog{Method: http.MethodPost}) + RecordAPIResponseMetadata(capCtx, cfg, http.StatusBadGateway, sixtyFive) + + capRendered := string(deferredResponseCaptureFrom(capGinCtx).RenderAPIResponse()) + for i := range 64 { + wantLine := fmt.Sprintf("X-Cap-%02d: val-%02d", i, i) + if !strings.Contains(capRendered, wantLine) { + t.Fatalf("rendered headers dropped retained entry %d (%q):\n%s", i, wantLine, capRendered) + } + } + if strings.Contains(capRendered, "X-Cap-64:") { + t.Fatalf("rendered headers unexpectedly retained 65th entry:\n%s", capRendered) + } + if !strings.Contains(capRendered, "[API RESPONSE HEADERS TRUNCATED]") { + t.Fatalf("rendered headers missing truncation marker:\n%s", capRendered) + } + }) +} + +func TestDeferredAPIResponseSkippedWhenFullLogCommercialOrDisabled(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("full request logging uses regular capture only", func(t *testing.T) { + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + cfg := &config.Config{SDKConfig: config.SDKConfig{RequestLog: true}} + + RecordAPIResponseMetadata(ctx, cfg, http.StatusOK, http.Header{"Content-Type": []string{"text/event-stream"}}) + AppendAPIResponseChunk(ctx, cfg, []byte(`data: {"type":"response.created"}`)) + RecordAPIResponseError(ctx, cfg, errors.New("EOF")) + + if _, exists := ginCtx.Get(logging.DeferredAPIResponseContextKey); exists { + t.Fatal("full logging must not populate DeferredAPIResponseContextKey") + } + if _, exists := ginCtx.Get(apiResponseKey); !exists { + t.Fatal("expected regular API_RESPONSE capture") + } + }) + + t.Run("commercial mode retains nothing", func(t *testing.T) { + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + cfg := &config.Config{CommercialMode: true} + + RecordAPIResponseMetadata(ctx, cfg, http.StatusBadGateway, http.Header{"X-Test": []string{"1"}}) + AppendAPIResponseChunk(ctx, cfg, []byte("upstream error")) + RecordAPIResponseError(ctx, cfg, errors.New("boom")) + RecordAPIWebsocketUpgradeRejection(ctx, cfg, UpstreamRequestLog{URL: "https://example.com"}, http.StatusForbidden, nil, []byte("denied")) + + for _, key := range []string{logging.DeferredAPIRequestContextKey, logging.DeferredAPIResponseContextKey, apiResponseKey} { + if _, exists := ginCtx.Get(key); exists { + t.Fatalf("commercial mode retained %s", key) + } + } + }) + + t.Run("disabled policy survives Gin context reuse", func(t *testing.T) { + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + parent := context.WithValue(context.Background(), "gin", ginCtx) + socketCtx, cancel := context.WithCancel(logging.WithDeferredAPIRequestCaptureDisabled(parent)) + cancel() + callbackCtx := context.WithoutCancel(socketCtx) + + RecordAPIRequest(parent, &config.Config{}, UpstreamRequestLog{Body: []byte("new-http-request")}) + RecordAPIResponseMetadata(parent, &config.Config{}, http.StatusBadGateway, nil) + + var callbacks sync.WaitGroup + for range 8 { + callbacks.Go(func() { + RecordAPIResponseMetadata(callbackCtx, &config.Config{}, http.StatusInternalServerError, nil) + AppendAPIResponseChunk(callbackCtx, &config.Config{}, []byte("stale-websocket-chunk")) + RecordAPIResponseError(callbackCtx, &config.Config{}, errors.New("stale-websocket-error")) + RecordAPIWebsocketUpgradeRejection(callbackCtx, &config.Config{}, UpstreamRequestLog{URL: "https://stale.invalid"}, http.StatusForbidden, nil, []byte("stale")) + }) + } + callbacks.Wait() + + rendered := string(deferredResponseCaptureFrom(ginCtx).RenderAPIResponse()) + if strings.Contains(rendered, "stale") { + t.Fatalf("disabled async callbacks polluted reused Gin context:\n%s", rendered) + } + }) +} + func TestAPIResponseAttemptsAreSeparated(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/internal/runtime/executor/helps/model_capabilities.go b/internal/runtime/executor/helps/model_capabilities.go index 24335be931f..4720a0a46f0 100644 --- a/internal/runtime/executor/helps/model_capabilities.go +++ b/internal/runtime/executor/helps/model_capabilities.go @@ -1,6 +1,9 @@ package helps import ( + "fmt" + "strings" + "github.com/MoeForge/moego/ojson" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" @@ -41,10 +44,23 @@ func ApplyRequestThinkingWithModelInfo(body []byte, req cliproxyexecutor.Request source = opts.OriginalRequest } summaryConfig := translatedRequestSummaryConfig(body, req.Payload, originalSource, req.Model, fromFormat, toFormat) + var out []byte + var err error if modelInfo, ok := cliproxyauth.ResolvedModelInfo(req); ok { - return thinking.ApplyThinkingWithModelInfoAndSummary(body, source, req.Model, fromFormat, toFormat, provider, modelInfo, summaryConfig, normalizedUpdatesChanged...) + out, err = thinking.ApplyThinkingWithModelInfoAndSummary(body, source, req.Model, fromFormat, toFormat, provider, modelInfo, summaryConfig, normalizedUpdatesChanged...) + } else { + out, err = thinking.ApplyThinkingWithFallbackModelInfoAndSummary(body, source, req.Model, fromFormat, toFormat, provider, fallbackModelInfo, summaryConfig, normalizedUpdatesChanged...) + } + if err != nil { + return out, err } - return thinking.ApplyThinkingWithFallbackModelInfoAndSummary(body, source, req.Model, fromFormat, toFormat, provider, fallbackModelInfo, summaryConfig, normalizedUpdatesChanged...) + if shouldReconcileClaudeOpenAICompatToolCallReasoning(req, fromFormat, toFormat) && len(out) > 0 { + doc := ojson.NewDoc(out) + if reconcileClaudeOpenAICompatToolCallReasoningDoc(doc) { + out = doc.Bytes() + } + } + return out, nil } // ApplyRequestThinkingWithModelInfoDoc applies request thinking onto doc in place @@ -63,8 +79,66 @@ func ApplyRequestThinkingWithModelInfoDoc(doc *ojson.Doc, req cliproxyexecutor.R source = opts.OriginalRequest } summaryConfig := translatedRequestSummaryConfigDoc(doc, req.Payload, originalSource, req.Model, fromFormat, toFormat) + var err error if modelInfo, ok := cliproxyauth.ResolvedModelInfo(req); ok { - return thinking.ApplyThinkingWithModelInfoAndSummaryDoc(doc, source, req.Model, fromFormat, toFormat, provider, modelInfo, summaryConfig, normalizedUpdatesChanged...) + err = thinking.ApplyThinkingWithModelInfoAndSummaryDoc(doc, source, req.Model, fromFormat, toFormat, provider, modelInfo, summaryConfig, normalizedUpdatesChanged...) + } else { + err = thinking.ApplyThinkingWithFallbackModelInfoAndSummaryDoc(doc, source, req.Model, fromFormat, toFormat, provider, fallbackModelInfo, summaryConfig, normalizedUpdatesChanged...) + } + if err != nil { + return err + } + if shouldReconcileClaudeOpenAICompatToolCallReasoning(req, fromFormat, toFormat) { + reconcileClaudeOpenAICompatToolCallReasoningDoc(doc) + } + return nil +} + +func shouldReconcileClaudeOpenAICompatToolCallReasoning(req cliproxyexecutor.Request, fromFormat, toFormat string) bool { + return APIKeyModelIsCompat(req) && + strings.EqualFold(strings.TrimSpace(fromFormat), "claude") && + strings.EqualFold(strings.TrimSpace(toFormat), "openai") +} + +func reconcileClaudeOpenAICompatToolCallReasoningDoc(doc *ojson.Doc) bool { + if doc == nil || doc.Len() == 0 { + return false + } + messages := doc.Get("messages") + if !messages.Exists() || !messages.IsArray() { + return false + } + reasoningActive := false + if effortRes := doc.Get("reasoning_effort"); effortRes.Exists() { + resolvedEffort := strings.ToLower(strings.TrimSpace(effortRes.String())) + if resolvedEffort != "" && resolvedEffort != string(thinking.LevelNone) && resolvedEffort != "0" && resolvedEffort != "false" { + reasoningActive = true + } + } + + modified := false + for idx, msg := range messages.Array() { + if strings.TrimSpace(msg.Get("role").String()) != "assistant" { + continue + } + toolCalls := msg.Get("tool_calls") + if !toolCalls.Exists() || !toolCalls.IsArray() || len(toolCalls.Array()) == 0 { + continue + } + reasoning := msg.Get("reasoning_content") + if reasoningActive { + if !reasoning.Exists() || (strings.TrimSpace(reasoning.String()) == "" && reasoning.String() != " ") { + if doc.Set(fmt.Sprintf("messages.%d.reasoning_content", idx), " ") == nil { + modified = true + } + } + continue + } + if reasoning.Exists() && strings.TrimSpace(reasoning.String()) == "" { + if doc.Delete(fmt.Sprintf("messages.%d.reasoning_content", idx)) == nil { + modified = true + } + } } - return thinking.ApplyThinkingWithFallbackModelInfoAndSummaryDoc(doc, source, req.Model, fromFormat, toFormat, provider, fallbackModelInfo, summaryConfig, normalizedUpdatesChanged...) + return modified } diff --git a/internal/runtime/executor/helps/model_capabilities_test.go b/internal/runtime/executor/helps/model_capabilities_test.go index ccc39f338b3..01334477e06 100644 --- a/internal/runtime/executor/helps/model_capabilities_test.go +++ b/internal/runtime/executor/helps/model_capabilities_test.go @@ -379,3 +379,125 @@ func TestAPIKeyModelIsCompatUsesAuthoritativeHomeCapabilities(t *testing.T) { } } } + +func TestApplyRequestThinkingReconcilesClaudeOpenAICompatToolCallReasoning(t *testing.T) { + toolCallWithPlaceholder := `{"model":"deepseek-v4-flash","reasoning_effort":"low","messages":[{"role":"assistant","content":"","reasoning_content":" ","tool_calls":[{"id":"call_1","type":"function","function":{"name":"Read","arguments":"{}"}}]}]}` + toolCallWithoutReasoning := `{"model":"deepseek-v4-flash","reasoning_effort":"none","messages":[{"role":"assistant","content":"","tool_calls":[{"id":"call_1","type":"function","function":{"name":"Read","arguments":"{}"}}]}]}` + toolCallWithRealReasoning := `{"model":"deepseek-v4-flash","reasoning_effort":"low","messages":[{"role":"assistant","content":"","reasoning_content":"actual thought","tool_calls":[{"id":"call_1","type":"function","function":{"name":"Read","arguments":"{}"}}]}]}` + + for _, tc := range []struct { + name string + model string + sourceBody string + translated string + fromFormat string + toFormat string + modelInfo *registry.ModelInfo + wantExists bool + wantReasoning string + }{ + { + name: "unsupported thinking model strips reasoning_effort and removes placeholder", + model: "deepseek-v4-flash", + sourceBody: `{"model":"deepseek-v4-flash","thinking":{"type":"enabled","budget_tokens":1024}}`, + translated: toolCallWithPlaceholder, + fromFormat: "claude", + toFormat: "openai", + modelInfo: ®istry.ModelInfo{ + ID: "deepseek-v4-flash", + IsCompat: true, + Thinking: nil, + }, + wantExists: false, + }, + { + name: "model disallowing zero clamps none to active level and injects placeholder", + model: "deepseek-v4-flash", + sourceBody: `{"model":"deepseek-v4-flash","thinking":{"type":"disabled"}}`, + translated: toolCallWithoutReasoning, + fromFormat: "claude", + toFormat: "openai", + modelInfo: ®istry.ModelInfo{ + ID: "deepseek-v4-flash", + IsCompat: true, + Thinking: ®istry.ThinkingSupport{ + Levels: []string{"low", "medium", "high"}, + ZeroAllowed: false, + }, + }, + wantExists: true, + wantReasoning: " ", + }, + { + name: "real reasoning preserved when suffix disables thinking", + model: "deepseek-v4-flash(none)", + sourceBody: `{"model":"deepseek-v4-flash(none)","thinking":{"type":"enabled","budget_tokens":1024}}`, + translated: toolCallWithRealReasoning, + fromFormat: "claude", + toFormat: "openai", + modelInfo: ®istry.ModelInfo{ + ID: "deepseek-v4-flash", + IsCompat: true, + Thinking: ®istry.ThinkingSupport{ + Levels: []string{"none", "low", "medium", "high"}, + ZeroAllowed: true, + }, + }, + wantExists: true, + wantReasoning: "actual thought", + }, + { + name: "non-compat model is untouched", + model: "deepseek-v4-flash(high)", + sourceBody: `{"model":"deepseek-v4-flash(high)","thinking":{"type":"disabled"}}`, + translated: toolCallWithoutReasoning, + fromFormat: "claude", + toFormat: "openai", + modelInfo: ®istry.ModelInfo{ + ID: "deepseek-v4-flash", + IsCompat: false, + Thinking: ®istry.ThinkingSupport{ + Levels: []string{"low", "medium", "high"}, + }, + }, + wantExists: false, + }, + } { + t.Run(tc.name, func(t *testing.T) { + req := cliproxyexecutor.Request{ + Model: tc.model, + Payload: []byte(tc.sourceBody), + Metadata: map[string]any{ + "cliproxy.resolved_api_key_model_info": tc.modelInfo, + }, + } + opts := cliproxyexecutor.Options{ + OriginalRequest: []byte(tc.sourceBody), + } + + outBytes, errBytes := helps.ApplyRequestThinking([]byte(tc.translated), req, opts, tc.fromFormat, tc.toFormat, "openai-compatibility") + if errBytes != nil { + t.Fatalf("ApplyRequestThinking() error = %v", errBytes) + } + gotBytes := ojson.GetBytes(outBytes, "messages.0.reasoning_content") + if gotBytes.Exists() != tc.wantExists { + t.Fatalf("ApplyRequestThinking() reasoning_content exists = %v, want %v; out=%s", gotBytes.Exists(), tc.wantExists, outBytes) + } + if tc.wantExists && gotBytes.String() != tc.wantReasoning { + t.Fatalf("ApplyRequestThinking() reasoning_content = %q, want %q; out=%s", gotBytes.String(), tc.wantReasoning, outBytes) + } + + doc := ojson.NewDocString(tc.translated) + if errDoc := helps.ApplyRequestThinkingDoc(doc, req, opts, tc.fromFormat, tc.toFormat, "openai-compatibility"); errDoc != nil { + t.Fatalf("ApplyRequestThinkingDoc() error = %v", errDoc) + } + gotDoc := doc.Get("messages.0.reasoning_content") + if gotDoc.Exists() != tc.wantExists { + t.Fatalf("ApplyRequestThinkingDoc() reasoning_content exists = %v, want %v; out=%s", gotDoc.Exists(), tc.wantExists, doc.String()) + } + if tc.wantExists && gotDoc.String() != tc.wantReasoning { + t.Fatalf("ApplyRequestThinkingDoc() reasoning_content = %q, want %q; out=%s", gotDoc.String(), tc.wantReasoning, doc.String()) + } + }) + } +} diff --git a/internal/runtime/executor/helps/payload_finalizer.go b/internal/runtime/executor/helps/payload_finalizer.go index a18cd6fdce5..b1d45f20869 100644 --- a/internal/runtime/executor/helps/payload_finalizer.go +++ b/internal/runtime/executor/helps/payload_finalizer.go @@ -9,6 +9,7 @@ import ( "github.com/MoeForge/moego/ojson" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" ) @@ -47,11 +48,15 @@ func (f PayloadFinalizer) FinalizeDoc(doc *ojson.Doc) { } // NewPayloadFinalizer snapshots matching context before built-in request mutations. -func NewPayloadFinalizer(cfg *config.Config, executor, model, protocol, root string, original []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) PayloadFinalizer { +func NewPayloadFinalizer(cfg *config.Config, executor, model, protocol, root string, original []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, auths ...*cliproxyauth.Auth) PayloadFinalizer { requestedModel := PayloadRequestedModel(opts, req.Model) requestPath := PayloadRequestPath(opts) headers := opts.Headers.Clone() source := append([]byte(nil), original...) + var auth *cliproxyauth.Auth + if len(auths) > 0 { + auth = auths[0] + } var formatCallback func(string) if opts.Metadata != nil { formatCallback, _ = opts.Metadata[cliproxyexecutor.FinalizedResponseFormatCallbackMetadataKey].(func(string)) @@ -61,7 +66,7 @@ func NewPayloadFinalizer(cfg *config.Config, executor, model, protocol, root str key := &body[:1][0] if v, ok := payloadDocProbes.LoadAndDelete(key); ok { if doc, okDoc := v.(*ojson.Doc); okDoc && doc != nil { - ApplyPayloadConfigWithRequestForExecutorDoc(cfg, executor, model, protocol, opts.SourceFormat.String(), root, doc, source, requestedModel, requestPath, headers) + applyPayloadConfigWithTrackedPathsForExecutorAndAuthDoc(cfg, executor, model, protocol, opts.SourceFormat.String(), root, doc, source, requestedModel, requestPath, headers, auth) if formatCallback != nil { formatCallback(strings.Clone(strings.TrimSpace(doc.Get(buildPayloadPath(root, "response_format")).String()))) } @@ -69,7 +74,12 @@ func NewPayloadFinalizer(cfg *config.Config, executor, model, protocol, root str return nil } } - out := ApplyPayloadConfigWithRequestForExecutor(cfg, executor, model, protocol, opts.SourceFormat.String(), root, body, source, requestedModel, requestPath, headers) + doc := ojson.NewDoc(body) + _, mutated := applyPayloadConfigWithTrackedPathsForExecutorAndAuthDoc(cfg, executor, model, protocol, opts.SourceFormat.String(), root, doc, source, requestedModel, requestPath, headers, auth) + out := body + if mutated { + out = doc.Bytes() + } if formatCallback != nil { formatCallback(strings.Clone(strings.TrimSpace(ojson.GetBytesNoCopy(out, buildPayloadPath(root, "response_format")).String()))) } diff --git a/internal/runtime/executor/helps/payload_helpers.go b/internal/runtime/executor/helps/payload_helpers.go index b53bafba4e8..f6e4150a3ce 100644 --- a/internal/runtime/executor/helps/payload_helpers.go +++ b/internal/runtime/executor/helps/payload_helpers.go @@ -6,14 +6,24 @@ import ( "reflect" "strconv" "strings" + "sync/atomic" "github.com/MoeForge/moego/ojson" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" ) +var payloadConfigEvaluations atomic.Int64 + +// PayloadConfigEvaluationCount returns the cumulative number of payload rule +// engine evaluations across the process. +func PayloadConfigEvaluationCount() int64 { + return payloadConfigEvaluations.Load() +} + // ApplyPayloadConfigWithRoot behaves like applyPayloadConfig but treats all parameter // paths as relative to the provided root path and restricts matches to the given // protocol when supplied. Defaults are checked @@ -91,6 +101,11 @@ func ApplyPayloadConfigWithTrackedPathsForExecutorDoc(cfg *config.Config, target } func applyPayloadConfigWithTrackedPathsForExecutorDoc(cfg *config.Config, targetExecutor, model, protocol, fromProtocol, root string, doc *ojson.Doc, original []byte, requestedModel, requestPath string, headers http.Header, trackedPaths ...string) (map[string]bool, bool) { + return applyPayloadConfigWithTrackedPathsForExecutorAndAuthDoc(cfg, targetExecutor, model, protocol, fromProtocol, root, doc, original, requestedModel, requestPath, headers, nil, trackedPaths...) +} + +func applyPayloadConfigWithTrackedPathsForExecutorAndAuthDoc(cfg *config.Config, targetExecutor, model, protocol, fromProtocol, root string, doc *ojson.Doc, original []byte, requestedModel, requestPath string, headers http.Header, auth *cliproxyauth.Auth, trackedPaths ...string) (map[string]bool, bool) { + payloadConfigEvaluations.Add(1) touched := make(map[string]bool) if doc == nil || doc.Len() == 0 { return touched, false @@ -133,6 +148,59 @@ func applyPayloadConfigWithTrackedPathsForExecutorDoc(cfg *config.Config, target model = strings.TrimSpace(model) requestedModel = strings.TrimSpace(requestedModel) if model != "" || requestedModel != "" { + toolsPath := buildPayloadPath(root, "tools") + toolChoicePath := buildPayloadPath(root, "tool_choice") + autoInjectedToolIdx := -1 + if isCodexTargetExecutor(targetExecutor) && + cfg.DisableImageGeneration == config.DisableImageGenerationOff && + len(original) > 0 && + !rawToolsContainImageGeneration(original, toolsPath) { + autoInjectedToolIdx = findLastImageGenerationToolIndexDoc(doc, toolsPath) + } + origTools := ojson.GetBytesNoCopy(original, toolsPath) + originalHadEmptyTools := len(original) > 0 && origTools.Exists() && origTools.IsArray() && len(origTools.Array()) == 0 + userWroteToolChoice := false + noteRuleWrite := func(resolvedPath string) { + markTouched(resolvedPath) + if toolChoicePath != "" && payloadRuleTargetsPath(resolvedPath, toolChoicePath) { + userWroteToolChoice = true + return + } + if autoInjectedToolIdx < 0 || toolsPath == "" || !payloadRuleTargetsPath(resolvedPath, toolsPath) { + return + } + if resolvedPath == toolsPath { + autoInjectedToolIdx = -1 + return + } + rest := strings.TrimPrefix(resolvedPath, toolsPath+".") + if idx := strings.IndexByte(rest, '.'); idx >= 0 { + rest = rest[:idx] + } + if elemIdx, errIdx := strconv.Atoi(rest); errIdx == nil && elemIdx == autoInjectedToolIdx { + autoInjectedToolIdx = -1 + } + } + noteRuleDelete := func(resolvedPath string) { + if autoInjectedToolIdx < 0 || toolsPath == "" || !payloadRuleTargetsPath(resolvedPath, toolsPath) { + return + } + if resolvedPath == toolsPath { + autoInjectedToolIdx = -1 + return + } + rest := strings.TrimPrefix(resolvedPath, toolsPath+".") + if strings.Contains(rest, ".") { + return + } + if delIdx, errIdx := strconv.Atoi(rest); errIdx == nil { + if delIdx == autoInjectedToolIdx { + autoInjectedToolIdx = -1 + } else if delIdx >= 0 && delIdx < autoInjectedToolIdx { + autoInjectedToolIdx-- + } + } + } candidates := payloadModelCandidates(model, requestedModel) appliedDefaults := make(map[string]struct{}) var createdByDefault map[string]struct{} @@ -223,7 +291,7 @@ func applyPayloadConfigWithTrackedPathsForExecutorDoc(cfg *config.Config, target } mutated = true appliedDefaults[resolvedPath] = struct{}{} - markTouched(resolvedPath) + noteRuleWrite(resolvedPath) } } } @@ -255,7 +323,7 @@ func applyPayloadConfigWithTrackedPathsForExecutorDoc(cfg *config.Config, target } mutated = true appliedDefaults[resolvedPath] = struct{}{} - markTouched(resolvedPath) + noteRuleWrite(resolvedPath) } } } @@ -276,7 +344,7 @@ func applyPayloadConfigWithTrackedPathsForExecutorDoc(cfg *config.Config, target mutated = true } if applied { - markTouched(resolvedPath) + noteRuleWrite(resolvedPath) } } } @@ -302,7 +370,7 @@ func applyPayloadConfigWithTrackedPathsForExecutorDoc(cfg *config.Config, target mutated = true } if applied { - markTouched(resolvedPath) + noteRuleWrite(resolvedPath) } } } @@ -327,16 +395,126 @@ func applyPayloadConfigWithTrackedPathsForExecutorDoc(cfg *config.Config, target } if existed { mutated = true + noteRuleDelete(resolvedPath) } markTouched(resolvedPath) } } } + if autoInjectedToolIdx >= 0 && !(userWroteToolChoice && docToolChoiceSelectsImageGeneration(doc, toolChoicePath)) { + if codexConfiguredPayloadIncompatibleWithAutoImageGenDoc(doc, root, model, auth, headers) { + if retractAutoInjectedImageGenerationToolAtIndexDoc(doc, toolsPath, autoInjectedToolIdx, originalHadEmptyTools) { + mutated = true + } + } + } } } return touched, mutated } +func findLastImageGenerationToolIndexDoc(doc *ojson.Doc, toolsPath string) int { + if doc == nil { + return -1 + } + tools := doc.Get(toolsPath) + if !tools.Exists() || !tools.IsArray() { + return -1 + } + items := tools.Array() + for idx := len(items) - 1; idx >= 0; idx-- { + if strings.TrimSpace(items[idx].Get("type").String()) == "image_generation" { + return idx + } + } + return -1 +} + +func rawToolsContainImageGeneration(raw []byte, toolsPath string) bool { + if len(raw) == 0 { + return false + } + tools := ojson.GetBytesNoCopy(raw, toolsPath) + if !tools.Exists() || !tools.IsArray() { + return false + } + for _, tool := range tools.Array() { + if strings.TrimSpace(tool.Get("type").String()) == "image_generation" { + return true + } + } + return false +} + +func docToolChoiceSelectsImageGeneration(doc *ojson.Doc, toolChoicePath string) bool { + if doc == nil || toolChoicePath == "" { + return false + } + choice := doc.Get(toolChoicePath) + if !choice.Exists() { + return false + } + if choice.Type == ojson.String { + return strings.EqualFold(strings.TrimSpace(choice.String()), "image_generation") + } + if !choice.IsObject() { + return false + } + switch strings.ToLower(strings.TrimSpace(choice.Get("type").String())) { + case "image_generation": + return true + case "tool": + return strings.EqualFold(strings.TrimSpace(choice.Get("name").String()), "image_generation") + case "allowed_tools": + allowed := choice.Get("tools") + if !allowed.IsArray() { + return false + } + for _, tool := range allowed.Array() { + if strings.EqualFold(strings.TrimSpace(tool.Get("type").String()), "image_generation") { + return true + } + } + } + return false +} + +func codexConfiguredPayloadIncompatibleWithAutoImageGenDoc(doc *ojson.Doc, root, fallbackModel string, auth *cliproxyauth.Auth, headers http.Header) bool { + if doc == nil { + return false + } + configuredModel := strings.TrimSpace(doc.Get(buildPayloadPath(root, "model")).String()) + if configuredModel == "" { + configuredModel = strings.TrimSpace(fallbackModel) + } + modelName := strings.TrimSpace(thinking.ParseSuffix(configuredModel).ModelName) + if CodexResponsesLiteRequestForAuthDoc(doc, modelName, auth, headers) { + return true + } + if strings.HasSuffix(strings.ToLower(modelName), "spark") { + return true + } + return CodexModelUsesResponsesLite(modelName) && CodexRequestHasReasoningForHostedImageDoc(doc, configuredModel) +} + +func retractAutoInjectedImageGenerationToolAtIndexDoc(doc *ojson.Doc, toolsPath string, targetIdx int, originalHadEmptyTools bool) bool { + tools := doc.Get(toolsPath) + if !tools.Exists() || !tools.IsArray() { + return false + } + toolItems := tools.Array() + if targetIdx < 0 || targetIdx >= len(toolItems) { + return false + } + if strings.TrimSpace(toolItems[targetIdx].Get("type").String()) != "image_generation" { + return false + } + if len(toolItems) == 1 && !originalHadEmptyTools { + return doc.Delete(toolsPath) == nil + } + return doc.Delete(toolsPath+"."+strconv.Itoa(targetIdx)) == nil +} + // ApplyPayloadConfigWithRequestTracked applies payload config and reports whether // an applied rule targeted trackedPath or one of its descendants. func ApplyPayloadConfigWithRequestTracked(cfg *config.Config, model, protocol, fromProtocol, root string, payload, original []byte, requestedModel string, requestPath string, headers http.Header, trackedPath string) ([]byte, bool) { diff --git a/internal/runtime/executor/helps/proxy_helpers.go b/internal/runtime/executor/helps/proxy_helpers.go index b0464c633eb..cd725e88a62 100644 --- a/internal/runtime/executor/helps/proxy_helpers.go +++ b/internal/runtime/executor/helps/proxy_helpers.go @@ -460,8 +460,7 @@ func authMetadataString(metadata map[string]any, key string) string { // must bypass the shared cache (zero/negative pool bounds or a fenced config // generation). It uses the kind's own builder so an unpooled uTLS transport keeps // its TLS fingerprint. DisableKeepAlives is always set: no cache owns this transport, -// so any connection left in its idle list would survive until an idle timer fires (or -// forever on a transport built with IdleConnTimeout=0, such as the Claude Code one). +// so any connection left in its idle list would survive until an idle timer fires. func unpooledTransport(build func() (*http.Transport, error)) *http.Transport { tr, errBuild := build() if errBuild != nil { diff --git a/internal/runtime/executor/helps/response_model.go b/internal/runtime/executor/helps/response_model.go index 20b5881d9c3..bd060a463f8 100644 --- a/internal/runtime/executor/helps/response_model.go +++ b/internal/runtime/executor/helps/response_model.go @@ -46,9 +46,28 @@ func extractClaudeResponseModelEvent(data []byte) (model string, terminal bool) } } return "", false + case "content_block_start": + if ojson.GetBytesNoCopy(data, "content_block.type").String() == "fallback" { + m := ojson.GetBytesNoCopy(data, "content_block.to.model") + if m.Type == ojson.String { + s := strings.TrimSpace(m.String()) + if len(s) <= maxResponseModelLength { + return strings.Clone(s), false + } + } + } + return "", false + case "message_delta": + if s := extractClaudeFallbackIterationModel(ojson.GetBytesNoCopy(data, "usage.iterations")); s != "" { + return s, false + } + return "", false case "message_stop": return "", true case "message": + if s := extractClaudeFallbackIterationModel(ojson.GetBytesNoCopy(data, "usage.iterations")); s != "" { + return s, true + } m := ojson.GetBytesNoCopy(data, "model") if m.Type == ojson.String { s := strings.TrimSpace(m.String()) @@ -76,6 +95,30 @@ func extractClaudeResponseModelEvent(data []byte) (model string, terminal bool) } } +func extractClaudeFallbackIterationModel(iterations ojson.Result) string { + if !iterations.Exists() || !iterations.IsArray() { + return "" + } + var served string + for _, it := range iterations.Array() { + if it.Get("type").String() != "fallback_message" { + continue + } + m := it.Get("model") + if m.Type != ojson.String { + continue + } + s := strings.TrimSpace(m.String()) + if s != "" && len(s) <= maxResponseModelLength { + served = s + } + } + if served == "" { + return "" + } + return strings.Clone(served) +} + // extractGeminiResponseModelEvent extracts the response model from a Google Gemini / Vertex / AIStudio response. func extractGeminiResponseModelEvent(data []byte) (model string, terminal bool) { if !ojson.ValidBytes(data) { diff --git a/internal/runtime/executor/helps/response_model_test.go b/internal/runtime/executor/helps/response_model_test.go index d17184add36..6911eb7bdb8 100644 --- a/internal/runtime/executor/helps/response_model_test.go +++ b/internal/runtime/executor/helps/response_model_test.go @@ -478,3 +478,25 @@ func TestExtractResponseModelClonesFromReusableBuffer(t *testing.T) { }) } } + +func TestExtractClaudeResponseModelMidStreamFallback(t *testing.T) { + lines := [][]byte{ + []byte(`data: {"type":"message_start","message":{"id":"msg_1","model":"claude-opus-5-5","usage":{"input_tokens":8,"output_tokens":0}}}`), + []byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"fallback","from":{"model":"claude-opus-5-5"},"to":{"model":"claude-opus-4-8"},"trigger":{"type":"refusal","category":"cyber"}}}`), + []byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":0},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":5}]}}`), + []byte(`data: {"type":"message_stop"}`), + } + + reporter := NewUsageReporter(context.Background(), "claude", "claude-opus-5-5", nil) + var buffer StreamUsageBuffer + for _, line := range lines { + reporter.ObserveResponseModel(line) + buffer.ObserveClaudeStream(line) + } + if got := reporter.ResponseModel(); got != "claude-opus-4-8" { + t.Fatalf("reporter.ResponseModel() = %q, want claude-opus-4-8", got) + } + if got := buffer.ResponseModel(); got != "claude-opus-4-8" { + t.Fatalf("buffer.ResponseModel() = %q, want claude-opus-4-8", got) + } +} diff --git a/internal/runtime/executor/helps/thinking_test.go b/internal/runtime/executor/helps/thinking_test.go index 8e1293f188d..cfcec31be42 100644 --- a/internal/runtime/executor/helps/thinking_test.go +++ b/internal/runtime/executor/helps/thinking_test.go @@ -98,6 +98,38 @@ func TestApplyThinkingWithSourcePayloadPreservesOriginalOnlySummary(t *testing.T } } +func TestApplyThinkingWithSourcePayload_AntigravityClaudeThinkingDisplayUpdates(t *testing.T) { + source := []byte(`{"model":"gemini-3.8-flash-high","max_tokens":4096,"thinking":{"type":"adaptive","display":"updates"},"messages":[{"role":"user","content":"Hello, think first."}]}`) + translated := sdktranslator.TranslateRequest( + sdktranslator.FormatClaude, + sdktranslator.FormatAntigravity, + "gemini-3.8-flash-high", + source, + false, + ) + + out, err := helps.ApplyThinkingWithSourcePayload( + translated, + source, + source, + "gemini-3.8-flash-high", + sdktranslator.FormatClaude.String(), + sdktranslator.FormatAntigravity.String(), + "antigravity", + ) + if err != nil { + t.Fatalf("ApplyThinkingWithSourcePayload() error = %v", err) + } + include := ojson.GetBytes(out, "request.generationConfig.thinkingConfig.includeThoughts") + if !include.Exists() || !include.Bool() { + t.Fatalf("includeThoughts not enabled: %s", out) + } + level := ojson.GetBytes(out, "request.generationConfig.thinkingConfig.thinkingLevel").String() + if level != "high" { + t.Fatalf("thinkingLevel = %q, want high: %s", level, out) + } +} + func TestApplyThinkingWithSourcePayload_AntigravityResponsesReasoningSummaryAuto(t *testing.T) { source := []byte(`{"model":"gemini-3.8-flash-high","reasoning":{"effort":"low","summary":"auto"},"input":"hi"}`) translated := sdktranslator.TranslateRequest( diff --git a/internal/runtime/executor/helps/usage_helpers.go b/internal/runtime/executor/helps/usage_helpers.go index fbff997aae2..8c346c63a3d 100644 --- a/internal/runtime/executor/helps/usage_helpers.go +++ b/internal/runtime/executor/helps/usage_helpers.go @@ -19,6 +19,7 @@ import ( "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" internallogging "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" @@ -32,6 +33,7 @@ type UsageReporter struct { requestID string traceID string selectionID string + homeSelection *usage.HomeSelection provider string baseURL string executorType string @@ -41,6 +43,7 @@ type UsageReporter struct { authIndex string authMu sync.RWMutex accessTokenHash string + requestScopedRules []internalconfig.RequestScopedErrorRule authType string apiKey string accessProvider string @@ -131,6 +134,7 @@ func NewUsageReporter(ctx context.Context, provider, model string, auth *cliprox requestID: uuid.NewString(), traceID: traceID, selectionID: usage.SelectionIDFromContext(ctx), + homeSelection: usage.HomeSelectionFromContext(ctx), provider: provider, baseURL: baseURL, model: model, @@ -152,6 +156,7 @@ func NewUsageReporter(ctx context.Context, provider, model string, auth *cliprox reporter.authID = auth.ID reporter.authIndex = auth.EnsureIndex() reporter.accessTokenHash = authAccessTokenSHA256(auth) + reporter.requestScopedRules = cliproxyauth.ResolveRequestScopedErrorRules(auth, cliproxyauth.RequestScopedErrorConfigFromContext(ctx)) } return reporter } @@ -200,11 +205,27 @@ func (r *UsageReporter) UpdateAccessTokenFingerprint(auth *cliproxyauth.Auth) { if r == nil { return } + var updatedRules []internalconfig.RequestScopedErrorRule + if auth != nil { + updatedRules = cliproxyauth.ResolveRequestScopedErrorRules(auth, nil) + } r.authMu.Lock() r.accessTokenHash = authAccessTokenSHA256(auth) + if len(updatedRules) > 0 { + r.requestScopedRules = updatedRules + } r.authMu.Unlock() } +func (r *UsageReporter) requestScopedErrorRules() []internalconfig.RequestScopedErrorRule { + if r == nil { + return nil + } + r.authMu.RLock() + defer r.authMu.RUnlock() + return r.requestScopedRules +} + func (r *UsageReporter) accessTokenFingerprint() string { if r == nil { return "" @@ -542,15 +563,22 @@ func (r *UsageReporter) buildAdditionalModelRecord(model string, detail usage.De } rec := r.buildRecordForModel(model, detail, false, usage.Failure{}) rec.RequestID = uuid.NewString() + if rec.HomeSelection != nil { + // Split billing details do not represent another scheduled request. + // Mark them separately without changing the primary usage metadata. + selection := *rec.HomeSelection + selection.Additional = true + rec.HomeSelection = &selection + } return rec, true } func (r *UsageReporter) PublishFailure(ctx context.Context, errs ...error) { - r.publishWithOutcome(ctx, usage.Detail{}, true, failFromErrors(errs...)) + r.publishWithOutcome(ctx, usage.Detail{}, true, r.failFromErrors(ctx, errs...)) } func (r *UsageReporter) PublishFailureWithDetail(ctx context.Context, detail usage.Detail, errs ...error) { - r.publishWithOutcome(ctx, detail, true, failFromErrors(errs...)) + r.publishWithOutcome(ctx, detail, true, r.failFromErrors(ctx, errs...)) } func (r *UsageReporter) TrackFailure(ctx context.Context, errPtr *error) { @@ -680,6 +708,7 @@ func (r *UsageReporter) buildRecordForModel(model string, detail usage.Detail, f RequestID: r.requestID, TraceID: r.traceID, SelectionID: r.selectionID, + HomeSelection: r.homeSelection, Provider: r.provider, BaseURL: r.baseURL, ExecutorType: r.executorType, @@ -711,7 +740,15 @@ func (r *UsageReporter) buildRecordForModel(model string, detail usage.Detail, f } } +func (r *UsageReporter) failFromErrors(_ context.Context, errs ...error) usage.Failure { + return failFromErrorsWithRules(r.requestScopedErrorRules(), errs...) +} + func failFromErrors(errs ...error) usage.Failure { + return failFromErrorsWithRules(nil, errs...) +} + +func failFromErrorsWithRules(rules []internalconfig.RequestScopedErrorRule, errs ...error) usage.Failure { for _, err := range errs { if err == nil { continue @@ -732,6 +769,12 @@ func failFromErrors(errs ...error) usage.Failure { } if truncatedErr, ok := errors.AsType[cliproxyexecutor.StreamTruncatedError](err); ok && truncatedErr != nil && truncatedErr.IsStreamTruncated() { fail.Code = usage.FailureStreamTruncatedCode + } else if action, okAction := cliproxyauth.MatchRequestScopedErrorRules(rules, err); okAction { + if action == cliproxyauth.RequestScopedActionStop || action == cliproxyauth.RequestScopedActionContinue { + fail.Code = usage.FailureRequestScopedCode + } else if action == cliproxyauth.RequestScopedActionStopAndCooldown || action == cliproxyauth.RequestScopedActionContinueAndCooldown { + fail.Code = usage.FailureForceCooldownCode + } } else if requestErr, ok := errors.AsType[cliproxyexecutor.RequestScopedError](err); ok && requestErr != nil && requestErr.IsRequestScoped() { fail.Code = usage.FailureRequestScopedCode } @@ -1343,7 +1386,7 @@ func (b *StreamUsageBuffer) ObserveClaudeStream(line []byte) { return } payload := jsonPayload(line) - if b.responseModel == "" && len(payload) > 0 { + if len(payload) > 0 { if model, _ := extractClaudeResponseModelEvent(payload); model != "" { b.responseModel = model } diff --git a/internal/runtime/executor/helps/usage_helpers_test.go b/internal/runtime/executor/helps/usage_helpers_test.go index 386cbe16b4e..f7a871ff137 100644 --- a/internal/runtime/executor/helps/usage_helpers_test.go +++ b/internal/runtime/executor/helps/usage_helpers_test.go @@ -1517,6 +1517,79 @@ func TestFailFromErrorsCarriesRequestScopedCode(t *testing.T) { if plain.Code != "" { t.Fatalf("upstream model rejection gained request-scoped classification: %+v", plain) } + + rules := []config.RequestScopedErrorRule{ + { + Status: http.StatusNotFound, + Match: []string{"model_not_found"}, + Action: cliproxyauth.RequestScopedActionStop, + }, + { + Status: http.StatusBadRequest, + Match: []string{"force_cool_marker"}, + Action: cliproxyauth.RequestScopedActionStopAndCooldown, + }, + } + authWithMetadataRules := &cliproxyauth.Auth{ + ID: "auth-rule-test", + Provider: "codex", + Metadata: map[string]any{"request_scoped_errors": rules}, + } + reporter := NewUsageReporter(context.Background(), "codex", "gpt-5.4", authWithMetadataRules) + var errNotFound error = &cliproxyauth.Error{HTTPStatus: http.StatusNotFound, Message: "model_not_found"} + failMatched := reporter.failFromErrors(context.Background(), errNotFound) + if failMatched.Code != usage.FailureRequestScopedCode || failMatched.StatusCode != http.StatusNotFound { + t.Fatalf("matched request-scoped rule must set fail.Code=%q, got %+v", usage.FailureRequestScopedCode, failMatched) + } + + var errForceCool error = &cliproxyauth.Error{HTTPStatus: http.StatusBadRequest, Message: "force_cool_marker"} + failCooldown := reporter.failFromErrors(context.Background(), errForceCool) + if failCooldown.Code != usage.FailureForceCooldownCode { + t.Fatalf("cooldown action rule must set fail.Code=%q, got %+v", usage.FailureForceCooldownCode, failCooldown) + } + + // A configured cooldown rule must also override an error that intrinsically implements RequestScopedError. + reqScopedForceCool := cliproxyauth.NewRequestScopedError("force_cool_marker", http.StatusBadRequest) + if failOverride := reporter.failFromErrors(context.Background(), reqScopedForceCool); failOverride.Code != usage.FailureForceCooldownCode { + t.Fatalf("cooldown rule must override intrinsic RequestScopedError: got %+v", failOverride) + } + + // Mutating the caller's slice after NewUsageReporter must not affect the reporter's snapshot. + rules[0].Match[0] = "mutated_after_creation" + failIsolated := reporter.failFromErrors(context.Background(), errNotFound) + if failIsolated.Code != usage.FailureRequestScopedCode { + t.Fatalf("reporter rule snapshot was mutated by caller slice modification: %+v", failIsolated) + } + + oauthAuth := &cliproxyauth.Auth{ + ID: "oauth-rule-test", + Provider: "codex", + Attributes: map[string]string{"auth_kind": "oauth"}, + } + cfg := &config.Config{ + OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{ + "codex": { + { + Status: http.StatusNotFound, + Match: []string{"endpoint_unsupported"}, + Action: cliproxyauth.RequestScopedActionContinue, + }, + }, + }, + } + ctxWithCfg := cliproxyauth.WithRequestScopedErrorConfig(context.Background(), cfg) + oauthReporter := NewUsageReporter(ctxWithCfg, "codex", "gpt-5.4", oauthAuth) + // Updating token fingerprint with an OAuth auth that has no per-auth metadata rules + // must preserve the OAuth rules resolved from the context config at reporter creation. + oauthReporter.UpdateAccessTokenFingerprint(&cliproxyauth.Auth{ + ID: "oauth-rule-test", + Provider: "codex", + Attributes: map[string]string{"auth_kind": "oauth", "api_key": "rotated-token"}, + }) + failOAuth := oauthReporter.failFromErrors(ctxWithCfg, &cliproxyauth.Error{HTTPStatus: http.StatusNotFound, Message: "endpoint_unsupported"}) + if failOAuth.Code != usage.FailureRequestScopedCode { + t.Fatalf("OAuth request-scoped rule from context config must set fail.Code=%q after token update, got %+v", usage.FailureRequestScopedCode, failOAuth) + } } func TestParseClaudeUsageExtractsCacheTTLServerToolsIterationsAndCost(t *testing.T) { diff --git a/internal/runtime/executor/helps/utls_client.go b/internal/runtime/executor/helps/utls_client.go index cdf1a63706a..42cf15b6e0b 100644 --- a/internal/runtime/executor/helps/utls_client.go +++ b/internal/runtime/executor/helps/utls_client.go @@ -374,8 +374,15 @@ func newClaudeCodeRoundTripperForDialerAndRoots(dialer proxy.Dialer, roots *x509 // so resumption never crosses proxy boundaries. sessionCache := tls.NewLRUClientSessionCache(claudeCodeSessionCacheCapacity) + // Default to short-lived connections (MaxIdleConnsPerHost < 0) so OAuth and + // unpooled API keys never park idle connections that intermediate NATs or + // transparent proxies may silently drop, while keeping DisableKeepAlives false + // so net/http does not overwrite the native Connection: keep-alive wire header. + // Credentials that explicitly opt into connection-pool override MaxIdleConnsPerHost + // and IdleConnTimeout in pooledTransport. transport := &http.Transport{ - ForceAttemptHTTP2: false, + ForceAttemptHTTP2: false, + MaxIdleConnsPerHost: -1, DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) { var ( conn net.Conn diff --git a/internal/runtime/executor/helps/utls_proxy_pool_test.go b/internal/runtime/executor/helps/utls_proxy_pool_test.go index e5f3ec3fe7a..6eda4370492 100644 --- a/internal/runtime/executor/helps/utls_proxy_pool_test.go +++ b/internal/runtime/executor/helps/utls_proxy_pool_test.go @@ -2,11 +2,15 @@ package helps import ( "context" + gotls "crypto/tls" + "crypto/x509" "io" "net" "net/http" "net/http/httptest" + "net/http/httptrace" "strconv" + "sync" "sync/atomic" "testing" @@ -96,15 +100,147 @@ func TestUtlsAnthropicTransportPoolsPerCredential(t *testing.T) { t.Fatal("max-idle-conns-per-host: 0 must disable keep-alives on the Anthropic transport") } - // Credentials that did not opt in keep the historical shared transport. - plain := func(id string) http.RoundTripper { + // Credentials that did not opt in keep the shared Claude Code transport with + // idle connection pooling disabled, while opted-in credentials enable pooling. + plain := func(id string) *http.Transport { t.Helper() client := NewUtlsHTTPClient(context.Background(), cfg, &cliproxyauth.Auth{ID: id}, 0) - return client.Transport.(*fallbackRoundTripper).anthropicRoundTripper() + tr, ok := client.Transport.(*fallbackRoundTripper).anthropicRoundTripper().(*http.Transport) + if !ok { + t.Fatalf("unpooled anthropic transport = %T, want *http.Transport", client.Transport.(*fallbackRoundTripper).anthropicRoundTripper()) + } + return tr } if plain("key-a") != plain("key-b") { t.Fatal("unpooled credentials must keep sharing the cached Claude Code transport") } + if plain("key-a").MaxIdleConnsPerHost >= 0 { + t.Fatalf("unpooled Claude Code transport MaxIdleConnsPerHost = %d, want < 0 to disable idle connection reuse", plain("key-a").MaxIdleConnsPerHost) + } +} + +// TestUtlsClaudeCodeDefaultDisablesConnectionReusePreservingExplicitPool verifies +// that by default (including OAuth and unpooled API keys) the Claude Code uTLS +// transport closes connections after each request instead of leaving them in an +// idle pool, while an API key that explicitly configures connection-pool still +// reuses its pooled connection. +func TestUtlsClaudeCodeDefaultDisablesConnectionReusePreservingExplicitPool(t *testing.T) { + ResetProxyTransports() + t.Cleanup(ResetProxyTransports) + + certificate := newResumptionTestCertificate(t) + roots := x509.NewCertPool() + roots.AddCert(certificate.Leaf) + + var ( + newConns atomic.Int32 + headerMu sync.Mutex + connHeader []string + ) + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + headerMu.Lock() + connHeader = append(connHeader, r.Header.Get("Connection")) + headerMu.Unlock() + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + server.TLS = &gotls.Config{ + Certificates: []gotls.Certificate{certificate}, + MinVersion: gotls.VersionTLS13, + NextProtos: []string{"http/1.1"}, + } + server.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateNew { + newConns.Add(1) + } + } + server.StartTLS() + defer server.Close() + + serverAddr := server.Listener.Addr().String() + dialer := contextDialerFunc(func(ctx context.Context, network, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, network, serverAddr) + }) + + doTwoRequests := func(t *testing.T, tr *http.Transport) []bool { + t.Helper() + t.Cleanup(tr.CloseIdleConnections) + var ( + mu sync.Mutex + reused []bool + ) + trace := &httptrace.ClientTrace{ + GotConn: func(info httptrace.GotConnInfo) { + mu.Lock() + reused = append(reused, info.Reused) + mu.Unlock() + }, + } + client := &http.Client{Transport: tr} + for i := 0; i < 2; i++ { + req, errReq := http.NewRequestWithContext( + httptrace.WithClientTrace(context.Background(), trace), + http.MethodPost, + "https://api.anthropic.com/v1/messages?beta=true", + nil, + ) + if errReq != nil { + t.Fatalf("NewRequest: %v", errReq) + } + req.Header.Set("Connection", "keep-alive") + resp, errDo := client.Do(req) + if errDo != nil { + t.Fatalf("round %d Do: %v", i+1, errDo) + } + if _, errCopy := io.Copy(io.Discard, resp.Body); errCopy != nil { + t.Fatalf("round %d read body: %v", i+1, errCopy) + } + if errClose := resp.Body.Close(); errClose != nil { + t.Fatalf("round %d close body: %v", i+1, errClose) + } + } + mu.Lock() + defer mu.Unlock() + return append([]bool(nil), reused...) + } + + // 1. Default / OAuth transport: must NOT reuse connections across requests, + // while keeping the wire Connection: keep-alive header intact. + defaultTransport := newClaudeCodeRoundTripperForDialerAndRoots(dialer, roots) + reusedDefault := doTwoRequests(t, defaultTransport) + if got := newConns.Load(); got != 2 { + t.Fatalf("default transport connections = %d, want 2 (reused = %v)", got, reusedDefault) + } + if len(reusedDefault) != 2 || reusedDefault[0] || reusedDefault[1] { + t.Fatalf("default transport GotConn reused = %v, want [false false]", reusedDefault) + } + headerMu.Lock() + gotHeaders := append([]string(nil), connHeader...) + headerMu.Unlock() + for i, h := range gotHeaders { + if h != "keep-alive" { + t.Fatalf("request %d Connection header = %q, want \"keep-alive\"", i+1, h) + } + } + + // 2. Explicit connection-pool opt-in on claude-api-key: MUST still reuse + // connections across requests. + newConns.Store(0) + cfg := testConfig() + pooled, ok := pooledTransport(proxyPoolKindClaudeCode, "direct", cfg, poolOptInAuth("claude-key-pooled"), func() (*http.Transport, error) { + return newClaudeCodeRoundTripperForDialerAndRoots(dialer, roots), nil + }) + if !ok || pooled == nil { + t.Fatal("expected pooled Claude Code transport for opted-in credential") + } + reusedPooled := doTwoRequests(t, pooled) + if got := newConns.Load(); got != 1 { + t.Fatalf("pooled transport connections = %d, want 1 (reused = %v)", got, reusedPooled) + } + if len(reusedPooled) != 2 || reusedPooled[0] || !reusedPooled[1] { + t.Fatalf("pooled transport GotConn reused = %v, want [false true]", reusedPooled) + } } // TestUtlsLazyPoolsDoNotEvictUsedPool pins that a request only populates the pool diff --git a/internal/runtime/executor/issue7513_zero_output_retry_test.go b/internal/runtime/executor/issue7513_zero_output_retry_test.go new file mode 100644 index 00000000000..73e637db4a6 --- /dev/null +++ b/internal/runtime/executor/issue7513_zero_output_retry_test.go @@ -0,0 +1,1299 @@ +package executor + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gorilla/websocket" + internalcache "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/wsrelay" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func issue7513RequestPayload(format sdktranslator.Format, model string, stream bool) []byte { + switch format { + case sdktranslator.FormatGemini: + return []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`) + case sdktranslator.FormatClaude: + if stream { + return []byte(`{"model":"` + model + `","max_tokens":1024,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + } + return []byte(`{"model":"` + model + `","max_tokens":1024,"messages":[{"role":"user","content":"hi"}]}`) + case sdktranslator.FormatOpenAI: + if stream { + return []byte(`{"model":"` + model + `","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + } + return []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]}`) + case sdktranslator.FormatOpenAIResponse: + if stream { + return []byte(`{"model":"` + model + `","stream":true,"input":"hi"}`) + } + return []byte(`{"model":"` + model + `","input":"hi"}`) + default: + return []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`) + } +} + +func TestIssue7513_AntigravityZeroOutputAbnormalFinishReturns502BeforeBootstrap(t *testing.T) { + reasons := []string{"MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "MALFORMED_RESPONSE"} + formats := []sdktranslator.Format{ + sdktranslator.FormatGemini, + sdktranslator.FormatClaude, + sdktranslator.FormatOpenAI, + sdktranslator.FormatOpenAIResponse, + } + + for _, reason := range reasons { + for _, format := range formats { + for _, model := range []string{"gemini-4-hydrogen", "gemini-3-pro"} { + // gemini-3-pro exercises AntigravityExecutor.executeClaudeNonStream in Execute(). + if model == "gemini-3-pro" && format != sdktranslator.FormatClaude && format != sdktranslator.FormatGemini { + continue + } + t.Run(reason+"/"+format.String()+"/"+model, func(t *testing.T) { + body := `{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"` + reason + `"}],"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"` + model + `","responseId":"resp-ag-7513"}}` + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+body+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, body) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: "ag-" + t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + capture := &malformedFunctionCallUsageCapture{authID: auth.ID, records: make(chan usage.Record, 2)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + exec := NewAntigravityExecutor(&config.Config{}) + nonStreamReq := cliproxyexecutor.Request{ + Model: model, + Payload: issue7513RequestPayload(format, model, false), + } + nonStreamOpts := cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + } + _, errExec := exec.Execute(context.Background(), auth, nonStreamReq, nonStreamOpts) + if errExec == nil { + t.Fatalf("Execute() error = nil, want 502 error for %s", reason) + } + status, okStatus := errExec.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("Execute() error = %T %v, want status 502", errExec, errExec) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + + streamReq := cliproxyexecutor.Request{ + Model: model, + Payload: issue7513RequestPayload(format, model, true), + } + streamOpts := cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + Stream: true, + } + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, streamReq, streamOpts) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var emittedPayloads [][]byte + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + if len(bytes.TrimSpace(chunk.Payload)) > 0 { + emittedPayloads = append(emittedPayloads, bytes.Clone(chunk.Payload)) + } + } + if len(emittedPayloads) > 0 { + t.Fatalf("ExecuteStream() emitted %d payload chunk(s) before error, want 0 so readStreamBootstrap does not commit 200: %q", len(emittedPayloads), emittedPayloads) + } + if streamErr == nil { + t.Fatalf("ExecuteStream() chunk.Err = nil, want 502 error for %s", reason) + } + streamStatus, okStreamStatus := streamErr.(interface{ StatusCode() int }) + if !okStreamStatus || streamStatus.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want status 502", streamErr, streamErr) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + }) + } + } + } +} + +func TestIssue7513_AntigravityLeadingEmptyAndSplitUsageZeroOutputReturns502WithoutPayload(t *testing.T) { + leadingEmpty := `{"response":{"candidates":[{"content":{"role":"model","parts":[]}}],"modelVersion":"gemini-4-hydrogen","responseId":"resp-split-7513"}}` + finishChunk := `{"response":{"candidates":[{"content":{"role":"model"},"finishReason":"UNEXPECTED_TOOL_CALL"}],"modelVersion":"gemini-4-hydrogen","responseId":"resp-split-7513"}}` + usageChunk := `{"response":{"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-hydrogen","responseId":"resp-split-7513"}}` + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+leadingEmpty+"\n\ndata: "+finishChunk+"\n\ndata: "+usageChunk+"\n\n") + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + capture := &malformedFunctionCallUsageCapture{authID: auth.ID, records: make(chan usage.Record, 1)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + exec := NewAntigravityExecutor(&config.Config{}) + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-hydrogen", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-4-hydrogen", true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatGemini, + ResponseFormat: sdktranslator.FormatGemini, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + + var emittedPayloads [][]byte + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + if len(bytes.TrimSpace(chunk.Payload)) > 0 { + emittedPayloads = append(emittedPayloads, bytes.Clone(chunk.Payload)) + } + } + if len(emittedPayloads) > 0 { + t.Fatalf("ExecuteStream() emitted %d payload chunk(s), want 0: %q", len(emittedPayloads), emittedPayloads) + } + if streamErr == nil { + t.Fatal("ExecuteStream() chunk.Err = nil, want 502") + } + status, okStatus := streamErr.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want 502", streamErr, streamErr) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) +} + +func issue7513GeminiOrVertexExecutor(t *testing.T, provider, baseURL, authID string) (context.Context, cliproxyauth.ProviderExecutor, *cliproxyauth.Auth) { + t.Helper() + ctx := t.Context() + cfg := &config.Config{} + auth := &cliproxyauth.Auth{ID: authID, Attributes: map[string]string{"api_key": "test-key", "base_url": baseURL}} + switch provider { + case "gemini": + auth.Provider = "gemini" + return ctx, NewGeminiExecutor(cfg), auth + case "vertex_api_key": + auth.Provider = "vertex" + return ctx, NewGeminiVertexExecutor(cfg), auth + case "vertex_service_account": + saRaw := testVertexServiceAccountJSON(t, baseURL+"/token") + saRoot := ojson.ParseBytes(saRaw) + serviceAccount := map[string]any{ + "type": saRoot.Get("type").String(), + "project_id": saRoot.Get("project_id").String(), + "private_key_id": saRoot.Get("private_key_id").String(), + "private_key": saRoot.Get("private_key").String(), + "client_email": saRoot.Get("client_email").String(), + "token_uri": saRoot.Get("token_uri").String(), + } + auth.Provider = "vertex" + auth.Attributes = nil + auth.Metadata = map[string]any{"project_id": "proxy-test", "location": "global", "service_account": serviceAccount} + target, errParse := url.Parse(baseURL) + if errParse != nil { + t.Fatal(errParse) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + t.Cleanup(transport.CloseIdleConnections) + ctx = context.WithValue(ctx, "cliproxy.roundtripper", issue6258RedirectTransport{target: target, base: transport}) + return ctx, NewGeminiVertexExecutor(cfg), auth + default: + t.Fatalf("unknown provider %q", provider) + return nil, nil, nil + } +} + +func TestIssue7513_GeminiVertexAIStudioZeroOutputAbnormalFinishReturns502BeforeBootstrap(t *testing.T) { + reasons := []string{"MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "MALFORMED_RESPONSE"} + formats := []sdktranslator.Format{ + sdktranslator.FormatGemini, + sdktranslator.FormatClaude, + sdktranslator.FormatOpenAI, + sdktranslator.FormatOpenAIResponse, + } + + for _, provider := range []string{"gemini", "vertex_api_key", "vertex_service_account"} { + for _, reason := range reasons { + for _, format := range formats { + t.Run(provider+"/"+reason+"/"+format.String(), func(t *testing.T) { + body := `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"` + reason + `"}],"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-argon","responseId":"resp-7513"}` + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"access_token":"local-token","token_type":"Bearer","expires_in":3600}`) + return + } + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+body+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, body) + })) + defer server.Close() + + ctx, exec, auth := issue7513GeminiOrVertexExecutor(t, provider, server.URL, provider+"-"+reason+"-"+format.String()) + capture := &malformedFunctionCallUsageCapture{authID: auth.ID, records: make(chan usage.Record, 2)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + _, errExec := exec.Execute(ctx, auth, cliproxyexecutor.Request{ + Model: "gemini-4-argon", + Payload: issue7513RequestPayload(format, "gemini-4-argon", false), + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + }) + if errExec == nil { + t.Fatalf("Execute() error = nil, want 502 error for %s", reason) + } + status, okStatus := errExec.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("Execute() error = %T %v, want status 502", errExec, errExec) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + + streamRes, errStream := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{ + Model: "gemini-4-argon", + Payload: issue7513RequestPayload(format, "gemini-4-argon", true), + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var emittedPayloads [][]byte + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + if len(bytes.TrimSpace(chunk.Payload)) > 0 { + emittedPayloads = append(emittedPayloads, bytes.Clone(chunk.Payload)) + } + } + if len(emittedPayloads) > 0 { + t.Fatalf("ExecuteStream() emitted %d payload chunk(s) before error, want 0: %q", len(emittedPayloads), emittedPayloads) + } + if streamErr == nil { + t.Fatalf("ExecuteStream() chunk.Err = nil, want 502 error for %s", reason) + } + streamStatus, okStreamStatus := streamErr.(interface{ StatusCode() int }) + if !okStreamStatus || streamStatus.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want status 502", streamErr, streamErr) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + }) + } + } + } +} + +func TestIssue7513_AIStudioZeroOutputAbnormalFinishReturns502BeforeBootstrap(t *testing.T) { + reasons := []string{"MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "MALFORMED_RESPONSE"} + formats := []sdktranslator.Format{ + sdktranslator.FormatGemini, + sdktranslator.FormatClaude, + sdktranslator.FormatOpenAI, + sdktranslator.FormatOpenAIResponse, + } + + for _, reason := range reasons { + for _, format := range formats { + t.Run(reason+"/"+format.String(), func(t *testing.T) { + malformedBody := `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"` + reason + `"}],"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-argon","responseId":"resp-as-7513"}` + authID := "aistudio-7513-" + reason + "-" + format.String() + connected := make(chan struct{}) + relay := wsrelay.NewManager(wsrelay.Options{ + ProviderFactory: func(*http.Request) (string, error) { return authID, nil }, + OnConnected: func(string) { close(connected) }, + }) + server := httptest.NewServer(relay.Handler()) + defer server.Close() + defer func() { + if errStop := relay.Stop(context.Background()); errStop != nil { + t.Error(errStop) + } + }() + conn, _, errDial := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+relay.Path(), nil) + if errDial != nil { + t.Fatal(errDial) + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Error(errClose) + } + }() + <-connected + + clientDone := make(chan error, 1) + go func() { + for i := 0; i < 3; i++ { + var msg wsrelay.Message + if errReadJSON := conn.ReadJSON(&msg); errReadJSON != nil { + clientDone <- errReadJSON + return + } + var responses []wsrelay.Message + switch i { + case 0, 2: + responses = []wsrelay.Message{{ + ID: msg.ID, + Type: wsrelay.MessageTypeHTTPResp, + Payload: map[string]any{ + "status": float64(http.StatusOK), + "headers": map[string]any{"Content-Type": "application/json"}, + "body": malformedBody, + }, + }} + case 1: + responses = []wsrelay.Message{ + {ID: msg.ID, Type: wsrelay.MessageTypeStreamStart, Payload: map[string]any{"status": 200}}, + {ID: msg.ID, Type: wsrelay.MessageTypeStreamChunk, Payload: map[string]any{"data": "data: " + malformedBody + "\n\n"}}, + {ID: msg.ID, Type: wsrelay.MessageTypeStreamEnd}, + } + } + for _, response := range responses { + if errWriteJSON := conn.WriteJSON(response); errWriteJSON != nil { + clientDone <- errWriteJSON + return + } + } + } + clientDone <- nil + }() + + capture := &malformedFunctionCallUsageCapture{authID: authID, records: make(chan usage.Record, 3)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + exec := NewAIStudioExecutor(&config.Config{}, "aistudio", relay) + auth := &cliproxyauth.Auth{ID: authID, Provider: "aistudio"} + + _, errExec := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-argon", + Payload: issue7513RequestPayload(format, "gemini-4-argon", false), + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + }) + if errExec == nil { + t.Fatalf("Execute() error = nil, want 502 error for %s", reason) + } + status, okStatus := errExec.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("Execute() error = %T %v, want 502", errExec, errExec) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + + for _, mode := range []string{"stream_chunk", "http_resp"} { + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-argon", + Payload: issue7513RequestPayload(format, "gemini-4-argon", true), + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + Stream: true, + }) + if errStream != nil { + t.Fatalf("%s ExecuteStream() error = %v", mode, errStream) + } + var emittedPayloads [][]byte + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + if len(bytes.TrimSpace(chunk.Payload)) > 0 { + emittedPayloads = append(emittedPayloads, bytes.Clone(chunk.Payload)) + } + } + if len(emittedPayloads) > 0 { + t.Fatalf("%s ExecuteStream() emitted %d payload chunk(s), want 0: %q", mode, len(emittedPayloads), emittedPayloads) + } + if streamErr == nil { + t.Fatalf("%s ExecuteStream() chunk.Err = nil, want 502", mode) + } + streamStatus, okStreamStatus := streamErr.(interface{ StatusCode() int }) + if !okStreamStatus || streamStatus.StatusCode() != http.StatusBadGateway { + t.Fatalf("%s ExecuteStream() chunk.Err = %T %v, want 502", mode, streamErr, streamErr) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + } + + if errClient := <-clientDone; errClient != nil { + t.Fatal(errClient) + } + }) + } + } +} + +func TestIssue7513_ZeroOutputGuardsPreserveValidContentAndToolCalls(t *testing.T) { + validToolResp := `{"response":{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"bash","args":{"command":"pwd"}}}]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":5,"totalTokenCount":25},"modelVersion":"gemini-4-hydrogen"}}` + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+validToolResp+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, validToolResp) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + exec := NewAntigravityExecutor(&config.Config{}) + + resp, errExec := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-hydrogen", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-4-hydrogen", false), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatGemini, + ResponseFormat: sdktranslator.FormatGemini, + }) + if errExec != nil { + t.Fatalf("Execute() error = %v, want nil when valid functionCall is present", errExec) + } + if got := ojson.GetBytesNoCopy(resp.Payload, "candidates.0.content.parts.0.functionCall.name").String(); got != "bash" { + t.Fatalf("functionCall.name = %q, want bash; payload=%s", got, resp.Payload) + } + + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-hydrogen", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-4-hydrogen", true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatGemini, + ResponseFormat: sdktranslator.FormatGemini, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var payload bytes.Buffer + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected stream chunk error when valid functionCall is present: %v", chunk.Err) + } + payload.Write(chunk.Payload) + } + if !strings.Contains(payload.String(), `"bash"`) { + t.Fatalf("expected valid functionCall payload, got %s", payload.String()) + } +} + +func TestIssue7513_AntigravityPostThinkingZeroOutputEmitsTerminalError(t *testing.T) { + thoughtChunk := `{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"thinking only"}]}}],"modelVersion":"gemini-4-hydrogen","responseId":"resp-thought-7513"}}` + malformedChunk := `{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"UNEXPECTED_TOOL_CALL"}],"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-hydrogen","responseId":"resp-thought-7513"}}` + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+thoughtChunk+"\n\ndata: "+malformedChunk+"\n\n") + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + capture := &malformedFunctionCallUsageCapture{authID: auth.ID, records: make(chan usage.Record, 1)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + exec := NewAntigravityExecutor(&config.Config{}) + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-hydrogen", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-4-hydrogen", true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatGemini, + ResponseFormat: sdktranslator.FormatGemini, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var combined bytes.Buffer + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + combined.Write(chunk.Payload) + } + if streamErr == nil { + t.Fatalf("ExecuteStream() chunk.Err = nil, want 502 after post-thinking UNEXPECTED_TOOL_CALL; payload=%s", combined.String()) + } + status, okStatus := streamErr.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want 502", streamErr, streamErr) + } + if strings.Contains(combined.String(), "UNEXPECTED_TOOL_CALL") { + t.Fatalf("stream unexpectedly forwarded abnormal terminal frame after post-thinking fault: %s", combined.String()) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) +} + +func TestIssue7513_PostThinkingSplitUsageClaudeEmitsBlockStopAndError(t *testing.T) { + for _, provider := range []string{"antigravity", "gemini"} { + t.Run(provider, func(t *testing.T) { + var frame1, frame2, frame3 string + if provider == "antigravity" { + frame1 = `{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"planning"}]}}],"modelVersion":"gemini-4-hydrogen","responseId":"resp-split-1"}}` + frame2 = `{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"modelVersion":"gemini-4-hydrogen","responseId":"resp-split-1"}}` + frame3 = `{"response":{"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-hydrogen","responseId":"resp-split-1"}}` + } else { + frame1 = `{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"planning"}]}}],"modelVersion":"gemini-4-argon","responseId":"resp-split-1"}` + frame2 = `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"modelVersion":"gemini-4-argon","responseId":"resp-split-1"}` + frame3 = `{"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-argon","responseId":"resp-split-1"}` + } + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+frame1+"\n\ndata: "+frame2+"\n\ndata: "+frame3+"\n\n") + })) + defer server.Close() + + var exec cliproxyauth.ProviderExecutor + var auth *cliproxyauth.Auth + model := "gemini-4-argon" + if provider == "antigravity" { + model = "gemini-4-hydrogen" + exec = NewAntigravityExecutor(&config.Config{}) + auth = &cliproxyauth.Auth{ + ID: "split-ag-" + t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + } else { + exec = NewGeminiExecutor(&config.Config{}) + auth = &cliproxyauth.Auth{ + ID: "split-gem-" + t.Name(), + Provider: "gemini", + Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL}, + } + } + + capture := &malformedFunctionCallUsageCapture{authID: auth.ID, records: make(chan usage.Record, 1)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: model, + Payload: issue7513RequestPayload(sdktranslator.FormatClaude, model, true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + ResponseFormat: sdktranslator.FormatClaude, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + + var combined bytes.Buffer + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + combined.Write(chunk.Payload) + } + if streamErr == nil { + t.Fatalf("ExecuteStream() chunk.Err = nil, want 502; payload=%s", combined.String()) + } + status, okStatus := streamErr.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want 502", streamErr, streamErr) + } + outText := combined.String() + stopIdx := strings.Index(outText, "event: content_block_stop\n") + errIdx := strings.Index(outText, "event: error\n") + if stopIdx < 0 || errIdx < 0 || stopIdx >= errIdx { + t.Fatalf("expected content_block_stop before error event on split post-thought Claude stream:\n%s", outText) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + }) + } +} + +func TestIssue7513_EarlyPreliminaryUsageDoesNotLoseFinalUsageOnZeroOutputFailure(t *testing.T) { + for _, provider := range []string{"antigravity", "gemini"} { + t.Run(provider, func(t *testing.T) { + var frame1, frame2, frame3 string + if provider == "antigravity" { + frame1 = `{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"planning"}]}}],"usageMetadata":{"promptTokenCount":120,"totalTokenCount":120},"modelVersion":"gemini-4-hydrogen","responseId":"resp-prelim-1"}}` + frame2 = `{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"modelVersion":"gemini-4-hydrogen","responseId":"resp-prelim-1"}}` + frame3 = `{"response":{"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-hydrogen","responseId":"resp-prelim-1"}}` + } else { + frame1 = `{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"planning"}]}}],"usageMetadata":{"promptTokenCount":120,"totalTokenCount":120},"modelVersion":"gemini-4-argon","responseId":"resp-prelim-1"}` + frame2 = `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"modelVersion":"gemini-4-argon","responseId":"resp-prelim-1"}` + frame3 = `{"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-argon","responseId":"resp-prelim-1"}` + } + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+frame1+"\n\ndata: "+frame2+"\n\ndata: "+frame3+"\n\n") + })) + defer server.Close() + + var exec cliproxyauth.ProviderExecutor + var auth *cliproxyauth.Auth + model := "gemini-4-argon" + if provider == "antigravity" { + model = "gemini-4-hydrogen" + exec = NewAntigravityExecutor(&config.Config{}) + auth = &cliproxyauth.Auth{ + ID: "prelim-ag-" + t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + } else { + exec = NewGeminiExecutor(&config.Config{}) + auth = &cliproxyauth.Auth{ + ID: "prelim-gem-" + t.Name(), + Provider: "gemini", + Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL}, + } + } + + capture := &malformedFunctionCallUsageCapture{authID: auth.ID, records: make(chan usage.Record, 1)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: model, + Payload: issue7513RequestPayload(sdktranslator.FormatClaude, model, true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + ResponseFormat: sdktranslator.FormatClaude, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + } + } + status, okStatus := streamErr.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want 502", streamErr, streamErr) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + }) + } +} + +func TestIssue7513_EmptyFunctionCallPlaceholderReturns502(t *testing.T) { + for _, provider := range []string{"antigravity", "gemini"} { + t.Run(provider, func(t *testing.T) { + var body string + model := "gemini-4-argon" + if provider == "antigravity" { + model = "gemini-4-hydrogen" + body = `{"response":{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{}}]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":60,"candidatesTokenCount":1,"totalTokenCount":61},"modelVersion":"gemini-4-hydrogen"}}` + } else { + body = `{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{}}]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":60,"candidatesTokenCount":1,"totalTokenCount":61},"modelVersion":"gemini-4-argon"}` + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+body+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, body) + })) + defer server.Close() + + var exec cliproxyauth.ProviderExecutor + var auth *cliproxyauth.Auth + if provider == "antigravity" { + exec = NewAntigravityExecutor(&config.Config{}) + auth = &cliproxyauth.Auth{ + ID: "empty-fc-ag-" + t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + } else { + exec = NewGeminiExecutor(&config.Config{}) + auth = &cliproxyauth.Auth{ + ID: "empty-fc-gem-" + t.Name(), + Provider: "gemini", + Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL}, + } + } + + resp, errExec := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: model, + Payload: issue7513RequestPayload(sdktranslator.FormatClaude, model, false), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + ResponseFormat: sdktranslator.FormatClaude, + }) + if len(resp.Payload) != 0 { + t.Fatalf("Execute() payload = %s, want empty for empty functionCall placeholder", resp.Payload) + } + status, okStatus := errExec.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("Execute() error = %T %v, want 502", errExec, errExec) + } + + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: model, + Payload: issue7513RequestPayload(sdktranslator.FormatClaude, model, true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + ResponseFormat: sdktranslator.FormatClaude, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var chunks []cliproxyexecutor.StreamChunk + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + if len(chunk.Payload) > 0 { + chunks = append(chunks, chunk) + } + } + if len(chunks) != 0 { + t.Fatalf("expected zero pre-bootstrap chunks for empty functionCall placeholder, got %d", len(chunks)) + } + status, okStatus = streamErr.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want 502", streamErr, streamErr) + } + }) + } +} + +func TestIssue7513_PartialVisibleTextWithAbnormalFinishIsPreserved(t *testing.T) { + for _, provider := range []string{"antigravity", "gemini"} { + for _, format := range []sdktranslator.Format{sdktranslator.FormatClaude, sdktranslator.FormatGemini} { + t.Run(provider+"/"+format.String(), func(t *testing.T) { + var nonStreamBody, streamChunk1, streamChunk2 string + model := "gemini-4-argon" + if provider == "antigravity" { + model = "gemini-4-hydrogen" + nonStreamBody = `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":50,"candidatesTokenCount":3,"totalTokenCount":53},"modelVersion":"gemini-4-hydrogen"}}` + streamChunk1 = `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]}}],"modelVersion":"gemini-4-hydrogen"}}` + streamChunk2 = `{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":50,"candidatesTokenCount":3,"totalTokenCount":53},"modelVersion":"gemini-4-hydrogen"}}` + } else { + nonStreamBody = `{"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":50,"candidatesTokenCount":3,"totalTokenCount":53},"modelVersion":"gemini-4-argon"}` + streamChunk1 = `{"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]}}],"modelVersion":"gemini-4-argon"}` + streamChunk2 = `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":50,"candidatesTokenCount":3,"totalTokenCount":53},"modelVersion":"gemini-4-argon"}` + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+streamChunk1+"\n\ndata: "+streamChunk2+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, nonStreamBody) + })) + defer server.Close() + + var exec cliproxyauth.ProviderExecutor + var auth *cliproxyauth.Auth + if provider == "antigravity" { + exec = NewAntigravityExecutor(&config.Config{}) + auth = &cliproxyauth.Auth{ + ID: "partial-ag-" + t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + } else { + exec = NewGeminiExecutor(&config.Config{}) + auth = &cliproxyauth.Auth{ + ID: "partial-gem-" + t.Name(), + Provider: "gemini", + Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL}, + } + } + + resp, errExec := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: model, + Payload: issue7513RequestPayload(format, model, false), + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + }) + if errExec != nil { + t.Fatalf("Execute() error = %v, want nil when partial answer exists", errExec) + } + if !strings.Contains(string(resp.Payload), "partial answer") { + t.Fatalf("Execute() payload missing partial answer: %s", resp.Payload) + } + + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: model, + Payload: issue7513RequestPayload(format, model, true), + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var payload bytes.Buffer + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("ExecuteStream() unexpected err when partial visible output already emitted: %v", chunk.Err) + } + payload.Write(chunk.Payload) + } + if !strings.Contains(payload.String(), "partial answer") { + t.Fatalf("ExecuteStream() payload missing partial answer: %s", payload.String()) + } + if format == sdktranslator.FormatClaude && strings.Contains(payload.String(), "event: error\n") { + t.Fatalf("unexpected Claude error event when partial answer exists: %s", payload.String()) + } + }) + } + } +} + +func TestIssue7513_ThoughtChunkStreamsSynchronouslyBeforeNextChunkForTTFT(t *testing.T) { + firstChunkSent := make(chan struct{}) + releaseSecondChunk := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + flusher, okFlusher := w.(http.Flusher) + _, _ = io.WriteString(w, "data: "+`{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"live thought"}]}}]}}`+"\n\n") + if okFlusher { + flusher.Flush() + } + close(firstChunkSent) + select { + case <-releaseSecondChunk: + case <-r.Context().Done(): + return + } + _, _ = io.WriteString(w, "data: "+`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"final answer"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":2,"totalTokenCount":12}}}`+"\n\n") + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + exec := NewAntigravityExecutor(&config.Config{}) + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-hydrogen", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-4-hydrogen", true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatGemini, + ResponseFormat: sdktranslator.FormatGemini, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + + <-firstChunkSent + select { + case chunk, okChunk := <-streamRes.Chunks: + if !okChunk || chunk.Err != nil { + t.Fatalf("unexpected chunk before second upstream frame: ok=%v err=%v", okChunk, chunk.Err) + } + if !strings.Contains(string(chunk.Payload), "live thought") { + t.Fatalf("first streamed chunk = %s, want live thought", chunk.Payload) + } + case <-time.After(3 * time.Second): + close(releaseSecondChunk) + t.Fatal("thought chunk was buffered instead of streaming immediately for TTFT") + } + close(releaseSecondChunk) + + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected trailing chunk error: %v", chunk.Err) + } + } +} + +func TestIssue7513_ZeroOutputAbnormalFinishDoesNotCommitReasoningReplay(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + t.Cleanup(internalcache.ClearAntigravityReasoningReplayCache) + + sessionKey := "session:replay-zero-output-7513" + body := `{"response":{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"thinking","thoughtSignature":"sig-should-not-cache"}]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":50,"thoughtsTokenCount":10,"totalTokenCount":60},"modelVersion":"gemini-3-flash-agent"}}` + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+body+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, body) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: t.Name(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + exec := NewAntigravityExecutor(&config.Config{}) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatGemini, + ResponseFormat: sdktranslator.FormatGemini, + Metadata: map[string]any{cliproxyexecutor.ExecutionSessionMetadataKey: sessionKey}, + } + + _, errExec := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-3-flash-agent", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-3-flash-agent", false), + }, opts) + if errExec == nil { + t.Fatal("Execute() error = nil, want 502") + } + if items, ok := internalcache.GetAntigravityReasoningReplayItems("gemini-3-flash-agent", sessionKey); ok && len(items) > 0 { + t.Fatalf("non-stream zero-output failure unexpectedly committed replay items: %d", len(items)) + } + + opts.Stream = true + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-3-flash-agent", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-3-flash-agent", true), + }, opts) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + for range streamRes.Chunks { + } + if items, ok := internalcache.GetAntigravityReasoningReplayItems("gemini-3-flash-agent", sessionKey); ok && len(items) > 0 { + t.Fatalf("stream zero-output failure unexpectedly committed replay items: %d", len(items)) + } +} + +func TestIssue7513_AIStudioMixedStreamChunkAndHTTPResp(t *testing.T) { + runRelayEvents := func(t *testing.T, format sdktranslator.Format, events []wsrelay.Message) ([]byte, error) { + t.Helper() + authID := "aistudio-mixed-" + t.Name() + connected := make(chan struct{}) + relay := wsrelay.NewManager(wsrelay.Options{ + ProviderFactory: func(*http.Request) (string, error) { return authID, nil }, + OnConnected: func(string) { close(connected) }, + }) + server := httptest.NewServer(relay.Handler()) + defer server.Close() + defer func() { + if errStop := relay.Stop(context.Background()); errStop != nil { + t.Error(errStop) + } + }() + + conn, _, errDial := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+relay.Path(), nil) + if errDial != nil { + t.Fatalf("dial failed: %v", errDial) + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Error(errClose) + } + }() + <-connected + + reqDone := make(chan error, 1) + go func() { + var first wsrelay.Message + if errRead := conn.ReadJSON(&first); errRead != nil { + reqDone <- errRead + return + } + for _, ev := range events { + ev.ID = first.ID + if errWrite := conn.WriteJSON(ev); errWrite != nil { + reqDone <- errWrite + return + } + } + reqDone <- nil + }() + + exec := NewAIStudioExecutor(&config.Config{}, "aistudio", relay) + auth := &cliproxyauth.Auth{ID: authID, Provider: "aistudio"} + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-argon", + Payload: issue7513RequestPayload(format, "gemini-4-argon", true), + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + if errClient := <-reqDone; errClient != nil { + t.Fatalf("relay client error = %v", errClient) + } + var payload bytes.Buffer + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + payload.Write(chunk.Payload) + } + return payload.Bytes(), streamErr + } + + t.Run("stream_chunk_visible_text_then_http_resp_malformed_preserves_text", func(t *testing.T) { + payload, streamErr := runRelayEvents(t, sdktranslator.FormatGemini, []wsrelay.Message{ + {Type: wsrelay.MessageTypeStreamStart, Payload: map[string]any{"status": float64(http.StatusOK)}}, + {Type: wsrelay.MessageTypeStreamChunk, Payload: map[string]any{"data": `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]}}]}` + "\n\n"}}, + {Type: wsrelay.MessageTypeHTTPResp, Payload: map[string]any{ + "status": float64(http.StatusOK), + "headers": map[string]any{"Content-Type": "application/json"}, + "body": `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":3,"totalTokenCount":23}}`, + }}, + }) + if streamErr != nil { + t.Fatalf("expected preserved partial output with nil error, got %v (payload=%s)", streamErr, payload) + } + if !strings.Contains(string(payload), "partial answer") { + t.Fatalf("expected partial answer in payload, got %s", payload) + } + }) + + t.Run("stream_chunk_visible_text_without_trailing_blank_line_then_http_resp_malformed_preserves_text", func(t *testing.T) { + payload, streamErr := runRelayEvents(t, sdktranslator.FormatGemini, []wsrelay.Message{ + {Type: wsrelay.MessageTypeStreamStart, Payload: map[string]any{"status": float64(http.StatusOK)}}, + {Type: wsrelay.MessageTypeStreamChunk, Payload: map[string]any{"data": `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]}}]}`}}, + {Type: wsrelay.MessageTypeHTTPResp, Payload: map[string]any{ + "status": float64(http.StatusOK), + "headers": map[string]any{"Content-Type": "application/json"}, + "body": `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":3,"totalTokenCount":23}}`, + }}, + }) + if streamErr != nil { + t.Fatalf("expected preserved partial output with nil error, got %v (payload=%s)", streamErr, payload) + } + if !strings.Contains(string(payload), "partial answer") { + t.Fatalf("expected partial answer in payload, got %s", payload) + } + }) + + t.Run("stream_chunk_thought_then_http_resp_malformed_claude_emits_error_and_502", func(t *testing.T) { + payload, streamErr := runRelayEvents(t, sdktranslator.FormatClaude, []wsrelay.Message{ + {Type: wsrelay.MessageTypeStreamStart, Payload: map[string]any{"status": float64(http.StatusOK)}}, + {Type: wsrelay.MessageTypeStreamChunk, Payload: map[string]any{"data": `data: {"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"hmm"}]}}]}` + "\n\n"}}, + {Type: wsrelay.MessageTypeHTTPResp, Payload: map[string]any{ + "status": float64(http.StatusOK), + "headers": map[string]any{"Content-Type": "application/json"}, + "body": `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":20,"thoughtsTokenCount":5,"totalTokenCount":25}}`, + }}, + }) + status, okStatus := streamErr.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("streamErr = %T %v, want 502", streamErr, streamErr) + } + if !strings.Contains(string(payload), "event: error\n") { + t.Fatalf("expected Claude error event in payload, got %s", payload) + } + }) + + t.Run("stream_chunk_empty_shell_then_http_resp_malformed_returns_empty_and_502", func(t *testing.T) { + payload, streamErr := runRelayEvents(t, sdktranslator.FormatOpenAI, []wsrelay.Message{ + {Type: wsrelay.MessageTypeStreamStart, Payload: map[string]any{"status": float64(http.StatusOK)}}, + {Type: wsrelay.MessageTypeStreamChunk, Payload: map[string]any{"data": `data: {"candidates":[{"content":{"role":"model","parts":[]}}]}` + "\n\n"}}, + {Type: wsrelay.MessageTypeHTTPResp, Payload: map[string]any{ + "status": float64(http.StatusOK), + "headers": map[string]any{"Content-Type": "application/json"}, + "body": `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"UNEXPECTED_TOOL_CALL"}],"usageMetadata":{"promptTokenCount":20,"totalTokenCount":20}}`, + }}, + }) + if len(payload) != 0 { + t.Fatalf("expected zero payload before bootstrap failure, got %s", payload) + } + status, okStatus := streamErr.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("streamErr = %T %v, want 502", streamErr, streamErr) + } + }) +} + +func TestIssue7513_ThoughtMediaOnlyWithMalformedResponseReturns502(t *testing.T) { + body := `{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"inlineData":{"mimeType":"image/png","data":"AA=="}}]},"finishReason":"MALFORMED_RESPONSE"}],"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443},"modelVersion":"gemini-4-argon"}` + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+`{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"inlineData":{"mimeType":"image/png","data":"AA=="}}]}}]}`+"\n\ndata: "+`{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_RESPONSE"}],"usageMetadata":{"promptTokenCount":120,"candidatesTokenCount":10,"thoughtsTokenCount":313,"totalTokenCount":443}}`+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, body) + })) + defer server.Close() + + ctx, exec, auth := issue7513GeminiOrVertexExecutor(t, "gemini", server.URL, "gemini-thought-media-7513") + capture := &malformedFunctionCallUsageCapture{authID: auth.ID, records: make(chan usage.Record, 2)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + resp, errExec := exec.Execute(ctx, auth, cliproxyexecutor.Request{ + Model: "gemini-4-argon", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-4-argon", false), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatGemini, + ResponseFormat: sdktranslator.FormatGemini, + }) + if len(resp.Payload) != 0 { + t.Fatalf("Execute() payload = %s, want empty when only thought media returned", resp.Payload) + } + status, okStatus := errExec.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("Execute() error = %T %v, want 502", errExec, errExec) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) + + streamRes, errStream := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{ + Model: "gemini-4-argon", + Payload: issue7513RequestPayload(sdktranslator.FormatGemini, "gemini-4-argon", true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatGemini, + ResponseFormat: sdktranslator.FormatGemini, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + } + } + status, okStatus = streamErr.(interface{ StatusCode() int }) + if !okStatus || status.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want 502", streamErr, streamErr) + } + assertMalformedFunctionCallFailedUsage(t, capture.records) +} diff --git a/internal/runtime/executor/issue7536_zero_output_stream_test.go b/internal/runtime/executor/issue7536_zero_output_stream_test.go new file mode 100644 index 00000000000..8c24f0f6b01 --- /dev/null +++ b/internal/runtime/executor/issue7536_zero_output_stream_test.go @@ -0,0 +1,169 @@ +package executor + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + internalcache "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestIssue7536_AntigravitySignatureOnlyZeroOutputWithoutFinishReasonFails502BeforeBootstrap(t *testing.T) { + internalcache.ClearAntigravityReasoningReplayCache() + t.Cleanup(internalcache.ClearAntigravityReasoningReplayCache) + + variants := []struct { + name string + part string + }{ + { + name: "non_thought_signature_only_empty_text", + part: `{"thoughtSignature":"opaque-sig-7536","text":""}`, + }, + { + name: "thought_flag_signature_only_empty_text", + part: `{"thought":true,"thoughtSignature":"opaque-sig-7536","text":""}`, + }, + } + + formats := []sdktranslator.Format{ + sdktranslator.FormatOpenAI, + sdktranslator.FormatClaude, + sdktranslator.FormatGemini, + sdktranslator.FormatOpenAIResponse, + } + + for _, variant := range variants { + for _, format := range formats { + t.Run(variant.name+"/"+format.String(), func(t *testing.T) { + sse := `data: {"response":{"candidates":[{"content":{"role":"model","parts":[` + variant.part + `]}}],"usageMetadata":{"promptTokenCount":378515,"cachedContentTokenCount":376466,"totalTokenCount":378515},"modelVersion":"gemini-4-hydrogen","responseId":"resp-7536"},"traceId":"trace-7536","metadata":{}}` + "\n\n" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, sse) + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: "ag-7536-" + variant.name + "-" + format.String(), + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + capture := &malformedFunctionCallUsageCapture{authID: auth.ID, records: make(chan usage.Record, 1)} + usage.RegisterNamedPlugin(t.Name(), capture) + t.Cleanup(func() { + usage.RegisterNamedPlugin(t.Name(), malformedFunctionCallUsageNoop{}) + }) + + exec := NewAntigravityExecutor(&config.Config{}) + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-hydrogen", + Payload: issue7513RequestPayload(format, "gemini-4-hydrogen", true), + Metadata: map[string]any{"session_id": "sess-7536"}, + }, cliproxyexecutor.Options{ + SourceFormat: format, + ResponseFormat: format, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + + var emittedPayloads [][]byte + var streamErr error + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + streamErr = chunk.Err + continue + } + if len(bytes.TrimSpace(chunk.Payload)) > 0 { + emittedPayloads = append(emittedPayloads, bytes.Clone(chunk.Payload)) + } + } + if len(emittedPayloads) > 0 { + t.Fatalf("ExecuteStream() emitted %d payload chunk(s) before error, want 0 so readStreamBootstrap does not commit 200: %q", len(emittedPayloads), emittedPayloads) + } + if streamErr == nil { + t.Fatal("ExecuteStream() chunk.Err = nil, want 502 error") + } + streamStatus, okStatus := streamErr.(interface{ StatusCode() int }) + if !okStatus || streamStatus.StatusCode() != http.StatusBadGateway { + t.Fatalf("ExecuteStream() chunk.Err = %T %v, want status 502", streamErr, streamErr) + } + var record usage.Record + select { + case record = <-capture.records: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for usage record") + } + if !record.Failed { + t.Fatalf("usage record Failed = false, want true; record=%+v", record) + } + if record.Detail.InputTokens != 378515 || record.Detail.CachedTokens != 376466 || record.Detail.OutputTokens != 0 || record.Detail.ReasoningTokens != 0 || record.Detail.TotalTokens != 378515 { + t.Fatalf("usage detail = %+v, want Input=378515 Cached=376466 Output=0 Reasoning=0 Total=378515", record.Detail) + } + if items, ok := internalcache.GetAntigravityReasoningReplayItems("gemini-4-hydrogen", "sess-7536"); ok || len(items) != 0 { + t.Fatalf("expected no reasoning replay items committed, got %v", items) + } + }) + } + } +} + +func TestIssue7536_AntigravityLeadingSignatureOnlyFollowedByVisibleContentSucceeds(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"opaque-sig-7536","text":""}]}}],"modelVersion":"gemini-4-hydrogen","responseId":"resp-7536-ok"}}`+"\n\n") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"recovered answer"}]}}],"usageMetadata":{"promptTokenCount":100,"candidatesTokenCount":5,"totalTokenCount":105},"modelVersion":"gemini-4-hydrogen","responseId":"resp-7536-ok"}}`+"\n\n") + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + ID: "ag-7536-follow-ok", + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "token-123", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-1", + }, + Attributes: map[string]string{"base_url": server.URL}, + } + exec := NewAntigravityExecutor(&config.Config{}) + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "gemini-4-hydrogen", + Payload: issue7513RequestPayload(sdktranslator.FormatOpenAI, "gemini-4-hydrogen", true), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + Stream: true, + }) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + + var combined bytes.Buffer + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("unexpected stream error: %v", chunk.Err) + } + combined.Write(chunk.Payload) + } + out := combined.String() + if !strings.Contains(out, "recovered answer") || !strings.Contains(out, `"finish_reason":"stop"`) { + t.Fatalf("expected recovered answer and finish_reason stop, got: %s", out) + } +} diff --git a/internal/runtime/executor/kimi_executor.go b/internal/runtime/executor/kimi_executor.go index d0b0cd468b3..6b913a0e515 100644 --- a/internal/runtime/executor/kimi_executor.go +++ b/internal/runtime/executor/kimi_executor.go @@ -42,6 +42,7 @@ func NewKimiExecutor(cfg *config.Config) *KimiExecutor { requestLogProvider: "kimi", upstreamModelNormalizer: normalizeKimiUpstreamModel, oauthToolAliases: &claudeOAuthToolAliasStore{}, + threadBetas: &helps.ClaudeThreadBetaStore{}, }, cfg: cfg, } @@ -210,18 +211,21 @@ func (e *KimiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) err = statusErr{code: httpResp.StatusCode, msg: string(b)} return resp, err } data, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) reporter.ObserveResponseModel(data) var param any // Note: TranslateNonStream uses req.Model (original with suffix) to preserve @@ -345,8 +349,11 @@ func (e *KimiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut } helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("kimi executor: close response body error: %v", errClose) @@ -507,19 +514,22 @@ func (e *KimiExecutor) executeResponses(ctx context.Context, auth *cliproxyauth. helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) err = statusErr{code: httpResp.StatusCode, msg: string(b)} return resp, err } data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) reporter.ObserveResponseModel(data) originalRequest := req.Payload @@ -633,11 +643,14 @@ func (e *KimiExecutor) executeResponsesStream(ctx context.Context, auth *cliprox helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("kimi executor: close response body error: %v", errClose) } helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) err = statusErr{code: httpResp.StatusCode, msg: string(b)} return nil, err diff --git a/internal/runtime/executor/meta_executor_execute.go b/internal/runtime/executor/meta_executor_execute.go index ed7e98095be..b08b534358c 100644 --- a/internal/runtime/executor/meta_executor_execute.go +++ b/internal/runtime/executor/meta_executor_execute.go @@ -46,7 +46,14 @@ func (e *MetaExecutor) prepareResponsesRequest(ctx context.Context, auth *clipro isCompat := helps.APIKeyModelIsCompat(req) targetModel := resolveMetaSignatureTargetModel(baseModel, req, opts) originalTranslated := helps.TranslateRequestWithAPIKeyModelCompatibility(ctx, opts.Headers, e.cfg, from, to, targetModel, originalPayload, stream, isCompat) - originalTranslated = helps.SetStringIfDifferent(originalTranslated, "model", baseModel) + origDoc := ojson.NewDoc(originalTranslated) + origChanged := helps.SetStringIfDifferentDoc(origDoc, "model", baseModel) + if syncMetaPromptCacheRetentionDoc(origDoc, originalPayload) { + origChanged = true + } + if origChanged { + originalTranslated = origDoc.Bytes() + } body, err := helps.TranslateRequestReturningError(ctx, opts.Headers, e.cfg, from, to, targetModel, bytes.Clone(req.Payload), stream, isCompat) if err != nil { return nil, err @@ -62,7 +69,7 @@ func (e *MetaExecutor) prepareResponsesRequest(ctx context.Context, auth *clipro helps.SetStringIfDifferentDoc(doc, "model", baseModel) helps.SetBoolIfDifferentDoc(doc, "stream", stream) _ = doc.Delete("generate") - _ = doc.Delete("prompt_cache_retention") + syncMetaPromptCacheRetentionDoc(doc, req.Payload) _ = doc.Delete("safety_identifier") _ = doc.Delete("stream_options") _ = doc.Delete("client_metadata") @@ -95,6 +102,33 @@ func (e *MetaExecutor) prepareResponsesRequest(ctx context.Context, auth *clipro }, nil } +// syncMetaPromptCacheRetentionDoc preserves an explicit non-empty string +// prompt_cache_retention supplied by the caller without injecting a default, +// and removes null, blank, or non-string values before user payload rules run. +func syncMetaPromptCacheRetentionDoc(doc *ojson.Doc, source []byte) bool { + if doc == nil { + return false + } + if retention := extractMetaPromptCacheRetention(source); retention != "" { + return helps.SetStringIfDifferentDoc(doc, "prompt_cache_retention", retention) + } + if !doc.Get("prompt_cache_retention").Exists() { + return false + } + return doc.Delete("prompt_cache_retention") == nil +} + +func extractMetaPromptCacheRetention(source []byte) string { + if len(source) == 0 { + return "" + } + val := ojson.GetBytesNoCopy(source, "prompt_cache_retention") + if val.Type != ojson.String { + return "" + } + return strings.TrimSpace(val.String()) +} + func (e *MetaExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { ctx = helps.EnsureSessionContext(ctx, opts, req.Payload) if opts.Alt == "responses/compact" { @@ -149,11 +183,11 @@ func (e *MetaExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) reporter.ObserveResponseModel(data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) diff --git a/internal/runtime/executor/meta_executor_stream.go b/internal/runtime/executor/meta_executor_stream.go index af94e144ccd..ff439c3160a 100644 --- a/internal/runtime/executor/meta_executor_stream.go +++ b/internal/runtime/executor/meta_executor_stream.go @@ -68,11 +68,11 @@ func (e *MetaExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Aut if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("meta executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return nil, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) return nil, wrapMetaUpstreamError(httpResp.StatusCode, data) } diff --git a/internal/runtime/executor/meta_executor_test.go b/internal/runtime/executor/meta_executor_test.go index 55d9f03361d..8b7f3a28801 100644 --- a/internal/runtime/executor/meta_executor_test.go +++ b/internal/runtime/executor/meta_executor_test.go @@ -2247,3 +2247,207 @@ func TestMetaExecutor_ResponsesCompactionTriggerAndReplay_Issue6781(t *testing.T } assertStatusErr(t, errIncStream, http.StatusBadGateway) } + +func TestMetaExecutor_PromptCacheRetentionPassthrough_Issue7424(t *testing.T) { + var gotBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read request body: %v", errRead) + http.Error(w, "bad body", http.StatusBadRequest) + return + } + gotBody = bytes.Clone(body) + writeMetaResponsesOK(w, "ok") + })) + defer server.Close() + + auth := &cliproxyauth.Auth{ + Provider: "meta", + Attributes: map[string]string{ + "api_key": "meta-token", + "base_url": server.URL, + }, + } + + runBothModes := func(t *testing.T, exec *MetaExecutor, format, payload string) [][]byte { + t.Helper() + raw := []byte(payload) + var bodies [][]byte + + gotBody = nil + _, errExec := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "muse-ember-1.0", + Payload: raw, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString(format), + OriginalRequest: raw, + }) + if errExec != nil { + t.Fatalf("Execute(%s) error = %v", format, errExec) + } + bodies = append(bodies, bytes.Clone(gotBody)) + + gotBody = nil + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{ + Model: "muse-ember-1.0", + Payload: raw, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FromString(format), + Stream: true, + OriginalRequest: raw, + }) + if errStream != nil { + t.Fatalf("ExecuteStream(%s) error = %v", format, errStream) + } + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("ExecuteStream(%s) chunk error = %v", format, chunk.Err) + } + } + bodies = append(bodies, bytes.Clone(gotBody)) + return bodies + } + + t.Run("omitted or blank values are not sent and never default to 24h", func(t *testing.T) { + exec := NewMetaExecutor(&config.Config{}) + cases := []struct { + name string + format string + payload string + }{ + { + name: "responses omitted", + format: "openai-response", + payload: `{"model":"muse-ember-1.0","input":"hello"}`, + }, + { + name: "responses null", + format: "openai-response", + payload: `{"model":"muse-ember-1.0","prompt_cache_retention":null,"input":"hello"}`, + }, + { + name: "responses blank", + format: "openai-response", + payload: `{"model":"muse-ember-1.0","prompt_cache_retention":" ","input":"hello"}`, + }, + { + name: "chat completions omitted", + format: "openai", + payload: `{"model":"muse-ember-1.0","messages":[{"role":"user","content":"hello"}]}`, + }, + { + name: "codex null", + format: "codex", + payload: `{"model":"muse-ember-1.0","prompt_cache_retention":null,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}]}`, + }, + { + name: "codex non-string", + format: "codex", + payload: `{"model":"muse-ember-1.0","prompt_cache_retention":24,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}]}`, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + for idx, body := range runBothModes(t, exec, tc.format, tc.payload) { + if ojson.GetBytes(body, "prompt_cache_retention").Exists() { + t.Fatalf("mode %d unexpectedly sent prompt_cache_retention: %s", idx, body) + } + } + }) + } + }) + + t.Run("explicit client prompt_cache_retention passes through", func(t *testing.T) { + exec := NewMetaExecutor(&config.Config{}) + cases := []struct { + name string + format string + payload string + want string + }{ + { + name: "responses 24h", + format: "openai-response", + payload: `{"model":"muse-ember-1.0","prompt_cache_retention":"24h","input":"hello"}`, + want: "24h", + }, + { + name: "responses in_memory", + format: "openai-response", + payload: `{"model":"muse-ember-1.0","prompt_cache_retention":"in_memory","input":"hello"}`, + want: "in_memory", + }, + { + name: "chat completions 24h", + format: "openai", + payload: `{"model":"muse-ember-1.0","prompt_cache_retention":"24h","messages":[{"role":"user","content":"hello"}]}`, + want: "24h", + }, + { + name: "codex 24h", + format: "codex", + payload: `{"model":"muse-ember-1.0","prompt_cache_retention":"24h","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}]}`, + want: "24h", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + for idx, body := range runBothModes(t, exec, tc.format, tc.payload) { + if got := ojson.GetBytes(body, "prompt_cache_retention").String(); got != tc.want { + t.Fatalf("mode %d prompt_cache_retention = %q, want %q; body=%s", idx, got, tc.want, body) + } + } + }) + } + }) + + t.Run("payload rules remain final semantic barrier", func(t *testing.T) { + defaultExec := NewMetaExecutor(&config.Config{ + Payload: config.PayloadConfig{ + Default: []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "muse-*", Protocol: "meta"}}, + Params: map[string]any{"prompt_cache_retention": "24h"}, + }}, + }, + }) + for idx, body := range runBothModes(t, defaultExec, "openai-response", `{"model":"muse-ember-1.0","input":"hello"}`) { + if got := ojson.GetBytes(body, "prompt_cache_retention").String(); got != "24h" { + t.Fatalf("default rule on omitted field mode %d = %q, want 24h; body=%s", idx, got, body) + } + } + for idx, body := range runBothModes(t, defaultExec, "openai-response", `{"model":"muse-ember-1.0","prompt_cache_retention":"in_memory","input":"hello"}`) { + if got := ojson.GetBytes(body, "prompt_cache_retention").String(); got != "in_memory" { + t.Fatalf("default rule overwrote explicit client in_memory in mode %d: got %q; body=%s", idx, got, body) + } + } + + overrideExec := NewMetaExecutor(&config.Config{ + Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "muse-*", Protocol: "meta"}}, + Params: map[string]any{"prompt_cache_retention": "24h"}, + }}, + }, + }) + for idx, body := range runBothModes(t, overrideExec, "openai-response", `{"model":"muse-ember-1.0","prompt_cache_retention":"in_memory","input":"hello"}`) { + if got := ojson.GetBytes(body, "prompt_cache_retention").String(); got != "24h" { + t.Fatalf("override rule mode %d = %q, want 24h; body=%s", idx, got, body) + } + } + + filterExec := NewMetaExecutor(&config.Config{ + Payload: config.PayloadConfig{ + Filter: []config.PayloadFilterRule{{ + Models: []config.PayloadModelRule{{Name: "muse-*", Protocol: "meta"}}, + Params: []string{"prompt_cache_retention"}, + }}, + }, + }) + for idx, body := range runBothModes(t, filterExec, "openai-response", `{"model":"muse-ember-1.0","prompt_cache_retention":"24h","input":"hello"}`) { + if ojson.GetBytes(body, "prompt_cache_retention").Exists() { + t.Fatalf("filter rule failed to remove prompt_cache_retention in mode %d: %s", idx, body) + } + } + }) +} diff --git a/internal/runtime/executor/openai_compat_executor.go b/internal/runtime/executor/openai_compat_executor.go index 17a06945a8a..1cfe5a49eb4 100644 --- a/internal/runtime/executor/openai_compat_executor.go +++ b/internal/runtime/executor/openai_compat_executor.go @@ -230,18 +230,21 @@ func (e *OpenAICompatExecutor) executeWithCredentials(ctx context.Context, auth }() helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) err = newOpenAICompatStatusError(httpResp.StatusCode, httpResp.Header, b) return resp, err } body, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, body) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, body) reporter.ObserveResponseModel(body) // Ensure we at least record the request even if upstream doesn't return usage // Translate response back to source format when needed @@ -332,12 +335,12 @@ func (e *OpenAICompatExecutor) executeImages(ctx context.Context, auth *cliproxy helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) body, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, body) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) err = errRead return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, body) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), body)) @@ -470,8 +473,11 @@ func (e *OpenAICompatExecutor) executeStreamWithCredentials(ctx context.Context, } helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { - b, _ := io.ReadAll(httpResp.Body) + b, errRead := io.ReadAll(httpResp.Body) helps.AppendAPIResponseChunk(ctx, e.cfg, b) + if errRead != nil { + helps.RecordAPIResponseError(ctx, e.cfg, errRead) + } helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), b)) if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("openai compat executor: close response body error: %v", errClose) @@ -759,11 +765,11 @@ func (e *OpenAICompatExecutor) executeImagesStream(ctx context.Context, auth *cl if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("openai compat executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, body) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return nil, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, body) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), body)) return nil, statusErr{code: httpResp.StatusCode, msg: string(body)} } @@ -1276,6 +1282,9 @@ type statusErr struct { credentialScoped bool streamTruncated bool transientRateLimit bool + tosViolation bool + tosAppealURL string + tosAppealURLText string // diagnostic is a content-free detail for logs only; it never reaches clients. diagnostic string } @@ -1301,6 +1310,33 @@ func (e statusErr) IsStreamTruncated() bool { return e.streamTruncated } // that must not be recorded as credential quota exhaustion. func (e statusErr) IsTransientRateLimit() bool { return e.transientRateLimit } +// IsTerminalTOSViolation marks a 403 PERMISSION_DENIED carrying an ErrorInfo +// reason=TOS_VIOLATION. The conductor must deactivate the credential rather +// than cool it, so sibling credentials are not hammered during a sweep. +func (e statusErr) IsTerminalTOSViolation() bool { return e.tosViolation } + +// TOSAppealMetadata exposes the operator-facing appeal detail extracted from +// the ErrorInfo metadata so the conductor can persist it on the auth record. +func (e statusErr) TOSAppealMetadata() map[string]string { + if !e.tosViolation || (e.tosAppealURL == "" && e.tosAppealURLText == "") { + return nil + } + meta := map[string]string{ + "tos_appeal_url": e.tosAppealURL, + "tos_appeal_url_text": e.tosAppealURLText, + } + return meta +} + +// ErrorCode exposes the machine-readable classification for terminal TOS +// violations so MarkResult can route them to the disabled credential path. +func (e statusErr) ErrorCode() string { + if e.tosViolation { + return "tos_violation" + } + return "" +} + const openAICompatTPMFallbackRetryAfter = time.Minute func newOpenAICompatStatusError(status int, headers http.Header, body []byte) statusErr { diff --git a/internal/runtime/executor/openai_compat_executor_reasoning_test.go b/internal/runtime/executor/openai_compat_executor_reasoning_test.go index d5cda5fc543..05ecc5a0b36 100644 --- a/internal/runtime/executor/openai_compat_executor_reasoning_test.go +++ b/internal/runtime/executor/openai_compat_executor_reasoning_test.go @@ -58,6 +58,142 @@ func TestOpenAICompatExecutorUsesCompatibleClaudeTranslation(t *testing.T) { } } +func TestOpenAICompatExecutorAddsPlaceholderReasoningForToolCallsWithoutThinkingWhenCompat(t *testing.T) { + models := []config.PayloadModelRule{{Name: "deepseek-v4-flash", Protocol: "openai"}} + basePayload := `{"model":"deepseek-v4-flash","thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"user","content":"what time"},{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"get_time","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"12:00"}]}]}` + disabledPayload := `{"model":"deepseek-v4-flash","thinking":{"type":"disabled"},"messages":[{"role":"user","content":"what time"},{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"get_time","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"12:00"}]}]}` + + for _, tt := range []struct { + name string + reqModel string + reqPayload string + payloadCfg config.PayloadConfig + wantExists bool + wantReasoning string + }{ + { + name: "placeholder injected when thinking enabled", + reqModel: "deepseek-v4-flash", + reqPayload: basePayload, + wantExists: true, + wantReasoning: " ", + }, + { + name: "placeholder omitted when thinking disabled", + reqModel: "deepseek-v4-flash", + reqPayload: disabledPayload, + wantExists: false, + }, + { + name: "model suffix high overrides disabled body and injects placeholder", + reqModel: "deepseek-v4-flash(high)", + reqPayload: disabledPayload, + wantExists: true, + wantReasoning: " ", + }, + { + name: "model suffix none overrides enabled body and removes placeholder", + reqModel: "deepseek-v4-flash(none)", + reqPayload: basePayload, + wantExists: false, + }, + { + name: "final payload override wins", + reqModel: "deepseek-v4-flash", + reqPayload: basePayload, + payloadCfg: config.PayloadConfig{Override: []config.PayloadRule{ + {Models: models, Params: map[string]any{"messages.1.reasoning_content": "custom-override"}}, + }}, + wantExists: true, + wantReasoning: "custom-override", + }, + { + name: "final payload filter is not restored", + reqModel: "deepseek-v4-flash", + reqPayload: basePayload, + payloadCfg: config.PayloadConfig{Filter: []config.PayloadFilterRule{ + {Models: models, Params: []string{"messages.1.reasoning_content"}}, + }}, + wantExists: false, + }, + } { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/stream=%v", tt.name, stream), func(t *testing.T) { + bodies := make(chan []byte, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read upstream request: %v", errRead) + } + bodies <- body + if stream { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"id\":\"chatcmpl-test\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"chatcmpl-test","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`) + })) + t.Cleanup(server.Close) + + executor := NewOpenAICompatExecutor("openai-compatibility", &config.Config{Payload: tt.payloadCfg}) + auth := &cliproxyauth.Auth{ + Provider: "openai-compatibility", + Attributes: map[string]string{ + "base_url": server.URL, + "api_key": "test-key", + }, + } + request := cliproxyexecutor.Request{ + Model: tt.reqModel, + Payload: []byte(tt.reqPayload), + Metadata: map[string]any{ + "cliproxy.resolved_api_key_model_info": ®istry.ModelInfo{ + IsCompat: true, + Thinking: ®istry.ThinkingSupport{ + Levels: []string{"none", "low", "medium", "high"}, + ZeroAllowed: true, + }, + }, + }, + } + options := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, + ResponseFormat: sdktranslator.FormatOpenAI, + Stream: stream, + } + + if stream { + result, errStream := executor.ExecuteStream(context.Background(), auth, request, options) + if errStream != nil { + t.Fatalf("ExecuteStream error: %v", errStream) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("stream chunk error: %v", chunk.Err) + } + } + } else if _, errExecute := executor.Execute(context.Background(), auth, request, options); errExecute != nil { + t.Fatalf("Execute error: %v", errExecute) + } + + upstreamBody := <-bodies + assistant := ojson.GetBytes(upstreamBody, "messages.1") + reasoning := assistant.Get("reasoning_content") + if reasoning.Exists() != tt.wantExists { + t.Fatalf("reasoning_content exists = %v, want %v; body=%s", reasoning.Exists(), tt.wantExists, upstreamBody) + } + if tt.wantExists && reasoning.String() != tt.wantReasoning { + t.Fatalf("reasoning_content = %q, want %q; body=%s", reasoning.String(), tt.wantReasoning, upstreamBody) + } + if !assistant.Get("tool_calls").Exists() { + t.Fatalf("tool_calls missing from upstream request: %s", upstreamBody) + } + }) + } + } +} + func TestOpenAICompatExecutorClaudeStandaloneEffortFinalPayload(t *testing.T) { models := []config.PayloadModelRule{{Name: "custom-openai", Protocol: "openai"}} for _, tt := range []struct { diff --git a/internal/runtime/executor/payload_barrier_test.go b/internal/runtime/executor/payload_barrier_test.go index ac3b9ad95a8..2dedb487961 100644 --- a/internal/runtime/executor/payload_barrier_test.go +++ b/internal/runtime/executor/payload_barrier_test.go @@ -21,7 +21,7 @@ import ( func TestPayloadBarrierCodexImageFilter(t *testing.T) { for _, transport := range []string{"http", "websocket"} { for _, stream := range []bool{false, true} { - for _, model := range []string{"gpt-5.4", "gpt-5.5"} { + for _, model := range []string{"gpt-5.4", "gpt-5.5", "gpt-6-astra", "gpt-6-sol"} { t.Run(transport+"/"+model+map[bool]string{false: "/execute", true: "/stream"}[stream], func(t *testing.T) { captured := make(chan []byte, 1) completed := []byte(`{"type":"response.completed","response":{"id":"resp_barrier","status":"completed","output":[],"usage":{"input_tokens":0,"output_tokens":0,"total_tokens":0}}}`) @@ -59,7 +59,7 @@ func TestPayloadBarrierCodexImageFilter(t *testing.T) { _, _ = w.Write(append(append([]byte("data: "), completed...), '\n', '\n')) })) defer server.Close() - cfg := &config.Config{Payload: config.PayloadConfig{Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "gpt-5.4"}}, Params: []string{`tools.#(type=="image_generation")#`, "instructions", "prompt_cache_key"}}}}} + cfg := &config.Config{Payload: config.PayloadConfig{Filter: []config.PayloadFilterRule{{Models: []config.PayloadModelRule{{Name: "gpt-5.4"}, {Name: "gpt-6-astra"}}, Params: []string{`tools.#(type=="image_generation")#`, "instructions", "prompt_cache_key"}}}}} var executor cliproxyauth.ProviderExecutor = NewCodexExecutor(cfg) if transport == "websocket" { executor = NewCodexWebsocketsExecutor(cfg) @@ -81,11 +81,12 @@ func TestPayloadBarrierCodexImageFilter(t *testing.T) { t.Fatal(errExecute) } body := <-captured + filteredModel := model == "gpt-5.4" || model == "gpt-6-astra" image := ojson.GetBytes(body, `tools.#(type=="image_generation")`).Exists() - if image != (model == "gpt-5.5") { + if image != !filteredModel { t.Fatalf("image tool presence = %v: %s", image, body) } - if model == "gpt-5.4" && (ojson.GetBytes(body, "instructions").Exists() || ojson.GetBytes(body, "prompt_cache_key").Exists()) { + if filteredModel && (ojson.GetBytes(body, "instructions").Exists() || ojson.GetBytes(body, "prompt_cache_key").Exists()) { t.Fatalf("late injection undid filter: %s", body) } }) @@ -381,7 +382,7 @@ func TestPayloadBarrierEffectiveServiceTierUsageAfterOverride(t *testing.T) { t.Run("devin omits unencoded effective service tier", func(t *testing.T) { var frames []byte - frame := appendDevinFieldBytes(nil, 2, []byte("ok")) + frame := appendDevinFieldBytes(nil, 3, []byte("ok")) frames = append(frames, helps.WrapConnectEnvelope(frame)...) frames = append(frames, helps.WrapConnectEnvelopeWithFlag(helps.ConnectFlagEndStream, []byte(`{}`))...) diff --git a/internal/runtime/executor/testdata/tool_search_disabled/dev_executor_golden.json b/internal/runtime/executor/testdata/tool_search_disabled/dev_executor_golden.json index aabd8c4b887..2080bdff494 100644 --- a/internal/runtime/executor/testdata/tool_search_disabled/dev_executor_golden.json +++ b/internal/runtime/executor/testdata/tool_search_disabled/dev_executor_golden.json @@ -3,8 +3,8 @@ "gateway/execute": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"create a calendar event\",\"cache_control\":{\"type\":\"ephemeral\"}}]}],\"metadata\":{},\"stream\":true,\"tools\":[{\"type\":\"tool_search\",\"execution\":\"client\",\"name\":\"ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"},\"cache_control\":{\"type\":\"ephemeral\"}}]}", "gateway/stream": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"create a calendar event\",\"cache_control\":{\"type\":\"ephemeral\"}}]}],\"metadata\":{},\"stream\":true,\"tools\":[{\"type\":\"tool_search\",\"execution\":\"client\",\"name\":\"ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"},\"cache_control\":{\"type\":\"ephemeral\"}}]}", "oauth/count_tokens": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":\"create a calendar event\"}],\"stream\":true,\"tools\":[{\"execution\":\"client\",\"name\":\"mcp__select_sight__disorder_ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"mcp__select_sight__push_exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"mcp__select_sight__elephant_lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"}}]}", - "oauth/execute": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"\u003csystem-reminder\u003e\\nAs you answer the user's questions, you can use the following context:\\n# currentDate\\nToday's date is 2026-10-11.\\n\\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\\n\u003c/system-reminder\u003e\\n\\n\"},{\"type\":\"text\",\"text\":\"create a calendar event\",\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}}]}],\"metadata\":{},\"stream\":true,\"tools\":[{\"execution\":\"client\",\"name\":\"mcp__select_sight__disorder_ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"mcp__select_sight__push_exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"mcp__select_sight__elephant_lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"}}],\"system\":[{\"type\":\"text\",\"text\":\"x-anthropic-billing-header: cc_version=2.1.280.283; cc_entrypoint=cli; cch=0; cc_prompt_id=ebb599d3-6b98-4fcc-bc9c-99d7dcbd62b9; cc_turn_origin=human;\"},{\"type\":\"text\",\"text\":\"You are Claude Code, Anthropic's official CLI for Claude.\",\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}}],\"diagnostics\":{\"previous_message_id\":null}}", - "oauth/stream": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"\u003csystem-reminder\u003e\\nAs you answer the user's questions, you can use the following context:\\n# currentDate\\nToday's date is 2026-10-11.\\n\\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\\n\u003c/system-reminder\u003e\\n\\n\"},{\"type\":\"text\",\"text\":\"create a calendar event\",\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}}]}],\"metadata\":{},\"stream\":true,\"tools\":[{\"execution\":\"client\",\"name\":\"mcp__select_sight__disorder_ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"mcp__select_sight__push_exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"mcp__select_sight__elephant_lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"}}],\"system\":[{\"type\":\"text\",\"text\":\"x-anthropic-billing-header: cc_version=2.1.280.283; cc_entrypoint=cli; cch=0; cc_prompt_id=ebb599d3-6b98-4fcc-bc9c-99d7dcbd62b9; cc_turn_origin=human;\"},{\"type\":\"text\",\"text\":\"You are Claude Code, Anthropic's official CLI for Claude.\",\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}}],\"diagnostics\":{\"previous_message_id\":null}}", + "oauth/execute": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"\u003csystem-reminder\u003e\\nAs you answer the user's questions, you can use the following context:\\n# currentDate\\nToday's date is 2026-10-11.\\n\\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\\n\u003c/system-reminder\u003e\\n\\n\"},{\"type\":\"text\",\"text\":\"create a calendar event\",\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}}]}],\"metadata\":{},\"stream\":true,\"tools\":[{\"execution\":\"client\",\"name\":\"mcp__select_sight__disorder_ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"mcp__select_sight__push_exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"mcp__select_sight__elephant_lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"}}],\"system\":[{\"type\":\"text\",\"text\":\"x-anthropic-billing-header: cc_version=2.1.321.882; cc_entrypoint=cli; cch=0; cc_prompt_id=ebb599d3-6b98-4fcc-bc9c-99d7dcbd62b9; cc_turn_origin=human;\"},{\"type\":\"text\",\"text\":\"You are Claude Code, Anthropic's official CLI for Claude.\",\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}}],\"diagnostics\":{\"previous_message_id\":null}}", + "oauth/stream": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"\u003csystem-reminder\u003e\\nAs you answer the user's questions, you can use the following context:\\n# currentDate\\nToday's date is 2026-10-11.\\n\\n IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\\n\u003c/system-reminder\u003e\\n\\n\"},{\"type\":\"text\",\"text\":\"create a calendar event\",\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}}]}],\"metadata\":{},\"stream\":true,\"tools\":[{\"execution\":\"client\",\"name\":\"mcp__select_sight__disorder_ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"mcp__select_sight__push_exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"mcp__select_sight__elephant_lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"}}],\"system\":[{\"type\":\"text\",\"text\":\"x-anthropic-billing-header: cc_version=2.1.321.882; cc_entrypoint=cli; cch=0; cc_prompt_id=ebb599d3-6b98-4fcc-bc9c-99d7dcbd62b9; cc_turn_origin=human;\"},{\"type\":\"text\",\"text\":\"You are Claude Code, Anthropic's official CLI for Claude.\",\"cache_control\":{\"type\":\"ephemeral\",\"ttl\":\"1h\"}}],\"diagnostics\":{\"previous_message_id\":null}}", "official/count_tokens": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":\"create a calendar event\"}],\"stream\":true,\"tools\":[{\"type\":\"tool_search\",\"execution\":\"client\",\"name\":\"ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"}}]}", "official/execute": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"create a calendar event\",\"cache_control\":{\"type\":\"ephemeral\"}}]}],\"metadata\":{},\"stream\":true,\"tools\":[{\"type\":\"tool_search\",\"execution\":\"client\",\"name\":\"ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"},\"cache_control\":{\"type\":\"ephemeral\"}}]}", "official/stream": "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":32000,\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"create a calendar event\",\"cache_control\":{\"type\":\"ephemeral\"}}]}],\"metadata\":{},\"stream\":true,\"tools\":[{\"type\":\"tool_search\",\"execution\":\"client\",\"name\":\"ClientSearch\",\"description\":\"Named search.\"},{\"name\":\"exec_command\",\"description\":\"Run a command.\",\"input_schema\":{\"properties\":{\"cmd\":{\"type\":\"string\"}},\"required\":[\"cmd\"],\"type\":\"object\"}},{\"name\":\"lookup_order\",\"description\":\"Look up an order.\",\"input_schema\":{\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"],\"type\":\"object\"},\"cache_control\":{\"type\":\"ephemeral\"}}]}" diff --git a/internal/runtime/executor/xai_executor_execute.go b/internal/runtime/executor/xai_executor_execute.go index 9f28f59b0ed..a6eb980b127 100644 --- a/internal/runtime/executor/xai_executor_execute.go +++ b/internal/runtime/executor/xai_executor_execute.go @@ -72,33 +72,53 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { data, errRead := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return resp, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) return resp, xaiStatusErr(httpResp.StatusCode, data) } data, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) outputItemsByIndex := make(map[int64][]byte) var outputItemsFallback [][]byte responseFilter := newXAIInternalXSearchResponseFilter(prepared.filterInternalXSearch, prepared.clientDeclaredTools) namespaceRestorer := newXAINamespaceRestorer(prepared.namespaceTools) var upstreamUsage helps.StreamUsageBuffer - for _, line := range bytes.Split(data, []byte("\n")) { - if !bytes.HasPrefix(line, xaiDataTag) { - continue + events := helps.NewCodexSSEScanner(ctx, bytes.NewReader(data), len(data)+1) + sawSSEData := false + var pendingEventName string + var pendingData []byte + hasPendingData := false + + dispatchSSEEvent := func(eventName string, rawEventData []byte) (cliproxyexecutor.Response, bool, error) { + rawEventData = bytes.TrimSpace(rawEventData) + if len(rawEventData) == 0 || bytes.Equal(rawEventData, []byte("[DONE]")) { + return cliproxyexecutor.Response{}, false, nil + } + sawSSEData = true + if !ojson.ValidBytes(rawEventData) { + if errTerminal, ok := xaiTerminalFailureErr(eventName, rawEventData); ok { + upstreamUsage.PublishFailure(ctx, reporter, errTerminal) + return cliproxyexecutor.Response{}, true, errTerminal + } + return cliproxyexecutor.Response{}, false, nil } - eventData := xaiNormalizeReasoningSummaryData(bytes.TrimSpace(line[len(xaiDataTag):])) + eventData := xaiNormalizeReasoningSummaryData(rawEventData) upstreamUsage.ObserveResponsesStream(eventData) + reporter.ObserveResponseModel(eventData) + if errTerminal, ok := xaiTerminalFailureErr(eventName, eventData); ok { + upstreamUsage.PublishFailure(ctx, reporter, errTerminal) + return cliproxyexecutor.Response{}, true, errTerminal + } prepared.applyPatch.RememberDispatcherEvent(eventData) eventData = namespaceRestorer.restore(eventData) if prepared.webSearchAlias != "" { @@ -106,15 +126,15 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req } eventData = responseFilter.apply(eventData) if len(eventData) == 0 { - continue + return cliproxyexecutor.Response{}, false, nil } - events, errBridge := prepared.applyPatch.Transform(eventData) + transformedEvents, errBridge := prepared.applyPatch.Transform(eventData) if errBridge != nil { errBridge = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} upstreamUsage.PublishFailure(ctx, reporter, errBridge) - return resp, errBridge + return cliproxyexecutor.Response{}, true, errBridge } - for _, eventData := range events { + for _, eventData := range transformedEvents { reporter.ObserveResponseModel(eventData) eventType := ojson.GetBytesNoCopy(eventData, "type").String() switch eventType { @@ -133,7 +153,7 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req if helps.ApplyPatchTranslationError(param) != nil || len(out) == 0 { errTranslation := statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} upstreamUsage.PublishFailure(ctx, reporter, errTranslation) - return cliproxyexecutor.Response{}, errTranslation + return cliproxyexecutor.Response{}, true, errTranslation } if !upstreamUsage.Publish(ctx, reporter) { if detail, ok := helps.ParseCodexUsageWithOutputItems(completedData, outputItemsByIndex, outputItemsFallback); ok { @@ -143,17 +163,92 @@ func (e *XAIExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, req if prepared.responseFormat == sdktranslator.FormatOpenAIResponse { out = helps.EnsureResponsesUsageDetails(out) } - return cliproxyexecutor.Response{Payload: out, Headers: httpResp.Header.Clone()}, nil + return cliproxyexecutor.Response{ + Payload: out, + Incomplete: eventType == "response.incomplete", + Headers: httpResp.Header.Clone(), + }, true, nil + } + } + return cliproxyexecutor.Response{}, false, nil + } + + flushPendingEvent := func() (cliproxyexecutor.Response, bool, error) { + if !hasPendingData { + pendingEventName = "" + pendingData = nil + return cliproxyexecutor.Response{}, false, nil + } + eventName := pendingEventName + eventPayload := pendingData + pendingEventName = "" + pendingData = nil + hasPendingData = false + return dispatchSSEEvent(eventName, eventPayload) + } + + for events.Scan() { + line := bytes.TrimRight(events.Bytes(), "\r") + if len(bytes.TrimSpace(line)) == 0 { + if outResp, done, errDispatch := flushPendingEvent(); done { + return outResp, errDispatch + } + continue + } + if bytes.HasPrefix(line, xaiEventTag) { + nextEventName := strings.TrimSpace(string(line[len(xaiEventTag):])) + if hasPendingData && pendingEventName != "" { + if outResp, done, errDispatch := flushPendingEvent(); done { + return outResp, errDispatch + } + } + pendingEventName = nextEventName + continue + } + if !bytes.HasPrefix(line, xaiDataTag) { + continue + } + rawEventData := bytes.TrimSpace(line[len(xaiDataTag):]) + if hasPendingData { + if ojson.ValidBytes(pendingData) || bytes.Equal(pendingData, []byte("[DONE]")) { + if outResp, done, errDispatch := flushPendingEvent(); done { + return outResp, errDispatch + } + } else { + pendingData = append(append(pendingData, '\n'), rawEventData...) + continue } } + pendingData = bytes.Clone(rawEventData) + hasPendingData = true + } + if outResp, done, errDispatch := flushPendingEvent(); done { + return outResp, errDispatch } - if errFinish := prepared.applyPatch.Finish(); errFinish != nil { - errFinish = statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage} - upstreamUsage.PublishFailure(ctx, reporter, errFinish) - return resp, errFinish + if !sawSSEData { + if trimmed := bytes.TrimSpace(data); len(trimmed) > 0 { + if errTerminal, ok := xaiTerminalFailureErr("", trimmed); ok { + upstreamUsage.PublishFailure(ctx, reporter, errTerminal) + return resp, errTerminal + } + } + } + if prepared.applyPatch.HasPatchActivity() { + if errFinish := prepared.applyPatch.Finish(); errFinish != nil { + errFinish = xaiRequestScopedStreamError{statusErr: statusErr{code: http.StatusBadGateway, msg: helps.ApplyPatchUpstreamErrorMessage}} + upstreamUsage.PublishFailure(ctx, reporter, errFinish) + return resp, errFinish + } + } + if !sawSSEData { + errEmpty := newXAIEmptyStreamError() + upstreamUsage.PublishFailure(ctx, reporter, errEmpty) + return resp, errEmpty } - return resp, statusErr{code: http.StatusRequestTimeout, msg: "xai stream error: stream disconnected before response.completed or response.incomplete"} + errIncomplete := newXAIIncompleteStreamError() + upstreamUsage.PublishFailure(ctx, reporter, errIncomplete) + return resp, errIncomplete } func (e *XAIExecutor) executeCompact(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (resp cliproxyexecutor.Response, err error) { @@ -242,11 +337,11 @@ func (e *XAIExecutor) executeCompactRequest(ctx context.Context, auth *cliproxya helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return nil, nil, nil, nil, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) diff --git a/internal/runtime/executor/xai_executor_media.go b/internal/runtime/executor/xai_executor_media.go index 9ebbdb42bf7..4799fd2c96b 100644 --- a/internal/runtime/executor/xai_executor_media.go +++ b/internal/runtime/executor/xai_executor_media.go @@ -63,11 +63,11 @@ func (e *XAIExecutor) executeImages(ctx context.Context, auth *cliproxyauth.Auth helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) @@ -145,11 +145,11 @@ func (e *XAIExecutor) executeVideos(ctx context.Context, auth *cliproxyauth.Auth helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) diff --git a/internal/runtime/executor/xai_executor_response.go b/internal/runtime/executor/xai_executor_response.go index a9afe42821b..fdb538ccb9c 100644 --- a/internal/runtime/executor/xai_executor_response.go +++ b/internal/runtime/executor/xai_executor_response.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "sort" + "strconv" "strings" "time" @@ -1313,6 +1314,269 @@ func xaiPatchCompletedOutput(eventData []byte, outputItemsByIndex map[int64][]by // cli-chat-proxy ("Usage resets over a rolling 24-hour window"). const xaiFreeUsageExhaustedCooldown = 24 * time.Hour +const ( + xaiEmptyStreamMessage = "xai stream error: empty upstream stream" + xaiIncompleteStreamMessage = "xai stream error: stream closed before response.completed or response.incomplete" +) + +type xaiRequestScopedStreamError struct { + statusErr +} + +func (xaiRequestScopedStreamError) IsRequestScoped() bool { + return true +} + +func newXAIEmptyStreamError() xaiRequestScopedStreamError { + return xaiRequestScopedStreamError{statusErr: statusErr{ + code: http.StatusBadGateway, + msg: xaiEmptyStreamMessage, + }} +} + +func newXAIIncompleteStreamError() xaiRequestScopedStreamError { + return xaiRequestScopedStreamError{statusErr: statusErr{ + code: http.StatusBadGateway, + msg: xaiIncompleteStreamMessage, + }} +} + +func xaiTerminalFailureErr(eventName string, eventData []byte) (statusErr, bool) { + doc, ok := xaiTerminalFailureDoc(eventName, eventData) + if !ok || doc == nil { + return statusErr{}, false + } + status := xaiTerminalFailureStatus(eventData, doc) + return xaiStatusErr(status, doc.Bytes()), true +} + +func xaiTerminalFailureDoc(eventName string, eventData []byte) (*ojson.Doc, bool) { + trimmed := bytes.TrimSpace(eventData) + if len(trimmed) == 0 { + return nil, false + } + if !ojson.ValidBytes(trimmed) { + if strings.EqualFold(strings.TrimSpace(eventName), "error") { + doc := ojson.NewDocString(`{"error":{}}`) + _ = doc.Set("error.message", string(trimmed)) + return doc, true + } + return nil, false + } + + eventType := strings.TrimSpace(ojson.GetBytesNoCopy(trimmed, "type").String()) + if eventType == "" { + normalizedEventName := strings.TrimSpace(eventName) + if normalizedEventName == "error" || normalizedEventName == "response.failed" { + eventType = normalizedEventName + } else if errField := ojson.GetBytesNoCopy(trimmed, "error"); errField.Exists() && errField.Type != ojson.Null && !ojson.GetBytesNoCopy(trimmed, "output").Exists() { + if errField.Type == ojson.JSON || strings.TrimSpace(errField.String()) != "" { + eventType = "error" + } + } + } + + var doc *ojson.Doc + switch eventType { + case "error": + doc = xaiTerminalErrorDoc(trimmed, "error") + if doc == nil { + doc = xaiTerminalErrorDoc(trimmed, "body.error") + } + if doc == nil { + doc = xaiTerminalTopLevelErrorDoc(trimmed) + } + case "response.failed": + doc = xaiTerminalErrorDoc(trimmed, "response.error") + if doc == nil { + doc = xaiTerminalErrorDoc(trimmed, "error") + } + default: + return nil, false + } + + if doc == nil { + doc = ojson.NewDocString(`{"error":{"message":"upstream stream failed without error details"}}`) + } + if seq := ojson.GetBytesNoCopy(trimmed, "sequence_number"); seq.Exists() && seq.Type == ojson.Number { + _ = doc.Set("sequence_number", seq.Int()) + } + return doc, true +} + +func xaiTerminalErrorDoc(eventData []byte, path string) *ojson.Doc { + errorResult := ojson.GetBytesNoCopy(eventData, path) + if !errorResult.Exists() || errorResult.Type == ojson.Null { + return nil + } + + doc := ojson.NewDocString(`{"error":{}}`) + hasField := false + if errorResult.Type == ojson.JSON { + if errorResult.IsObject() && len(errorResult.Map()) > 0 { + _ = doc.SetRawBytes("error", []byte(errorResult.Raw)) + hasField = true + } + } else if message := strings.TrimSpace(errorResult.String()); message != "" { + _ = doc.Set("error.message", message) + hasField = true + } + + if strings.TrimSpace(doc.Get("error.code").String()) == "" { + for _, codePath := range []string{"response.error.code", "code", "body.error.code"} { + if code := strings.TrimSpace(ojson.GetBytesNoCopy(eventData, codePath).String()); code != "" { + _ = doc.Set("error.code", code) + hasField = true + break + } + } + } + if strings.TrimSpace(doc.Get("error.type").String()) == "" { + for _, typePath := range []string{"response.error.type", "error_type", "body.error.type"} { + if errType := strings.TrimSpace(ojson.GetBytesNoCopy(eventData, typePath).String()); errType != "" { + _ = doc.Set("error.type", errType) + hasField = true + break + } + } + } + if strings.TrimSpace(doc.Get("error.param").String()) == "" { + for _, paramPath := range []string{"response.error.param", "param", "body.error.param"} { + if param := strings.TrimSpace(ojson.GetBytesNoCopy(eventData, paramPath).String()); param != "" { + _ = doc.Set("error.param", param) + hasField = true + break + } + } + } + if strings.TrimSpace(doc.Get("error.message").String()) == "" { + for _, msgPath := range []string{"response.error.message", "message", "body.error.message"} { + if message := strings.TrimSpace(ojson.GetBytesNoCopy(eventData, msgPath).String()); message != "" { + _ = doc.Set("error.message", message) + hasField = true + break + } + } + } + if strings.TrimSpace(doc.Get("error.message").String()) == "" { + if code := strings.TrimSpace(doc.Get("error.code").String()); code != "" { + _ = doc.Set("error.message", code) + hasField = true + } else if errType := strings.TrimSpace(doc.Get("error.type").String()); errType != "" { + _ = doc.Set("error.message", errType) + hasField = true + } + } + if !hasField { + return nil + } + return doc +} + +func xaiTerminalTopLevelErrorDoc(eventData []byte) *ojson.Doc { + message := strings.TrimSpace(ojson.GetBytesNoCopy(eventData, "message").String()) + code := strings.TrimSpace(ojson.GetBytesNoCopy(eventData, "code").String()) + errorType := strings.TrimSpace(ojson.GetBytesNoCopy(eventData, "error_type").String()) + param := strings.TrimSpace(ojson.GetBytesNoCopy(eventData, "param").String()) + if message == "" && code == "" && errorType == "" && param == "" { + return nil + } + + doc := ojson.NewDocString(`{"error":{}}`) + if message != "" { + _ = doc.Set("error.message", message) + } + if code != "" { + _ = doc.Set("error.code", code) + } + if errorType != "" { + _ = doc.Set("error.type", errorType) + } + if param != "" { + _ = doc.Set("error.param", param) + } + if strings.TrimSpace(doc.Get("error.message").String()) == "" { + if code != "" { + _ = doc.Set("error.message", code) + } else if errorType != "" { + _ = doc.Set("error.message", errorType) + } + } + return doc +} + +func xaiTerminalFailureStatus(eventData []byte, doc *ojson.Doc) int { + for _, path := range []string{"status", "status_code", "error.status", "error.status_code", "response.error.status", "response.error.status_code", "body.status", "body.error.status"} { + res := ojson.GetBytesNoCopy(eventData, path) + switch res.Type { + case ojson.Number: + if status := int(res.Int()); status >= 400 && status <= 599 { + return status + } + case ojson.String: + if status, errAtoi := strconv.Atoi(strings.TrimSpace(res.String())); errAtoi == nil && status >= 400 && status <= 599 { + return status + } + } + } + + errorType := strings.ToLower(strings.TrimSpace(doc.Get("error.type").String())) + errorCode := strings.ToLower(strings.TrimSpace(doc.Get("error.code").String())) + errorMsg := strings.ToLower(strings.TrimSpace(doc.Get("error.message").String())) + if status, errAtoi := strconv.Atoi(errorCode); errAtoi == nil && status >= 400 && status <= 599 { + return status + } + + switch { + case errorType == "authentication_error", + errorCode == "invalid_api_key", + errorCode == "unauthorized", + strings.HasPrefix(errorCode, "unauthenticated"), + strings.Contains(errorCode, "bad-credentials"), + strings.Contains(errorMsg, "access token could not be validated"): + return http.StatusUnauthorized + case errorType == "permission_error", + errorCode == "forbidden", + errorCode == "permission_denied", + errorCode == "permission-denied", + strings.HasPrefix(errorCode, "permission_denied:"), + strings.HasPrefix(errorCode, "permission-denied:"): + return http.StatusForbidden + case errorType == "not_found_error", + errorCode == "not_found", + errorCode == "model_not_found": + return http.StatusNotFound + case errorType == "rate_limit_error", + errorCode == "rate_limit_exceeded", + errorCode == "rate_limit", + strings.Contains(errorCode, "free-usage-exhausted"), + strings.Contains(errorCode, "resource_exhausted"), + strings.Contains(errorCode, "resource-exhausted"), + strings.Contains(errorMsg, "free-usage-exhausted"), + strings.Contains(errorMsg, "included free usage"): + return http.StatusTooManyRequests + case errorCode == "cyber_policy", + errorCode == "content_policy_violation", + errorType == "invalid_request_error", + errorType == "invalid_request", + errorType == "bad_request_error", + errorType == "image_generation_user_error", + errorCode == "invalid_value", + errorCode == "invalid_request_error", + errorCode == "invalid_argument", + errorCode == "invalid-argument", + errorCode == "context_length_exceeded", + errorCode == "context_too_large": + return http.StatusBadRequest + case errorType == "service_unavailable_error", + errorCode == "server_is_overloaded", + errorCode == "service_unavailable": + return http.StatusServiceUnavailable + default: + return http.StatusBadGateway + } +} + // xaiStatusErr normalizes upstream xAI error bodies for conductor behavior: // - credential invalidation (403 bad-credentials) is remapped to 401 so the // existing OAuth refresh-once-and-retry path runs instead of payment cooldown @@ -1335,7 +1599,13 @@ func xaiStatusErr(code int, body []byte) statusErr { return err } codeStr := strings.ToLower(ojson.GetBytesNoCopy(body, "code").String()) - msg := strings.ToLower(ojson.GetBytesNoCopy(body, "error").String()) + if codeStr == "" { + codeStr = strings.ToLower(ojson.GetBytesNoCopy(body, "error.code").String()) + } + msg := strings.ToLower(ojson.GetBytesNoCopy(body, "error.message").String()) + if msg == "" { + msg = strings.ToLower(ojson.GetBytesNoCopy(body, "error").String()) + } if msg == "" { msg = strings.ToLower(string(body)) } diff --git a/internal/runtime/executor/xai_executor_speech.go b/internal/runtime/executor/xai_executor_speech.go index 93b678af64d..a185839d8b0 100644 --- a/internal/runtime/executor/xai_executor_speech.go +++ b/internal/runtime/executor/xai_executor_speech.go @@ -119,11 +119,11 @@ func (e *XAIExecutor) executeSpeech(ctx context.Context, auth *cliproxyauth.Auth helps.RecordAPIResponseMetadata(ctx, e.cfg, httpResp.StatusCode, httpResp.Header.Clone()) data, err := io.ReadAll(httpResp.Body) + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) return resp, err } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) diff --git a/internal/runtime/executor/xai_executor_stream.go b/internal/runtime/executor/xai_executor_stream.go index 5c7c55bf9c8..a517643636e 100644 --- a/internal/runtime/executor/xai_executor_stream.go +++ b/internal/runtime/executor/xai_executor_stream.go @@ -65,11 +65,11 @@ func (e *XAIExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Auth if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("xai executor: close response body error: %v", errClose) } + helps.AppendAPIResponseChunk(ctx, e.cfg, data) if errRead != nil { helps.RecordAPIResponseError(ctx, e.cfg, errRead) return nil, errRead } - helps.AppendAPIResponseChunk(ctx, e.cfg, data) helps.LogWithRequestID(ctx).Debugf("request error, error status: %d, error message: %s", httpResp.StatusCode, helps.SummarizeErrorBody(httpResp.Header.Get("Content-Type"), data)) return nil, xaiStatusErr(httpResp.StatusCode, data) } diff --git a/internal/runtime/executor/xai_executor_test.go b/internal/runtime/executor/xai_executor_test.go index 581b8bf47ba..8598bbc8a39 100644 --- a/internal/runtime/executor/xai_executor_test.go +++ b/internal/runtime/executor/xai_executor_test.go @@ -13,6 +13,7 @@ import ( "net/http/httptest" "runtime" "strings" + "sync/atomic" "testing" "time" @@ -23,8 +24,10 @@ import ( xaiauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" internalcache "github.com/router-for-me/CLIProxyAPI/v8/internal/cache" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + sdkhandlers "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" @@ -8110,3 +8113,551 @@ func TestXAIWebsocketUsagePreservesFilteredSearch(t *testing.T) { t.Fatal("usage not published") } } + +func TestXAIExecutorExecuteReturnsTerminalStreamFailures(t *testing.T) { + t.Parallel() + + want24h := 24 * time.Hour + tests := []struct { + name string + sseBody string + contentType string + wantStatus int + wantMsg string + wantCode string + wantType string + wantRetryAfter *time.Duration + }{ + { + name: "error event with invalid_request_error", + sseBody: "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\",\"model\":\"grok-4.7-build\"}}\n\ndata: {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"code\":\"invalid_value\",\"message\":\"Invalid input.\"},\"sequence_number\":2}\n\n", + contentType: "text/event-stream", + wantStatus: http.StatusBadRequest, + wantMsg: "Invalid input.", + wantCode: "invalid_value", + wantType: "invalid_request_error", + }, + { + name: "error event with bad-credentials remaps to 401", + sseBody: "data: {\"type\":\"error\",\"status\":403,\"error\":{\"code\":\"unauthenticated:bad-credentials\",\"message\":\"The OAuth2 access token could not be validated.\"}}\n\n", + contentType: "text/event-stream", + wantStatus: http.StatusUnauthorized, + wantMsg: "The OAuth2 access token could not be validated.", + wantCode: "unauthenticated:bad-credentials", + }, + { + name: "error event with free-usage-exhausted maps to 429 with 24h retry-after", + sseBody: "data: {\"type\":\"error\",\"error\":{\"code\":\"subscription:free-usage-exhausted\",\"message\":\"You've used all the included free usage for model grok-4.7 for now.\"}}\n\n", + contentType: "text/event-stream", + wantStatus: http.StatusTooManyRequests, + wantMsg: "You've used all the included free usage for model grok-4.7 for now.", + wantCode: "subscription:free-usage-exhausted", + wantRetryAfter: &want24h, + }, + { + name: "event error header with flat xai refusal payload", + sseBody: "event: error\ndata: {\"code\":\"permission-denied\",\"error\":\"I'm sorry, I can't help with that request.\"}\n\n", + contentType: "text/event-stream", + wantStatus: http.StatusForbidden, + wantMsg: "I'm sorry, I can't help with that request.", + wantCode: "permission-denied", + }, + { + name: "data line before event error header", + sseBody: "data: {\"code\":\"invalid_argument\",\"message\":\"Invalid input.\"}\nevent: error\n\n", + contentType: "text/event-stream", + wantStatus: http.StatusBadRequest, + wantMsg: "Invalid input.", + wantCode: "invalid_argument", + }, + { + name: "response.failed event with server_error", + sseBody: "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\",\"model\":\"grok-4.7-build\"}}\n\ndata: {\"type\":\"response.failed\",\"sequence_number\":3,\"response\":{\"id\":\"resp_1\",\"status\":\"failed\",\"error\":{\"type\":\"server_error\",\"code\":\"server_error\",\"message\":\"Upstream generation failed.\"}}}\n\n", + contentType: "text/event-stream", + wantStatus: http.StatusBadGateway, + wantMsg: "Upstream generation failed.", + wantCode: "server_error", + wantType: "server_error", + }, + { + name: "multiline sse data error event", + sseBody: "event: error\ndata: {\"type\":\"error\",\ndata: \"error\":{\"type\":\"invalid_request_error\",\"code\":\"invalid_argument\",\"message\":\"Multiline error.\"}}\n\n", + contentType: "text/event-stream", + wantStatus: http.StatusBadRequest, + wantMsg: "Multiline error.", + wantCode: "invalid_argument", + wantType: "invalid_request_error", + }, + { + name: "plain text data under event error header", + sseBody: "event: error\ndata: upstream gateway error\n\n", + contentType: "text/event-stream", + wantStatus: http.StatusBadGateway, + wantMsg: "upstream gateway error", + }, + { + name: "non-sse json error body on 200", + sseBody: `{"code":"permission-denied","error":"Request blocked."}`, + contentType: "application/json", + wantStatus: http.StatusForbidden, + wantMsg: "Request blocked.", + wantCode: "permission-denied", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", tc.contentType) + _, _ = io.WriteString(w, tc.sseBody) + })) + defer server.Close() + + exec := NewXAIExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "xai", + Attributes: map[string]string{"base_url": server.URL}, + Metadata: map[string]any{"access_token": "xai-token"}, + } + payload := []byte(`{"model":"grok-4.7","stream":false,"messages":[{"role":"user","content":"Reply with one word: ready."}]}`) + _, err := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "grok-4.7", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: payload, + Stream: false, + }) + if err == nil { + t.Fatal("Execute() error = nil, want terminal stream error") + } + + var statusCoder cliproxyexecutor.StatusError + if !errors.As(err, &statusCoder) || statusCoder.StatusCode() != tc.wantStatus { + t.Fatalf("status = %v, want %d; err=%v", statusCoder, tc.wantStatus, err) + } + var scopedErr cliproxyexecutor.RequestScopedError + if errors.As(err, &scopedErr) && scopedErr.IsRequestScoped() { + t.Fatalf("explicit upstream terminal error must not set IsRequestScoped() = true: %T (%v)", err, err) + } + + clientBody := sdkhandlers.BuildErrorResponseBodyWithError(statusCoder.StatusCode(), err.Error(), err) + if got := ojson.GetBytes(clientBody, "error.message").String(); got != tc.wantMsg { + t.Fatalf("error.message = %q, want %q; body=%s", got, tc.wantMsg, clientBody) + } + if got := ojson.GetBytes(clientBody, "error.code").String(); got != tc.wantCode { + t.Fatalf("error.code = %q, want %q; body=%s", got, tc.wantCode, clientBody) + } + if tc.wantType != "" { + if got := ojson.GetBytes(clientBody, "error.type").String(); got != tc.wantType { + t.Fatalf("error.type = %q, want %q; body=%s", got, tc.wantType, clientBody) + } + } + + type retryAfterProvider interface { + RetryAfter() *time.Duration + } + var raProvider retryAfterProvider + if tc.wantRetryAfter != nil { + if !errors.As(err, &raProvider) || raProvider.RetryAfter() == nil || *raProvider.RetryAfter() != *tc.wantRetryAfter { + t.Fatalf("RetryAfter = %v, want %v; err=%v", raProvider, *tc.wantRetryAfter, err) + } + } + }) + } +} + +func TestXAIExecutorExecuteEmptyStreamReturns502(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + body string + }{ + {name: "zero byte body", body: ""}, + {name: "sse comment only", body: ": keep-alive\n\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, tc.body) + })) + defer server.Close() + + exec := NewXAIExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "xai", + Attributes: map[string]string{"base_url": server.URL}, + Metadata: map[string]any{"access_token": "xai-token"}, + } + payload := []byte(`{"model":"grok-4.7","stream":false,"messages":[{"role":"user","content":"hello"}]}`) + _, err := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "grok-4.7", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: payload, + Stream: false, + }) + if err == nil { + t.Fatal("Execute() error = nil, want 502 empty stream error") + } + + var statusCoder cliproxyexecutor.StatusError + if !errors.As(err, &statusCoder) || statusCoder.StatusCode() != http.StatusBadGateway { + t.Fatalf("status = %v, want %d; err=%v", statusCoder, http.StatusBadGateway, err) + } + lower := strings.ToLower(err.Error()) + if !strings.Contains(lower, "empty") || !strings.Contains(lower, "stream") { + t.Fatalf("error = %q, want empty stream message", err.Error()) + } + if strings.Contains(lower, "timeout") { + t.Fatalf("error = %q, must not claim timeout", err.Error()) + } + var scopedErr cliproxyexecutor.RequestScopedError + if !errors.As(err, &scopedErr) || !scopedErr.IsRequestScoped() { + t.Fatalf("empty stream error %T (%v) must implement IsRequestScoped() = true", err, err) + } + clientBody := sdkhandlers.BuildErrorResponseBodyWithError(statusCoder.StatusCode(), err.Error(), err) + if got := ojson.GetBytes(clientBody, "error.code").String(); got == "request_timeout" { + t.Fatalf("client body error.code = %q, must not be request_timeout; body=%s", got, clientBody) + } + }) + } +} + +func TestXAIExecutorExecuteIncompleteStreamDoesNotCooldownCredential(t *testing.T) { + var upstreamCalls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + call := upstreamCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + if call == 1 { + _, _ = io.WriteString(w, "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\",\"model\":\"grok-4.7-build\"}}\n\n") + return + } + _, _ = io.WriteString(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_2\",\"object\":\"response\",\"status\":\"completed\",\"model\":\"grok-4.7-build\",\"output\":[{\"id\":\"msg_2\",\"type\":\"message\",\"role\":\"assistant\",\"status\":\"completed\",\"content\":[{\"type\":\"output_text\",\"text\":\"ready\"}]}],\"usage\":{\"input_tokens\":5,\"output_tokens\":1,\"total_tokens\":6}}}\n\n") + })) + defer server.Close() + + cfg := &config.Config{ + RequestRetry: 3, + MaxRetryInterval: 30, + } + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(3, 30*time.Second, 0) + manager.RegisterExecutor(NewXAIExecutor(cfg)) + + authID := "xai-single-cred-issue-7419" + auth := &cliproxyauth.Auth{ + ID: authID, + Provider: "xai", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"base_url": server.URL}, + Metadata: map[string]any{"access_token": "xai-token"}, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register() error = %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "xai", []*registry.ModelInfo{{ID: "grok-4.7"}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(authID) }) + + payload := []byte(`{"model":"grok-4.7","stream":false,"messages":[{"role":"user","content":"hello"}]}`) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: payload, + Stream: false, + } + _, err := manager.Execute(context.Background(), []string{"xai"}, cliproxyexecutor.Request{ + Model: "grok-4.7", + Payload: payload, + }, opts) + if err == nil { + t.Fatal("manager.Execute() error = nil, want incomplete stream error") + } + if gotCalls := upstreamCalls.Load(); gotCalls != 1 { + t.Fatalf("upstream calls on request-scoped incomplete stream = %d, want 1", gotCalls) + } + + var statusCoder cliproxyexecutor.StatusError + if !errors.As(err, &statusCoder) || statusCoder.StatusCode() != http.StatusBadGateway { + t.Fatalf("status = %v, want %d; err=%v", statusCoder, http.StatusBadGateway, err) + } + if strings.Contains(strings.ToLower(err.Error()), "timeout") { + t.Fatalf("error = %q, must not claim timeout", err.Error()) + } + var scopedErr cliproxyexecutor.RequestScopedError + if !errors.As(err, &scopedErr) || !scopedErr.IsRequestScoped() { + t.Fatalf("incomplete stream error %T (%v) must implement IsRequestScoped() = true", err, err) + } + clientBody := sdkhandlers.BuildErrorResponseBodyWithError(statusCoder.StatusCode(), err.Error(), err) + if got := ojson.GetBytes(clientBody, "error.code").String(); got == "request_timeout" { + t.Fatalf("client body error.code = %q, must not be request_timeout; body=%s", got, clientBody) + } + + stored, ok := manager.GetByID(authID) + if !ok || stored == nil { + t.Fatalf("GetByID(%q) missing", authID) + } + if state := stored.ModelStates["grok-4.7"]; state != nil && (state.Unavailable || !state.NextRetryAfter.IsZero()) { + t.Fatalf("model state cooled down after incomplete stream: Unavailable=%v NextRetryAfter=%v", state.Unavailable, state.NextRetryAfter) + } + + // Verify the single credential remains immediately selectable without a 60s transient cooldown. + resp, errNext := manager.Execute(context.Background(), []string{"xai"}, cliproxyexecutor.Request{ + Model: "grok-4.7", + Payload: payload, + }, opts) + if errNext != nil { + t.Fatalf("subsequent manager.Execute() failed on uncooled credential: %v", errNext) + } + if got := ojson.GetBytes(resp.Payload, "choices.0.message.content").String(); got != "ready" { + t.Fatalf("subsequent response content = %q, want %q; payload=%s", got, "ready", resp.Payload) + } + if gotCalls := upstreamCalls.Load(); gotCalls != 2 { + t.Fatalf("total upstream calls = %d, want 2", gotCalls) + } +} + +func TestXAIExecutorExecuteTruncatedCompletedFrameReturnsIncompleteStream(t *testing.T) { + t.Parallel() + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_1\",\"status\":\"completed\",\"output\":[{\"id\":\"msg_1\"") + })) + defer server.Close() + + exec := NewXAIExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "xai", + Attributes: map[string]string{"base_url": server.URL}, + Metadata: map[string]any{"access_token": "xai-token"}, + } + payload := []byte(`{"model":"grok-4.7","input":"hello"}`) + _, err := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{ + Model: "grok-4.7", + Payload: payload, + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + Stream: false, + }) + if err == nil { + t.Fatal("Execute() error = nil, want incomplete stream error on truncated response.completed") + } + var scopedErr cliproxyexecutor.RequestScopedError + if !errors.As(err, &scopedErr) || !scopedErr.IsRequestScoped() { + t.Fatalf("truncated stream error %T (%v) must implement IsRequestScoped() = true", err, err) + } + if strings.Contains(err.Error(), "apply_patch") { + t.Fatalf("truncated response.completed misclassified as apply_patch error: %v", err) + } +} + +func TestXAIExecutorExecuteCustomApplyPatchEmptyAndIncompleteStreamsDoNotCooldown(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + firstStream string + wantStatus int + wantMessage string + }{ + { + name: "empty_stream_with_custom_apply_patch", + firstStream: "", + wantStatus: http.StatusBadGateway, + wantMessage: xaiEmptyStreamMessage, + }, + { + name: "response_created_eof_with_custom_apply_patch", + firstStream: "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\",\"status\":\"in_progress\"}}\n\n", + wantStatus: http.StatusBadGateway, + wantMessage: xaiIncompleteStreamMessage, + }, + { + name: "partial_apply_patch_call_eof_preserves_patch_error_without_cooldown", + firstStream: "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\",\"status\":\"in_progress\"}}\n\n" + + "data: {\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"type\":\"function_call\",\"id\":\"a\",\"call_id\":\"c\",\"name\":\"apply_patch\",\"arguments\":\"\"}}\n\n" + + "data: {\"type\":\"response.function_call_arguments.done\",\"output_index\":0,\"item_id\":\"a\",\"call_id\":\"c\",\"arguments\":\"{\\\"input\\\":\\\"valid patch\\\"}\"}\n\n", + wantStatus: http.StatusBadGateway, + wantMessage: "Invalid apply_patch tool arguments received from upstream.", + }, + { + name: "raw_json_error_with_custom_apply_patch", + firstStream: `{"error":{"message":"Upstream overloaded","type":"server_error","code":"server_is_overloaded"}}`, + wantStatus: http.StatusServiceUnavailable, + wantMessage: "Upstream overloaded", + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + var upstreamCalls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + call := upstreamCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + if call == 1 { + _, _ = io.WriteString(w, tc.firstStream) + return + } + _, _ = io.WriteString(w, "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ok\",\"object\":\"response\",\"status\":\"completed\",\"model\":\"grok-4.7\",\"output\":[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"recovered\"}]}],\"usage\":{\"input_tokens\":3,\"output_tokens\":2,\"total_tokens\":5}}}\n\n") + })) + defer server.Close() + + manager := cliproxyauth.NewManager(nil, &cliproxyauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(NewXAIExecutor(&config.Config{})) + + authID := "xai-patch-cooldown-" + tc.name + auth := &cliproxyauth.Auth{ + ID: authID, + Provider: "xai", + Status: cliproxyauth.StatusActive, + Attributes: map[string]string{"base_url": server.URL}, + Metadata: map[string]any{"access_token": "xai-token"}, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("manager.Register() error = %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "xai", []*registry.ModelInfo{{ID: "grok-4.7"}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + payload := []byte(`{"model":"grok-4.7","input":"hello","tools":[{"type":"custom","name":"apply_patch"}]}`) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + ResponseFormat: sdktranslator.FormatOpenAIResponse, + OriginalRequest: payload, + Stream: false, + } + + _, errFirst := manager.Execute(context.Background(), []string{"xai"}, cliproxyexecutor.Request{ + Model: "grok-4.7", + Payload: payload, + }, opts) + if errFirst == nil { + t.Fatal("first manager.Execute() error = nil, want failure") + } + var statusErrVal cliproxyexecutor.StatusError + if !errors.As(errFirst, &statusErrVal) || statusErrVal.StatusCode() != tc.wantStatus { + t.Fatalf("first error status = %v (%T), want %d", errFirst, errFirst, tc.wantStatus) + } + if !strings.Contains(errFirst.Error(), tc.wantMessage) { + t.Fatalf("first error = %q, want substring %q", errFirst.Error(), tc.wantMessage) + } + + if tc.name == "raw_json_error_with_custom_apply_patch" { + return + } + + var scopedErr cliproxyexecutor.RequestScopedError + if !errors.As(errFirst, &scopedErr) || !scopedErr.IsRequestScoped() { + t.Fatalf("first error %T (%v) must implement IsRequestScoped() = true", errFirst, errFirst) + } + + resp, errSecond := manager.Execute(context.Background(), []string{"xai"}, cliproxyexecutor.Request{ + Model: "grok-4.7", + Payload: payload, + }, opts) + if errSecond != nil { + t.Fatalf("subsequent manager.Execute() failed on uncooled credential: %v", errSecond) + } + if got := ojson.GetBytes(resp.Payload, "output.0.content.0.text").String(); got != "recovered" { + t.Fatalf("subsequent response text = %q, want %q; payload=%s", got, "recovered", resp.Payload) + } + }) + } +} + +func TestXAIExecutorPreservesPartialUpstreamBodyOnReadErrorWhenRequestLogDisabled(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, tc := range []struct { + name string + statusLine string + partial string + }{ + { + name: "200 stream truncated mid-body", + statusLine: "HTTP/1.1 200 OK", + partial: `data: {"type":"response.created","response":{"id":"resp_partial_200"}}`, + }, + { + name: "502 error body truncated mid-body", + statusLine: "HTTP/1.1 502 Bad Gateway", + partial: `{"error":{"message":"partial upstream 502 detail"`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hijacker, ok := w.(http.Hijacker) + if !ok { + t.Error("response writer does not support hijacking") + return + } + conn, buf, errHijack := hijacker.Hijack() + if errHijack != nil { + t.Errorf("hijack: %v", errHijack) + return + } + rawResponse := fmt.Sprintf("%s\r\nContent-Type: text/event-stream\r\nContent-Length: 4096\r\n\r\n%s", tc.statusLine, tc.partial) + _, _ = buf.WriteString(rawResponse) + _ = buf.Flush() + _ = conn.Close() + })) + defer server.Close() + + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + exec := NewXAIExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "xai", + Attributes: map[string]string{"base_url": server.URL}, + Metadata: map[string]any{"access_token": "test-token"}, + } + _, errExec := exec.Execute( + ctx, + auth, + cliproxyexecutor.Request{ + Model: "grok-4.7", + Payload: []byte(`{"model":"grok-4.7","messages":[{"role":"user","content":"hi"}],"stream":false}`), + }, + cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + ResponseFormat: sdktranslator.FormatOpenAI, + }, + ) + if errExec == nil { + t.Fatal("expected read error from truncated upstream connection") + } + + value, exists := ginCtx.Get(logging.DeferredAPIResponseContextKey) + if !exists { + t.Fatal("deferred API response was not captured") + } + deferred, ok := value.(logging.DeferredAPIResponse) + if !ok || deferred == nil { + t.Fatalf("deferred API response = %#v, want logging.DeferredAPIResponse", value) + } + rendered := string(deferred.RenderAPIResponse()) + if !strings.Contains(rendered, tc.partial) { + t.Fatalf("deferred API response dropped partial body %q on read error:\n%s", tc.partial, rendered) + } + if !strings.Contains(rendered, "Error: unexpected EOF") { + t.Fatalf("deferred API response missing read error:\n%s", rendered) + } + }) + } +} diff --git a/internal/runtime/executor/xai_websockets_executor.go b/internal/runtime/executor/xai_websockets_executor.go index a86beff28ca..09943aaac70 100644 --- a/internal/runtime/executor/xai_websockets_executor.go +++ b/internal/runtime/executor/xai_websockets_executor.go @@ -580,15 +580,11 @@ func (e *XAIWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *cliprox upstreamHeaders = respHS.Header.Clone() } if errDial != nil { - bodyErr := websocketHandshakeBody(respHS) - if respHS != nil { - helps.RecordAPIWebsocketUpgradeRejection(ctx, e.cfg, websocketUpgradeRequestLog(wsReqLog), respHS.StatusCode, respHS.Header.Clone(), bodyErr) - } + bodyErr := recordWebsocketDialFailure(ctx, e.cfg, wsReqLog, respHS, errDial) if respHS != nil && respHS.StatusCode > 0 { unlockStreamSession() return nil, xaiStatusErr(respHS.StatusCode, bodyErr) } - helps.RecordAPIWebsocketError(ctx, e.cfg, "dial", errDial) unlockStreamSession() return nil, errDial } @@ -631,9 +627,7 @@ func (e *XAIWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *cliprox } connRetry, closerRetry, respHSRetry, errDialRetry := e.ensureUpstreamConn(ctx, auth, sess, authID, wsURL, wsHeaders) if errDialRetry != nil || connRetry == nil { - bodyErrRetry := websocketHandshakeBody(respHSRetry) - closeHTTPResponseBody(respHSRetry, "xai websockets executor: close handshake response body error") - helps.RecordAPIWebsocketError(ctx, e.cfg, "dial_retry", errDialRetry) + bodyErrRetry := recordWebsocketDialRetryFailure(ctx, e.cfg, wsReqLog, respHSRetry, errDialRetry) sess.clearActive(conn, readCh) sess.reqMu.Unlock() if respHSRetry != nil && respHSRetry.StatusCode > 0 { diff --git a/internal/runtime/executor/xai_websockets_executor_test.go b/internal/runtime/executor/xai_websockets_executor_test.go index 5e3a11950b4..e65295c2a10 100644 --- a/internal/runtime/executor/xai_websockets_executor_test.go +++ b/internal/runtime/executor/xai_websockets_executor_test.go @@ -10,12 +10,15 @@ import ( "net/http/httptest" "strings" "sync" + "sync/atomic" "testing" "time" "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" "github.com/gorilla/websocket" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" @@ -2645,3 +2648,242 @@ func TestApplyXAIWebsocketHeaders_UserAgent(t *testing.T) { } }) } + +func TestXAIWebsocketReconnectUpgradeRejectionRecordedWhenRequestLogDisabled(t *testing.T) { + gin.SetMode(gin.TestMode) + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + var dials atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if dials.Add(1) == 1 { + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + return + } + defer func() { _ = conn.Close() }() + for { + if _, _, errRead := conn.ReadMessage(); errRead != nil { + return + } + } + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Retry-After", "9") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"error":{"message":"xai websocket reconnect rate limited"}}`)) + })) + defer server.Close() + + var writes atomic.Int32 + testWebsocketWritePayloadHook = func(conn *websocket.Conn) { + if writes.Add(1) == 1 { + _ = conn.SetWriteDeadline(time.Now().Add(-time.Second)) + } + } + defer func() { testWebsocketWritePayloadHook = nil }() + + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ctx := context.WithValue(context.Background(), "gin", ginCtx) + exec := NewXAIWebsocketsExecutor(&config.Config{}) + exec.store = &codexWebsocketSessionStore{sessions: make(map[string]*codexWebsocketSession)} + auth := &cliproxyauth.Auth{ + ID: "xai-ws-reconnect", + Provider: "xai", + Attributes: map[string]string{ + "base_url": server.URL, + "api_key": "xai-secret-key", + "websockets": "true", + }, + } + _, errExec := exec.ExecuteStream( + ctx, + auth, + cliproxyexecutor.Request{ + Model: "grok-4", + Payload: []byte(`{"model":"grok-4","input":[{"type":"message","role":"user","content":"reconnect"}]}`), + }, + cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + Metadata: map[string]any{ + cliproxyexecutor.ExecutionSessionMetadataKey: "sess-xai-reconnect", + }, + }, + ) + if errExec == nil { + t.Fatal("expected ExecuteStream reconnect rejection to fail") + } + + value, exists := ginCtx.Get(logging.DeferredAPIResponseContextKey) + if !exists { + t.Fatal("deferred API response was not recorded on websocket reconnect rejection") + } + deferred, ok := value.(logging.DeferredAPIResponse) + if !ok || deferred == nil { + t.Fatalf("deferred API response = %#v, want logging.DeferredAPIResponse", value) + } + rendered := string(deferred.RenderAPIResponse()) + for _, want := range []string{ + "=== API RESPONSE 1 ===", + "Status: 101", + "Error: send:", + "=== API RESPONSE 2 ===", + "Status: 429", + "Retry-After: 9", + `{"error":{"message":"xai websocket reconnect rate limited"}}`, + "Error: dial_retry:", + } { + if !strings.Contains(rendered, want) { + t.Fatalf("deferred API response missing %q:\n%s", want, rendered) + } + } + + t.Run("reconnect transport failure without HTTP response", func(t *testing.T) { + var transportDials atomic.Int32 + var transportServer *httptest.Server + transportServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if transportDials.Add(1) == 1 { + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + return + } + defer func() { _ = conn.Close() }() + for { + if _, _, errRead := conn.ReadMessage(); errRead != nil { + return + } + } + } + hijacker, ok := w.(http.Hijacker) + if ok { + if rawConn, _, errHijack := hijacker.Hijack(); errHijack == nil { + _ = rawConn.Close() + } + } + })) + defer transportServer.Close() + + var transportWrites atomic.Int32 + testWebsocketWritePayloadHook = func(conn *websocket.Conn) { + if transportWrites.Add(1) == 1 { + _ = conn.SetWriteDeadline(time.Now().Add(-time.Second)) + } + } + defer func() { testWebsocketWritePayloadHook = nil }() + + subGinCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + subCtx := context.WithValue(context.Background(), "gin", subGinCtx) + subExec := NewXAIWebsocketsExecutor(&config.Config{}) + subExec.store = &codexWebsocketSessionStore{sessions: make(map[string]*codexWebsocketSession)} + _, errSub := subExec.ExecuteStream( + subCtx, + &cliproxyauth.Auth{ + ID: "xai-ws-transport", + Provider: "xai", + Attributes: map[string]string{ + "base_url": transportServer.URL, + "api_key": "xai-secret-key", + "websockets": "true", + }, + }, + cliproxyexecutor.Request{ + Model: "grok-4", + Payload: []byte(`{"model":"grok-4","input":[{"type":"message","role":"user","content":"reconnect"}]}`), + }, + cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + Metadata: map[string]any{ + cliproxyexecutor.ExecutionSessionMetadataKey: "sess-xai-transport", + }, + }, + ) + if errSub == nil { + t.Fatal("expected transport reconnect failure") + } + subVal, ok := subGinCtx.Get(logging.DeferredAPIResponseContextKey) + if !ok { + t.Fatal("deferred API response missing on transport reconnect failure") + } + subRendered := string(subVal.(logging.DeferredAPIResponse).RenderAPIResponse()) + for _, want := range []string{ + "=== API RESPONSE 1 ===", + "Error: send:", + "=== API RESPONSE 2 ===", + "Error: dial_retry:", + } { + if !strings.Contains(subRendered, want) { + t.Fatalf("transport reconnect response missing %q:\n%s", want, subRendered) + } + } + }) + + t.Run("initial handshake failure with HTTP response records dial error", func(t *testing.T) { + for _, invalid101 := range []bool{false, true} { + caseName := "status_403" + if invalid101 { + caseName = "invalid_101" + } + t.Run(caseName, func(t *testing.T) { + initServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if invalid101 { + hijacker, ok := w.(http.Hijacker) + if !ok { + t.Error("hijacker unsupported") + return + } + rawConn, rawBuf, errHijack := hijacker.Hijack() + if errHijack != nil { + t.Errorf("hijack: %v", errHijack) + return + } + _, _ = rawBuf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: invalid\r\n\r\n") + _ = rawBuf.Flush() + _ = rawConn.Close() + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"error":{"message":"initial xai ws forbidden"}}`)) + })) + defer initServer.Close() + + initGinCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + initCtx := context.WithValue(context.Background(), "gin", initGinCtx) + initExec := NewXAIWebsocketsExecutor(&config.Config{}) + initExec.store = &codexWebsocketSessionStore{sessions: make(map[string]*codexWebsocketSession)} + _, errInit := initExec.ExecuteStream( + initCtx, + &cliproxyauth.Auth{ + ID: "xai-ws-init", + Provider: "xai", + Attributes: map[string]string{ + "base_url": initServer.URL, + "api_key": "xai-secret-key", + "websockets": "true", + }, + }, + cliproxyexecutor.Request{ + Model: "grok-4", + Payload: []byte(`{"model":"grok-4","input":[{"type":"message","role":"user","content":"init"}]}`), + }, + cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAIResponse}, + ) + if errInit == nil { + t.Fatal("expected initial handshake failure") + } + initVal, ok := initGinCtx.Get(logging.DeferredAPIResponseContextKey) + if !ok { + t.Fatal("deferred API response missing on initial handshake failure") + } + initRendered := string(initVal.(logging.DeferredAPIResponse).RenderAPIResponse()) + wantStatus := "Status: 403" + if invalid101 { + wantStatus = "Status: 101" + } + for _, want := range []string{wantStatus, "Error: dial:"} { + if !strings.Contains(initRendered, want) { + t.Fatalf("initial handshake response missing %q:\n%s", want, initRendered) + } + } + }) + } + }) +} diff --git a/internal/store/codex_power_darwin_test.go b/internal/store/codex_power_darwin_test.go new file mode 100644 index 00000000000..bdc6f150b1a --- /dev/null +++ b/internal/store/codex_power_darwin_test.go @@ -0,0 +1,18 @@ +//go:build darwin + +package store + +import ( + "context" + "os" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" +) + +func TestMain(m *testing.M) { + codex.ReadSIWCSystemState = func(context.Context) ([]byte, error) { + return []byte("Current System Capabilities are: CPU Graphics Audio Network\nCurrent Power State: 4\n"), nil + } + os.Exit(m.Run()) +} diff --git a/internal/store/git_refresh_journal.go b/internal/store/git_refresh_journal.go index c0b9292977d..eb51807d85a 100644 --- a/internal/store/git_refresh_journal.go +++ b/internal/store/git_refresh_journal.go @@ -35,8 +35,9 @@ func (s *GitTokenStore) RefreshClaim(ctx context.Context, key string) (claimed b if _, errRand := rand.Read(nonce); errRand != nil { return errRand } - errPublish := s.publishRefreshRecord(ctx, repo, ref, fmt.Sprintf("refresh claim %x", nonce)) + createdHash, errPublish := s.publishRefreshRecord(ctx, repo, ref, fmt.Sprintf("refresh claim %x", nonce)) if errPublish == nil { + s.refreshClaims.Store(key, createdHash) claimed = true return nil } @@ -80,8 +81,50 @@ func (s *GitTokenStore) RefreshRead(ctx context.Context, key string) (receipt [] } func (s *GitTokenStore) RefreshComplete(ctx context.Context, key string, receipt []byte) error { + s.refreshClaims.Delete(key) return s.withRefreshRepository(ctx, func(repo *git.Repository) error { - return s.publishRefreshRecord(ctx, repo, refreshGitRef("receipt", key), string(receipt)) + _, errPublish := s.publishRefreshRecord(ctx, repo, refreshGitRef("receipt", key), string(receipt)) + return errPublish + }) +} + +func (s *GitTokenStore) RefreshRelease(ctx context.Context, key string) error { + if s == nil { + return fmt.Errorf("git refresh journal is unavailable") + } + ownedVal, owned := s.refreshClaims.LoadAndDelete(key) + if !owned { + return fmt.Errorf("refresh claim is not owned by this store") + } + ownedHash, okHash := ownedVal.(plumbing.Hash) + if !okHash || ownedHash.IsZero() { + return fmt.Errorf("invalid owned refresh claim hash") + } + return s.withRefreshRepository(ctx, func(repo *git.Repository) error { + receiptHash, errReceipt := s.refreshRemoteRef(ctx, repo, refreshGitRef("receipt", key)) + if errReceipt != nil { + return errReceipt + } + if !receiptHash.IsZero() { + return fmt.Errorf("refresh receipt already exists") + } + claimRef := refreshGitRef("claim", key) + claimHash, errClaim := s.refreshRemoteRef(ctx, repo, claimRef) + if errClaim != nil { + return errClaim + } + if claimHash != ownedHash { + return fmt.Errorf("refresh claim ownership changed") + } + errPush := repo.PushContext(ctx, &git.PushOptions{ + RemoteName: "origin", + ClientOptions: s.gitClientOptions(), + RefSpecs: []config.RefSpec{config.RefSpec(":" + claimRef.String())}, + }) + if errors.Is(errPush, git.NoErrAlreadyUpToDate) { + return nil + } + return errPush }) } @@ -149,35 +192,38 @@ func (s *GitTokenStore) refreshRemoteRef(ctx context.Context, repo *git.Reposito return plumbing.ZeroHash, nil } -func (s *GitTokenStore) publishRefreshRecord(ctx context.Context, repo *git.Repository, ref plumbing.ReferenceName, message string) error { +func (s *GitTokenStore) publishRefreshRecord(ctx context.Context, repo *git.Repository, ref plumbing.ReferenceName, message string) (plumbing.Hash, error) { tree := &object.Tree{} treeObject := repo.Storer.NewEncodedObject() if errEncode := tree.Encode(treeObject); errEncode != nil { - return errEncode + return plumbing.ZeroHash, errEncode } treeHash, errTree := repo.Storer.SetEncodedObject(treeObject) if errTree != nil { - return errTree + return plumbing.ZeroHash, errTree } signature := object.Signature{Name: "CLIProxyAPI", Email: "refresh@cliproxyapi.local", When: time.Now()} commit := &object.Commit{Author: signature, Committer: signature, Message: message, TreeHash: treeHash} encoded := repo.Storer.NewEncodedObject() if errEncode := commit.Encode(encoded); errEncode != nil { - return errEncode + return plumbing.ZeroHash, errEncode } hash, errStore := repo.Storer.SetEncodedObject(encoded) if errStore != nil { - return errStore + return plumbing.ZeroHash, errStore } // A unique local source avoids updating a tag fetched from another claimant. localRef := plumbing.ReferenceName("refs/cliproxy-refresh-pending/" + hash.String()) if errReference := repo.Storer.SetReference(plumbing.NewHashReference(localRef, hash)); errReference != nil { - return errReference + return plumbing.ZeroHash, errReference } defer func() { if errRemove := repo.Storer.RemoveReference(localRef); errRemove != nil { log.Warnf("remove temporary refresh journal reference: %v", errRemove) } }() - return repo.PushContext(ctx, &git.PushOptions{RemoteName: "origin", ClientOptions: s.gitClientOptions(), RefSpecs: []config.RefSpec{config.RefSpec(localRef.String() + ":" + ref.String())}}) + if errPush := repo.PushContext(ctx, &git.PushOptions{RemoteName: "origin", ClientOptions: s.gitClientOptions(), RefSpecs: []config.RefSpec{config.RefSpec(localRef.String() + ":" + ref.String())}}); errPush != nil { + return plumbing.ZeroHash, errPush + } + return hash, nil } diff --git a/internal/store/gitstore.go b/internal/store/gitstore.go index c3c044bee56..487a5464760 100644 --- a/internal/store/gitstore.go +++ b/internal/store/gitstore.go @@ -35,18 +35,19 @@ const ( // GitTokenStore persists token records and auth metadata using git as the backing storage. type GitTokenStore struct { - mu sync.Mutex - dirLock sync.RWMutex - baseDir string - repoDir string - configDir string - remote string - branch string - username string - password string - lastGC time.Time - pullFn func(ctx context.Context, worktree *git.Worktree, pullOpts *git.PullOptions) error - pushFn func(ctx context.Context, repo *git.Repository, pushOpts *git.PushOptions) error + mu sync.Mutex + dirLock sync.RWMutex + baseDir string + repoDir string + configDir string + remote string + branch string + username string + password string + lastGC time.Time + pullFn func(ctx context.Context, worktree *git.Worktree, pullOpts *git.PullOptions) error + pushFn func(ctx context.Context, repo *git.Repository, pushOpts *git.PushOptions) error + refreshClaims sync.Map } type resolvedRemoteBranch struct { diff --git a/internal/store/object_refresh_journal.go b/internal/store/object_refresh_journal.go index 02ed032c4ee..c12a231227d 100644 --- a/internal/store/object_refresh_journal.go +++ b/internal/store/object_refresh_journal.go @@ -25,7 +25,11 @@ func (s *ObjectTokenStore) RefreshClaim(ctx context.Context, key string) (bool, if errProbe := s.ensureRefreshConditionalCreate(ctx); errProbe != nil { return false, errProbe } - return s.createRefreshObject(ctx, s.refreshObjectKey(key, "claim"), []byte("pending")) + claimed, errClaim := s.createRefreshObject(ctx, s.refreshObjectKey(key, "claim"), []byte("pending")) + if errClaim == nil && claimed { + s.refreshClaims.Store(key, struct{}{}) + } + return claimed, errClaim } func (s *ObjectTokenStore) RefreshRead(ctx context.Context, key string) ([]byte, error) { @@ -53,6 +57,7 @@ func (s *ObjectTokenStore) RefreshRead(ctx context.Context, key string) ([]byte, } func (s *ObjectTokenStore) RefreshComplete(ctx context.Context, key string, receipt []byte) error { + s.refreshClaims.Delete(key) created, errCreate := s.createRefreshObject(ctx, s.refreshObjectKey(key, "receipt"), receipt) if errCreate != nil { return errCreate @@ -63,25 +68,72 @@ func (s *ObjectTokenStore) RefreshComplete(ctx context.Context, key string, rece return nil } +// RefreshRelease deletes a pending claim owned by this store using a single +// unretried HTTP request. Uncertain responses fail closed without retrying so a +// delayed or retried DELETE can never erase a successor claimant's lock. +func (s *ObjectTokenStore) RefreshRelease(ctx context.Context, key string) error { + if s == nil || s.client == nil { + return fmt.Errorf("object refresh journal is unavailable") + } + if _, owned := s.refreshClaims.LoadAndDelete(key); !owned { + return fmt.Errorf("refresh claim is not owned by this store") + } + receiptExists, errReceipt := s.headRefreshObject(ctx, s.refreshObjectKey(key, "receipt")) + if errReceipt != nil { + return errReceipt + } + if receiptExists { + return fmt.Errorf("refresh receipt already exists") + } + return s.deleteRefreshObject(ctx, s.refreshObjectKey(key, "claim")) +} + func (s *ObjectTokenStore) refreshObjectKey(key, kind string) string { return path.Join(s.cfg.Prefix, "codex-refresh", key, kind) } -func (s *ObjectTokenStore) createRefreshObject(ctx context.Context, key string, data []byte) (bool, error) { - headers := http.Header{"If-None-Match": []string{"*"}} - // The bundled minio PutObjectOptions quotes "*" as an ETag; use signed - // headers to send the actual HTTP wildcard, not the literal ETag "*". - url, errPresign := s.client.PresignHeader(ctx, http.MethodPut, s.cfg.Bucket, key, time.Minute, nil, headers) +func newSingleAttemptObjectTransport() *http.Transport { + if base, ok := http.DefaultTransport.(*http.Transport); ok && base != nil { + cloned := base.Clone() + cloned.DisableKeepAlives = true + return cloned + } + return &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DisableKeepAlives: true, + } +} + +func (s *ObjectTokenStore) singleAttemptRefreshRequest(ctx context.Context, method, key string, headers http.Header, data []byte) (*http.Response, error) { + presignedURL, errPresign := s.client.PresignHeader(ctx, method, s.cfg.Bucket, key, time.Minute, nil, headers) if errPresign != nil { - return false, fmt.Errorf("sign conditional refresh journal write: %w", errPresign) + return nil, fmt.Errorf("sign refresh journal %s: %w", method, errPresign) + } + var body io.Reader + if data != nil { + body = bytes.NewReader(data) } - req, errRequest := http.NewRequestWithContext(ctx, http.MethodPut, url.String(), bytes.NewReader(data)) + req, errRequest := http.NewRequestWithContext(ctx, method, presignedURL.String(), body) if errRequest != nil { - return false, fmt.Errorf("create conditional refresh journal request") + return nil, fmt.Errorf("create refresh journal %s request", method) } - req.Header = headers - client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} - resp, errDo := client.Do(req) + if len(headers) > 0 { + req.Header = headers + } + transport := newSingleAttemptObjectTransport() + defer transport.CloseIdleConnections() + client := &http.Client{ + Transport: transport, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + return client.Do(req) +} + +func (s *ObjectTokenStore) createRefreshObject(ctx context.Context, key string, data []byte) (bool, error) { + headers := http.Header{"If-None-Match": []string{"*"}} + // The bundled minio PutObjectOptions quotes "*" as an ETag; use signed + // headers to send the actual HTTP wildcard, not the literal ETag "*". + resp, errDo := s.singleAttemptRefreshRequest(ctx, http.MethodPut, key, headers, data) if errDo != nil { return false, fmt.Errorf("conditional refresh journal write outcome unknown") } @@ -99,6 +151,41 @@ func (s *ObjectTokenStore) createRefreshObject(ctx context.Context, key string, return true, nil } +func (s *ObjectTokenStore) headRefreshObject(ctx context.Context, key string) (bool, error) { + resp, errDo := s.singleAttemptRefreshRequest(ctx, http.MethodHead, key, nil, nil) + if errDo != nil { + return false, fmt.Errorf("refresh journal receipt check outcome unknown") + } + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + log.Warnf("close refresh journal head response: %v", errClose) + } + }() + if resp.StatusCode == http.StatusNotFound { + return false, nil + } + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return true, nil + } + return false, fmt.Errorf("refresh journal receipt check returned HTTP %d", resp.StatusCode) +} + +func (s *ObjectTokenStore) deleteRefreshObject(ctx context.Context, key string) error { + resp, errDo := s.singleAttemptRefreshRequest(ctx, http.MethodDelete, key, nil, nil) + if errDo != nil { + return fmt.Errorf("refresh journal claim delete outcome unknown") + } + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + log.Warnf("close refresh journal delete response: %v", errClose) + } + }() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("refresh journal claim delete returned HTTP %d", resp.StatusCode) + } + return nil +} + func (s *ObjectTokenStore) ensureRefreshConditionalCreate(ctx context.Context) error { s.refreshProbeMu.Lock() defer s.refreshProbeMu.Unlock() diff --git a/internal/store/object_refresh_journal_test.go b/internal/store/object_refresh_journal_test.go index 88715e63f47..801537e9424 100644 --- a/internal/store/object_refresh_journal_test.go +++ b/internal/store/object_refresh_journal_test.go @@ -5,6 +5,8 @@ import ( "io" "net/http" "net/http/httptest" + "os" + "os/exec" "strconv" "strings" "sync" @@ -131,4 +133,289 @@ func exerciseSharedRefreshJournal(t *testing.T, journals []codex.RefreshJournal) t.Fatalf("completed unknown outcome was reclaimed: %v, %v", claimed, errClaim) } } + if errReleaseCompleted := owner.RefreshRelease(ctx, key); errReleaseCompleted == nil { + t.Fatal("completed receipt must never be released") + } + releaseKey := strings.Repeat("c", 64) + claimedRelease, errClaimRelease := journals[0].RefreshClaim(ctx, releaseKey) + if !claimedRelease || errClaimRelease != nil { + t.Fatalf("claim releaseKey: %v, %v", claimedRelease, errClaimRelease) + } + if len(journals) > 1 { + if errForeignRelease := journals[len(journals)-1].RefreshRelease(ctx, releaseKey); errForeignRelease == nil { + t.Fatal("non-owner store released another store's pending claim") + } + } + if errRelease := journals[0].RefreshRelease(ctx, releaseKey); errRelease != nil { + t.Fatalf("release pending claim: %v", errRelease) + } + reclaimed, errReclaim := journals[len(journals)-1].RefreshClaim(ctx, releaseKey) + if !reclaimed || errReclaim != nil { + t.Fatalf("released pre-send claim could not be reclaimed: %v, %v", reclaimed, errReclaim) + } + if errStaleRelease := journals[0].RefreshRelease(ctx, releaseKey); errStaleRelease == nil { + t.Fatal("previous owner released a successor store's active claim") + } +} + +func TestObjectRefreshReleaseDoesNotRetryOrDeleteSuccessorClaim(t *testing.T) { + ctx := context.Background() + key := strings.Repeat("d", 64) + var mu sync.Mutex + objects := map[string][]byte{} + deleteCalls := 0 + var storeB, storeC *ObjectTokenStore + successorClaimed := false + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodPut: + data, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Error(errRead) + w.WriteHeader(http.StatusInternalServerError) + return + } + mu.Lock() + _, exists := objects[r.URL.Path] + if exists { + mu.Unlock() + w.WriteHeader(http.StatusPreconditionFailed) + return + } + objects[r.URL.Path] = data + mu.Unlock() + w.Header().Set("ETag", `"synthetic-etag"`) + w.WriteHeader(http.StatusOK) + case http.MethodGet, http.MethodHead: + mu.Lock() + data, exists := objects[r.URL.Path] + mu.Unlock() + if !exists { + w.WriteHeader(http.StatusNotFound) + return + } + w.Header().Set("ETag", `"synthetic-etag"`) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.Header().Set("Last-Modified", "Thu, 01 Jan 2026 00:00:00 GMT") + if r.Method == http.MethodGet { + _, _ = w.Write(data) + } + case http.MethodDelete: + if strings.HasSuffix(r.URL.Path, "/"+key+"/claim") { + mu.Lock() + deleteCalls++ + callNum := deleteCalls + delete(objects, r.URL.Path) + mu.Unlock() + if callNum == 1 { + // Simulate S3 applying the delete while the gateway returns a retryable 503, + // and a successor instance acquiring the claim before any client retry. + claimedB, errClaimB := storeB.RefreshClaim(ctx, key) + if errClaimB != nil || !claimedB { + t.Errorf("successor claim after applied delete failed: claimed=%v, err=%v", claimedB, errClaimB) + } else { + mu.Lock() + successorClaimed = true + mu.Unlock() + } + w.WriteHeader(http.StatusServiceUnavailable) + return + } + } else { + mu.Lock() + delete(objects, r.URL.Path) + mu.Unlock() + } + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected method %s", r.Method) + w.WriteHeader(http.StatusInternalServerError) + } + })) + defer server.Close() + + newStore := func() *ObjectTokenStore { + t.Helper() + s, errNew := NewObjectTokenStore(ObjectStoreConfig{ + Endpoint: strings.TrimPrefix(server.URL, "http://"), + Bucket: "test-bucket", + AccessKey: "synthetic", + SecretKey: "synthetic", + Region: "us-east-1", + PathStyle: true, + LocalRoot: t.TempDir(), + }) + if errNew != nil { + t.Fatal(errNew) + } + return s + } + storeA := newStore() + storeB = newStore() + storeC = newStore() + + claimedA, errClaimA := storeA.RefreshClaim(ctx, key) + if errClaimA != nil || !claimedA { + t.Fatalf("storeA initial claim: claimed=%v, err=%v", claimedA, errClaimA) + } + if errReleaseB := storeB.RefreshRelease(ctx, key); errReleaseB == nil { + t.Fatal("non-owner storeB must not be allowed to release storeA's claim") + } + + errReleaseA := storeA.RefreshRelease(ctx, key) + if errReleaseA == nil { + t.Fatal("uncertain 503 DELETE response must fail closed on storeA") + } + + mu.Lock() + gotDeletes := deleteCalls + gotSuccessor := successorClaimed + mu.Unlock() + if !gotSuccessor { + t.Fatal("successor storeB did not acquire claim") + } + if gotDeletes != 1 { + t.Fatalf("claim DELETE calls = %d, want 1 (must not retry and delete successor claim)", gotDeletes) + } + + claimedC, errClaimC := storeC.RefreshClaim(ctx, key) + if errClaimC != nil || claimedC { + t.Fatalf("storeB's active claim was erased (storeC claimed=%v, err=%v)", claimedC, errClaimC) + } +} + +func TestObjectRefreshJournalHonorsEnvironmentProxy(t *testing.T) { + if os.Getenv("CLIPROXY_TEST_OBJECT_PROXY") == "1" { + ctx := context.Background() + store, errNew := NewObjectTokenStore(ObjectStoreConfig{ + Endpoint: "s3-proxy-only.invalid:80", + Bucket: "proxy-bucket", + AccessKey: "synthetic", + SecretKey: "synthetic", + Region: "us-east-1", + PathStyle: true, + LocalRoot: t.TempDir(), + }) + if errNew != nil { + t.Fatal(errNew) + } + key := strings.Repeat("e", 64) + claimed, errClaim := store.RefreshClaim(ctx, key) + if errClaim != nil || !claimed { + t.Fatalf("RefreshClaim via HTTP_PROXY failed: claimed=%v, err=%v", claimed, errClaim) + } + if errRelease := store.RefreshRelease(ctx, key); errRelease != nil { + t.Fatalf("RefreshRelease via HTTP_PROXY failed: %v", errRelease) + } + reclaimed, errReclaim := store.RefreshClaim(ctx, key) + if errReclaim != nil || !reclaimed { + t.Fatalf("reclaim via HTTP_PROXY failed: claimed=%v, err=%v", reclaimed, errReclaim) + } + if errComplete := store.RefreshComplete(ctx, key, []byte(`{"value":{"access_token":"ok"}}`)); errComplete != nil { + t.Fatalf("RefreshComplete via HTTP_PROXY failed: %v", errComplete) + } + return + } + + var mu sync.Mutex + objects := map[string][]byte{} + proxiedRequests := 0 + + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + switch r.Method { + case http.MethodPut: + if _, exists := objects[r.URL.Path]; exists { + w.WriteHeader(http.StatusPreconditionFailed) + return + } + data, errRead := io.ReadAll(r.Body) + if errRead != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + objects[r.URL.Path] = data + w.Header().Set("ETag", `"proxy-etag"`) + w.WriteHeader(http.StatusOK) + case http.MethodHead, http.MethodGet: + data, exists := objects[r.URL.Path] + if !exists { + w.WriteHeader(http.StatusNotFound) + return + } + w.Header().Set("ETag", `"proxy-etag"`) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.Header().Set("Last-Modified", "Thu, 01 Jan 2026 00:00:00 GMT") + if r.Method == http.MethodGet { + _, _ = w.Write(data) + } + case http.MethodDelete: + delete(objects, r.URL.Path) + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + })) + defer backend.Close() + + proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + proxiedRequests++ + mu.Unlock() + outReq, errReq := http.NewRequestWithContext(r.Context(), r.Method, backend.URL+r.URL.RequestURI(), r.Body) + if errReq != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + outReq.Header = r.Header.Clone() + resp, errDo := backend.Client().Do(outReq) + if errDo != nil { + w.WriteHeader(http.StatusBadGateway) + return + } + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + t.Errorf("close backend response: %v", errClose) + } + }() + for k, vals := range resp.Header { + for _, v := range vals { + w.Header().Add(k, v) + } + } + w.WriteHeader(resp.StatusCode) + _, _ = io.Copy(w, resp.Body) + })) + defer proxyServer.Close() + + binary, errExecutable := os.Executable() + if errExecutable != nil { + t.Fatal(errExecutable) + } + cmd := exec.Command(binary, "-test.run=^TestObjectRefreshJournalHonorsEnvironmentProxy$") + var filteredEnv []string + for _, entry := range os.Environ() { + upper := strings.ToUpper(entry) + if strings.HasPrefix(upper, "HTTP_PROXY=") || strings.HasPrefix(upper, "HTTPS_PROXY=") || strings.HasPrefix(upper, "NO_PROXY=") { + continue + } + filteredEnv = append(filteredEnv, entry) + } + cmd.Env = append(filteredEnv, + "CLIPROXY_TEST_OBJECT_PROXY=1", + "HTTP_PROXY="+proxyServer.URL, + "HTTPS_PROXY="+proxyServer.URL, + "NO_PROXY=", + ) + if output, errRun := cmd.CombinedOutput(); errRun != nil { + t.Fatalf("subprocess proxy test failed: %v\n%s", errRun, output) + } + mu.Lock() + gotProxied := proxiedRequests + mu.Unlock() + if gotProxied == 0 { + t.Fatal("expected refresh journal requests to traverse HTTP_PROXY") + } } diff --git a/internal/store/objectstore.go b/internal/store/objectstore.go index 22db97cb6b2..51513c129e6 100644 --- a/internal/store/objectstore.go +++ b/internal/store/objectstore.go @@ -53,6 +53,7 @@ type ObjectTokenStore struct { putObjectFn func(ctx context.Context, key string, data []byte, contentType string) error refreshProbeMu sync.Mutex refreshProbeReady bool + refreshClaims sync.Map } // NewObjectTokenStore initializes an object storage backed token store. diff --git a/internal/store/postgres_refresh_journal.go b/internal/store/postgres_refresh_journal.go index 52d2b8f9f36..31470318d93 100644 --- a/internal/store/postgres_refresh_journal.go +++ b/internal/store/postgres_refresh_journal.go @@ -32,6 +32,9 @@ func (s *PostgresStore) RefreshClaim(ctx context.Context, key string) (bool, err return false, errInsert } count, errCount := result.RowsAffected() + if errCount == nil && count == 1 { + s.refreshClaims.Store(key, struct{}{}) + } return count == 1, errCount } @@ -80,6 +83,7 @@ func (s *PostgresStore) RefreshRead(ctx context.Context, key string) ([]byte, er } func (s *PostgresStore) RefreshComplete(ctx context.Context, key string, receipt []byte) error { + s.refreshClaims.Delete(key) result, errUpdate := s.db.ExecContext(ctx, "UPDATE "+s.refreshTable()+" SET receipt = $2 WHERE id = $1 AND receipt IS NULL", key, receipt) if errUpdate != nil { return errUpdate @@ -93,3 +97,33 @@ func (s *PostgresStore) RefreshComplete(ctx context.Context, key string, receipt } return nil } + +func (s *PostgresStore) RefreshRelease(ctx context.Context, key string) error { + if s == nil || s.db == nil { + return fmt.Errorf("postgres refresh journal is unavailable") + } + if _, owned := s.refreshClaims.LoadAndDelete(key); !owned { + return fmt.Errorf("refresh claim is not owned by this store") + } + tx, errBegin := s.db.BeginTx(ctx, nil) + if errBegin != nil { + return errBegin + } + defer func() { + if errRollback := tx.Rollback(); errRollback != nil && !errors.Is(errRollback, sql.ErrTxDone) { + log.Warnf("postgres refresh release: rollback: %v", errRollback) + } + }() + result, errDelete := tx.ExecContext(ctx, "DELETE FROM "+s.refreshTable()+" WHERE id = $1 AND receipt IS NULL", key) + if errDelete != nil { + return errDelete + } + count, errCount := result.RowsAffected() + if errCount != nil { + return errCount + } + if count != 1 { + return fmt.Errorf("refresh receipt already completed or claim missing") + } + return tx.Commit() +} diff --git a/internal/store/postgres_refresh_journal_test.go b/internal/store/postgres_refresh_journal_test.go index c9d387a6058..7c28f60cedc 100644 --- a/internal/store/postgres_refresh_journal_test.go +++ b/internal/store/postgres_refresh_journal_test.go @@ -86,6 +86,13 @@ func (c *refreshSQLConn) ExecContext(_ context.Context, query string, args []dri c.database.rows[key] = append([]byte(nil), args[1].Value.([]byte)...) return driver.RowsAffected(1), nil } + if strings.HasPrefix(query, "DELETE FROM ") && strings.Contains(query, "AND receipt IS NULL") { + if data, exists := c.database.rows[key]; !exists || data != nil { + return driver.RowsAffected(0), nil + } + delete(c.database.rows, key) + return driver.RowsAffected(1), nil + } return nil, fmt.Errorf("unexpected journal SQL: %s", query) } func (c *refreshSQLConn) QueryContext(_ context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { diff --git a/internal/store/postgresstore.go b/internal/store/postgresstore.go index 1db51c28e7c..43ae262eb05 100644 --- a/internal/store/postgresstore.go +++ b/internal/store/postgresstore.go @@ -50,6 +50,7 @@ type PostgresStore struct { persistAuthFn func(ctx context.Context, relID string, data []byte) error refreshSchemaMu sync.Mutex refreshSchemaReady bool + refreshClaims sync.Map } // NewPostgresStore establishes a connection to PostgreSQL and prepares the local workspace. diff --git a/internal/thinking/apply.go b/internal/thinking/apply.go index 348d40fcf09..9f8f628b1b1 100644 --- a/internal/thinking/apply.go +++ b/internal/thinking/apply.go @@ -316,12 +316,19 @@ func applyThinkingDocCore(doc *ojson.Doc, docValid bool, sourceBody []byte, mode } // 3. Model capability check + if nativeResponses { + normalized, errNormalize := normalizeNativeResponsesEffortDoc(doc, docValid, modelInfo, applier, fromFormat, providerFormat, HasThinkingSuffix(model)) + modified = modified || normalized + if errNormalize != nil { + return modified, errNormalize + } + } if !suffixResult.HasSuffix && len(sourceBody) > 0 && isResponsesFormat(fromFormat) && !docValid && hasThinkingConfig(extractConfigurationUpdateConfig(sourceBody)) { // Do not rebuild a malformed target from a separate source update. return modified, nil } if nativeResponses && !suffixResult.HasSuffix { - // Native Responses keeps the top-level baseline and in-turn updates as-is. + // Native Responses preserves the baseline and update timeline after validation. if log.IsLevelEnabled(log.DebugLevel) && (modelInfo.Thinking != nil || modelInfo.UserDefined) { if config := extractCodexUsageConfigDoc(doc, docValid); hasThinkingConfig(config) { fields := log.Fields{ diff --git a/internal/thinking/apply_codex_usage_test.go b/internal/thinking/apply_codex_usage_test.go index 684c95b1ba5..12e16a5c16d 100644 --- a/internal/thinking/apply_codex_usage_test.go +++ b/internal/thinking/apply_codex_usage_test.go @@ -151,7 +151,7 @@ func TestExtractCodexReasoningEffortWithConfigurationUpdateTargetRouting(t *test name = "supported" } t.Run(name, func(t *testing.T) { - info := ®istry.ModelInfo{ID: "opaque-route", Type: "codex", SupportConfigurationUpdate: supported, Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "high", "xhigh"}}} + info := ®istry.ModelInfo{ID: "opaque-route", Type: "codex", SupportConfigurationUpdate: supported, Thinking: ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high", "xhigh"}}} body, err := thinking.ApplyThinkingWithModelInfoAndSummary([]byte(source), []byte(source), "opaque-route(high)", "openai-response", "codex", "codex", info, thinking.SummaryConfig{}) if err != nil { t.Fatalf("ApplyThinkingWithModelInfoAndSummary() error = %v", err) @@ -348,6 +348,7 @@ func TestApplyThinkingLogsNativeResponsesEffectiveEffort(t *testing.T) { tests := []struct { name string body string + wantBody string wantEffort string wantLevel thinking.ThinkingLevel wantMode thinking.ThinkingMode @@ -379,9 +380,10 @@ func TestApplyThinkingLogsNativeResponsesEffectiveEffort(t *testing.T) { wantEffort: "xhigh", wantLevel: thinking.LevelXHigh, wantMode: thinking.ModeLevel, }, { - name: "update disables thinking", + name: "unsupported none uses minimum effort", body: `{"model":"gpt-6-sol","reasoning":{"effort":"high"},"input":[{"type":"configuration_update","reasoning":{"effort":"none"}}]}`, - wantEffort: "none", wantMode: thinking.ModeNone, wantBaseline: thinking.LevelHigh, + wantBody: `{"model":"gpt-6-sol","reasoning":{"effort":"high"},"input":[{"type":"configuration_update","reasoning":{"effort":"low"}}]}`, + wantEffort: "low", wantLevel: thinking.LevelLow, wantMode: thinking.ModeLevel, wantBaseline: thinking.LevelHigh, }, } for _, tc := range tests { @@ -408,8 +410,12 @@ func TestApplyThinkingLogsNativeResponsesEffectiveEffort(t *testing.T) { if err != nil { t.Fatalf("ApplyThinking() error = %v", err) } - if !bytes.Equal(applied, body) { - t.Fatalf("native Responses body changed: got %s, want %s", applied, body) + wantBody := body + if tc.wantBody != "" { + wantBody = []byte(tc.wantBody) + } + if !bytes.Equal(applied, wantBody) { + t.Fatalf("native Responses body = %s, want %s", applied, wantBody) } if got := thinking.ExtractTranslatedReasoningEffort(applied, "codex"); got != tc.wantEffort { t.Errorf("effective effort = %q, want %q", got, tc.wantEffort) diff --git a/internal/thinking/apply_responses_effort_test.go b/internal/thinking/apply_responses_effort_test.go new file mode 100644 index 00000000000..f7e1afcb36c --- /dev/null +++ b/internal/thinking/apply_responses_effort_test.go @@ -0,0 +1,140 @@ +package thinking_test + +import ( + "bytes" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" + _ "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking/provider/codex" +) + +func TestApplyThinkingNativeResponsesValidatesEffort(t *testing.T) { + for _, model := range []string{"gpt-6-sol", "gpt-6.1-sol"} { + for _, format := range []string{"openai-response", "codex"} { + for _, tc := range []struct { + name string + suffix string + body string + want string + }{ + { + name: "unsupported baseline uses minimum effort", + body: `{"reasoning":{"effort":"none","summary":"auto","other":7},"input":[{"role":"user","content":"hi"}]}`, + want: `{"reasoning":{"effort":"low","summary":"auto","other":7},"input":[{"role":"user","content":"hi"}]}`, + }, + { + name: "every update is validated without flattening the baseline", + body: `{"reasoning":{"effort":"xhigh","summary":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"none","other":7}},{"role":"user","content":"first"},{"type":"configuration_update","reasoning":{"effort":"high"}},{"role":"assistant","content":"reply"},{"type":"configuration_update","reasoning":{"effort":"none"}}]}`, + want: `{"reasoning":{"effort":"xhigh","summary":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"low","other":7}},{"role":"user","content":"first"},{"type":"configuration_update","reasoning":{"effort":"high"}},{"role":"assistant","content":"reply"},{"type":"configuration_update","reasoning":{"effort":"low"}}]}`, + }, + { + name: "update does not invent a baseline", + body: `{"input":[{"type":"configuration_update","reasoning":{"effort":"none"}},{"role":"user","content":"hi"}]}`, + want: `{"input":[{"type":"configuration_update","reasoning":{"effort":"low"}},{"role":"user","content":"hi"}]}`, + }, + { + name: "suffix overrides baseline but updates are still validated", + suffix: "(high)", + body: `{"reasoning":{"effort":"invalid","summary":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"none"}}]}`, + want: `{"reasoning":{"effort":"high","summary":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"low"}}]}`, + }, + { + name: "invalid suffix does not bypass effort validation", + suffix: "(invalid)", + body: `{"reasoning":{"effort":"none"},"input":[{"type":"configuration_update","reasoning":{"effort":"none"}}]}`, + want: `{"reasoning":{"effort":"low"},"input":[{"type":"configuration_update","reasoning":{"effort":"low"}}]}`, + }, + { + name: "auto uses the existing model fallback", + body: `{"reasoning":{"effort":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"auto"}}]}`, + want: `{"reasoning":{"effort":"medium"},"input":[{"type":"configuration_update","reasoning":{"effort":"medium"}}]}`, + }, + { + name: "supported efforts remain byte identical", + body: `{ "reasoning": {"effort":"max", "summary":"auto"}, "input":[{"type":"configuration_update","reasoning":{"effort":"low"}},{"type":"configuration_update","reasoning":{"effort":"medium"}},{"type":"configuration_update","reasoning":{"effort":"high"}},{"type":"configuration_update","reasoning":{"effort":"xhigh"}},{"type":"configuration_update","reasoning":{"effort":"max"}}] }`, + }, + { + name: "missing effort remains absent", + body: `{"reasoning":{"summary":"auto"},"input":[{"type":"configuration_update","tools":[]},{"role":"user","content":"hi"}]}`, + }, + } { + t.Run(model+"/"+format+"/"+tc.name, func(t *testing.T) { + var info *registry.ModelInfo + for _, candidate := range registry.GetCodexPlusModels() { + if candidate.ID == model { + info = candidate + break + } + } + if info == nil || !info.SupportConfigurationUpdate { + t.Fatalf("missing native Responses model definition for %s", model) + } + got, errApply := thinking.ApplyThinkingWithModelInfo([]byte(tc.body), nil, model+tc.suffix, format, "codex", "codex", info) + if errApply != nil { + t.Fatalf("ApplyThinkingWithModelInfo() error = %v", errApply) + } + want := tc.want + if want == "" { + want = tc.body + } + if !bytes.Equal(got, []byte(want)) { + t.Fatalf("body = %s, want %s", got, want) + } + }) + } + } + } +} + +func TestApplyThinkingNativeResponsesRespectsModelCapabilities(t *testing.T) { + const body = `{"reasoning":{"effort":"none","summary":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"none"}}]}` + for _, tc := range []struct { + name string + thinking *registry.ThinkingSupport + userDefined bool + want string + }{ + { + name: "none is a supported level", + thinking: ®istry.ThinkingSupport{Levels: []string{"none", "low", "high"}}, + want: body, + }, + { + name: "model permits zero effort", + thinking: ®istry.ThinkingSupport{ZeroAllowed: true, Levels: []string{"low", "high"}}, + want: body, + }, + { + name: "missing thinking metadata remains opaque", + want: body, + }, + { + name: "missing levels remain opaque", + thinking: ®istry.ThinkingSupport{}, + want: body, + }, + { + name: "user defined capabilities remain opaque", + thinking: ®istry.ThinkingSupport{Levels: []string{"low", "high"}}, + userDefined: true, + want: body, + }, + { + name: "configured model uses its lowest level rather than a hardcoded low", + thinking: ®istry.ThinkingSupport{Levels: []string{"high", "medium"}}, + want: `{"reasoning":{"effort":"medium","summary":"auto"},"input":[{"type":"configuration_update","reasoning":{"effort":"medium"}}]}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + info := ®istry.ModelInfo{ID: "opaque-route", Type: "codex", SupportConfigurationUpdate: true, Thinking: tc.thinking, UserDefined: tc.userDefined} + got, errApply := thinking.ApplyThinkingWithModelInfo([]byte(body), nil, info.ID, "openai-response", "codex", "codex", info) + if errApply != nil { + t.Fatalf("ApplyThinkingWithModelInfo() error = %v", errApply) + } + if string(got) != tc.want { + t.Fatalf("body = %s, want %s", got, tc.want) + } + }) + } +} diff --git a/internal/thinking/configuration_update.go b/internal/thinking/configuration_update.go index 94ef8cb3334..70651f56ac5 100644 --- a/internal/thinking/configuration_update.go +++ b/internal/thinking/configuration_update.go @@ -1,9 +1,11 @@ package thinking import ( + "strconv" "strings" "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" ) func isResponsesFormat(format string) bool { @@ -54,6 +56,55 @@ func extractConfigurationUpdateConfigFromInput(input ojson.Result) ThinkingConfi } } +// normalizeNativeResponsesEffortDoc validates each effort without collapsing the +// baseline or update timeline. A valid model suffix replaces the baseline later. +func normalizeNativeResponsesEffortDoc(doc *ojson.Doc, docValid bool, modelInfo *registry.ModelInfo, applier ProviderApplier, fromFormat, toFormat string, skipBaseline bool) (bool, error) { + if doc == nil || !docValid || IsUserDefinedModel(modelInfo) || modelInfo.Thinking == nil || len(modelInfo.Thinking.Levels) == 0 { + return false, nil + } + + var paths []string + if !skipBaseline { + paths = append(paths, "reasoning.effort") + } + if input := doc.Get("input"); input.IsArray() { + input.ForEach(func(index, item ojson.Result) bool { + if item.Get("type").String() == "configuration_update" { + paths = append(paths, "input."+strconv.FormatInt(index.Int(), 10)+".reasoning.effort") + } + return true + }) + } + + modified := false + for _, path := range paths { + effort := doc.Get(path) + if effort.Type != ojson.String || strings.TrimSpace(effort.String()) == "" || HasLevel(modelInfo.Thinking.Levels, effort.String()) { + continue + } + config := ThinkingConfig{Mode: ModeLevel, Level: ThinkingLevel(strings.ToLower(strings.TrimSpace(effort.String())))} + validated, errValidate := ValidateConfig(config, modelInfo, fromFormat, toFormat, false) + if errValidate != nil { + return modified, errValidate + } + + // Use the provider's output rules, including ModeNone with a minimum Level. + normalized := ojson.NewDocString("{}") + normalizedValid := true + if _, errApply := invokeProviderApplierOnDoc(applier, normalized, &normalizedValid, *validated, modelInfo); errApply != nil { + return modified, errApply + } + value := normalized.Get("reasoning.effort") + if value.Type == ojson.String && value.String() != effort.String() { + if errSet := doc.Set(path, value.String()); errSet != nil { + return modified, errSet + } + modified = true + } + } + return modified, nil +} + // CollapseConfigurationUpdates removes every configuration_update input item. // Unless keepTopLevelEffort is true, the last nonempty update effort is also // promoted into the top-level reasoning.effort. Targets that reject diff --git a/internal/thinking/summary.go b/internal/thinking/summary.go index 78d3862afd9..287dc80abd6 100644 --- a/internal/thinking/summary.go +++ b/internal/thinking/summary.go @@ -324,6 +324,9 @@ func applySummaryConfigForProviderDoc(doc *ojson.Doc, docValid bool, format, mod value := "omitted" if enabled { value = "summarized" + if strings.EqualFold(strings.TrimSpace(doc.Get("thinking.display").String()), "updates") { + value = "updates" + } } if doc.Set("thinking.display", value) == nil { modified = true @@ -554,7 +557,7 @@ func claudeSummaryConfigFromGetter(get func(string) ojson.Result, path string) ( return SummaryConfig{}, false } switch strings.ToLower(strings.TrimSpace(value.String())) { - case "summarized": + case "summarized", "updates": return SummaryConfig{Mode: SummaryEnabled, Detail: "auto"}, true case "omitted": return SummaryConfig{Mode: SummaryDisabled}, true diff --git a/internal/thinking/summary_test.go b/internal/thinking/summary_test.go index ba18c9d45ac..3c1deb6bac4 100644 --- a/internal/thinking/summary_test.go +++ b/internal/thinking/summary_test.go @@ -37,13 +37,17 @@ func TestExtractSummaryConfig(t *testing.T) { {name: "responses boolean summary invalid", format: "openai-response", body: `{"reasoning":{"summary":true}}`, wantMode: SummaryUnspecified}, {name: "responses deprecated generate summary", format: "openai-response", body: `{"reasoning":{"generate_summary":"detailed"}}`, wantMode: SummaryEnabled, wantDetail: "detailed"}, {name: "claude summarized", format: "claude", body: `{"thinking":{"type":"adaptive","display":"summarized"}}`, wantMode: SummaryEnabled, wantDetail: "auto"}, + {name: "claude updates", format: "claude", body: `{"thinking":{"type":"adaptive","display":"updates"}}`, wantMode: SummaryEnabled, wantDetail: "auto"}, {name: "claude omitted", format: "claude", body: `{"thinking":{"type":"enabled","budget_tokens":2048,"display":"omitted"}}`, wantMode: SummaryDisabled}, {name: "claude display without type is invalid", format: "claude", body: `{"thinking":{"display":"summarized"}}`, wantMode: SummaryUnspecified}, + {name: "claude updates without type is invalid", format: "claude", body: `{"thinking":{"display":"updates"}}`, wantMode: SummaryUnspecified}, {name: "claude display with auto type is invalid", format: "claude", body: `{"thinking":{"type":"auto","display":"summarized"}}`, wantMode: SummaryUnspecified}, // ApplySummaryConfig runs before ApplyThinking fills budget_tokens, so an // absent budget must not be read as inactive thinking. {name: "claude enabled display without budget is valid", format: "claude", body: `{"thinking":{"type":"enabled","display":"summarized"}}`, wantMode: SummaryEnabled, wantDetail: "auto"}, + {name: "claude enabled updates without budget is valid", format: "claude", body: `{"thinking":{"type":"enabled","display":"updates"}}`, wantMode: SummaryEnabled, wantDetail: "auto"}, {name: "claude enabled display with zero budget is invalid", format: "claude", body: `{"thinking":{"type":"enabled","budget_tokens":0,"display":"summarized"}}`, wantMode: SummaryUnspecified}, + {name: "claude enabled updates with zero budget is invalid", format: "claude", body: `{"thinking":{"type":"enabled","budget_tokens":0,"display":"updates"}}`, wantMode: SummaryUnspecified}, {name: "claude auto compatibility budget summarized", format: "claude", body: `{"thinking":{"type":"enabled","budget_tokens":-1,"display":"summarized"}}`, wantMode: SummaryEnabled, wantDetail: "auto"}, {name: "claude auto compatibility budget omitted", format: "claude", body: `{"thinking":{"type":"enabled","budget_tokens":-1,"display":"omitted"}}`, wantMode: SummaryDisabled}, {name: "gemini include true", format: "gemini", body: `{"generationConfig":{"thinkingConfig":{"includeThoughts":true}}}`, wantMode: SummaryEnabled, wantDetail: "auto"}, @@ -107,7 +111,9 @@ func TestApplySummaryConfig(t *testing.T) { {name: "chat disabled updates legacy include_reasoning when present", format: "openai", body: `{"reasoning_effort":"high","include_reasoning":true}`, config: SummaryConfig{Mode: SummaryDisabled}, path: "include_reasoning", want: "false"}, {name: "chat disabled invents no openrouter field", format: "openai", body: `{"reasoning_effort":"high"}`, config: SummaryConfig{Mode: SummaryDisabled}, path: "reasoning", want: ""}, {name: "claude enabled", format: "claude", body: `{"thinking":{"type":"adaptive"}}`, config: SummaryConfig{Mode: SummaryEnabled}, path: "thinking.display", want: "summarized"}, + {name: "claude enabled preserves existing updates", format: "claude", body: `{"thinking":{"type":"adaptive","display":"updates"}}`, config: SummaryConfig{Mode: SummaryEnabled}, path: "thinking.display", want: "updates"}, {name: "claude disabled", format: "claude", body: `{"thinking":{"type":"enabled","budget_tokens":2048}}`, config: SummaryConfig{Mode: SummaryDisabled}, path: "thinking.display", want: "omitted"}, + {name: "claude disabled overrides existing updates", format: "claude", body: `{"thinking":{"type":"adaptive","display":"updates"}}`, config: SummaryConfig{Mode: SummaryDisabled}, path: "thinking.display", want: "omitted"}, {name: "gemini enabled", format: "gemini", config: SummaryConfig{Mode: SummaryEnabled}, path: "generationConfig.thinkingConfig.includeThoughts", want: "true"}, {name: "gemini disabled", format: "gemini", config: SummaryConfig{Mode: SummaryDisabled}, path: "generationConfig.thinkingConfig.includeThoughts", want: "false"}, {name: "antigravity enabled", format: "antigravity", config: SummaryConfig{Mode: SummaryEnabled}, path: "request.generationConfig.thinkingConfig.includeThoughts", want: "true"}, diff --git a/internal/translator/antigravity/claude/antigravity_claude_issue7513_test.go b/internal/translator/antigravity/claude/antigravity_claude_issue7513_test.go new file mode 100644 index 00000000000..50b8060e1a5 --- /dev/null +++ b/internal/translator/antigravity/claude/antigravity_claude_issue7513_test.go @@ -0,0 +1,281 @@ +package claude + +import ( + "bytes" + "context" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" +) + +func TestConvertAntigravityResponseToClaudeNonStream_MalformedFunctionCallWithoutToolUseReturnsAPIError(t *testing.T) { + requestJSON := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + rawJSON := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": []}, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": { + "promptTokenCount": 120, + "candidatesTokenCount": 10, + "thoughtsTokenCount": 313, + "totalTokenCount": 443 + }, + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_antigravity_malformed" + } + }`) + + output := ConvertAntigravityResponseToClaudeNonStream(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, rawJSON, nil) + if got := ojson.GetBytesNoCopy(output, "stop_reason").String(); got == "refusal" { + t.Fatalf("unexpected stop_reason = %q, output: %s", got, output) + } + if got := ojson.GetBytesNoCopy(output, "type").String(); got != "error" { + t.Fatalf("type = %q, want error; output: %s", got, output) + } + if got := ojson.GetBytesNoCopy(output, "error.type").String(); got != "api_error" { + t.Fatalf("error.type = %q, want api_error; output: %s", got, output) + } + if !strings.Contains(ojson.GetBytesNoCopy(output, "error.message").String(), "MALFORMED_FUNCTION_CALL") { + t.Fatalf("error.message = %q, want mention of MALFORMED_FUNCTION_CALL; output: %s", ojson.GetBytesNoCopy(output, "error.message").String(), output) + } +} + +func TestConvertAntigravityResponseToClaudeStream_MalformedFunctionCallEmitsAPIError(t *testing.T) { + requestJSON := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + + t.Run("partless_with_usage", func(t *testing.T) { + chunk := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": []}, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": { + "promptTokenCount": 120, + "candidatesTokenCount": 10, + "thoughtsTokenCount": 313, + "totalTokenCount": 443 + }, + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_stream_1" + } + }`) + + var param any + output := bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, chunk, ¶m), nil) + output = append(output, bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + if strings.Contains(outputText, `"stop_reason":"refusal"`) { + t.Fatalf("unexpected stop_reason refusal in output:\n%s", outputText) + } + if strings.Contains(outputText, `"type":"message_delta"`) || strings.Contains(outputText, `"type":"message_stop"`) { + t.Fatalf("unexpected normal completion events in output:\n%s", outputText) + } + if !strings.Contains(outputText, "event: error\n") || !strings.Contains(outputText, `"type":"api_error"`) { + t.Fatalf("expected SSE api_error event in output:\n%s", outputText) + } + }) + + t.Run("after_thinking_closes_block_before_error", func(t *testing.T) { + chunk1 := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": [{"thought": true, "text": "planning tool call"}]} + }], + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_stream_2" + } + }`) + chunk2 := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": []}, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": { + "promptTokenCount": 120, + "candidatesTokenCount": 10, + "thoughtsTokenCount": 313, + "totalTokenCount": 443 + }, + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_stream_2" + } + }`) + + var param any + output := bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, chunk1, ¶m), nil) + output = append(output, bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, chunk2, ¶m), nil)...) + output = append(output, bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + outputText := string(output) + + stopIdx := strings.Index(outputText, "event: content_block_stop\n") + errIdx := strings.Index(outputText, "event: error\n") + if stopIdx < 0 || errIdx < 0 || stopIdx >= errIdx { + t.Fatalf("expected content_block_stop before error event in output:\n%s", outputText) + } + if strings.Contains(outputText, `"type":"message_delta"`) || strings.Contains(outputText, `"type":"message_stop"`) { + t.Fatalf("unexpected normal completion events after MALFORMED_FUNCTION_CALL:\n%s", outputText) + } + }) + + t.Run("without_usage_and_with_duplicate_terminal", func(t *testing.T) { + chunkWithoutUsage := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": []}, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_stream_3" + } + }`) + duplicateChunk := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": [{"text": "late text"}]}, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 1, "totalTokenCount": 11}, + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_stream_3" + } + }`) + + var param any + out1 := bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, chunkWithoutUsage, ¶m), nil) + lateOut := bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, duplicateChunk, ¶m), nil) + doneOut := bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil) + if len(lateOut) != 0 || len(doneOut) != 0 { + t.Fatalf("expected no chunks after error event, got late=%q done=%q", lateOut, doneOut) + } + if got := strings.Count(string(out1), "event: error\n"); got != 1 { + t.Fatalf("error event count = %d, want 1; output:\n%s", got, out1) + } + }) + + t.Run("with_valid_tool_use_preserves_tool_use", func(t *testing.T) { + toolReq := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}],"tools":[{"name":"Bash","input_schema":{"type":"object"}}]}`) + rawJSON := []byte(`{ + "response": { + "candidates": [{ + "content": { + "role": "model", + "parts": [{"functionCall": {"name": "Bash", "args": {"command": "ls"}}}] + }, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": {"promptTokenCount": 50, "candidatesTokenCount": 10, "totalTokenCount": 60}, + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_tool" + } + }`) + + nonStream := ConvertAntigravityResponseToClaudeNonStream(context.Background(), "claude-opus-5-5-high", toolReq, toolReq, rawJSON, nil) + if got := ojson.GetBytesNoCopy(nonStream, "stop_reason").String(); got != "tool_use" { + t.Fatalf("non-stream stop_reason = %q, want tool_use; output: %s", got, nonStream) + } + + var param any + streamOut := bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", toolReq, toolReq, rawJSON, ¶m), nil) + streamOut = append(streamOut, bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", toolReq, toolReq, []byte("[DONE]"), ¶m), nil)...) + streamText := string(streamOut) + if strings.Contains(streamText, "event: error\n") { + t.Fatalf("unexpected error event when valid functionCall is present:\n%s", streamText) + } + if !strings.Contains(streamText, `"stop_reason":"tool_use"`) { + t.Fatalf("expected stop_reason tool_use in stream output:\n%s", streamText) + } + }) + + t.Run("with_partial_visible_text_preserves_text", func(t *testing.T) { + nonStreamRaw := []byte(`{ + "response": { + "candidates": [{ + "content": { + "role": "model", + "parts": [{"text": "partial answer"}] + }, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": {"promptTokenCount": 50, "candidatesTokenCount": 3, "totalTokenCount": 53}, + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_partial" + } + }`) + + nonStream := ConvertAntigravityResponseToClaudeNonStream(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, nonStreamRaw, nil) + if got := ojson.GetBytesNoCopy(nonStream, "type").String(); got != "message" { + t.Fatalf("non-stream type = %q, want message preserving partial text; output: %s", got, nonStream) + } + if got := ojson.GetBytesNoCopy(nonStream, "content.0.text").String(); got != "partial answer" { + t.Fatalf("non-stream text = %q, want partial answer; output: %s", got, nonStream) + } + if got := ojson.GetBytesNoCopy(nonStream, "stop_reason").String(); got != "end_turn" { + t.Fatalf("non-stream stop_reason = %q, want end_turn; output: %s", got, nonStream) + } + + chunk1 := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": [{"text": "partial answer"}]} + }], + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_partial" + } + }`) + chunk2 := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": []}, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": {"promptTokenCount": 50, "candidatesTokenCount": 3, "totalTokenCount": 53}, + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_partial" + } + }`) + + var param any + streamOut := bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, chunk1, ¶m), nil) + streamOut = append(streamOut, bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, chunk2, ¶m), nil)...) + streamOut = append(streamOut, bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + streamText := string(streamOut) + if strings.Contains(streamText, "event: error\n") { + t.Fatalf("unexpected error event when partial visible text was already emitted:\n%s", streamText) + } + if !strings.Contains(streamText, "partial answer") || !strings.Contains(streamText, `"type":"message_stop"`) { + t.Fatalf("expected preserved partial text and message_stop in stream output:\n%s", streamText) + } + }) + + t.Run("with_empty_functionCall_placeholder_still_returns_error", func(t *testing.T) { + rawJSON := []byte(`{ + "response": { + "candidates": [{ + "content": {"role": "model", "parts": [{"functionCall": {}}]}, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": {"promptTokenCount": 50, "candidatesTokenCount": 1, "totalTokenCount": 51}, + "modelVersion": "claude-opus-5-5-high", + "responseId": "req_ag_empty_fc" + } + }`) + + nonStream := ConvertAntigravityResponseToClaudeNonStream(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, rawJSON, nil) + if got := ojson.GetBytesNoCopy(nonStream, "type").String(); got != "error" { + t.Fatalf("non-stream type = %q, want error for empty functionCall placeholder; output: %s", got, nonStream) + } + + var param any + streamOut := bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, rawJSON, ¶m), nil) + streamOut = append(streamOut, bytes.Join(ConvertAntigravityResponseToClaude(context.Background(), "claude-opus-5-5-high", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + if !strings.Contains(string(streamOut), "event: error\n") { + t.Fatalf("expected error event for empty functionCall placeholder, got:\n%s", streamOut) + } + }) +} diff --git a/internal/translator/antigravity/claude/antigravity_claude_response.go b/internal/translator/antigravity/claude/antigravity_claude_response.go index ab41a1f218d..cc005a33ec7 100644 --- a/internal/translator/antigravity/claude/antigravity_claude_response.go +++ b/internal/translator/antigravity/claude/antigravity_claude_response.go @@ -76,7 +76,9 @@ type Params struct { TotalTokenCount int64 // Cached total token count from usage metadata CachedTokenCount int64 // Cached content token count (indicates prompt caching) HasSentFinalEvents bool // Indicates if final content/message events have been sent + HasMalformedError bool // Indicates whether a MALFORMED_FUNCTION_CALL error event was already emitted HasToolUse bool // Indicates if tool use was observed in the stream + HasVisibleOutput bool // Tracks whether non-thought visible output (non-whitespace text or tool use) was observed HasContent bool // Tracks whether any content (text, thinking, or tool use) has been output HasSemanticContent bool LastSemanticKind string @@ -101,6 +103,25 @@ type Params struct { // toolUseIDCounter provides a process-wide unique counter for tool use identifiers. var toolUseIDCounter uint64 +const antigravityMalformedFunctionCallErrorPayload = `{"type":"error","error":{"type":"api_error","message":"Gemini response finished with MALFORMED_FUNCTION_CALL"}}` + +func isAntigravityMalformedFunctionCall(finishReason string, hasVisibleOutput bool) bool { + return strings.EqualFold(strings.TrimSpace(finishReason), "MALFORMED_FUNCTION_CALL") && !hasVisibleOutput +} + +func isAntigravityNonEmptyFunctionCall(fc ojson.Result) bool { + if !fc.IsObject() { + return false + } + if strings.TrimSpace(fc.Get("name").String()) != "" || strings.TrimSpace(fc.Get("id").String()) != "" { + return true + } + if args := fc.Get("args"); args.IsObject() && len(args.Map()) > 0 { + return true + } + return false +} + func antigravityClaudeToolUseID(modelName string, functionCall ojson.Result, fallback string) string { if sigcompat.SignatureProviderFromModelName(modelName) == sigcompat.SignatureProviderGemini { if stableID := util.GeminiClaudeToolUseID(functionCall.Get("id").String(), functionCall.Get("name").String(), functionCall.Get("args").Raw); stableID != "" { @@ -147,6 +168,31 @@ func ConvertAntigravityResponseToClaude(ctx context.Context, _ string, originalR if bytes.Equal(rawJSON, []byte("[DONE]")) { output := make([]byte, 0, 256) + if params.HasMalformedError && params.HasSentFinalEvents { + return [][]byte{} + } + if isAntigravityMalformedFunctionCall(params.FinishReason, params.HasVisibleOutput) { + if params.ResponseType != 0 { + if params.ResponseType == 3 && params.CurrentToolPendingEmpty && !params.CurrentToolInputEmitted { + deltaDoc := ojson.NewDocString(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"input_json_delta","partial_json":""}}`, params.ResponseIndex)) + _ = deltaDoc.Set("delta.partial_json", "{}") + output = translatorcommon.AppendSSEEventString(output, "content_block_delta", deltaDoc.String(), 3) + params.CurrentToolInputEmitted = true + params.CurrentToolPendingEmpty = false + } + output = translatorcommon.AppendSSEEventString(output, "content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, params.ResponseIndex), 3) + params.ResponseType = 0 + } + if !params.HasSentFinalEvents { + output = translatorcommon.AppendSSEEventString(output, "error", antigravityMalformedFunctionCallErrorPayload, 3) + params.HasSentFinalEvents = true + params.HasMalformedError = true + } + if len(output) > 0 { + return [][]byte{output} + } + return [][]byte{} + } if params.HasFirstResponse && !params.HasContent { output = translatorcommon.AppendSSEEventString(output, "content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"text","text":""}}`, params.ResponseIndex), 3) params.ResponseType = 1 @@ -160,6 +206,10 @@ func ConvertAntigravityResponseToClaude(ctx context.Context, _ string, originalR return [][]byte{} } + if params.HasMalformedError && params.HasSentFinalEvents { + return [][]byte{} + } + output := make([]byte, 0, 1024) appendEvent := func(event, payload string) { output = translatorcommon.AppendSSEEventString(output, event, payload, 3) @@ -269,6 +319,7 @@ func ConvertAntigravityResponseToClaude(ctx context.Context, _ string, originalR params.HasWebSearchTool = true params.WebSearchRequests = 1 params.HasContent = true + params.HasVisibleOutput = true params.ResponseType = 0 handledWebSearchGrounding = true } @@ -362,6 +413,9 @@ func ConvertAntigravityResponseToClaude(ctx context.Context, _ string, originalR if partText != "" { params.HasSemanticContent = true params.LastSemanticKind = geminiClaudeCarrierText + if strings.TrimSpace(partText) != "" { + params.HasVisibleOutput = true + } if signatureTargetsVisibleText { closeCurrentBlock() } @@ -369,13 +423,21 @@ func ConvertAntigravityResponseToClaude(ctx context.Context, _ string, originalR } } else if functionCallResult.Exists() { toolSignature := thoughtSignatureResult.String() + fcName := util.RestoreSanitizedToolName(params.ToolNameMap, functionCallResult.Get("name").String()) + isContinuation := params.ResponseType == 3 && fcName == "" && params.CurrentToolName != "" + if !isContinuation && !isAntigravityNonEmptyFunctionCall(functionCallResult) { + if hasThoughtSignature { + appendPartSignature(toolSignature, geminiClaudeCarrierPrevious, params.LastSemanticKind) + } + continue + } if cache.GetModelGroup(modelName) != "claude" { appendPartSignature(toolSignature, geminiClaudeCarrierNext, geminiClaudeCarrierFunction) } // Handle function/tool calls from the AI model // This processes tool usage requests and formats them for Claude Code API compatibility params.HasToolUse = true - fcName := util.RestoreSanitizedToolName(params.ToolNameMap, functionCallResult.Get("name").String()) + params.HasVisibleOutput = true if params.ResponseType == 3 && fcName == "" && params.CurrentToolName != "" { if fcArgsResult := functionCallResult.Get("args"); fcArgsResult.Exists() { @@ -506,6 +568,18 @@ func ConvertAntigravityResponseToClaude(ctx context.Context, _ string, originalR appendBufferedWebSearchTextBlock(params, appendEvent) } + if isAntigravityMalformedFunctionCall(params.FinishReason, params.HasVisibleOutput) && !params.HasSentFinalEvents { + if params.ResponseType != 0 { + flushPendingToolInput() + appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, params.ResponseIndex)) + params.ResponseType = 0 + } + appendEvent("error", antigravityMalformedFunctionCallErrorPayload) + params.HasSentFinalEvents = true + params.HasMalformedError = true + return [][]byte{output} + } + if params.HasUsageMetadata && params.HasFinishReason { appendFinalEvents(params, &output, false) } @@ -600,7 +674,7 @@ func resolveAntigravityClaudeStopReason(finishReason string, hasToolUse bool) st switch strings.ToUpper(strings.TrimSpace(finishReason)) { case "MAX_TOKENS": return "max_tokens" - case "SAFETY", "RECITATION", "PROHIBITED_CONTENT", "SPII", "BLOCKLIST", "IMAGE_SAFETY", "MALFORMED_RESPONSE", "MALFORMED_FUNCTION_CALL": + case "SAFETY", "RECITATION", "PROHIBITED_CONTENT", "SPII", "BLOCKLIST", "IMAGE_SAFETY", "MALFORMED_RESPONSE": return "refusal" case "STOP", "FINISH_REASON_UNSPECIFIED", "UNKNOWN", "": return "end_turn" @@ -670,6 +744,7 @@ func ConvertAntigravityResponseToClaudeNonStream(_ context.Context, _ string, or thinkingSignatureTargetKind := geminiClaudeCarrierText toolIDCounter := 0 hasToolCall := false + hasVisibleOutput := false hasSemanticContent := false lastSemanticKind := geminiClaudeCarrierAny @@ -721,6 +796,12 @@ func ConvertAntigravityResponseToClaudeNonStream(_ context.Context, _ string, or } if functionCall := part.Get("functionCall"); functionCall.Exists() { + if !isAntigravityNonEmptyFunctionCall(functionCall) { + if signature != "" { + appendSignatureCarrier(signature, geminiClaudeCarrierNext, geminiClaudeCarrierAny) + } + continue + } signatureAttachedToThought := false isClaudeTarget := cache.GetModelGroup(modelName) == "claude" if !isClaudeTarget && signature != "" && thinkingBuilder.Len() > 0 && thinkingSignature == "" { @@ -732,6 +813,7 @@ func ConvertAntigravityResponseToClaudeNonStream(_ context.Context, _ string, or flushThinking() flushText() hasToolCall = true + hasVisibleOutput = true name := util.RestoreSanitizedToolName(toolNameMap, functionCall.Get("name").String()) toolIDCounter++ @@ -810,6 +892,9 @@ func ConvertAntigravityResponseToClaudeNonStream(_ context.Context, _ string, or if text.Exists() && text.String() != "" { flushThinking() textBuilder.WriteString(text.String()) + if strings.TrimSpace(text.String()) != "" { + hasVisibleOutput = true + } hasSemanticContent = true lastSemanticKind = geminiClaudeCarrierText if visibleSignatureCarrier { @@ -830,6 +915,9 @@ func ConvertAntigravityResponseToClaudeNonStream(_ context.Context, _ string, or if finish := root.Get("response.candidates.0.finishReason"); finish.Exists() { finishReason = finish.String() } + if isAntigravityMalformedFunctionCall(finishReason, hasVisibleOutput) { + return []byte(antigravityMalformedFunctionCallErrorPayload) + } stopReason := resolveAntigravityClaudeStopReason(finishReason, hasToolCall) _ = responseDoc.Set("stop_reason", stopReason) diff --git a/internal/translator/antigravity/claude/antigravity_claude_response_test.go b/internal/translator/antigravity/claude/antigravity_claude_response_test.go index 3f61868bcfc..4eedc05990b 100644 --- a/internal/translator/antigravity/claude/antigravity_claude_response_test.go +++ b/internal/translator/antigravity/claude/antigravity_claude_response_test.go @@ -1745,7 +1745,6 @@ func TestConvertAntigravityResponseToClaudeNonStream_RefusalFinishReasons(t *tes {finishReason: "BLOCKLIST", wantReason: "refusal"}, {finishReason: "IMAGE_SAFETY", wantReason: "refusal"}, {finishReason: "MALFORMED_RESPONSE", wantReason: "refusal"}, - {finishReason: "MALFORMED_FUNCTION_CALL", wantReason: "refusal"}, {finishReason: "MAX_TOKENS", wantReason: "max_tokens"}, {finishReason: "STOP", wantReason: "end_turn"}, } @@ -1856,7 +1855,6 @@ func TestConvertAntigravityResponseToClaudeStream_RefusalPreservedAcrossTrailing "BLOCKLIST", "IMAGE_SAFETY", "MALFORMED_RESPONSE", - "MALFORMED_FUNCTION_CALL", } { t.Run(reason, func(t *testing.T) { for _, textPart := range []string{"partial", ""} { diff --git a/internal/translator/antigravity/claude/signature_validation.go b/internal/translator/antigravity/claude/signature_validation.go index db4ae326b08..d325bb25f25 100644 --- a/internal/translator/antigravity/claude/signature_validation.go +++ b/internal/translator/antigravity/claude/signature_validation.go @@ -2,7 +2,6 @@ package claude import ( - "github.com/MoeForge/moego/base64" "strings" "github.com/MoeForge/moego/ojson" @@ -16,62 +15,23 @@ const ( // Gemini carrier envelopes exist only on the Claude-facing wire. The request // translator validates and unwraps them before writing native Gemini parts. - geminiClaudeCarrierPrefix = "cpa-gemini-carrier-v1:" - geminiClaudeCarrierNext = "next" - geminiClaudeCarrierPrevious = "previous" - geminiClaudeCarrierStandalone = "standalone" - geminiClaudeCarrierText = "text" - geminiClaudeCarrierFunction = "function" - geminiClaudeCarrierAny = "any" + geminiClaudeCarrierPrefix = translatorcommon.GeminiClaudeCarrierPrefix + geminiClaudeCarrierNext = translatorcommon.GeminiClaudeCarrierNext + geminiClaudeCarrierPrevious = translatorcommon.GeminiClaudeCarrierPrevious + geminiClaudeCarrierStandalone = translatorcommon.GeminiClaudeCarrierStandalone + geminiClaudeCarrierText = translatorcommon.GeminiClaudeCarrierText + geminiClaudeCarrierFunction = translatorcommon.GeminiClaudeCarrierFunction + geminiClaudeCarrierAny = translatorcommon.GeminiClaudeCarrierAny ) type claudeSignatureTree = signature.ClaudeSignatureTree func encodeGeminiClaudeCarrierSignature(rawSignature, direction, targetKind string) string { - rawSignature = strings.TrimSpace(rawSignature) - if rawSignature == "" { - return "" - } - return geminiClaudeCarrierPrefix + direction + ":" + targetKind + ":" + base64.RawStdEncoding.EncodeToString([]byte(rawSignature)) + return translatorcommon.EncodeGeminiClaudeCarrierSignature(rawSignature, direction, targetKind) } func decodeGeminiClaudeCarrierSignature(rawSignature string) (signatureValue, direction, targetKind string, marked, ok bool) { - rawSignature = strings.TrimSpace(rawSignature) - if !strings.HasPrefix(rawSignature, geminiClaudeCarrierPrefix) { - return rawSignature, "", "", false, true - } - marked = true - if len(rawSignature) > (signature.MaxGeminiThoughtSignatureLen*4/3)+1024 { - return "", "", "", true, false - } - fields := strings.SplitN(strings.TrimPrefix(rawSignature, geminiClaudeCarrierPrefix), ":", 3) - if len(fields) != 3 { - return "", "", "", true, false - } - direction, targetKind = fields[0], fields[1] - switch direction { - case geminiClaudeCarrierNext, geminiClaudeCarrierPrevious, geminiClaudeCarrierStandalone: - default: - return "", "", "", true, false - } - switch targetKind { - case geminiClaudeCarrierText, geminiClaudeCarrierFunction, geminiClaudeCarrierAny: - default: - return "", "", "", true, false - } - decoded, errDecode := base64.RawStdEncoding.DecodeString(fields[2]) - if errDecode != nil || len(decoded) == 0 || strings.HasPrefix(string(decoded), geminiClaudeCarrierPrefix) { - return "", "", "", true, false - } - blockKind := signature.SignatureBlockKindGeminiModelPart - if targetKind == geminiClaudeCarrierFunction { - blockKind = signature.SignatureBlockKindGeminiFunctionCall - } - normalized, compatible := signature.CompatibleSignatureForProviderBlock(signature.SignatureProviderGemini, string(decoded), blockKind) - if !compatible || signature.IsGeminiThoughtSignatureBypass(signature.SignaturePayloadWithoutProviderPrefix(normalized)) { - return "", "", "", true, false - } - return normalized, direction, targetKind, true, true + return translatorcommon.DecodeGeminiClaudeCarrierSignature(rawSignature) } func geminiClaudeSemanticTargetKind(block ojson.Result) string { diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response.go index a0f5559d4ff..c822c6c4bdd 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response.go @@ -137,6 +137,7 @@ func ConvertAntigravityResponseToOpenAI(_ context.Context, _ string, originalReq } // Process the main content part of the response. + hasDeltaContent := false partsResult := ojson.GetBytesNoCopy(rawJSON, "response.candidates.0.content.parts") if partsResult.IsArray() { partResults := partsResult.Array() @@ -235,6 +236,7 @@ func ConvertAntigravityResponseToOpenAI(_ context.Context, _ string, originalReq if hasReasoningContent { _ = templateDoc.Set("choices.0.delta.reasoning_content", reasoningContent.String()) } + hasDeltaContent = hasTextContent || hasReasoningContent || hasToolCallsArray || imageCount > 0 } // Determine finish_reason only on the final chunk, which upstream marks with @@ -252,18 +254,40 @@ func ConvertAntigravityResponseToOpenAI(_ context.Context, _ string, originalReq params.SawFinishReason = true } + if !hasDeltaContent && !isFinalChunk && !usageResult.Exists() { + return [][]byte{} + } + return [][]byte{templateDoc.Bytes()} } // hasAntigravityResponsePayload reports whether a chunk carries actual generated -// content or token accounting. Presence alone is not enough: an envelope such as -// `{}`, `{"response":{}}` or `{"response":{"candidates":[]}}` must not count as a -// started stream, otherwise a keepalive or malformed event would be enough to +// content or non-zero output token accounting. Presence alone is not enough: an +// envelope such as `{}`, `{"response":{}}`, `{"response":{"candidates":[]}}`, or +// a signature-only empty-text part with zero output tokens must not count as a +// started stream, otherwise a keepalive or zero-output event would be enough to // finalize a stream that produced nothing. func hasAntigravityResponsePayload(rawJSON []byte) bool { for _, path := range []string{"response.candidates", "candidates"} { - if candidates := ojson.GetBytesNoCopy(rawJSON, path); candidates.IsArray() && len(candidates.Array()) > 0 { - return true + if candidates := ojson.GetBytesNoCopy(rawJSON, path); candidates.IsArray() { + for _, cand := range candidates.Array() { + if strings.TrimSpace(cand.Get("finishReason").String()) != "" { + return true + } + if chunks := cand.Get("groundingMetadata.groundingChunks"); chunks.IsArray() && len(chunks.Array()) > 0 { + return true + } + for _, part := range cand.Get("content.parts").Array() { + if part.Get("text").String() != "" || + part.Get("functionCall").Exists() || part.Get("function_call").Exists() || + part.Get("inlineData").Exists() || part.Get("inline_data").Exists() || + part.Get("fileData").Exists() || part.Get("file_data").Exists() || + part.Get("executableCode").Exists() || part.Get("executable_code").Exists() || + part.Get("codeExecutionResult").Exists() || part.Get("code_execution_result").Exists() { + return true + } + } + } } } // FilterSSEUsageMetadata renames non-terminal usage to cpaUsageMetadata before @@ -272,8 +296,10 @@ func hasAntigravityResponsePayload(rawJSON []byte) bool { "response.usageMetadata", "response.cpaUsageMetadata", "usageMetadata", "cpaUsageMetadata", } { - if usage := ojson.GetBytesNoCopy(rawJSON, path); usage.IsObject() && len(usage.Map()) > 0 { - return true + if usage := ojson.GetBytesNoCopy(rawJSON, path); usage.IsObject() { + if usage.Get("candidatesTokenCount").Int() > 0 || usage.Get("thoughtsTokenCount").Int() > 0 { + return true + } } } return false @@ -287,7 +313,7 @@ func resolveOpenAIFinishReason(params *convertCliResponseToOpenAIChatParams) (fi case params.SawToolCall: finishReason = "tool_calls" case params.UpstreamFinishReason == "MAX_TOKENS": - finishReason = "max_tokens" + finishReason = "length" case isAntigravityContentFilterFinishReason(params.UpstreamFinishReason): finishReason = "content_filter" default: diff --git a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response_test.go b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response_test.go index 855b569df0a..01fcac91cc7 100644 --- a/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response_test.go +++ b/internal/translator/antigravity/openai/chat-completions/antigravity_openai_response_test.go @@ -77,10 +77,15 @@ func TestFinishReasonMaxTokens(t *testing.T) { chunk2 := []byte(`{"response":{"candidates":[{"finishReason":"MAX_TOKENS"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":100,"totalTokenCount":110}}}`) result2 := ConvertAntigravityResponseToOpenAI(ctx, "model", nil, nil, chunk2, ¶m) - // Verify finish_reason is "max_tokens" + // Verify finish_reason is "length" (the OpenAI value for an output token limit) fr := ojson.GetBytesNoCopy(result2[0], "choices.0.finish_reason").String() - if fr != "max_tokens" { - t.Errorf("Expected finish_reason 'max_tokens', got: %s", fr) + if fr != "length" { + t.Errorf("Expected finish_reason 'length', got: %s", fr) + } + // Verify native_finish_reason preserves the upstream value + nfr := ojson.GetBytesNoCopy(result2[0], "choices.0.native_finish_reason").String() + if nfr != "max_tokens" { + t.Errorf("Expected native_finish_reason 'max_tokens', got: %s", nfr) } } @@ -96,7 +101,7 @@ func TestToolCallTakesPriorityOverMaxTokens(t *testing.T) { chunk2 := []byte(`{"response":{"candidates":[{"finishReason":"MAX_TOKENS"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":100,"totalTokenCount":110}}}`) result2 := ConvertAntigravityResponseToOpenAI(ctx, "model", nil, nil, chunk2, ¶m) - // Verify finish_reason is "tool_calls" (takes priority over max_tokens) + // Verify finish_reason is "tool_calls" (takes priority over upstream MAX_TOKENS) fr := ojson.GetBytesNoCopy(result2[0], "choices.0.finish_reason").String() if fr != "tool_calls" { t.Errorf("Expected finish_reason 'tool_calls', got: %s", fr) @@ -501,3 +506,18 @@ func TestConvertAntigravityResponseToOpenAI_MultiPartThoughtAndTrailingSignature } }) } + +func TestConvertAntigravityResponseToOpenAI_SignatureOnlyEmptyTextDoesNotStartStreamOrEmitNullDelta(t *testing.T) { + ctx := context.Background() + var param any + + chunk := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"opaque-sig","text":""}]}}],"cpaUsageMetadata":{"promptTokenCount":378515,"cachedContentTokenCount":376466,"totalTokenCount":378515},"modelVersion":"gemini-4-hydrogen","responseId":"resp-7536"}}`) + out := ConvertAntigravityResponseToOpenAI(ctx, "gemini-4-hydrogen", nil, nil, chunk, ¶m) + if len(out) != 0 { + t.Fatalf("signature-only empty-text chunk with filtered usage must not emit all-null delta, got %d chunk(s): %s", len(out), out[0]) + } + done := ConvertAntigravityResponseToOpenAI(ctx, "gemini-4-hydrogen", nil, nil, []byte("[DONE]"), ¶m) + if len(done) != 0 { + t.Fatalf("signature-only empty-text stream must not synthesize stop on [DONE], got %d chunk(s): %s", len(done), done[0]) + } +} diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_response.go b/internal/translator/claude/openai/chat-completions/claude_openai_response.go index f9a6afb4718..eafdb41dd4e 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_response.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_response.go @@ -25,6 +25,8 @@ var ( type ConvertAnthropicResponseToOpenAIParams struct { CreatedAt int64 ResponseID string + Model string + Fallbacks translatorcommon.ClaudeFallbackChain FinishReason string Usage claudeUsageTokens TrailingUsageSent bool @@ -93,6 +95,13 @@ func (u claudeUsageTokens) OpenAIUsage() (promptTokens, completionTokens, totalT return promptTokens, completionTokens, totalTokens, cachedTokens, cachedCreationTokens } +func effectiveChatResponseModel(servedModel, requestedModel string) string { + if servedModel != "" { + return servedModel + } + return requestedModel +} + // ConvertClaudeResponseToOpenAI converts Claude Code streaming response format to OpenAI Chat Completions format. // This function processes various Claude Code event types and transforms them into OpenAI-compatible JSON responses. // It handles text content, tool calls, reasoning content, and usage metadata, outputting responses that match @@ -126,47 +135,88 @@ func ConvertClaudeResponseToOpenAI(_ context.Context, modelName string, original // Base OpenAI streaming response template templateDoc := ojson.NewDoc([]byte(`{"id":"","object":"chat.completion.chunk","created":0,"model":"","choices":[{"index":0,"delta":{},"finish_reason":null}]}`)) - // Set model - if modelName != "" { - _ = templateDoc.Set("model", modelName) + p := (*param).(*ConvertAnthropicResponseToOpenAIParams) + + // Set model (prefer authoritative upstream serving model when known) + if chunkModel := effectiveChatResponseModel(p.Model, modelName); chunkModel != "" { + _ = templateDoc.Set("model", chunkModel) } // Set response ID and creation time - if (*param).(*ConvertAnthropicResponseToOpenAIParams).ResponseID != "" { - _ = templateDoc.Set("id", (*param).(*ConvertAnthropicResponseToOpenAIParams).ResponseID) + if p.ResponseID != "" { + _ = templateDoc.Set("id", p.ResponseID) } - if (*param).(*ConvertAnthropicResponseToOpenAIParams).CreatedAt > 0 { - _ = templateDoc.Set("created", (*param).(*ConvertAnthropicResponseToOpenAIParams).CreatedAt) + if p.CreatedAt > 0 { + _ = templateDoc.Set("created", p.CreatedAt) } switch eventType { case "message_start": // Initialize response with message metadata when a new message begins if message := root.Get("message"); message.Exists() { - (*param).(*ConvertAnthropicResponseToOpenAIParams).ResponseID = strings.Clone(message.Get("id").String()) - (*param).(*ConvertAnthropicResponseToOpenAIParams).CreatedAt = time.Now().Unix() + p.ResponseID = strings.Clone(message.Get("id").String()) + p.CreatedAt = time.Now().Unix() + p.Fallbacks.Reset() + upstreamModel := strings.TrimSpace(message.Get("model").String()) + if upstreamModel != "" { + p.Model = strings.Clone(upstreamModel) + } - _ = templateDoc.Set("id", (*param).(*ConvertAnthropicResponseToOpenAIParams).ResponseID) - _ = templateDoc.Set("model", modelName) - _ = templateDoc.Set("created", (*param).(*ConvertAnthropicResponseToOpenAIParams).CreatedAt) + _ = templateDoc.Set("id", p.ResponseID) + if chunkModel := effectiveChatResponseModel(p.Model, modelName); chunkModel != "" { + _ = templateDoc.Set("model", chunkModel) + } + _ = templateDoc.Set("created", p.CreatedAt) // Set initial role to assistant for the response _ = templateDoc.Set("choices.0.delta.role", "assistant") + if fromModel, toModel, ok := translatorcommon.ClaudePreTokenFallbackModels(originalRequestRawJSON, requestRawJSON, modelName, upstreamModel); ok { + if fbBytes := p.Fallbacks.RecordPreToken(fromModel, toModel, "", nil); len(fbBytes) > 0 { + _ = templateDoc.SetRawBytes("choices.0.delta.fallback", fbBytes) + } + } // Initialize tool calls accumulator for tracking tool call progress - if (*param).(*ConvertAnthropicResponseToOpenAIParams).ToolCallsAccumulator == nil { - (*param).(*ConvertAnthropicResponseToOpenAIParams).ToolCallsAccumulator = make(map[int]*ToolCallAccumulator) + if p.ToolCallsAccumulator == nil { + p.ToolCallsAccumulator = make(map[int]*ToolCallAccumulator) } - (*param).(*ConvertAnthropicResponseToOpenAIParams).NextToolCallIndex = 0 - (*param).(*ConvertAnthropicResponseToOpenAIParams).Usage.Merge(message.Get("usage")) + p.NextToolCallIndex = 0 + p.Usage.Merge(message.Get("usage")) } return [][]byte{templateDoc.Bytes()} case "content_block_start": - // Start of a content block (text, tool use, or reasoning) + // Start of a content block (text, tool use, fallback boundary, or reasoning) if contentBlock := root.Get("content_block"); contentBlock.Exists() { blockType := contentBlock.Get("type").String() + if blockType == "fallback" { + toModel := strings.TrimSpace(contentBlock.Get("to.model").String()) + fromModel := strings.TrimSpace(contentBlock.Get("from.model").String()) + if toModel != "" { + p.Model = strings.Clone(toModel) + _ = templateDoc.Set("model", p.Model) + } + fbBytes := p.Fallbacks.RecordBlock( + contentBlock, + effectiveChatResponseModel(fromModel, modelName), + effectiveChatResponseModel(toModel, p.Model), + "", + nil, + ) + if len(fbBytes) > 0 { + _ = templateDoc.SetRawBytes("choices.0.delta.fallback", fbBytes) + if allBytes := p.Fallbacks.ArrayBytes(); len(allBytes) > 0 { + _ = templateDoc.SetRawBytes("choices.0.delta.fallbacks", allBytes) + } + return [][]byte{templateDoc.Bytes()} + } + if toModel != "" { + return [][]byte{templateDoc.Bytes()} + } + return [][]byte{} + } + if blockType == "tool_use" { // Start of tool call - initialize accumulator to track arguments toolCallID := strings.Clone(contentBlock.Get("id").String()) @@ -266,29 +316,38 @@ func ConvertClaudeResponseToOpenAI(_ context.Context, modelName string, original // Handle usage information for token counts if usage := root.Get("usage"); usage.Exists() { - (*param).(*ConvertAnthropicResponseToOpenAIParams).Usage.Merge(usage) - promptTokens, completionTokens, totalTokens, cachedTokens, cachedCreationTokens := (*param).(*ConvertAnthropicResponseToOpenAIParams).Usage.OpenAIUsage() + if iterModel, newHops := p.Fallbacks.RecordIterations(usage.Get("iterations"), modelName, "", nil); iterModel != "" { + p.Model = iterModel + _ = templateDoc.Set("model", p.Model) + if len(newHops) > 0 { + _ = templateDoc.SetRawBytes("choices.0.delta.fallback", p.Fallbacks.Latest()) + if allBytes := p.Fallbacks.ArrayBytes(); len(allBytes) > 0 { + _ = templateDoc.SetRawBytes("choices.0.delta.fallbacks", allBytes) + } + } + } + p.Usage.Merge(usage) + promptTokens, completionTokens, totalTokens, cachedTokens, cachedCreationTokens := p.Usage.OpenAIUsage() _ = templateDoc.Set("usage.prompt_tokens", promptTokens) _ = templateDoc.Set("usage.completion_tokens", completionTokens) _ = templateDoc.Set("usage.total_tokens", totalTokens) _ = templateDoc.Set("usage.prompt_tokens_details.cached_tokens", cachedTokens) _ = templateDoc.Set("usage.prompt_tokens_details.cached_creation_tokens", cachedCreationTokens) _ = templateDoc.Set("usage.prompt_tokens_details.cache_write_tokens", cachedCreationTokens) - (*param).(*ConvertAnthropicResponseToOpenAIParams).Usage.applyReasoningTokensDoc(templateDoc) + p.Usage.applyReasoningTokensDoc(templateDoc) } return [][]byte{templateDoc.Bytes()} case "message_stop": // Final message event - emit standard OpenAI trailing usage chunk with empty choices array if usage was tracked. - p := (*param).(*ConvertAnthropicResponseToOpenAIParams) if p.Usage.HasUsage && !p.TrailingUsageSent { p.TrailingUsageSent = true usageDoc := ojson.NewDoc([]byte(`{"id":"","object":"chat.completion.chunk","created":0,"model":"","choices":[]}`)) if p.ResponseID != "" { _ = usageDoc.Set("id", p.ResponseID) } - if modelName != "" { - _ = usageDoc.Set("model", modelName) + if chunkModel := effectiveChatResponseModel(p.Model, modelName); chunkModel != "" { + _ = usageDoc.Set("model", chunkModel) } if p.CreatedAt > 0 { _ = usageDoc.Set("created", p.CreatedAt) @@ -356,7 +415,7 @@ func mapAnthropicStopReasonToOpenAI(anthropicReason string) string { // // Returns: // - []byte: An OpenAI-compatible JSON response containing all message content and metadata -func ConvertClaudeResponseToOpenAINonStream(_ context.Context, _ string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, _ *any) []byte { +func ConvertClaudeResponseToOpenAINonStream(_ context.Context, modelName string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, _ *any) []byte { rawJSON, _ = translatorcommon.ClaudeMessagesJSONToSSE(rawJSON) chunks := make([][]byte, 0) @@ -377,6 +436,8 @@ func ConvertClaudeResponseToOpenAINonStream(_ context.Context, _ string, origina var stopReason string var contentParts []string var reasoningParts []string + var fallbacks translatorcommon.ClaudeFallbackChain + currentContentLen := 0 usageTokens := claudeUsageTokens{} toolCallsAccumulator := make(map[int]*ToolCallAccumulator) @@ -389,7 +450,13 @@ func ConvertClaudeResponseToOpenAINonStream(_ context.Context, _ string, origina // Extract initial message metadata including ID, model, and input token count if message := root.Get("message"); message.Exists() { messageID = message.Get("id").String() - model = message.Get("model").String() + if m := strings.TrimSpace(message.Get("model").String()); m != "" { + model = m + } + if fromModel, toModel, ok := translatorcommon.ClaudePreTokenFallbackModels(originalRequestRawJSON, requestRawJSON, modelName, model); ok { + offset := 0 + fallbacks.RecordPreToken(fromModel, toModel, "content_offset", &offset) + } createdAt = time.Now().Unix() usageTokens.Merge(message.Get("usage")) } @@ -401,6 +468,20 @@ func ConvertClaudeResponseToOpenAINonStream(_ context.Context, _ string, origina if blockType == "thinking" { // Start of thinking/reasoning content - skip for now as it's handled in delta continue + } else if blockType == "fallback" { + toModel := strings.TrimSpace(contentBlock.Get("to.model").String()) + fromModel := strings.TrimSpace(contentBlock.Get("from.model").String()) + if toModel != "" { + model = toModel + } + offset := currentContentLen + fallbacks.RecordBlock( + contentBlock, + effectiveChatResponseModel(fromModel, modelName), + effectiveChatResponseModel(toModel, model), + "content_offset", + &offset, + ) } else if blockType == "tool_use" { // Initialize tool call accumulator for this index index := int(root.Get("index").Int()) @@ -419,7 +500,9 @@ func ConvertClaudeResponseToOpenAINonStream(_ context.Context, _ string, origina case "text_delta": // Accumulate text content if text := delta.Get("text"); text.Exists() { - contentParts = append(contentParts, text.String()) + textStr := text.String() + contentParts = append(contentParts, textStr) + currentContentLen += len(textStr) } case "thinking_delta": // Accumulate reasoning/thinking content @@ -454,6 +537,10 @@ func ConvertClaudeResponseToOpenAINonStream(_ context.Context, _ string, origina } } if usage := root.Get("usage"); usage.Exists() { + offset := 0 + if iterModel, _ := fallbacks.RecordIterations(usage.Get("iterations"), modelName, "content_offset", &offset); iterModel != "" { + model = iterModel + } usageTokens.Merge(usage) } } @@ -473,11 +560,15 @@ func ConvertClaudeResponseToOpenAINonStream(_ context.Context, _ string, origina // Set basic response fields including message ID, creation time, and model _ = outDoc.Set("id", messageID) _ = outDoc.Set("created", createdAt) - _ = outDoc.Set("model", model) + _ = outDoc.Set("model", effectiveChatResponseModel(model, modelName)) // Set message content by combining all text parts messageContent := strings.Join(contentParts, "") _ = outDoc.Set("choices.0.message.content", messageContent) + if latestFB := fallbacks.Latest(); len(latestFB) > 0 { + _ = outDoc.SetRawBytes("choices.0.message.fallback", latestFB) + _ = outDoc.SetRawBytes("choices.0.message.fallbacks", fallbacks.ArrayBytes()) + } // Add reasoning content if available (following OpenAI reasoning format) if len(reasoningParts) > 0 { diff --git a/internal/translator/claude/openai/chat-completions/claude_openai_response_test.go b/internal/translator/claude/openai/chat-completions/claude_openai_response_test.go index 1c1bcd3def7..7ad817d303b 100644 --- a/internal/translator/claude/openai/chat-completions/claude_openai_response_test.go +++ b/internal/translator/claude/openai/chat-completions/claude_openai_response_test.go @@ -619,3 +619,172 @@ func TestConvertClaudeResponseToOpenAI_ReportsZeroReasoningTokensWhenThinkingIsZ } assertReasoningTokens(t, out[0], 0) } + +func TestConvertClaudeResponseToOpenAI_StreamPreservesUpstreamServingModel(t *testing.T) { + ctx := context.Background() + var param any + + events := [][]byte{ + []byte(`data: {"type":"message_start","message":{"id":"msg_fb_1","model":"claude-opus-4-8","usage":{"input_tokens":10,"output_tokens":0}}}`), + []byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"fallback answer"}}`), + []byte(`data: {"type":"content_block_stop","index":0}`), + []byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":4,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":0},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":4}]}}`), + []byte(`data: {"type":"message_stop"}`), + } + + var chunks [][]byte + for _, ev := range events { + chunks = append(chunks, ConvertClaudeResponseToOpenAI(ctx, "claude-opus-5-5", nil, nil, ev, ¶m)...) + } + if len(chunks) == 0 { + t.Fatal("expected stream chunks") + } + sawFallbackDelta := false + for i, chunk := range chunks { + if got := ojson.GetBytesNoCopy(chunk, "model").String(); got != "claude-opus-4-8" { + t.Fatalf("chunk[%d] model = %q, want claude-opus-4-8; payload=%s", i, got, string(chunk)) + } + if fb := ojson.GetBytesNoCopy(chunk, "choices.0.delta.fallback"); fb.Exists() { + sawFallbackDelta = true + if fb.Get("from.model").String() != "claude-opus-5-5" || fb.Get("to.model").String() != "claude-opus-4-8" { + t.Fatalf("chunk[%d] delta.fallback = %s, want from claude-opus-5-5 to claude-opus-4-8", i, fb.Raw) + } + } + } + if !sawFallbackDelta { + t.Fatal("expected pre-token fallback stream to surface choices[0].delta.fallback") + } + + // Also verify when message_start already reports claude-opus-4-8 AND a fallback content_block is emitted. + var paramPreBlock any + preBlockEvents := [][]byte{ + []byte(`data: {"type":"message_start","message":{"id":"msg_fb_preblock","model":"claude-opus-4-8","usage":{"input_tokens":10,"output_tokens":0}}}`), + []byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"fallback","from":{"model":"claude-opus-5-5"},"to":{"model":"claude-opus-4-8"},"trigger":{"type":"refusal","category":"reasoning_extraction"}}}`), + []byte(`data: {"type":"content_block_stop","index":0}`), + []byte(`data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"ok"}}`), + []byte(`data: {"type":"content_block_stop","index":1}`), + []byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`), + []byte(`data: {"type":"message_stop"}`), + } + sawTriggerChunk := false + for _, ev := range preBlockEvents { + for _, chunk := range ConvertClaudeResponseToOpenAI(ctx, "claude-opus-5-5", nil, nil, ev, ¶mPreBlock) { + if fb := ojson.GetBytesNoCopy(chunk, "choices.0.delta.fallback"); fb.Exists() && fb.Get("trigger.category").String() == "reasoning_extraction" { + sawTriggerChunk = true + } + } + } + if !sawTriggerChunk { + t.Fatal("expected fallback content_block to surface trigger in choices[0].delta.fallback even when message_start already reported target model") + } + + // Pre-token non-stream response via iterations also surfaces choices[0].message.fallback with content_offset=0. + preNonStreamRaw := []byte(`{"id":"msg_fb_1","type":"message","role":"assistant","model":"claude-opus-4-8","content":[{"type":"text","text":"fallback answer"}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":4,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":0},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":4}]}}`) + preNonStreamOut := ConvertClaudeResponseToOpenAINonStream(ctx, "claude-opus-5-5", nil, nil, preNonStreamRaw, nil) + preFB := ojson.GetBytesNoCopy(preNonStreamOut, "choices.0.message.fallback") + if !preFB.Exists() || preFB.Get("from.model").String() != "claude-opus-5-5" || preFB.Get("to.model").String() != "claude-opus-4-8" || preFB.Get("content_offset").Int() != 0 { + t.Fatalf("pre-token non-stream choices[0].message.fallback = %s, want from=5-5 to=4-8 content_offset=0", preFB.Raw) + } +} + +func TestConvertClaudeResponseToOpenAI_MidStreamFallbackUpdatesServingModelAndEmitsBoundary(t *testing.T) { + ctx := context.Background() + var param any + + events := [][]byte{ + []byte(`data: {"type":"message_start","message":{"id":"msg_fb_mid","model":"claude-opus-5-5","usage":{"input_tokens":10,"output_tokens":0}}}`), + []byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial "}}`), + []byte(`data: {"type":"content_block_stop","index":0}`), + []byte(`data: {"type":"content_block_start","index":1,"content_block":{"type":"fallback","from":{"model":"claude-opus-5-5"},"to":{"model":"claude-opus-4-8"},"trigger":{"type":"refusal","category":"cyber"}}}`), + []byte(`data: {"type":"content_block_stop","index":1}`), + []byte(`data: {"type":"content_block_start","index":2,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"fallback text"}}`), + []byte(`data: {"type":"content_block_stop","index":2}`), + []byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":6,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":2},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":4}]}}`), + []byte(`data: {"type":"message_stop"}`), + } + + var models []string + var rawChunks [][]byte + var content string + for _, ev := range events { + for _, chunk := range ConvertClaudeResponseToOpenAI(ctx, "claude-opus-5-5", nil, nil, ev, ¶m) { + rawChunks = append(rawChunks, chunk) + models = append(models, ojson.GetBytesNoCopy(chunk, "model").String()) + if deltaText := ojson.GetBytesNoCopy(chunk, "choices.0.delta.content"); deltaText.Exists() { + content += deltaText.String() + } + } + } + + // Expected sequence: message_start (5.5), partial delta (5.5), fallback boundary (4.8), fallback delta (4.8), message_delta (4.8), trailing usage (4.8). + wantModels := []string{ + "claude-opus-5-5", + "claude-opus-5-5", + "claude-opus-4-8", + "claude-opus-4-8", + "claude-opus-4-8", + "claude-opus-4-8", + } + if len(models) != len(wantModels) { + t.Fatalf("chunk models = %v (len %d), want %v (len %d)", models, len(models), wantModels, len(wantModels)) + } + for i := range wantModels { + if models[i] != wantModels[i] { + t.Fatalf("chunk[%d] model = %q, want %q (all=%v)", i, models[i], wantModels[i], models) + } + } + boundaryFB := ojson.GetBytesNoCopy(rawChunks[2], "choices.0.delta.fallback") + if !boundaryFB.Exists() || boundaryFB.Get("from.model").String() != "claude-opus-5-5" || boundaryFB.Get("to.model").String() != "claude-opus-4-8" || boundaryFB.Get("trigger.category").String() != "cyber" { + t.Fatalf("boundary chunk[2] delta.fallback = %s, want from=claude-opus-5-5 to=claude-opus-4-8 trigger.category=cyber", boundaryFB.Raw) + } + if content != "partial fallback text" { + t.Fatalf("accumulated content = %q, want %q", content, "partial fallback text") + } + + nonStreamRaw := []byte(`{"id":"msg_fb_mid","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"partial "},{"type":"fallback","from":{"model":"claude-opus-5-5"},"to":{"model":"claude-opus-4-8"},"trigger":{"type":"refusal","category":"cyber"}},{"type":"text","text":"fallback text"}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":6,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":2},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":4}]}}`) + nonStreamOut := ConvertClaudeResponseToOpenAINonStream(ctx, "claude-opus-5-5", nil, nil, nonStreamRaw, nil) + if got := ojson.GetBytesNoCopy(nonStreamOut, "model").String(); got != "claude-opus-4-8" { + t.Fatalf("non-stream model = %q, want claude-opus-4-8; payload=%s", got, string(nonStreamOut)) + } + if gotContent := ojson.GetBytesNoCopy(nonStreamOut, "choices.0.message.content").String(); gotContent != "partial fallback text" { + t.Fatalf("non-stream content = %q, want %q", gotContent, "partial fallback text") + } + msgFB := ojson.GetBytesNoCopy(nonStreamOut, "choices.0.message.fallback") + if !msgFB.Exists() || msgFB.Get("from.model").String() != "claude-opus-5-5" || msgFB.Get("to.model").String() != "claude-opus-4-8" || msgFB.Get("trigger.category").String() != "cyber" || msgFB.Get("content_offset").Int() != int64(len("partial ")) { + t.Fatalf("non-stream choices[0].message.fallback = %s, want from=5-5 to=4-8 trigger=cyber content_offset=8", msgFB.Raw) + } +} + +func TestConvertClaudeResponseToOpenAI_MultiHopFallbackAndStickyDefault(t *testing.T) { + ctx := context.Background() + + // 1. Multi-hop chain: claude-fable-5-1 ("partA ") -> claude-opus-5 ("partB ") -> claude-opus-4-8 ("partC"). + rawJSON := []byte(`{"id":"msg_chat_chain","type":"message","role":"assistant","model":"claude-fable-5-1","content":[{"type":"text","text":"partA "},{"type":"fallback","from":{"model":"claude-fable-5-1"},"to":{"model":"claude-opus-5"},"trigger":{"type":"refusal","category":"reasoning_extraction"}},{"type":"text","text":"partB "},{"type":"fallback","from":{"model":"claude-opus-5"},"to":{"model":"claude-opus-4-8"},"trigger":{"type":"refusal","category":"cyber"}},{"type":"text","text":"partC"}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":9}}`) + out := ConvertClaudeResponseToOpenAINonStream(ctx, "claude-fable-5-1", nil, nil, rawJSON, nil) + if got := ojson.GetBytesNoCopy(out, "model").String(); got != "claude-opus-4-8" { + t.Fatalf("multi-hop Chat model = %q, want claude-opus-4-8", got) + } + hops := ojson.GetBytesNoCopy(out, "choices.0.message.fallbacks").Array() + if len(hops) != 2 { + t.Fatalf("multi-hop Chat choices[0].message.fallbacks len = %d, want 2; payload=%s", len(hops), string(out)) + } + if hops[0].Get("from.model").String() != "claude-fable-5-1" || hops[0].Get("to.model").String() != "claude-opus-5" || hops[0].Get("content_offset").Int() != 6 { + t.Fatalf("Chat hop[0] = %s, want fable-5-1 -> opus-5 at content_offset=6", hops[0].Raw) + } + if hops[1].Get("from.model").String() != "claude-opus-5" || hops[1].Get("to.model").String() != "claude-opus-4-8" || hops[1].Get("content_offset").Int() != 12 { + t.Fatalf("Chat hop[1] = %s, want opus-5 -> opus-4-8 at content_offset=12", hops[1].Raw) + } + + // 2. Sticky routing with "fallbacks": "default" (no fallback block, no usage.iterations). + translatedDefaultReq := []byte(`{"model":"claude-opus-5-5","fallbacks":"default","messages":[{"role":"user","content":"turn 2"}]}`) + var stickyParam any + stickyStart := []byte(`data: {"type":"message_start","message":{"id":"msg_sticky_chat","model":"claude-opus-4-8","usage":{"input_tokens":5,"output_tokens":0}}}`) + stickyChunks := ConvertClaudeResponseToOpenAI(ctx, "claude-opus-5-5", nil, translatedDefaultReq, stickyStart, &stickyParam) + if len(stickyChunks) != 1 || ojson.GetBytesNoCopy(stickyChunks[0], "choices.0.delta.fallback.to.model").String() != "claude-opus-4-8" { + t.Fatalf("sticky default Chat start chunk = %s, want delta.fallback.to.model=claude-opus-4-8", string(stickyChunks[0])) + } +} diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_response.go b/internal/translator/claude/openai/responses/claude_openai-responses_response.go index 19ff756f913..b1b273c78be 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_response.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_response.go @@ -72,6 +72,8 @@ type claudeToResponsesState struct { WebSearchByToolID map[string]*claudeResponsesWebSearchItem WebSearchItems []*claudeResponsesWebSearchItem StopReason string + FallbackModel string + Fallbacks translatorcommon.ClaudeFallbackChain // usage aggregation Usage claudeResponsesUsageTokens } @@ -941,6 +943,8 @@ func ConvertClaudeResponseToOpenAIResponses(ctx context.Context, modelName strin st.ReasoningIndex = -1 st.ReasoningItems = nil st.StopReason = "" + st.FallbackModel = "" + st.Fallbacks.Reset() st.ApplyPatchCalls = make(map[string]*translatorcommon.ApplyPatchCallState) st.FuncItemAdded = make(map[int]bool) st.FuncArgsSent = make(map[int]int) @@ -967,9 +971,19 @@ func ConvertClaudeResponseToOpenAIResponses(ctx context.Context, modelName strin if requestModelName == "" { requestModelName = modelName } + upstreamModel := strings.TrimSpace(msg.Get("model").String()) + if fromModel, toModel, ok := translatorcommon.ClaudePreTokenFallbackModels(originalRequestRawJSON, requestRawJSON, requestModelName, upstreamModel); ok { + st.FallbackModel = toModel + st.Fallbacks.RecordPreToken(fromModel, toModel, "", nil) + requestModelName = toModel + } if requestModelName != "" { _ = createdDoc.Set("response.model", requestModelName) } + if latestFB := st.Fallbacks.Latest(); len(latestFB) > 0 { + _ = createdDoc.SetRawBytes("response.fallback", latestFB) + _ = createdDoc.SetRawBytes("response.fallbacks", st.Fallbacks.ArrayBytes()) + } out = append(out, emitEvent("response.created", createdDoc.Bytes())) // response.in_progress inprogDoc := ojson.NewDocString(`{"type":"response.in_progress","sequence_number":0,"response":{"id":"","object":"response","created_at":0,"status":"in_progress","output":[]}}`) @@ -979,6 +993,10 @@ func ConvertClaudeResponseToOpenAIResponses(ctx context.Context, modelName strin if requestModelName != "" { _ = inprogDoc.Set("response.model", requestModelName) } + if latestFB := st.Fallbacks.Latest(); len(latestFB) > 0 { + _ = inprogDoc.SetRawBytes("response.fallback", latestFB) + _ = inprogDoc.SetRawBytes("response.fallbacks", st.Fallbacks.ArrayBytes()) + } out = append(out, emitEvent("response.in_progress", inprogDoc.Bytes())) } case "content_block_start": @@ -1018,6 +1036,35 @@ func ConvertClaudeResponseToOpenAIResponses(ctx context.Context, modelName strin } } + if typ == "fallback" { + toModel := strings.TrimSpace(cb.Get("to.model").String()) + fromModel := strings.TrimSpace(cb.Get("from.model").String()) + if toModel != "" { + st.FallbackModel = strings.Clone(toModel) + } + defaultFrom := fromModel + if defaultFrom == "" { + defaultFrom = st.RequestEcho.model + } + if defaultFrom == "" { + defaultFrom = modelName + } + boundaryIdx := st.NextOutputIndex + if fbBytes := st.Fallbacks.RecordBlock(cb, defaultFrom, st.FallbackModel, "output_index", &boundaryIdx); len(fbBytes) > 0 { + inprogDoc := ojson.NewDocString(`{"type":"response.in_progress","sequence_number":0,"response":{"id":"","object":"response","created_at":0,"status":"in_progress","output":[]}}`) + _ = inprogDoc.Set("sequence_number", nextSeq()) + _ = inprogDoc.Set("response.id", st.ResponseID) + _ = inprogDoc.Set("response.created_at", st.CreatedAt) + if st.FallbackModel != "" { + _ = inprogDoc.Set("response.model", st.FallbackModel) + } + _ = inprogDoc.SetRawBytes("response.fallback", fbBytes) + _ = inprogDoc.SetRawBytes("response.fallbacks", st.Fallbacks.ArrayBytes()) + out = append(out, emitEvent("response.in_progress", inprogDoc.Bytes())) + } + return noSSEOutput(out) + } + if typ == "text" { st.InTextBlock = true outputIndex := st.messageOutputIndex() @@ -1218,10 +1265,28 @@ func ConvertClaudeResponseToOpenAIResponses(ctx context.Context, modelName strin } return noSSEOutput(out) case "message_delta": - st.Usage.Merge(root.Get("usage")) + usage := root.Get("usage") + st.Usage.Merge(usage) if stopReason := root.Get("delta.stop_reason"); stopReason.Exists() { st.StopReason = strings.Clone(stopReason.String()) } + defaultFrom := st.RequestEcho.model + if defaultFrom == "" { + defaultFrom = modelName + } + if iterModel, newHops := st.Fallbacks.RecordIterations(usage.Get("iterations"), defaultFrom, "", nil); iterModel != "" { + st.FallbackModel = iterModel + if len(newHops) > 0 { + inprogDoc := ojson.NewDocString(`{"type":"response.in_progress","sequence_number":0,"response":{"id":"","object":"response","created_at":0,"status":"in_progress","output":[]}}`) + _ = inprogDoc.Set("sequence_number", nextSeq()) + _ = inprogDoc.Set("response.id", st.ResponseID) + _ = inprogDoc.Set("response.created_at", st.CreatedAt) + _ = inprogDoc.Set("response.model", st.FallbackModel) + _ = inprogDoc.SetRawBytes("response.fallback", st.Fallbacks.Latest()) + _ = inprogDoc.SetRawBytes("response.fallbacks", st.Fallbacks.ArrayBytes()) + return [][]byte{emitEvent("response.in_progress", inprogDoc.Bytes())} + } + } return [][]byte{} case "message_stop": toolStatus := claudeResponsesOutputStatus(st.StopReason) @@ -1258,6 +1323,13 @@ func ConvertClaudeResponseToOpenAIResponses(ctx context.Context, modelName strin } // Inject original request fields into response as per docs/response.completed.json st.RequestEcho.applyDoc(completedDoc, "response.") + if st.FallbackModel != "" { + _ = completedDoc.Set("response.model", st.FallbackModel) + } + if latestFB := st.Fallbacks.Latest(); len(latestFB) > 0 { + _ = completedDoc.SetRawBytes("response.fallback", latestFB) + _ = completedDoc.SetRawBytes("response.fallbacks", st.Fallbacks.ArrayBytes()) + } // Build response.output from aggregated state outputsWrapperDoc := ojson.NewDocString(`{"arr":[]}`) @@ -1391,7 +1463,7 @@ func ConvertClaudeResponseToOpenAIResponses(ctx context.Context, modelName strin } // ConvertClaudeResponseToOpenAIResponsesNonStream aggregates Claude SSE into a single OpenAI Responses JSON. -func ConvertClaudeResponseToOpenAIResponsesNonStream(ctx context.Context, _ string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, param *any) []byte { +func ConvertClaudeResponseToOpenAIResponsesNonStream(ctx context.Context, modelName string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, param *any) []byte { rawJSON, nativeModel := translatorcommon.ClaudeMessagesJSONToSSE(rawJSON) // Aggregate Claude SSE lines into a single OpenAI Responses JSON (non-stream) // We follow the same aggregation logic as the streaming variant but produce @@ -1428,10 +1500,12 @@ func ConvertClaudeResponseToOpenAIResponsesNonStream(ctx context.Context, _ stri // Aggregation state var ( - responseID string - createdAt int64 - stopReason string - usageTokens claudeResponsesUsageTokens + responseID string + createdAt int64 + stopReason string + usageTokens claudeResponsesUsageTokens + fallbackModel string + fallbacks translatorcommon.ClaudeFallbackChain ) type nonStreamOutputItem struct { @@ -1486,6 +1560,14 @@ func ConvertClaudeResponseToOpenAIResponsesNonStream(ctx context.Context, _ stri responseID = msg.Get("id").String() createdAt = time.Now().Unix() usageTokens.Merge(msg.Get("usage")) + defaultReqModel := st.RequestEcho.model + if defaultReqModel == "" { + defaultReqModel = modelName + } + if fromModel, toModel, ok := translatorcommon.ClaudePreTokenFallbackModels(originalRequestRawJSON, requestRawJSON, defaultReqModel, msg.Get("model").String()); ok { + fallbackModel = toModel + fallbacks.RecordPreToken(fromModel, toModel, "", nil) + } } case "content_block_start": @@ -1499,6 +1581,21 @@ func ConvertClaudeResponseToOpenAIResponsesNonStream(ctx context.Context, _ stri activeMessageItem = nil } switch typ { + case "fallback": + toModel := strings.TrimSpace(cb.Get("to.model").String()) + fromModel := strings.TrimSpace(cb.Get("from.model").String()) + if toModel != "" { + fallbackModel = strings.Clone(toModel) + } + defaultFrom := fromModel + if defaultFrom == "" { + defaultFrom = st.RequestEcho.model + } + if defaultFrom == "" { + defaultFrom = modelName + } + boundaryIdx := nextOutputIndex + fallbacks.RecordBlock(cb, defaultFrom, fallbackModel, "output_index", &boundaryIdx) case "text": item := activeMessageItem if item == nil { @@ -1648,10 +1745,18 @@ func ConvertClaudeResponseToOpenAIResponsesNonStream(ctx context.Context, _ stri // Output items are finalized after all deltas have been aggregated. case "message_delta": - usageTokens.Merge(root.Get("usage")) + usage := root.Get("usage") + usageTokens.Merge(usage) if value := root.Get("delta.stop_reason"); value.Exists() { stopReason = value.String() } + defaultFrom := st.RequestEcho.model + if defaultFrom == "" { + defaultFrom = modelName + } + if iterModel, _ := fallbacks.RecordIterations(usage.Get("iterations"), defaultFrom, "", nil); iterModel != "" { + fallbackModel = iterModel + } } } @@ -1675,6 +1780,13 @@ func ConvertClaudeResponseToOpenAIResponsesNonStream(ctx context.Context, _ stri if nativeModel != "" { _ = outDoc.Set("model", nativeModel) } + if fallbackModel != "" { + _ = outDoc.Set("model", fallbackModel) + } + if latestFB := fallbacks.Latest(); len(latestFB) > 0 { + _ = outDoc.SetRawBytes("fallback", latestFB) + _ = outDoc.SetRawBytes("fallbacks", fallbacks.ArrayBytes()) + } // Build output array in the order of the original content blocks. outputs := make([][]byte, 0, len(outputItems)) diff --git a/internal/translator/claude/openai/responses/claude_openai-responses_response_test.go b/internal/translator/claude/openai/responses/claude_openai-responses_response_test.go index 948551ab610..d499bd43078 100644 --- a/internal/translator/claude/openai/responses/claude_openai-responses_response_test.go +++ b/internal/translator/claude/openai/responses/claude_openai-responses_response_test.go @@ -2501,3 +2501,221 @@ func BenchmarkConvertClaudeResponseToOpenAIResponses_TextDelta(b *testing.B) { ConvertClaudeResponseToOpenAIResponses(context.Background(), "claude-test", request, nil, delta, ¶m) } } + +func TestConvertClaudeResponseToOpenAIResponses_PreTokenAndMidStreamFallbackTransparency(t *testing.T) { + ctx := context.Background() + + // 1. Pre-token fallback with requestRawJSON fallbacks: created, in_progress, completed, and non-stream all surface claude-opus-4-8 + fallback metadata. + originalReq := []byte(`{"model":"claude-opus-5-5","input":[{"role":"user","content":"hi"}]}`) + translatedReq := []byte(`{"model":"claude-opus-5-5","fallbacks":[{"model":"claude-opus-4-8"}],"messages":[{"role":"user","content":"hi"}]}`) + preEvents := [][]byte{ + []byte(`data: {"type":"message_start","message":{"id":"msg_resp_pre","model":"claude-opus-4-8","usage":{"input_tokens":8,"output_tokens":0}}}`), + []byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"fallback answer"}}`), + []byte(`data: {"type":"content_block_stop","index":0}`), + []byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":0},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":3}]}}`), + []byte(`data: {"type":"message_stop"}`), + } + var preParam any + var createdData, completedData ojson.Result + for _, ev := range preEvents { + for _, out := range ConvertClaudeResponseToOpenAIResponses(ctx, "claude-opus-5-5", originalReq, translatedReq, ev, &preParam) { + event, data := parseClaudeResponsesSSEEvent(t, out) + switch event { + case "response.created": + createdData = data + case "response.completed": + completedData = data + } + } + } + if got := createdData.Get("response.model").String(); got != "claude-opus-4-8" { + t.Fatalf("pre-token response.created model = %q, want claude-opus-4-8", got) + } + if createdData.Get("response.fallback.from.model").String() != "claude-opus-5-5" || createdData.Get("response.fallback.to.model").String() != "claude-opus-4-8" { + t.Fatalf("pre-token response.created fallback = %s, want from=5-5 to=4-8", createdData.Get("response.fallback").Raw) + } + if got := completedData.Get("response.model").String(); got != "claude-opus-4-8" { + t.Fatalf("pre-token response.completed model = %q, want claude-opus-4-8", got) + } + if completedData.Get("response.fallback.from.model").String() != "claude-opus-5-5" || completedData.Get("response.fallback.to.model").String() != "claude-opus-4-8" { + t.Fatalf("pre-token response.completed fallback = %s, want from=5-5 to=4-8", completedData.Get("response.fallback").Raw) + } + + preNonStreamSSE := bytes.Join(preEvents, []byte("\n\n")) + preNonStreamOut := ConvertClaudeResponseToOpenAIResponsesNonStream(ctx, "claude-opus-5-5", originalReq, translatedReq, preNonStreamSSE, nil) + if got := ojson.GetBytesNoCopy(preNonStreamOut, "model").String(); got != "claude-opus-4-8" { + t.Fatalf("pre-token non-stream Responses model = %q, want claude-opus-4-8; payload=%s", got, string(preNonStreamOut)) + } + if fb := ojson.GetBytesNoCopy(preNonStreamOut, "fallback"); !fb.Exists() || fb.Get("from.model").String() != "claude-opus-5-5" || fb.Get("to.model").String() != "claude-opus-4-8" { + t.Fatalf("pre-token non-stream Responses fallback = %s, want from=5-5 to=4-8", fb.Raw) + } + + // 2. Mid-stream fallback: output[0] closes at fallback boundary, response.in_progress announces fallback + output_index=1, and completed/non-stream preserve serving model + boundary. + midEvents := [][]byte{ + []byte(`data: {"type":"message_start","message":{"id":"msg_resp_mid","model":"claude-opus-5-5","usage":{"input_tokens":8,"output_tokens":0}}}`), + []byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial "}}`), + []byte(`data: {"type":"content_block_stop","index":0}`), + []byte(`data: {"type":"content_block_start","index":1,"content_block":{"type":"fallback","from":{"model":"claude-opus-5-5"},"to":{"model":"claude-opus-4-8"},"trigger":{"type":"refusal","category":"cyber"}}}`), + []byte(`data: {"type":"content_block_stop","index":1}`), + []byte(`data: {"type":"content_block_start","index":2,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"fallback text"}}`), + []byte(`data: {"type":"content_block_stop","index":2}`), + []byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":6,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":2},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":4}]}}`), + []byte(`data: {"type":"message_stop"}`), + } + + var midParam any + var boundaryInProgress, midCompleted ojson.Result + for _, ev := range midEvents { + for _, out := range ConvertClaudeResponseToOpenAIResponses(ctx, "claude-opus-5-5", originalReq, translatedReq, ev, &midParam) { + event, data := parseClaudeResponsesSSEEvent(t, out) + if event == "response.in_progress" && data.Get("response.fallback").Exists() { + boundaryInProgress = data + } + if event == "response.completed" { + midCompleted = data + } + } + } + if !boundaryInProgress.Exists() { + t.Fatal("expected mid-stream fallback to emit response.in_progress with response.fallback") + } + if got := boundaryInProgress.Get("response.model").String(); got != "claude-opus-4-8" { + t.Fatalf("boundary response.in_progress model = %q, want claude-opus-4-8", got) + } + if boundaryInProgress.Get("response.fallback.trigger.category").String() != "cyber" || boundaryInProgress.Get("response.fallback.output_index").Int() != 1 { + t.Fatalf("boundary response.in_progress fallback = %s, want trigger=cyber output_index=1", boundaryInProgress.Get("response.fallback").Raw) + } + if got := midCompleted.Get("response.model").String(); got != "claude-opus-4-8" { + t.Fatalf("mid-stream response.completed model = %q, want claude-opus-4-8", got) + } + if midCompleted.Get("response.fallback.output_index").Int() != 1 || len(midCompleted.Get("response.output").Array()) != 2 { + t.Fatalf("mid-stream response.completed = %s, want fallback.output_index=1 and 2 split message items", midCompleted.Get("response").Raw) + } + + midNativeRaw := []byte(`{"id":"msg_resp_mid","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"partial "},{"type":"fallback","from":{"model":"claude-opus-5-5"},"to":{"model":"claude-opus-4-8"},"trigger":{"type":"refusal","category":"cyber"}},{"type":"text","text":"fallback text"}],"stop_reason":"end_turn","usage":{"input_tokens":8,"output_tokens":6,"iterations":[{"type":"message","model":"claude-opus-5-5","output_tokens":2},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":4}]}}`) + midNonStreamOut := ConvertClaudeResponseToOpenAIResponsesNonStream(ctx, "claude-opus-5-5", originalReq, translatedReq, midNativeRaw, nil) + if got := ojson.GetBytesNoCopy(midNonStreamOut, "model").String(); got != "claude-opus-4-8" { + t.Fatalf("mid-stream non-stream Responses model = %q, want claude-opus-4-8; payload=%s", got, string(midNonStreamOut)) + } + midFB := ojson.GetBytesNoCopy(midNonStreamOut, "fallback") + if !midFB.Exists() || midFB.Get("trigger.category").String() != "cyber" || midFB.Get("output_index").Int() != 1 { + t.Fatalf("mid-stream non-stream Responses fallback = %s, want trigger=cyber output_index=1", midFB.Raw) + } +} + +func TestConvertClaudeResponseToOpenAIResponses_DefaultStringFallbackAndStickyRouting(t *testing.T) { + ctx := context.Background() + + // 1. "fallbacks": "default" + sticky routing (upstream serves claude-opus-4-8 directly in message_start with no fallback block and no usage.iterations). + origReq := []byte(`{"model":"claude-opus-5-5","input":[{"role":"user","content":"turn 2"}]}`) + translatedDefaultReq := []byte(`{"model":"claude-opus-5-5","fallbacks":"default","messages":[{"role":"user","content":"turn 2"}]}`) + stickyEvents := [][]byte{ + []byte(`data: {"type":"message_start","message":{"id":"msg_sticky","model":"claude-opus-4-8","usage":{"input_tokens":12,"output_tokens":0}}}`), + []byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"sticky answer"}}`), + []byte(`data: {"type":"content_block_stop","index":0}`), + []byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`), + []byte(`data: {"type":"message_stop"}`), + } + + var param any + var created, inProgress, completed ojson.Result + for _, ev := range stickyEvents { + for _, out := range ConvertClaudeResponseToOpenAIResponses(ctx, "claude-opus-5-5", origReq, translatedDefaultReq, ev, ¶m) { + event, data := parseClaudeResponsesSSEEvent(t, out) + switch event { + case "response.created": + created = data + case "response.in_progress": + if !inProgress.Exists() { + inProgress = data + } + case "response.completed": + completed = data + } + } + } + if created.Get("response.model").String() != "claude-opus-4-8" || inProgress.Get("response.model").String() != "claude-opus-4-8" || completed.Get("response.model").String() != "claude-opus-4-8" { + t.Fatalf("sticky default fallback models = (%q, %q, %q), want all claude-opus-4-8", + created.Get("response.model").String(), inProgress.Get("response.model").String(), completed.Get("response.model").String()) + } + if created.Get("response.fallback.from.model").String() != "claude-opus-5-5" || created.Get("response.fallback.to.model").String() != "claude-opus-4-8" { + t.Fatalf("sticky created fallback = %s, want from=5-5 to=4-8", created.Get("response.fallback").Raw) + } + + stickyNonStream := ConvertClaudeResponseToOpenAIResponsesNonStream(ctx, "claude-opus-5-5", origReq, translatedDefaultReq, bytes.Join(stickyEvents, []byte("\n\n")), nil) + if got := ojson.GetBytesNoCopy(stickyNonStream, "model").String(); got != "claude-opus-4-8" { + t.Fatalf("sticky non-stream model = %q, want claude-opus-4-8", got) + } + + // 2. Dated snapshot of the primary model (claude-opus-5-5-20260501) must NOT be misclassified as a fallback. + var snapParam any + snapStart := []byte(`data: {"type":"message_start","message":{"id":"msg_snap","model":"claude-opus-5-5-20260501","usage":{"input_tokens":4,"output_tokens":0}}}`) + for _, out := range ConvertClaudeResponseToOpenAIResponses(ctx, "claude-opus-5-5", origReq, translatedDefaultReq, snapStart, &snapParam) { + event, data := parseClaudeResponsesSSEEvent(t, out) + if event == "response.created" && data.Get("response.fallback").Exists() { + t.Fatalf("dated primary snapshot should not emit fallback metadata: %s", data.Get("response.fallback").Raw) + } + } +} + +func TestConvertClaudeResponseToOpenAIResponses_MultiHopFallbackChainPreservesAllBoundaries(t *testing.T) { + ctx := context.Background() + origReq := []byte(`{"model":"claude-fable-5-1","input":[{"role":"user","content":"chain"}]}`) + translatedReq := []byte(`{"model":"claude-fable-5-1","fallbacks":[{"model":"claude-opus-5"},{"model":"claude-opus-4-8"}],"messages":[{"role":"user","content":"chain"}]}`) + + events := [][]byte{ + []byte(`data: {"type":"message_start","message":{"id":"msg_chain","model":"claude-fable-5-1","usage":{"input_tokens":10,"output_tokens":0}}}`), + []byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partA "}}`), + []byte(`data: {"type":"content_block_stop","index":0}`), + []byte(`data: {"type":"content_block_start","index":1,"content_block":{"type":"fallback","from":{"model":"claude-fable-5-1"},"to":{"model":"claude-opus-5"},"trigger":{"type":"refusal","category":"reasoning_extraction"}}}`), + []byte(`data: {"type":"content_block_stop","index":1}`), + []byte(`data: {"type":"content_block_start","index":2,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"partB "}}`), + []byte(`data: {"type":"content_block_stop","index":2}`), + []byte(`data: {"type":"content_block_start","index":3,"content_block":{"type":"fallback","from":{"model":"claude-opus-5"},"to":{"model":"claude-opus-4-8"},"trigger":{"type":"refusal","category":"cyber"}}}`), + []byte(`data: {"type":"content_block_stop","index":3}`), + []byte(`data: {"type":"content_block_start","index":4,"content_block":{"type":"text","text":""}}`), + []byte(`data: {"type":"content_block_delta","index":4,"delta":{"type":"text_delta","text":"partC"}}`), + []byte(`data: {"type":"content_block_stop","index":4}`), + []byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":9,"iterations":[{"type":"message","model":"claude-fable-5-1","output_tokens":3},{"type":"fallback_message","model":"claude-opus-5","output_tokens":3},{"type":"fallback_message","model":"claude-opus-4-8","output_tokens":3}]}}`), + []byte(`data: {"type":"message_stop"}`), + } + + var param any + var completed ojson.Result + for _, ev := range events { + for _, out := range ConvertClaudeResponseToOpenAIResponses(ctx, "claude-fable-5-1", origReq, translatedReq, ev, ¶m) { + event, data := parseClaudeResponsesSSEEvent(t, out) + if event == "response.completed" { + completed = data + } + } + } + if got := completed.Get("response.model").String(); got != "claude-opus-4-8" { + t.Fatalf("multi-hop completed model = %q, want claude-opus-4-8", got) + } + hops := completed.Get("response.fallbacks").Array() + if len(hops) != 2 { + t.Fatalf("multi-hop response.fallbacks len = %d, want 2; raw=%s", len(hops), completed.Get("response.fallbacks").Raw) + } + if hops[0].Get("from.model").String() != "claude-fable-5-1" || hops[0].Get("to.model").String() != "claude-opus-5" || hops[0].Get("output_index").Int() != 1 { + t.Fatalf("hop[0] = %s, want fable-5-1 -> opus-5 at output_index=1", hops[0].Raw) + } + if hops[1].Get("from.model").String() != "claude-opus-5" || hops[1].Get("to.model").String() != "claude-opus-4-8" || hops[1].Get("output_index").Int() != 2 { + t.Fatalf("hop[1] = %s, want opus-5 -> opus-4-8 at output_index=2", hops[1].Raw) + } + if len(completed.Get("response.output").Array()) != 3 { + t.Fatalf("multi-hop response.output len = %d, want 3 message items", len(completed.Get("response.output").Array())) + } + + nonStreamOut := ConvertClaudeResponseToOpenAIResponsesNonStream(ctx, "claude-fable-5-1", origReq, translatedReq, bytes.Join(events, []byte("\n\n")), nil) + nonStreamHops := ojson.GetBytesNoCopy(nonStreamOut, "fallbacks").Array() + if len(nonStreamHops) != 2 || nonStreamHops[0].Get("output_index").Int() != 1 || nonStreamHops[1].Get("output_index").Int() != 2 { + t.Fatalf("non-stream multi-hop fallbacks = %s, want 2 hops with output_index 1 and 2", ojson.GetBytesNoCopy(nonStreamOut, "fallbacks").Raw) + } +} diff --git a/internal/translator/codex/openai/responses/codex_openai-responses_request.go b/internal/translator/codex/openai/responses/codex_openai-responses_request.go index aee02e15a7f..a1ad3fa7324 100644 --- a/internal/translator/codex/openai/responses/codex_openai-responses_request.go +++ b/internal/translator/codex/openai/responses/codex_openai-responses_request.go @@ -74,6 +74,7 @@ func ConvertOpenAIResponsesRequestToCodex(modelName string, inputRawJSON []byte, inputResult = convertSystemRoleToDeveloperDoc(inputResult, ensureDoc) normalizeCodexBuiltinToolsDoc(rawJSON, ensureDoc) normalizeEmptyFunctionCallArgumentsDoc(inputResult, ensureDoc) + translatorcommon.SanitizeOrphanResponsesToolOutputsInputDoc(inputResult, ensureDoc) if doc != nil { return doc.Bytes(), nil diff --git a/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go b/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go index bede0ae168c..2769fa913d8 100644 --- a/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go +++ b/internal/translator/codex/openai/responses/codex_openai-responses_request_test.go @@ -1098,3 +1098,86 @@ func TestConvertOpenAIResponsesRequestToCodexParallelToolCalls(t *testing.T) { } }) } + +func TestConvertOpenAIResponsesRequestToCodexSanitizesOrphanToolOutputs(t *testing.T) { + raw := []byte(`{ + "model":"gpt-5.4", + "input":[ + {"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}, + {"type":"function_call_output","id":"fco_1","name":"codex_apps_open_page","namespace":"agent","output":"{\"page_id\":null}"}, + {"type":"custom_tool_call_output","id":"fco_2","name":"custom_ctx","output":[{"type":"input_text","text":"part one"},{"type":"input_text","text":"part two"},{"type":"input_image","image_url":"https://example.com/page.png"}]}, + {"type":"function_call","call_id":"call_ok","name":"shell","arguments":""}, + {"type":"function_call_output","call_id":"call_ok","output":"ok"}, + {"type":"function_call_output","call_id":" ","output":"blank id"}, + {"type":"function_call_output","id":"fco_3","name":"create_thread","namespace":"codex_app","output":"task"}, + {"type":"function_call","call_id":"call_pair","name":"shell","arguments":"{}"}, + {"type":"function_call_output","output":"paired without call_id"} + ] + }`) + + out, errConvert := ConvertOpenAIResponsesRequestToCodex("gpt-5.4", raw, false) + if errConvert != nil { + t.Fatalf("ConvertOpenAIResponsesRequestToCodex returned error: %v", errConvert) + } + input := ojson.GetBytesNoCopy(out, "input").Array() + if len(input) != 9 { + t.Fatalf("input len = %d, want 9", len(input)) + } + + if got := input[1].Get("type").String(); got != "message" { + t.Fatalf("input[1].type = %q, want %q", got, "message") + } + if got := input[1].Get("role").String(); got != "user" { + t.Fatalf("input[1].role = %q, want %q", got, "user") + } + want1 := "Tool output from codex_apps_open_page:\n{\"page_id\":null}" + if got := input[1].Get("content.0.text").String(); got != want1 { + t.Fatalf("input[1].content.0.text = %q, want %q", got, want1) + } + + if got := input[2].Get("type").String(); got != "message" { + t.Fatalf("input[2].type = %q, want %q", got, "message") + } + want2 := "Tool output from custom_ctx:\npart one\npart two" + if got := input[2].Get("content.0.text").String(); got != want2 { + t.Fatalf("input[2].content.0.text = %q, want %q", got, want2) + } + if got := input[2].Get("content.1.type").String(); got != "input_image" { + t.Fatalf("input[2].content.1.type = %q, want %q", got, "input_image") + } + if got := input[2].Get("content.1.image_url").String(); got != "https://example.com/page.png" { + t.Fatalf("input[2].content.1.image_url = %q, want %q", got, "https://example.com/page.png") + } + + if got := input[3].Get("arguments").String(); got != "{}" { + t.Fatalf("input[3].arguments = %q, want %q", got, "{}") + } + if got := input[4].Get("type").String(); got != "function_call_output" { + t.Fatalf("input[4].type = %q, want %q", got, "function_call_output") + } + if got := input[4].Get("call_id").String(); got != "call_ok" { + t.Fatalf("input[4].call_id = %q, want %q", got, "call_ok") + } + + if got := input[5].Get("type").String(); got != "message" { + t.Fatalf("input[5].type = %q, want %q", got, "message") + } + want5 := "Tool output from tool:\nblank id" + if got := input[5].Get("content.0.text").String(); got != want5 { + t.Fatalf("input[5].content.0.text = %q, want %q", got, want5) + } + + if got := input[6].Get("type").String(); got != "function_call_output" { + t.Fatalf("input[6].type = %q, want %q", got, "function_call_output") + } + if got := input[6].Get("namespace").String(); got != "codex_app" { + t.Fatalf("input[6].namespace = %q, want %q", got, "codex_app") + } + + if got := input[8].Get("type").String(); got != "function_call_output" { + t.Fatalf("input[8].type = %q, want %q", got, "function_call_output") + } + if got := input[8].Get("call_id").String(); got != "call_pair" { + t.Fatalf("input[8].call_id = %q, want %q", got, "call_pair") + } +} diff --git a/internal/translator/common/claude_native_response.go b/internal/translator/common/claude_native_response.go index b1dd1ae8c77..1cb67dd640f 100644 --- a/internal/translator/common/claude_native_response.go +++ b/internal/translator/common/claude_native_response.go @@ -83,3 +83,233 @@ func ClaudeMessagesJSONToSSE(rawJSON []byte) ([]byte, string) { emit(map[string]any{"type": "message_stop"}) return out.Bytes(), strings.Clone(root.Get("model").String()) } + +// ClaudeModelSameOrSnapshot reports whether primaryModel and upstreamModel +// refer to the same Anthropic model or an 8-digit YYYYMMDD snapshot thereof. +func ClaudeModelSameOrSnapshot(primaryModel, upstreamModel string) bool { + p := strings.ToLower(strings.TrimSpace(primaryModel)) + u := strings.ToLower(strings.TrimSpace(upstreamModel)) + if p == "" || u == "" { + return false + } + if p == u { + return true + } + return isClaudeDatedSnapshotOf(p, u) || isClaudeDatedSnapshotOf(u, p) +} + +func isClaudeDatedSnapshotOf(base, candidate string) bool { + if !strings.HasPrefix(candidate, base+"-") { + return false + } + suffix := candidate[len(base)+1:] + if len(suffix) != 8 { + return false + } + for i := 0; i < len(suffix); i++ { + if suffix[i] < '0' || suffix[i] > '9' { + return false + } + } + return true +} + +func claudeRequestHasFallbacks(raw []byte) bool { + if len(raw) == 0 || !ojson.ValidBytes(raw) { + return false + } + fb := ojson.GetBytesNoCopy(raw, "fallbacks") + if !fb.Exists() { + return false + } + switch fb.Type { + case ojson.String: + return strings.TrimSpace(fb.String()) != "" + case ojson.JSON: + if fb.IsArray() { + return len(fb.Array()) > 0 + } + if fb.IsObject() { + return len(fb.Map()) > 0 + } + } + return false +} + +func claudePayloadStringModel(raw []byte) string { + if len(raw) == 0 || !ojson.ValidBytes(raw) { + return "" + } + m := ojson.GetBytesNoCopy(raw, "model") + if m.Type != ojson.String { + return "" + } + return strings.TrimSpace(m.String()) +} + +func isCanonicalClaudeModelID(model string) bool { + return strings.HasPrefix(strings.ToLower(strings.TrimSpace(model)), "claude-") +} + +// ClaudePreTokenFallbackModels detects when an Anthropic message_start model +// already switched to a fallback model (including array fallbacks, +// fallbacks: "default", and sticky-routing turns). +func ClaudePreTokenFallbackModels(originalRequestRawJSON, requestRawJSON []byte, fallbackRequestedModel, upstreamModel string) (fromModel, toModel string, ok bool) { + upstreamModel = strings.TrimSpace(upstreamModel) + if upstreamModel == "" { + return "", "", false + } + primary := claudePayloadStringModel(requestRawJSON) + if primary == "" { + primary = claudePayloadStringModel(originalRequestRawJSON) + } + if primary == "" { + primary = strings.TrimSpace(fallbackRequestedModel) + } + if primary != "" && ClaudeModelSameOrSnapshot(primary, upstreamModel) { + return "", "", false + } + hasFallbacks := claudeRequestHasFallbacks(requestRawJSON) || claudeRequestHasFallbacks(originalRequestRawJSON) + if !hasFallbacks && !(isCanonicalClaudeModelID(primary) && isCanonicalClaudeModelID(upstreamModel)) { + return "", "", false + } + return strings.Clone(primary), strings.Clone(upstreamModel), true +} + +// BuildClaudeFallbackMetadata serializes a structured fallback metadata object +// preserving upstream from/to/trigger objects and an optional boundary index. +func BuildClaudeFallbackMetadata(contentBlock ojson.Result, defaultFromModel, defaultToModel, boundaryKey string, boundaryIndex *int) []byte { + doc := ojson.NewDocString("{}") + hasField := false + if contentBlock.Exists() && contentBlock.Get("from").IsObject() { + _ = doc.SetRawBytes("from", []byte(contentBlock.Get("from").Raw)) + hasField = true + } else if m := strings.TrimSpace(defaultFromModel); m != "" { + _ = doc.Set("from.model", m) + hasField = true + } + if contentBlock.Exists() && contentBlock.Get("to").IsObject() { + _ = doc.SetRawBytes("to", []byte(contentBlock.Get("to").Raw)) + hasField = true + } else if m := strings.TrimSpace(defaultToModel); m != "" { + _ = doc.Set("to.model", m) + hasField = true + } + if contentBlock.Exists() && contentBlock.Get("trigger").IsObject() { + _ = doc.SetRawBytes("trigger", []byte(contentBlock.Get("trigger").Raw)) + hasField = true + } + if !hasField { + return nil + } + if boundaryKey != "" && boundaryIndex != nil { + _ = doc.Set(boundaryKey, *boundaryIndex) + } + return doc.Bytes() +} + +// ClaudeFallbackChain accumulates ordered Anthropic fallback hops across +// pre-token message_start switches, mid-stream fallback content blocks, and +// usage.iterations fallback_message entries without losing earlier boundaries. +type ClaudeFallbackChain struct { + Entries [][]byte + inferredPreTokenSrc string + hasExplicitBlock bool +} + +// Reset clears all accumulated fallback state for a new message. +func (c *ClaudeFallbackChain) Reset() { + c.Entries = nil + c.inferredPreTokenSrc = "" + c.hasExplicitBlock = false +} + +// RecordPreToken records a pre-token or sticky fallback detected at message_start. +func (c *ClaudeFallbackChain) RecordPreToken(fromModel, toModel, boundaryKey string, boundaryIndex *int) []byte { + fb := BuildClaudeFallbackMetadata(ojson.Result{}, fromModel, toModel, boundaryKey, boundaryIndex) + if len(fb) == 0 { + return nil + } + c.Entries = [][]byte{fb} + c.inferredPreTokenSrc = strings.Clone(strings.TrimSpace(fromModel)) + c.hasExplicitBlock = false + return fb +} + +// RecordBlock records an explicit Anthropic content_block of type "fallback". +// If the first explicit block describes the same transition already inferred at +// message_start, it upgrades that entry with trigger/boundary details; otherwise +// it appends a new hop in order. +func (c *ClaudeFallbackChain) RecordBlock(contentBlock ojson.Result, defaultFromModel, defaultToModel, boundaryKey string, boundaryIndex *int) []byte { + fb := BuildClaudeFallbackMetadata(contentBlock, defaultFromModel, defaultToModel, boundaryKey, boundaryIndex) + if len(fb) == 0 { + return nil + } + blockFrom := strings.TrimSpace(contentBlock.Get("from.model").String()) + if blockFrom == "" { + blockFrom = strings.TrimSpace(defaultFromModel) + } + if !c.hasExplicitBlock && len(c.Entries) == 1 && c.inferredPreTokenSrc != "" && ClaudeModelSameOrSnapshot(c.inferredPreTokenSrc, blockFrom) { + c.Entries[0] = fb + } else { + c.Entries = append(c.Entries, fb) + } + c.inferredPreTokenSrc = "" + c.hasExplicitBlock = true + return fb +} + +// RecordIterations reconciles usage.iterations fallback_message entries, +// returning the final fallback serving model and any newly discovered hop +// metadata when explicit fallback content blocks were absent. +func (c *ClaudeFallbackChain) RecordIterations(iterations ojson.Result, defaultFromModel, boundaryKey string, boundaryIndex *int) (finalModel string, newEntries [][]byte) { + if !iterations.Exists() || !iterations.IsArray() { + return "", nil + } + curFrom := strings.TrimSpace(defaultFromModel) + var hops [][]byte + for _, it := range iterations.Array() { + m := strings.TrimSpace(it.Get("model").String()) + if m == "" { + continue + } + switch it.Get("type").String() { + case "message": + curFrom = m + case "fallback_message": + finalModel = strings.Clone(m) + if !c.hasExplicitBlock { + if fb := BuildClaudeFallbackMetadata(ojson.Result{}, curFrom, m, boundaryKey, boundaryIndex); len(fb) > 0 { + hops = append(hops, fb) + } + } + curFrom = m + } + } + if finalModel == "" || c.hasExplicitBlock || len(hops) == 0 { + return finalModel, nil + } + prevLen := len(c.Entries) + if len(hops) > prevLen { + c.Entries = hops + newEntries = hops[prevLen:] + } + c.inferredPreTokenSrc = "" + return finalModel, newEntries +} + +// Latest returns the most recent fallback hop metadata, or nil when none occurred. +func (c *ClaudeFallbackChain) Latest() []byte { + if len(c.Entries) == 0 { + return nil + } + return c.Entries[len(c.Entries)-1] +} + +// ArrayBytes serializes all ordered fallback hops as a JSON array, or nil when empty. +func (c *ClaudeFallbackChain) ArrayBytes() []byte { + if len(c.Entries) == 0 { + return nil + } + return JoinRawArray(c.Entries) +} diff --git a/internal/translator/common/gemini_claude_carrier.go b/internal/translator/common/gemini_claude_carrier.go new file mode 100644 index 00000000000..a28d975cce5 --- /dev/null +++ b/internal/translator/common/gemini_claude_carrier.go @@ -0,0 +1,68 @@ +package common + +import ( + "strings" + + "github.com/MoeForge/moego/base64" + "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" +) + +// Gemini Claude carriers encode direction and semantic target on the client-facing wire. +const ( + GeminiClaudeCarrierPrefix = "cpa-gemini-carrier-v1:" + GeminiClaudeCarrierNext = "next" + GeminiClaudeCarrierPrevious = "previous" + GeminiClaudeCarrierStandalone = "standalone" + GeminiClaudeCarrierText = "text" + GeminiClaudeCarrierFunction = "function" + GeminiClaudeCarrierAny = "any" +) + +// EncodeGeminiClaudeCarrierSignature marks the native part a Claude-facing signature belongs to. +func EncodeGeminiClaudeCarrierSignature(rawSignature, direction, targetKind string) string { + rawSignature = strings.TrimSpace(rawSignature) + if rawSignature == "" { + return "" + } + return GeminiClaudeCarrierPrefix + direction + ":" + targetKind + ":" + base64.RawStdEncoding.EncodeToString([]byte(rawSignature)) +} + +// DecodeGeminiClaudeCarrierSignature validates and unwraps a marked carrier, or returns a legacy raw signature. +func DecodeGeminiClaudeCarrierSignature(rawSignature string) (signatureValue, direction, targetKind string, marked, ok bool) { + rawSignature = strings.TrimSpace(rawSignature) + if !strings.HasPrefix(rawSignature, GeminiClaudeCarrierPrefix) { + return rawSignature, "", "", false, true + } + marked = true + if len(rawSignature) > (signature.MaxGeminiThoughtSignatureLen*4/3)+1024 { + return "", "", "", true, false + } + fields := strings.SplitN(strings.TrimPrefix(rawSignature, GeminiClaudeCarrierPrefix), ":", 3) + if len(fields) != 3 { + return "", "", "", true, false + } + direction, targetKind = fields[0], fields[1] + switch direction { + case GeminiClaudeCarrierNext, GeminiClaudeCarrierPrevious, GeminiClaudeCarrierStandalone: + default: + return "", "", "", true, false + } + switch targetKind { + case GeminiClaudeCarrierText, GeminiClaudeCarrierFunction, GeminiClaudeCarrierAny: + default: + return "", "", "", true, false + } + decoded, errDecode := base64.RawStdEncoding.DecodeString(fields[2]) + if errDecode != nil || len(decoded) == 0 || strings.HasPrefix(string(decoded), GeminiClaudeCarrierPrefix) { + return "", "", "", true, false + } + blockKind := signature.SignatureBlockKindGeminiModelPart + if targetKind == GeminiClaudeCarrierFunction { + blockKind = signature.SignatureBlockKindGeminiFunctionCall + } + normalized, compatible := signature.CompatibleSignatureForProviderBlock(signature.SignatureProviderGemini, string(decoded), blockKind) + if !compatible || signature.IsGeminiThoughtSignatureBypass(signature.SignaturePayloadWithoutProviderPrefix(normalized)) { + return "", "", "", true, false + } + return normalized, direction, targetKind, true, true +} diff --git a/internal/translator/common/responses.go b/internal/translator/common/responses.go index 51e5e4cd2a5..434d06b41b8 100644 --- a/internal/translator/common/responses.go +++ b/internal/translator/common/responses.go @@ -1,6 +1,7 @@ package common import ( + "fmt" "strings" "github.com/MoeForge/moego/ojson" @@ -131,7 +132,7 @@ func NormalizeResponsesToolCallOutputs(items []ojson.Result) []ojson.Result { expectedName := pendingCallNames[pendingID] if expectedName != "" { for outIdx, out := range outputs { - if !used[outIdx] && ExtractResponsesCallID(out) == "" { + if !used[outIdx] && ExtractResponsesCallID(out) == "" && !isCodexDelegationToolOutput(out) { outName := strings.TrimSpace(out.Get("name").String()) if outName != "" && outName == expectedName { used[outIdx] = true @@ -150,7 +151,7 @@ func NormalizeResponsesToolCallOutputs(items []ojson.Result) []ojson.Result { continue } for outIdx, out := range outputs { - if !used[outIdx] && ExtractResponsesCallID(out) == "" { + if !used[outIdx] && ExtractResponsesCallID(out) == "" && !isCodexDelegationToolOutput(out) { outName := strings.TrimSpace(out.Get("name").String()) expectedName := pendingCallNames[pendingID] if outName == "" || expectedName == "" || outName == expectedName { @@ -187,3 +188,189 @@ func NormalizeResponsesToolCallOutputs(items []ojson.Result) []ojson.Result { return normalized } + +// SanitizeOrphanResponsesToolOutputsDoc rewrites standalone function_call_output +// and custom_tool_call_output items that carry no call_id into user message +// items. Codex Desktop Companion Page context is injected as function_call_output +// items without call_id, which strict Responses upstreams reject with HTTP 400 +// ("responses function_call_output call_id is required"). +func SanitizeOrphanResponsesToolOutputsDoc(doc *ojson.Doc) bool { + if doc == nil { + return false + } + return SanitizeOrphanResponsesToolOutputsInputDoc(doc.Get("input"), func() *ojson.Doc { + return doc + }) +} + +// SanitizeOrphanResponsesToolOutputsInputDoc pairs tool outputs missing call_id +// with preceding unmatched tool calls when possible, and rewrites remaining +// standalone function_call_output and custom_tool_call_output items without +// call_id into user message items in-place on the document returned by ensureDoc. +func SanitizeOrphanResponsesToolOutputsInputDoc(inputResult ojson.Result, ensureDoc func() *ojson.Doc) bool { + if !inputResult.IsArray() || ensureDoc == nil { + return false + } + inputItems := inputResult.Array() + if len(inputItems) == 0 { + return false + } + + normalizedItems := NormalizeResponsesToolCallOutputs(inputItems) + + changed := false + pendingMissingCallIDOutputType := "" + for i := 0; i < len(inputItems); i++ { + item := normalizedItems[i] + if !item.IsObject() { + pendingMissingCallIDOutputType = "" + continue + } + itemType := strings.TrimSpace(item.Get("type").String()) + if itemType == "function_call" || itemType == "custom_tool_call" { + if ExtractResponsesCallID(item) == "" { + pendingMissingCallIDOutputType = itemType + "_output" + } else { + pendingMissingCallIDOutputType = "" + } + continue + } + if itemType != "function_call_output" && itemType != "custom_tool_call_output" { + pendingMissingCallIDOutputType = "" + continue + } + if isCodexDelegationToolOutput(item) { + pendingMissingCallIDOutputType = "" + continue + } + if resolvedCallID := responsesToolOutputExplicitCallID(item); resolvedCallID != "" { + pendingMissingCallIDOutputType = "" + origCallID := strings.TrimSpace(inputItems[i].Get("call_id").String()) + if origCallID != resolvedCallID { + itemPath := fmt.Sprintf("input.%d.call_id", i) + if errSet := ensureDoc().Set(itemPath, resolvedCallID); errSet == nil { + changed = true + } + } + continue + } + if pendingMissingCallIDOutputType == itemType && + strings.TrimSpace(item.Get("name").String()) == "" && + strings.TrimSpace(item.Get("id").String()) == "" { + pendingMissingCallIDOutputType = "" + continue + } + pendingMissingCallIDOutputType = "" + + itemPath := fmt.Sprintf("input.%d", i) + if setOrphanResponsesToolOutputMessageDoc(ensureDoc(), itemPath, item) { + changed = true + } + } + return changed +} + +func responsesToolOutputExplicitCallID(item ojson.Result) string { + for _, key := range []string{"call_id", "tool_call_id", "callId"} { + val := item.Get(key) + if val.Type == ojson.String { + if s := strings.TrimSpace(val.String()); s != "" { + return s + } + } + } + return "" +} + +func isCodexDelegationToolOutput(item ojson.Result) bool { + if strings.TrimSpace(item.Get("type").String()) != "function_call_output" { + return false + } + if strings.TrimSpace(item.Get("namespace").String()) != "codex_app" { + return false + } + switch strings.TrimSpace(item.Get("name").String()) { + case "create_thread", "send_message_to_thread": + return true + default: + return false + } +} + +func setOrphanResponsesToolOutputMessageDoc(targetDoc *ojson.Doc, itemPath string, item ojson.Result) bool { + if targetDoc == nil { + return false + } + fullText, extraParts := buildOrphanResponsesToolOutputContent(item) + if errSet := targetDoc.SetRawBytes(itemPath, []byte(`{"type":"message","role":"user","content":[{"type":"input_text","text":""}]}`)); errSet != nil { + return false + } + if errSet := targetDoc.Set(itemPath+".content.0.text", fullText); errSet != nil { + return false + } + for idx, partRaw := range extraParts { + partPath := fmt.Sprintf("%s.content.%d", itemPath, idx+1) + if errSet := targetDoc.SetRawBytes(partPath, partRaw); errSet != nil { + return false + } + } + return true +} + +func buildOrphanResponsesToolOutputContent(item ojson.Result) (string, [][]byte) { + name := strings.TrimSpace(item.Get("name").String()) + if name == "" { + name = "tool" + } + outputText, extraParts := extractOrphanResponsesToolOutputParts(item.Get("output")) + if outputText == "" { + outputText = "(empty)" + } + return "Tool output from " + name + ":\n" + outputText, extraParts +} + +func extractOrphanResponsesToolOutputParts(output ojson.Result) (string, [][]byte) { + if !output.Exists() || output.Type == ojson.Null { + return "", nil + } + if output.Type == ojson.String { + return strings.TrimSpace(output.String()), nil + } + if output.IsArray() { + items := output.Array() + parts := make([]string, 0, len(items)) + var extraParts [][]byte + for i := 0; i < len(items); i++ { + part := items[i] + if part.Type == ojson.String { + if s := strings.TrimSpace(part.String()); s != "" { + parts = append(parts, s) + } + continue + } + if !part.IsObject() { + continue + } + matchedText := false + for _, key := range []string{"text", "input_text", "output_text"} { + val := part.Get(key) + if val.Type == ojson.String { + matchedText = true + if s := strings.TrimSpace(val.String()); s != "" { + parts = append(parts, s) + } + break + } + } + if !matchedText { + if raw := strings.TrimSpace(part.Raw); raw != "" { + extraParts = append(extraParts, []byte(raw)) + } + } + } + if len(parts) > 0 || len(extraParts) > 0 { + return strings.Join(parts, "\n"), extraParts + } + } + return strings.TrimSpace(output.Raw), nil +} diff --git a/internal/translator/gemini/claude/gemini_claude_carrier_test.go b/internal/translator/gemini/claude/gemini_claude_carrier_test.go new file mode 100644 index 00000000000..44429ac0aef --- /dev/null +++ b/internal/translator/gemini/claude/gemini_claude_carrier_test.go @@ -0,0 +1,532 @@ +package claude + +import ( + "bytes" + "context" + "strconv" + "strings" + "testing" + + "github.com/MoeForge/moego/base64" + "github.com/MoeForge/moego/ojson" + sigcompat "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" +) + +func TestGeminiClaudeCarrierPlacement(t *testing.T) { + signature := capturedGeminiThinkingSignature + carrier := `{"type":"thinking","thinking":"","signature":"` + signature + `"}` + tool := `{"type":"tool_use","id":"call-1","name":"lookup","input":{}}` + text := `{"type":"text","text":"answer"}` + marked := func(direction, target string) string { + return `{"type":"thinking","thinking":"","signature":"cpa-gemini-carrier-v1:` + direction + `:` + target + `:` + base64.RawStdEncoding.EncodeToString([]byte(signature)) + `"}` + } + for _, tt := range []struct { + name string + content string + signatures []string + }{ + {"leading function", carrier + `,` + tool, []string{signature}}, + {"trailing function", tool + `,` + carrier, []string{signature}}, + {"signed text before tool", carrier + `,` + text + `,` + tool, []string{signature, sigcompat.GeminiSkipThoughtSignatureValidator}}, + {"text only", carrier + `,` + text, []string{signature}}, + {"trailing text", text + `,` + carrier, []string{signature}}, + {"standalone", carrier, []string{signature}}, + {"marked next function", marked("next", "function") + `,` + tool, []string{signature}}, + {"prefixed signature", `{"type":"thinking","thinking":"","signature":"gemini#` + signature + `"},` + tool, []string{signature}}, + {"consecutive carriers", carrier + `,{"type":"thinking","thinking":"","signature":"EjQKMgEMOdbHO0Gd+c9Mxk4ELwPGbpCEcp2mFfYYLix2UVtBH3fL8GECc4+JITVnHF4qZDsE"},` + tool, []string{signature, "EjQKMgEMOdbHO0Gd+c9Mxk4ELwPGbpCEcp2mFfYYLix2UVtBH3fL8GECc4+JITVnHF4qZDsE"}}, + {"marked previous text", text + `,` + marked("previous", "text") + `,` + tool, []string{signature, sigcompat.GeminiSkipThoughtSignatureValidator}}, + {"marked standalone", marked("standalone", "any") + `,` + tool, []string{signature, sigcompat.GeminiSkipThoughtSignatureValidator}}, + {"wrong target", marked("next", "function") + `,` + text + `,` + tool, []string{"", sigcompat.GeminiSkipThoughtSignatureValidator}}, + {"foreign carrier", `{"type":"thinking","thinking":"","signature":"claude#invalid"},` + tool, []string{sigcompat.GeminiSkipThoughtSignatureValidator}}, + {"malformed carrier", `{"type":"thinking","thinking":"","signature":"cpa-gemini-carrier-v1:next:function:invalid"},` + tool, []string{sigcompat.GeminiSkipThoughtSignatureValidator}}, + {"no carrier", tool, []string{sigcompat.GeminiSkipThoughtSignatureValidator}}, + {"parallel sibling", carrier + `,` + tool + `,{"type":"tool_use","id":"call-2","name":"lookup","input":{}}`, []string{signature, sigcompat.GeminiSkipThoughtSignatureValidator}}, + } { + t.Run(tt.name, func(t *testing.T) { + request := ojson.NewDocString(`{"messages":[{"role":"assistant","content":[` + tt.content + `]},{"role":"user","content":[]}]}`) + for _, block := range request.Get("messages.0.content").Array() { + if block.Get("type").String() == "tool_use" { + result := ojson.NewDocString(`{"type":"tool_result","tool_use_id":"","content":"ok"}`) + _ = result.Set("tool_use_id", block.Get("id").String()) + _ = request.SetRawBytes("messages.1.content.-1", result.Bytes()) + } + } + if request.Get("messages.1.content.#").Int() == 0 { + _ = request.SetRaw("messages.1.content", `[{"type":"text","text":"continue"}]`) + } + output, errConvert := ConvertClaudeRequestToGemini("gemini-4-carbon", request.Bytes(), false) + if errConvert != nil { + t.Fatal(errConvert) + } + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != len(tt.signatures) { + t.Fatalf("got %d parts, want %d: %s", len(parts), len(tt.signatures), output) + } + for i, want := range tt.signatures { + if got := parts[i].Get("thoughtSignature").String(); got != want { + t.Errorf("part %d signature = %q, want %q; output=%s", i, got, want, output) + } + } + }) + } +} + +func TestGeminiClaudeCarrierStaysInAssistantMessage(t *testing.T) { + carrier := `{"type":"thinking","thinking":"","signature":"` + capturedGeminiThinkingSignature + `"}` + request := []byte(`{"messages":[{"role":"assistant","content":[` + carrier + `]},{"role":"user","content":[` + carrier + `,{"type":"text","text":"continue"}]},{"role":"assistant","content":[{"type":"tool_use","id":"call-1","name":"lookup","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call-1","content":"ok"}]}]}`) + output, errConvert := ConvertClaudeRequestToGemini("gemini-4-carbon", request, false) + if errConvert != nil { + t.Fatal(errConvert) + } + var sawCall bool + for _, content := range ojson.GetBytes(output, "contents").Array() { + for _, part := range content.Get("parts").Array() { + if content.Get("role").String() == "user" && part.Get("thoughtSignature").Exists() { + t.Fatalf("user message replayed assistant signature: %s", output) + } + if part.Get("functionCall").Exists() { + sawCall = true + if part.Get("thoughtSignature").String() != sigcompat.GeminiSkipThoughtSignatureValidator { + t.Fatalf("carrier leaked between messages: %s", output) + } + } + } + } + if !sawCall { + t.Fatalf("functionCall missing: %s", output) + } +} + +func TestGeminiClaudePartMetadataPreservesSupportedPayload(t *testing.T) { + for _, tt := range []struct { + name string + part string + tool bool + }{ + {"text", `{"text":"answer","partMetadata":{"source":"model"}}`, false}, + {"tool", `{"functionCall":{"name":"lookup","args":{}},"partMetadata":{"source":"model"}}`, true}, + } { + for _, mode := range []string{"nonstream", "stream same chunk", "stream split chunks"} { + for _, signed := range []bool{false, true} { + t.Run(tt.name+"/"+mode+"/signed="+strconv.FormatBool(signed), func(t *testing.T) { + part := ojson.NewDocString(tt.part) + if signed { + _ = part.Set("thoughtSignature", capturedGeminiThinkingSignature) + } + content := geminiClaudeContentForParts(t, []string{part.String()}, mode) + output := replayGeminiClaudeContent(t, content) + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if ojson.GetBytes(output, "contents.0.role").String() != "model" || len(parts) != 1 { + t.Fatalf("supported payload with metadata was dropped: %s; content=%s", output, content) + } + if tt.tool { + if parts[0].Get("functionCall.name").String() != "lookup" || parts[0].Get("functionCall.args").Raw != `{}` { + t.Errorf("metadata changed tool payload: %s", output) + } + } else if parts[0].Get("text").String() != "answer" { + t.Errorf("metadata changed text payload: %s", output) + } + if signed && parts[0].Get("thoughtSignature").String() != capturedGeminiThinkingSignature { + t.Errorf("metadata dropped native signature: %s", output) + } + }) + } + } + } +} + +func TestGeminiClaudeDelayedTextSignaturePartBoundaryRoundTrip(t *testing.T) { + parts := []string{`{"text":"unsigned"}`, `{"text":"signed"}`, `{"thoughtSignature":"` + capturedGeminiThinkingSignature + `"}`} + for _, mode := range []string{"nonstream", "stream same chunk", "stream split chunks"} { + t.Run(mode, func(t *testing.T) { + content := geminiClaudeContentForParts(t, parts, mode) + output := replayGeminiClaudeContent(t, content) + actual := ojson.GetBytes(output, "contents.0.parts").Array() + if len(actual) != 2 || actual[0].Get("text").String() != "unsigned" || actual[0].Get("thoughtSignature").Exists() || actual[1].Get("text").String() != "signed" || actual[1].Get("thoughtSignature").String() != capturedGeminiThinkingSignature { + t.Fatalf("delayed signature changed native text part contents: %s; content=%s", output, content) + } + }) + } +} + +func TestGeminiClaudeUnsupportedPayloadDoesNotRetargetSignature(t *testing.T) { + signature := capturedGeminiThinkingSignature + for _, tt := range []struct { + name string + parts []string + }{ + {"inline data", []string{`{"inlineData":{"mimeType":"image/png","data":"eA=="},"thoughtSignature":"` + signature + `"}`}}, + {"file data", []string{`{"fileData":{"mimeType":"image/png","fileUri":"gs://bucket/image"},"thoughtSignature":"` + signature + `"}`}}, + {"code", []string{`{"executableCode":{"language":"PYTHON","code":"1"},"thoughtSignature":"` + signature + `"}`}}, + {"delayed image signature", []string{`{"inlineData":{"mimeType":"image/png","data":"eA=="}}`, `{"thoughtSignature":"` + signature + `"}`}}, + {"delayed file signature", []string{`{"fileData":{"mimeType":"image/png","fileUri":"gs://bucket/image"}}`, `{"text":"","thought":true}`, `{"thoughtSignature":"` + signature + `"}`}}, + } { + for _, mode := range []string{"nonstream", "stream same chunk", "stream split chunks"} { + for _, prefix := range []string{`{"text":"before"}`, `{"functionCall":{"name":"lookup","args":{}}}`} { + t.Run(tt.name+"/"+mode+"/"+prefix, func(t *testing.T) { + parts := append([]string{prefix}, tt.parts...) + parts = append(parts, `{"text":"after"}`) + content := geminiClaudeContentForParts(t, parts, mode) + output := replayGeminiClaudeContent(t, content) + for _, part := range ojson.GetBytes(output, "contents.0.parts").Array() { + if got := part.Get("thoughtSignature").String(); got != "" && got != sigcompat.GeminiSkipThoughtSignatureValidator { + t.Errorf("unsupported payload signature was attached to a different part: %s; content=%s", output, content) + } + } + }) + } + } + } +} + +func geminiClaudeContentForParts(t *testing.T, parts []string, mode string) string { + t.Helper() + full := `{"candidates":[{"content":{"parts":[` + strings.Join(parts, ",") + `]},"finishReason":"STOP"}]}` + if mode == "nonstream" { + response := ConvertGeminiResponseToClaudeNonStream(context.Background(), "gemini-4-carbon", nil, nil, []byte(full), nil) + return ojson.GetBytes(response, "content").Raw + } + chunks := []string{full} + if mode == "stream split chunks" { + chunks = nil + for _, part := range parts { + chunks = append(chunks, `{"candidates":[{"content":{"parts":[`+part+`]}}]}`) + } + chunks = append(chunks, `{"candidates":[{"finishReason":"STOP"}]}`) + } + chunks = append(chunks, "[DONE]") + var param any + var events []byte + for _, chunk := range chunks { + events = append(events, bytes.Join(ConvertGeminiResponseToClaude(context.Background(), "gemini-4-carbon", nil, nil, []byte(chunk), ¶m), nil)...) + } + return claudeContentFromGeminiStream(t, events).String() +} + +func TestGeminiClaudeSignedTextPartBoundaryRoundTrip(t *testing.T) { + signed := `{"text":"signed","thoughtSignature":"` + capturedGeminiThinkingSignature + `"}` + unsigned := `{"text":"unsigned"}` + full := `{"candidates":[{"content":{"parts":[` + signed + `,` + unsigned + `]},"finishReason":"STOP"}]}` + for _, mode := range []string{"nonstream", "stream same chunk", "stream split chunks"} { + t.Run(mode, func(t *testing.T) { + var content string + if mode == "nonstream" { + response := ConvertGeminiResponseToClaudeNonStream(context.Background(), "gemini-4-carbon", nil, nil, []byte(full), nil) + content = ojson.GetBytes(response, "content").Raw + } else { + chunks := []string{full, "[DONE]"} + if mode == "stream split chunks" { + chunks = []string{`{"candidates":[{"content":{"parts":[` + signed + `]}}]}`, `{"candidates":[{"content":{"parts":[` + unsigned + `]},"finishReason":"STOP"}]}`, "[DONE]"} + } + var param any + var events []byte + for _, chunk := range chunks { + events = append(events, bytes.Join(ConvertGeminiResponseToClaude(context.Background(), "gemini-4-carbon", nil, nil, []byte(chunk), ¶m), nil)...) + } + content = claudeContentFromGeminiStream(t, events).String() + } + output := replayGeminiClaudeContent(t, content) + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 2 || parts[0].Get("text").String() != "signed" || parts[0].Get("thoughtSignature").String() != capturedGeminiThinkingSignature || parts[1].Get("text").String() != "unsigned" || parts[1].Get("thoughtSignature").Exists() { + t.Fatalf("signed text was merged with another native part: %s; content=%s", output, content) + } + }) + } +} + +func TestGeminiClaudeCarrierDoesNotCrossNonEmptyThinking(t *testing.T) { + signature := capturedGeminiThinkingSignature + previous := `{"type":"thinking","thinking":"","signature":"cpa-gemini-carrier-v1:previous:text:` + base64.RawStdEncoding.EncodeToString([]byte(signature)) + `"}` + for _, content := range []string{ + `[{"type":"text","text":"visible"},{"type":"thinking","thinking":"reasoning"},` + previous + `]`, + `[{"type":"text","text":"visible"},{"type":"thinking","thinking":"","signature":"` + signature + `"},{"type":"thinking","thinking":"reasoning"},{"type":"text","text":"unrelated"}]`, + } { + for _, compat := range []bool{false, true} { + request := []byte(`{"messages":[{"role":"assistant","content":` + content + `},{"role":"user","content":"continue"}]}`) + output, errConvert := convertClaudeRequestToGemini("gemini-4-carbon", request, false, compat) + if errConvert != nil { + t.Fatal(errConvert) + } + for _, part := range ojson.GetBytes(output, "contents.0.parts").Array() { + if !part.Get("thought").Bool() && part.Get("thoughtSignature").Exists() { + t.Errorf("compat=%t: signature crossed nonempty thought: %s", compat, output) + } + } + } + } +} + +func TestGeminiClaudeDroppedThoughtSignatureDoesNotReachVisibleText(t *testing.T) { + chunks := []string{ + `{"candidates":[{"content":{"parts":[{"text":"visible"}]}}]}`, + `{"candidates":[{"content":{"parts":[{"text":"reasoning","thought":true}]}}]}`, + `{"candidates":[{"content":{"parts":[{"text":""}]}}]}`, + `{"candidates":[{"content":{"parts":[{"thoughtSignature":"` + capturedGeminiThinkingSignature + `"}]},"finishReason":"STOP"}]}`, + `[DONE]`, + } + var param any + var events []byte + for _, chunk := range chunks { + events = append(events, bytes.Join(ConvertGeminiResponseToClaude(context.Background(), "gemini-4-carbon", nil, nil, []byte(chunk), ¶m), nil)...) + } + content := claudeContentFromGeminiStream(t, events) + output := replayGeminiClaudeContent(t, content.String()) + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 1 || parts[0].Get("text").String() != "visible" || parts[0].Get("thoughtSignature").Exists() { + t.Fatalf("dropped thought signature rebound to visible text: %s; content=%s", output, content.String()) + } +} + +func TestGeminiClaudeCarrierDoesNotConsumeWhitespaceThinking(t *testing.T) { + request := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":" ","signature":"` + capturedGeminiThinkingSignature + `"},{"type":"tool_use","id":"call-1","name":"lookup","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call-1","content":"ok"}]}]}`) + for _, compat := range []bool{false, true} { + output, errConvert := convertClaudeRequestToGemini("gemini-4-carbon", request, false, compat) + if errConvert != nil { + t.Fatal(errConvert) + } + parts := ojson.GetBytes(output, "contents.0.parts").Array() + wantParts := 1 + if compat { + wantParts = 2 + } + if len(parts) != wantParts { + t.Fatalf("compat=%t: nonempty thinking was consumed as a carrier: %s", compat, output) + } + if compat && (parts[0].Get("text").String() != " " || !parts[0].Get("thought").Bool() || parts[0].Get("thoughtSignature").String() != capturedGeminiThinkingSignature) { + t.Errorf("compat thinking changed: %s", output) + } + if parts[len(parts)-1].Get("thoughtSignature").String() != sigcompat.GeminiSkipThoughtSignatureValidator { + t.Errorf("compat=%t: nonempty thought signature leaked to tool: %s", compat, output) + } + } +} + +func TestGeminiClaudeStreamingEmptyBlockDoesNotRetargetSignature(t *testing.T) { + for _, empty := range []string{`{"text":""}`, `{"text":"","thought":true}`} { + chunks := []string{ + `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"first","partialArgs":[],"willContinue":false}}]}}]}`, + `{"candidates":[{"content":{"parts":[` + empty + `]}}]}`, + `{"candidates":[{"content":{"parts":[{"thoughtSignature":"` + capturedGeminiThinkingSignature + `"}]}}]}`, + `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"second","args":{}}}]},"finishReason":"STOP"}]}`, + `[DONE]`, + } + var param any + var events []byte + for _, chunk := range chunks { + events = append(events, bytes.Join(ConvertGeminiResponseToClaude(context.Background(), "gemini-4-carbon", nil, nil, []byte(chunk), ¶m), nil)...) + } + content := claudeContentFromGeminiStream(t, events) + output := replayGeminiClaudeContent(t, content.String()) + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != capturedGeminiThinkingSignature || parts[1].Get("thoughtSignature").String() != sigcompat.GeminiSkipThoughtSignatureValidator { + t.Errorf("empty block %s retargeted tool signature: %s; content=%s", empty, output, content.String()) + } + } +} + +func TestGeminiClaudeNonStreamSignatureOnlyThoughtPartRoundTrip(t *testing.T) { + upstream := []byte(`{"candidates":[{"content":{"parts":[{"text":"answer"},{"text":"","thought":true,"thoughtSignature":"` + capturedGeminiThinkingSignature + `"},{"functionCall":{"name":"lookup","args":{}}}]},"finishReason":"STOP"}]}`) + response := ConvertGeminiResponseToClaudeNonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream, nil) + output := replayGeminiClaudeContent(t, ojson.GetBytes(response, "content").Raw) + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 2 || parts[0].Get("text").String() != "answer" || parts[0].Get("thoughtSignature").String() != capturedGeminiThinkingSignature || parts[1].Get("thoughtSignature").String() != sigcompat.GeminiSkipThoughtSignatureValidator { + t.Fatalf("empty thought part retargeted visible text signature: %s; response=%s", output, response) + } +} + +func TestGeminiClaudeNonStreamConsecutiveTrailingSignatures(t *testing.T) { + second := "EjQKMgEMOdbHO0Gd+c9Mxk4ELwPGbpCEcp2mFfYYLix2UVtBH3fL8GECc4+JITVnHF4qZDsE" + upstream := []byte(`{"candidates":[{"content":{"parts":[{"functionCall":{"name":"lookup","args":{}}},{"thoughtSignature":"` + capturedGeminiThinkingSignature + `"},{"thoughtSignature":"` + second + `"}]},"finishReason":"STOP"}]}`) + response := ConvertGeminiResponseToClaudeNonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream, nil) + output := replayGeminiClaudeContent(t, ojson.GetBytes(response, "content").Raw) + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != second || parts[1].Get("thoughtSignature").String() != capturedGeminiThinkingSignature { + t.Fatalf("consecutive signatures must retain their function target: %s; response=%s", output, response) + } +} + +func replayGeminiClaudeContent(t *testing.T, content string) []byte { + t.Helper() + request := ojson.NewDocString(`{"messages":[{"role":"assistant","content":` + content + `},{"role":"user","content":[]}]}`) + for _, block := range ojson.Parse(content).Array() { + if block.Get("type").String() == "tool_use" { + result := ojson.NewDocString(`{"type":"tool_result","tool_use_id":"","content":"ok"}`) + _ = result.Set("tool_use_id", block.Get("id").String()) + _ = request.SetRawBytes("messages.1.content.-1", result.Bytes()) + } + } + if request.Get("messages.1.content.#").Int() == 0 { + _ = request.SetRaw("messages.1.content", `[{"type":"text","text":"continue"}]`) + } + output, errConvert := ConvertClaudeRequestToGemini("gemini-4-carbon", request.Bytes(), false) + if errConvert != nil { + t.Fatal(errConvert) + } + return output +} + +func TestGeminiClaudeStreamingCompletedToolSignatureRoundTrip(t *testing.T) { + chunks := []string{ + `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"first","partialArgs":[],"willContinue":false}}]}}]}`, + `{"candidates":[{"content":{"parts":[{"thoughtSignature":"` + capturedGeminiThinkingSignature + `"}]}}]}`, + `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"second","args":{}}}]},"finishReason":"STOP"}]}`, + `[DONE]`, + } + var param any + var events []byte + for _, chunk := range chunks { + events = append(events, bytes.Join(ConvertGeminiResponseToClaude(context.Background(), "gemini-4-carbon", nil, nil, []byte(chunk), ¶m), nil)...) + } + content := claudeContentFromGeminiStream(t, events) + request := ojson.NewDocString(`{"messages":[{"role":"assistant","content":[]},{"role":"user","content":[]}]}`) + _ = request.SetRawBytes("messages.0.content", content.Bytes()) + for _, block := range ojson.Parse(content.String()).Array() { + if block.Get("type").String() == "tool_use" { + result := ojson.NewDocString(`{"type":"tool_result","tool_use_id":"","content":"ok"}`) + _ = result.Set("tool_use_id", block.Get("id").String()) + _ = request.SetRawBytes("messages.1.content.-1", result.Bytes()) + } + } + output, errConvert := ConvertClaudeRequestToGemini("gemini-4-carbon", request.Bytes(), false) + if errConvert != nil { + t.Fatal(errConvert) + } + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != capturedGeminiThinkingSignature || parts[1].Get("thoughtSignature").String() != sigcompat.GeminiSkipThoughtSignatureValidator { + t.Fatalf("signature after a closed tool block must bind backward: %s; content=%s", output, content.String()) + } +} + +func TestGeminiClaudeStreamingLateSignatureRoundTrip(t *testing.T) { + chunks := []string{ + `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"first","partialArgs":[{"jsonPath":"$.q","stringValue":"Paris"}],"willContinue":true}}]}}]}`, + `{"candidates":[{"content":{"parts":[{"thoughtSignature":"` + capturedGeminiThinkingSignature + `"}]}}]}`, + `{"candidates":[{"content":{"parts":[{"functionCall":{}}]}}]}`, + `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"second","args":{}}}]},"finishReason":"STOP"}]}`, + `[DONE]`, + } + var param any + var events []byte + for _, chunk := range chunks { + events = append(events, bytes.Join(ConvertGeminiResponseToClaude(context.Background(), "gemini-4-carbon", nil, nil, []byte(chunk), ¶m), nil)...) + } + content := claudeContentFromGeminiStream(t, events) + request := ojson.NewDocString(`{"messages":[{"role":"assistant","content":[]},{"role":"user","content":[]}]}`) + _ = request.SetRawBytes("messages.0.content", content.Bytes()) + for _, block := range ojson.Parse(content.String()).Array() { + if block.Get("type").String() == "tool_use" { + result := ojson.NewDocString(`{"type":"tool_result","tool_use_id":"","content":"ok"}`) + _ = result.Set("tool_use_id", block.Get("id").String()) + _ = request.SetRawBytes("messages.1.content.-1", result.Bytes()) + } + } + output, errConvert := ConvertClaudeRequestToGemini("gemini-4-carbon", request.Bytes(), false) + if errConvert != nil { + t.Fatal(errConvert) + } + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 2 || parts[0].Get("thoughtSignature").String() != capturedGeminiThinkingSignature || parts[1].Get("thoughtSignature").String() != sigcompat.GeminiSkipThoughtSignatureValidator { + t.Fatalf("late signature must stay on first call, got %s; content=%s", output, content.String()) + } +} + +func claudeContentFromGeminiStream(t *testing.T, events []byte) *ojson.Doc { + t.Helper() + content := ojson.NewDocString(`[]`) + arguments := make(map[int]string) + for _, line := range strings.Split(string(events), "\n") { + if !strings.HasPrefix(line, "data:") { + continue + } + event := ojson.Parse(strings.TrimSpace(strings.TrimPrefix(line, "data:"))) + index := int(event.Get("index").Int()) + switch event.Get("type").String() { + case "content_block_start": + _ = content.SetRaw("-1", event.Get("content_block").Raw) + case "content_block_delta": + switch event.Get("delta.type").String() { + case "signature_delta": + _ = content.Set(strconv.Itoa(index)+".signature", event.Get("delta.signature").String()) + case "input_json_delta": + arguments[index] += event.Get("delta.partial_json").String() + case "text_delta": + path := strconv.Itoa(index) + ".text" + _ = content.Set(path, content.Get(path).String()+event.Get("delta.text").String()) + case "thinking_delta": + path := strconv.Itoa(index) + ".thinking" + _ = content.Set(path, content.Get(path).String()+event.Get("delta.thinking").String()) + } + case "content_block_stop": + if args := arguments[index]; args != "" { + if !ojson.Valid(args) { + t.Fatalf("invalid streamed tool arguments: %q", args) + } + _ = content.SetRaw(strconv.Itoa(index)+".input", args) + } + } + } + return content +} + +func TestGeminiClaudeTrailingTextSignatureRoundTrip(t *testing.T) { + for _, stream := range []bool{false, true} { + upstream := []byte(`{"candidates":[{"content":{"parts":[{"text":"answer"},{"thoughtSignature":"` + capturedGeminiThinkingSignature + `"},{"functionCall":{"name":"lookup","args":{}}}]},"finishReason":"STOP"}]}`) + var content string + if stream { + var param any + events := bytes.Join(ConvertGeminiResponseToClaude(context.Background(), "gemini-4-carbon", nil, nil, upstream, ¶m), nil) + events = append(events, bytes.Join(ConvertGeminiResponseToClaude(context.Background(), "gemini-4-carbon", nil, nil, []byte("[DONE]"), ¶m), nil)...) + content = claudeContentFromGeminiStream(t, events).String() + } else { + response := ConvertGeminiResponseToClaudeNonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream, nil) + content = ojson.GetBytes(response, "content").Raw + } + request := ojson.NewDocString(`{"messages":[{"role":"assistant","content":` + content + `},{"role":"user","content":[{"type":"tool_result","tool_use_id":"","content":"ok"}]}]}`) + _ = request.Set("messages.1.content.0.tool_use_id", ojson.Parse(content).Get("2.id").String()) + output, errConvert := ConvertClaudeRequestToGemini("gemini-4-carbon", request.Bytes(), false) + if errConvert != nil { + t.Fatal(errConvert) + } + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 2 || parts[0].Get("text").String() != "answer" || parts[0].Get("thoughtSignature").String() != capturedGeminiThinkingSignature || parts[1].Get("thoughtSignature").String() != sigcompat.GeminiSkipThoughtSignatureValidator { + t.Fatalf("stream=%t: text signature was rebound to a later tool: %s", stream, output) + } + } +} + +func TestGeminiClaudeThoughtSignatureRoundTrip(t *testing.T) { + vertexPayload := make([]byte, 405) + copy(vertexPayload, []byte{1, 0x8f, 0x3d, 0x6b, 0x5f}) + for i := 5; i < len(vertexPayload); i++ { + vertexPayload[i] = byte(0xa0 + i%0x20) + } + for _, signature := range []string{capturedGeminiThinkingSignature, base64.StdEncoding.EncodeToString(vertexPayload)} { + t.Run(signature[:8], func(t *testing.T) { + upstream := ojson.NewDocString(`{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"lookup","args":{"q":"Paris"}}}]},"finishReason":"STOP"}]}`) + _ = upstream.Set("candidates.0.content.parts.0.thoughtSignature", signature) + response := ConvertGeminiResponseToClaudeNonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream.Bytes(), nil) + content := ojson.GetBytes(response, "content") + toolID := content.Get("1.id").String() + if toolID == "" { + t.Fatalf("missing tool_use after signature carrier: %s", response) + } + request := ojson.NewDocString(`{"messages":[{"role":"assistant","content":[]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"","content":"ok"}]}]}`) + _ = request.SetRaw("messages.0.content", content.Raw) + _ = request.Set("messages.1.content.0.tool_use_id", toolID) + for _, compat := range []bool{false, true} { + output, errConvert := convertClaudeRequestToGemini("gemini-4-carbon", request.Bytes(), false, compat) + if errConvert != nil { + t.Fatal(errConvert) + } + output = sigcompat.SanitizeGeminiRequestThoughtSignatures(output, "contents") + parts := ojson.GetBytes(output, "contents.0.parts").Array() + if len(parts) != 1 || !parts[0].Get("functionCall").Exists() { + t.Fatalf("compat=%t: carrier must be attached to functionCall, got %s", compat, output) + } + if got := parts[0].Get("thoughtSignature").String(); got != signature { + t.Fatalf("compat=%t: replayed signature = %q, want original %q", compat, got, signature) + } + } + }) + } +} diff --git a/internal/translator/gemini/claude/gemini_claude_request.go b/internal/translator/gemini/claude/gemini_claude_request.go index db1022ed940..a02fb02a4a3 100644 --- a/internal/translator/gemini/claude/gemini_claude_request.go +++ b/internal/translator/gemini/claude/gemini_claude_request.go @@ -117,24 +117,43 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, if originalRole == "user" { contentsResult = translatorcommon.AlignClaudeToolResults(contentsResult, precedingToolUseIDs) } - contentsResult.ForEach(func(_, contentResult ojson.Result) bool { + var carrierSignatures map[int]string + if originalRole == "assistant" { + carrierSignatures = geminiClaudeCarrierSignatures(contentsResult.Array()) + } + contentsResult.ForEach(func(contentIndex, contentResult ojson.Result) bool { + carrierSignature := carrierSignatures[int(contentIndex.Int())] switch contentResult.Get("type").String() { case "text": text := contentResult.Get("text").String() if text == "" { return true } - part := []byte(`{"text":""}`) - part, _ = ojson.SetBytes(part, "text", text) - partItems = append(partItems, part) + partDoc := ojson.NewDocString(`{"text":""}`) + _ = partDoc.Set("text", text) + if carrierSignature != "" { + _ = partDoc.Set("thoughtSignature", carrierSignature) + } + partItems = append(partItems, partDoc.Bytes()) case "thinking": + if contentResult.Get("thinking").String() == "" && strings.TrimSpace(contentResult.Get("signature").String()) != "" { + if carrierSignature != "" { + partDoc := ojson.NewDocString(`{"text":"","thought":true}`) + _ = partDoc.Set("thoughtSignature", carrierSignature) + partItems = append(partItems, partDoc.Bytes()) + } + return true + } if !preserveEmptyThinkingBlocks { return true } partDoc := ojson.NewDocString(`{"text":"","thought":true,"thoughtSignature":""}`) _ = partDoc.Set("text", contentResult.Get("thinking").String()) signature := sigcompat.GeminiReplaySignatureOrBypass(contentResult.Get("signature").String(), sigcompat.SignatureBlockKindGeminiModelPart) + if carrierSignature != "" { + signature = carrierSignature + } _ = partDoc.Set("thoughtSignature", signature) partItems = append(partItems, partDoc.Bytes()) @@ -149,7 +168,11 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool, argsResult := ojson.Parse(functionArgs) if argsResult.IsObject() && ojson.Valid(functionArgs) { partDoc := ojson.NewDocString(`{"thoughtSignature":"","functionCall":{"name":"","args":{}}}`) - _ = partDoc.Set("thoughtSignature", geminiClaudeThoughtSignature) + signature := geminiClaudeThoughtSignature + if carrierSignature != "" { + signature = carrierSignature + } + _ = partDoc.Set("thoughtSignature", signature) if toolUseID != "" { _ = partDoc.Set("functionCall.id", toolUseID) } diff --git a/internal/translator/gemini/claude/gemini_claude_response.go b/internal/translator/gemini/claude/gemini_claude_response.go index eecb94028ef..e967c616194 100644 --- a/internal/translator/gemini/claude/gemini_claude_response.go +++ b/internal/translator/gemini/claude/gemini_claude_response.go @@ -15,6 +15,7 @@ import ( "github.com/MoeForge/moego/ojson" translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + geminicommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/gemini/common" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" ) @@ -28,7 +29,9 @@ type Params struct { ToolNameMap map[string]string SanitizedNameMap map[string]string SawToolCall bool + HasVisibleOutput bool HasFinalEvents bool + HasMalformedError bool FinishReason string InputTokens int64 OutputTokens int64 @@ -40,12 +43,33 @@ type Params struct { ActiveToolCall *translatorcommon.VertexStreamingToolCall PendingToolThoughtSignatures []string HasIncompleteToolCall bool + LastSignatureTarget string + CurrentThinkingHasText bool } const geminiMalformedFunctionCallErrorPayload = `{"type":"error","error":{"type":"api_error","message":"Gemini response finished with MALFORMED_FUNCTION_CALL"}}` -func isGeminiMalformedFunctionCall(finishReason string, sawToolCall bool) bool { - return finishReason == "MALFORMED_FUNCTION_CALL" && !sawToolCall +func isGeminiMalformedFunctionCall(finishReason string, hasVisibleOutput bool) bool { + return strings.EqualFold(strings.TrimSpace(finishReason), "MALFORMED_FUNCTION_CALL") && !hasVisibleOutput +} + +func isGeminiNonEmptyFunctionCall(fc ojson.Result) bool { + if !fc.IsObject() { + return false + } + if strings.TrimSpace(fc.Get("name").String()) != "" || strings.TrimSpace(fc.Get("id").String()) != "" { + return true + } + if partial := fc.Get("partialArgs"); partial.IsArray() && len(partial.Array()) > 0 { + return true + } + if partial := fc.Get("partial_args"); partial.IsArray() && len(partial.Array()) > 0 { + return true + } + if args := fc.Get("args"); args.IsObject() && len(args.Map()) > 0 { + return true + } + return false } func resolveGeminiClaudeStopReason(finishReason string, sawToolCall bool) string { @@ -111,6 +135,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR } abortActiveToolCall := func() { p.HasIncompleteToolCall = true + p.LastSignatureTarget = "" if p.ActiveToolCall != nil { p.ActiveToolCall = nil p.PendingToolThoughtSignatures = nil @@ -126,7 +151,10 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR if p.ActiveToolCall != nil || p.HasIncompleteToolCall { return [][]byte{} } - if isGeminiMalformedFunctionCall(p.FinishReason, p.SawToolCall) { + if p.HasMalformedError && p.HasFinalEvents { + return [][]byte{} + } + if isGeminiMalformedFunctionCall(p.FinishReason, p.HasVisibleOutput) { if p.ResponseType != 0 { flushPendingToolInput() appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, p.ResponseIndex)) @@ -135,6 +163,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR if !p.HasFinalEvents { appendEvent("error", geminiMalformedFunctionCallErrorPayload) p.HasFinalEvents = true + p.HasMalformedError = true } if len(output) > 0 { return [][]byte{output} @@ -169,7 +198,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR return [][]byte{} } - if isGeminiMalformedFunctionCall(p.FinishReason, p.SawToolCall) && p.HasFinalEvents { + if p.HasMalformedError && p.HasFinalEvents { return [][]byte{} } @@ -202,6 +231,17 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR p.HasContent = true } + appendTrailingCarrierThinkingBlock := func(signature string) { + target := p.LastSignatureTarget + if target == geminiClaudeUnsupportedSignatureTarget { + return + } + if target != "" { + signature = translatorcommon.EncodeGeminiClaudeCarrierSignature(signature, translatorcommon.GeminiClaudeCarrierPrevious, target) + } + appendCarrierThinkingBlock(signature) + } + // Initialize the streaming session with a message_start event // This is only sent for the very first response chunk if !(*param).(*Params).HasFirstResponse { @@ -228,6 +268,20 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR partResults := partsResult.Array() for i := 0; i < len(partResults); i++ { partResult := partResults[i] + if geminicommon.HasUnsupportedPartPayload(partResult, "text", "functionCall") { + if p.ActiveToolCall != nil { + abortActiveToolCall() + } + if p.ResponseType != 0 { + flushPendingToolInput() + appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, p.ResponseIndex)) + p.ResponseIndex++ + p.ResponseType = 0 + } + p.LastSignatureTarget = geminiClaudeUnsupportedSignatureTarget + p.CurrentThinkingHasText = false + continue + } // Extract the different types of content from each part partTextResult := partResult.Get("text") @@ -244,7 +298,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR isThought := partResult.Get("thought").Bool() if hasThoughtSignature && (!partTextResult.Exists() || partTextResult.String() == "") && !functionCallResult.Exists() { - if (*param).(*Params).ResponseType == 2 { + if p.ResponseType == 2 && p.CurrentThinkingHasText { appendSignatureDelta(partSig) continue } @@ -252,13 +306,13 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR p.PendingToolThoughtSignatures = append(p.PendingToolThoughtSignatures, partSig) continue } - appendCarrierThinkingBlock(partSig) + appendTrailingCarrierThinkingBlock(partSig) continue } if isThought { if hasThoughtSignature && (!partTextResult.Exists() || partTextResult.String() == "") { - if (*param).(*Params).ResponseType == 2 { + if p.ResponseType == 2 && p.CurrentThinkingHasText { appendSignatureDelta(partSig) } else if p.ActiveToolCall != nil { p.PendingToolThoughtSignatures = append(p.PendingToolThoughtSignatures, partSig) @@ -286,12 +340,17 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR (*param).(*Params).ResponseIndex++ } + p.CurrentThinkingHasText = false appendEvent("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"thinking","thinking":""}}`, (*param).(*Params).ResponseIndex)) data, _ := ojson.SetBytes([]byte(fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"thinking_delta","thinking":""}}`, (*param).(*Params).ResponseIndex)), "delta.thinking", partText) appendEvent("content_block_delta", string(data)) (*param).(*Params).ResponseType = 2 (*param).(*Params).HasContent = true } + if partText != "" { + p.CurrentThinkingHasText = true + p.LastSignatureTarget = translatorcommon.GeminiClaudeCarrierText + } if hasThoughtSignature { appendSignatureDelta(partSig) } @@ -306,6 +365,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR if active := p.ActiveToolCall; active != nil && active.CanContinueWith(functionCallResult) { p.SawToolCall = true + p.HasVisibleOutput = true delta, fcDone := active.Assembler.PushFunctionCall(functionCallResult) if active.Assembler.Err() != nil { abortActiveToolCall() @@ -337,7 +397,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR sigs := p.PendingToolThoughtSignatures p.PendingToolThoughtSignatures = nil for _, sig := range sigs { - appendCarrierThinkingBlock(sig) + appendCarrierThinkingBlock(translatorcommon.EncodeGeminiClaudeCarrierSignature(sig, translatorcommon.GeminiClaudeCarrierPrevious, translatorcommon.GeminiClaudeCarrierFunction)) } } } @@ -370,6 +430,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR } p.SawToolCall = true + p.HasVisibleOutput = true if hasThoughtSignature { appendCarrierThinkingBlock(partSig) } @@ -391,6 +452,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR appendEvent("content_block_start", dataDoc.String()) p.ResponseType = 3 p.HasContent = true + p.LastSignatureTarget = translatorcommon.GeminiClaudeCarrierFunction if p.CurrentToolIsParameterless { if fcDone { @@ -420,6 +482,9 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR if (*param).(*Params).ResponseType == 3 && upstreamToolName == "" { if fcArgsResult := functionCallResult.Get("args"); fcArgsResult.Exists() { (*param).(*Params).SawToolCall = true + if fcArgsResult.IsObject() && len(fcArgsResult.Map()) > 0 { + (*param).(*Params).HasVisibleOutput = true + } partialJSON := util.CleanClaudeToolArgumentsWithTranslated(fcArgsResult.Raw, (*param).(*Params).CurrentToolName, originalRequestRawJSON, requestRawJSON) if (*param).(*Params).CurrentToolIsParameterless { if (*param).(*Params).CurrentToolInputEmitted { @@ -443,17 +508,18 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR } } if hasThoughtSignature { - appendCarrierThinkingBlock(partSig) + appendTrailingCarrierThinkingBlock(partSig) } continue } - if rawToolName == "" && !functionCallResult.Get("args").Exists() { + if !isGeminiNonEmptyFunctionCall(functionCallResult) { if hasThoughtSignature { - appendCarrierThinkingBlock(partSig) + appendTrailingCarrierThinkingBlock(partSig) } continue } (*param).(*Params).SawToolCall = true + (*param).(*Params).HasVisibleOutput = true if hasThoughtSignature { appendCarrierThinkingBlock(partSig) @@ -501,13 +567,14 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR } (*param).(*Params).ResponseType = 3 (*param).(*Params).HasContent = true + p.LastSignatureTarget = translatorcommon.GeminiClaudeCarrierFunction continue } if partTextResult.Exists() { partText := partTextResult.String() if hasThoughtSignature && partText == "" { - if (*param).(*Params).ResponseType == 2 { + if p.ResponseType == 2 && p.CurrentThinkingHasText { appendSignatureDelta(partSig) continue } @@ -543,6 +610,18 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR (*param).(*Params).ResponseType = 1 (*param).(*Params).HasContent = true } + if partText != "" { + p.LastSignatureTarget = translatorcommon.GeminiClaudeCarrierText + if strings.TrimSpace(partText) != "" { + p.HasVisibleOutput = true + } + } + if partText != "" { + // Preserve native part boundaries for signatures that may arrive later. + appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, p.ResponseIndex)) + p.ResponseIndex++ + p.ResponseType = 0 + } continue } @@ -581,7 +660,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR (*param).(*Params).CachedTokens = cachedTokens } - if isGeminiMalformedFunctionCall((*param).(*Params).FinishReason, (*param).(*Params).SawToolCall) && !(*param).(*Params).HasFinalEvents { + if isGeminiMalformedFunctionCall((*param).(*Params).FinishReason, (*param).(*Params).HasVisibleOutput) && !(*param).(*Params).HasFinalEvents { if (*param).(*Params).ResponseType != 0 { flushPendingToolInput() appendEvent("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, (*param).(*Params).ResponseIndex)) @@ -589,6 +668,7 @@ func ConvertGeminiResponseToClaude(_ context.Context, _ string, originalRequestR } appendEvent("error", geminiMalformedFunctionCallErrorPayload) (*param).(*Params).HasFinalEvents = true + (*param).(*Params).HasMalformedError = true return [][]byte{output} } @@ -660,6 +740,8 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina thinkingBuilder := strings.Builder{} var thinkingSignature string hasToolCall := false + hasVisibleOutput := false + lastSignatureTarget := "" var blocks [][]byte flushText := func() { @@ -697,6 +779,12 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina if parts.IsArray() { for _, part := range parts.Array() { + if geminicommon.HasUnsupportedPartPayload(part, "text", "functionCall") { + flushThinking() + flushText() + lastSignatureTarget = geminiClaudeUnsupportedSignatureTarget + continue + } thoughtSignatureResult := part.Get("thoughtSignature") if !thoughtSignatureResult.Exists() { thoughtSignatureResult = part.Get("thought_signature") @@ -710,13 +798,14 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina functionCall := part.Get("functionCall") isThought := part.Get("thought").Bool() - if isThought { + if isThought && (text.String() != "" || partSig == "") { flushText() if partSig != "" { thinkingSignature = partSig } if text.Exists() && text.String() != "" { thinkingBuilder.WriteString(text.String()) + lastSignatureTarget = translatorcommon.GeminiClaudeCarrierText } continue } @@ -729,8 +818,14 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina continue } if partSig != "" { + if lastSignatureTarget == geminiClaudeUnsupportedSignatureTarget { + continue + } flushThinking() flushText() + if lastSignatureTarget != "" { + partSig = translatorcommon.EncodeGeminiClaudeCarrierSignature(partSig, translatorcommon.GeminiClaudeCarrierPrevious, lastSignatureTarget) + } appendCarrierThinkingBlock(partSig) continue } @@ -741,11 +836,20 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina flushThinking() if functionCall.Exists() { + if !isGeminiNonEmptyFunctionCall(functionCall) { + if partSig != "" { + flushText() + appendCarrierThinkingBlock(partSig) + } + continue + } flushText() if partSig != "" { appendCarrierThinkingBlock(partSig) } hasToolCall = true + hasVisibleOutput = true + lastSignatureTarget = translatorcommon.GeminiClaudeCarrierFunction upstreamToolName := functionCall.Get("name").String() upstreamToolName = util.RestoreSanitizedToolName(sanitizedNameMap, upstreamToolName) @@ -768,6 +872,11 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina appendCarrierThinkingBlock(partSig) } textBuilder.WriteString(text.String()) + if strings.TrimSpace(text.String()) != "" { + hasVisibleOutput = true + } + lastSignatureTarget = translatorcommon.GeminiClaudeCarrierText + flushText() continue } @@ -790,7 +899,7 @@ func ConvertGeminiResponseToClaudeNonStream(_ context.Context, _ string, origina if finish := root.Get("candidates.0.finishReason"); finish.Exists() { finishReason = finish.String() } - if isGeminiMalformedFunctionCall(finishReason, hasToolCall) { + if isGeminiMalformedFunctionCall(finishReason, hasVisibleOutput) { return []byte(geminiMalformedFunctionCallErrorPayload) } _ = outDoc.Set("stop_reason", resolveGeminiClaudeStopReason(finishReason, hasToolCall)) diff --git a/internal/translator/gemini/claude/gemini_claude_response_test.go b/internal/translator/gemini/claude/gemini_claude_response_test.go index 3bf45b52620..e2516bd0f53 100644 --- a/internal/translator/gemini/claude/gemini_claude_response_test.go +++ b/internal/translator/gemini/claude/gemini_claude_response_test.go @@ -150,8 +150,8 @@ func TestConvertGeminiResponseToClaude_VertexStreamingPartialArgs(t *testing.T) if got := block0JSON.String(); got != `{"city":"Berlin"}` { t.Fatalf("block 0 JSON = %q, want %q", got, `{"city":"Berlin"}`) } - if len(deferredSigs) != 2 || deferredSigs[0] != "sig-mid-1" || deferredSigs[1] != "sig-mid-2" { - t.Fatalf("expected deferred signatures [sig-mid-1 sig-mid-2], got %v", deferredSigs) + if len(deferredSigs) != 2 || deferredSigs[0] != "cpa-gemini-carrier-v1:previous:function:c2lnLW1pZC0x" || deferredSigs[1] != "cpa-gemini-carrier-v1:previous:function:c2lnLW1pZC0y" { + t.Fatalf("expected backward-bound deferred function signatures, got %v", deferredSigs) } }) @@ -355,8 +355,8 @@ func TestConvertGeminiResponseToClaudeNonStream_PartWithThoughtSignatureWithoutT outputJSON := util.ParseGJSONBytesNoCopy(output) blocks := outputJSON.Get("content").Array() - if len(blocks) != 2 { - t.Fatalf("expected 2 content blocks (thinking + text), got %d: %s", len(blocks), string(output)) + if len(blocks) != 3 { + t.Fatalf("expected 3 content blocks (carrier + signed text + unsigned text), got %d: %s", len(blocks), string(output)) } thinkingBlock := blocks[0] @@ -371,9 +371,12 @@ func TestConvertGeminiResponseToClaudeNonStream_PartWithThoughtSignatureWithoutT } textBlock := blocks[1] - if textBlock.Get("type").String() != "text" || textBlock.Get("text").String() != "inferred reasoningfinal answer" { + if textBlock.Get("type").String() != "text" || textBlock.Get("text").String() != "inferred reasoning" { t.Fatalf("unexpected text block: %s", textBlock.Raw) } + if blocks[2].Get("type").String() != "text" || blocks[2].Get("text").String() != "final answer" { + t.Fatalf("unsigned text must remain a separate block: %s", blocks[2].Raw) + } } func TestConvertGeminiResponseToClaudeNonStream_TrailingSignatureOnlyPart(t *testing.T) { @@ -1093,7 +1096,7 @@ func TestConvertGeminiResponseToClaudeStream_Issue6409_SplitTrailingSignature(t if !strings.Contains(outputText, `{"type":"content_block_start","index":1,"content_block":{"type":"thinking","thinking":""}}`) { t.Fatalf("expected block 1 trailing carrier thinking, got: %s", outputText) } - if !strings.Contains(outputText, `{"type":"content_block_delta","index":1,"delta":{"type":"signature_delta","signature":"sig-stream-trailing"}}`) { + if !strings.Contains(outputText, `{"type":"content_block_delta","index":1,"delta":{"type":"signature_delta","signature":"cpa-gemini-carrier-v1:previous:text:c2lnLXN0cmVhbS10cmFpbGluZw"}}`) { t.Fatalf("expected block 1 signature_delta, got: %s", outputText) } if !strings.Contains(outputText, `{"type":"content_block_stop","index":1}`) { @@ -1182,8 +1185,8 @@ func TestConvertGeminiResponseToClaudeStream_Issue6409_FunctionCallContinuationS if !strings.Contains(outputText, `"type":"input_json_delta"`) { t.Fatalf("expected input_json_delta, got: %s", outputText) } - if !strings.Contains(outputText, `"signature":"sig-fc-cont-done"`) { - t.Fatalf("expected signature_delta with 'sig-fc-cont-done', got: %s", outputText) + if !strings.Contains(outputText, `"signature":"cpa-gemini-carrier-v1:previous:function:c2lnLWZjLWNvbnQtZG9uZQ"`) { + t.Fatalf("expected backward-bound signature_delta for the continued call, got: %s", outputText) } } @@ -1429,3 +1432,86 @@ func TestConvertGeminiResponseToClaude_ImplicitOpenToolContinuationOrdering(t *t }) } } + +func TestConvertGeminiResponseToClaude_PartialVisibleTextWithMalformedFunctionCallPreservesText(t *testing.T) { + requestJSON := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + rawNonStream := []byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": [{"text": "partial answer"}]}, + "index": 0, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": {"promptTokenCount": 50, "candidatesTokenCount": 3, "totalTokenCount": 53}, + "modelVersion": "m", + "responseId": "resp-partial" + }`) + + ctx := context.Background() + nonStream := ConvertGeminiResponseToClaudeNonStream(ctx, "claude-opus-5-5", requestJSON, requestJSON, rawNonStream, nil) + nonStreamJSON := util.ParseGJSONBytesNoCopy(nonStream) + if got := nonStreamJSON.Get("type").String(); got != "message" { + t.Fatalf("non-stream type = %q, want message; output: %s", got, nonStream) + } + if got := nonStreamJSON.Get("content.0.text").String(); got != "partial answer" { + t.Fatalf("non-stream text = %q, want partial answer; output: %s", got, nonStream) + } + if got := nonStreamJSON.Get("stop_reason").String(); got != "end_turn" { + t.Fatalf("non-stream stop_reason = %q, want end_turn; output: %s", got, nonStream) + } + + chunk1 := []byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": [{"text": "partial answer"}]}, + "index": 0 + }], + "modelVersion": "m", + "responseId": "resp-partial" + }`) + chunk2 := []byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": []}, + "index": 0, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": {"promptTokenCount": 50, "candidatesTokenCount": 3, "totalTokenCount": 53}, + "modelVersion": "m", + "responseId": "resp-partial" + }`) + var param any + streamOut := bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, chunk1, ¶m), nil) + streamOut = append(streamOut, bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, chunk2, ¶m), nil)...) + streamOut = append(streamOut, bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + streamText := string(streamOut) + if strings.Contains(streamText, "event: error\n") { + t.Fatalf("unexpected error event when partial text was already emitted:\n%s", streamText) + } + if !strings.Contains(streamText, "partial answer") || !strings.Contains(streamText, `"type":"message_stop"`) { + t.Fatalf("expected partial text and message_stop in stream output:\n%s", streamText) + } +} + +func TestConvertGeminiResponseToClaude_EmptyFunctionCallPlaceholderReturnsError(t *testing.T) { + requestJSON := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + rawJSON := []byte(`{ + "candidates": [{ + "content": {"role": "model", "parts": [{"functionCall": {}}]}, + "index": 0, + "finishReason": "MALFORMED_FUNCTION_CALL" + }], + "usageMetadata": {"promptTokenCount": 50, "candidatesTokenCount": 1, "totalTokenCount": 51}, + "modelVersion": "m", + "responseId": "resp-empty-fc" + }`) + + ctx := context.Background() + nonStream := ConvertGeminiResponseToClaudeNonStream(ctx, "claude-opus-5-5", requestJSON, requestJSON, rawJSON, nil) + if got := util.ParseGJSONBytesNoCopy(nonStream).Get("type").String(); got != "error" { + t.Fatalf("non-stream type = %q, want error for empty functionCall placeholder; output: %s", got, nonStream) + } + var param any + streamOut := bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, rawJSON, ¶m), nil) + streamOut = append(streamOut, bytes.Join(ConvertGeminiResponseToClaude(ctx, "claude-opus-5-5", requestJSON, requestJSON, []byte("[DONE]"), ¶m), nil)...) + if !strings.Contains(string(streamOut), "event: error\n") { + t.Fatalf("expected error event for empty functionCall placeholder:\n%s", streamOut) + } +} diff --git a/internal/translator/gemini/claude/signature_carrier.go b/internal/translator/gemini/claude/signature_carrier.go new file mode 100644 index 00000000000..8eedd0e5682 --- /dev/null +++ b/internal/translator/gemini/claude/signature_carrier.go @@ -0,0 +1,106 @@ +package claude + +import ( + "github.com/MoeForge/moego/ojson" + sigcompat "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" +) + +const geminiClaudeUnsupportedSignatureTarget = "unsupported" + +// geminiClaudeCarrierSignatures binds assistant signature carriers to native +// parts without allowing a signature to cross another semantic block or message. +func geminiClaudeCarrierSignatures(blocks []ojson.Result) map[int]string { + kinds := make([]string, len(blocks)) + transparent := make([]bool, len(blocks)) + previous := make([]int, len(blocks)) + next := make([]int, len(blocks)) + for i, block := range blocks { + switch block.Get("type").String() { + case "text": + if block.Get("text").String() != "" { + kinds[i] = translatorcommon.GeminiClaudeCarrierText + } else { + transparent[i] = true + } + case "tool_use": + if block.Get("input").IsObject() { + kinds[i] = translatorcommon.GeminiClaudeCarrierFunction + } + case "thinking": + // Omitted reasoning still forms a semantic boundary for its signature. + if block.Get("thinking").String() != "" { + kinds[i] = translatorcommon.GeminiClaudeCarrierText + } else { + transparent[i] = true + } + } + } + adjacent := -1 + for i := range blocks { + previous[i] = adjacent + if kinds[i] != "" { + adjacent = i + } else if !transparent[i] { + adjacent = -1 + } + } + adjacent = -1 + for i := len(blocks) - 1; i >= 0; i-- { + next[i] = adjacent + if kinds[i] != "" { + adjacent = i + } else if !transparent[i] { + adjacent = -1 + } + } + + var signatures map[int]string + sources := make(map[int]int) + for i, block := range blocks { + if block.Get("type").String() != "thinking" || block.Get("thinking").String() != "" { + continue + } + raw, direction, targetKind, marked, ok := translatorcommon.DecodeGeminiClaudeCarrierSignature(block.Get("signature").String()) + if !ok || raw == "" { + continue + } + target := next[i] + if marked { + switch direction { + case translatorcommon.GeminiClaudeCarrierPrevious: + target = previous[i] + case translatorcommon.GeminiClaudeCarrierStandalone: + target = i + } + if target < 0 || (target != i && targetKind != translatorcommon.GeminiClaudeCarrierAny && targetKind != kinds[target]) { + continue + } + } else { + if target < 0 { + target = previous[i] + } + if target < 0 { + target = i + } + } + blockKind := sigcompat.SignatureBlockKindGeminiModelPart + if kinds[target] == translatorcommon.GeminiClaudeCarrierFunction { + blockKind = sigcompat.SignatureBlockKindGeminiFunctionCall + } + signature, compatible := sigcompat.CompatibleSignatureForProviderBlock(sigcompat.SignatureProviderGemini, raw, blockKind) + if !compatible || sigcompat.IsGeminiThoughtSignatureBypass(signature) { + continue + } + if signatures == nil { + signatures = make(map[int]string) + } + if oldSource, exists := sources[target]; exists && signatures[target] != signature { + // Keep an earlier detached signature rather than silently replacing it. + signatures[oldSource] = signatures[target] + } + signatures[target] = signature + sources[target] = i + } + return signatures +} diff --git a/internal/translator/gemini/common/parts.go b/internal/translator/gemini/common/parts.go new file mode 100644 index 00000000000..66f93f39547 --- /dev/null +++ b/internal/translator/gemini/common/parts.go @@ -0,0 +1,31 @@ +package common + +import "github.com/MoeForge/moego/ojson" + +// HasUnsupportedPartPayload keeps omitted payloads from being mistaken for +// detached signatures belonging to a neighboring supported part. +func HasUnsupportedPartPayload(part ojson.Result, supportedFields ...string) bool { + unsupported := false + part.ForEach(func(key, _ ojson.Result) bool { + name := key.String() + switch name { + case "text", "functionCall", "function_call", "functionResponse", "function_response", + "inlineData", "inline_data", "fileData", "file_data", + "executableCode", "executable_code", "codeExecutionResult", "code_execution_result", + "toolCall", "tool_call", "toolResponse", "tool_response", + "audioTranscription", "audio_transcription": + // Only semantic payload fields can create an unsupported boundary. + default: + // Metadata such as partMetadata must not hide supported content. + return true + } + for _, field := range supportedFields { + if name == field { + return true + } + } + unsupported = true + return false + }) + return unsupported +} diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_carrier_test.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_carrier_test.go new file mode 100644 index 00000000000..34fcf9b95e4 --- /dev/null +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_carrier_test.go @@ -0,0 +1,251 @@ +package chat_completions + +import ( + "context" + "strconv" + "testing" + + "github.com/MoeForge/moego/ojson" +) + +func TestGeminiOpenAIPartMetadataPreservesSupportedPayload(t *testing.T) { + for _, tt := range []struct { + name string + part string + tool bool + }{ + {"text", `{"text":"answer","partMetadata":{"source":"model"}}`, false}, + {"tool", `{"functionCall":{"name":"lookup","args":{}},"partMetadata":{"source":"model"}}`, true}, + } { + for _, stream := range []bool{false, true} { + for _, signed := range []bool{false, true} { + t.Run(tt.name+"/stream="+strconv.FormatBool(stream)+"/signed="+strconv.FormatBool(signed), func(t *testing.T) { + part := ojson.NewDocString(tt.part) + if signed { + _ = part.Set("thoughtSignature", capturedGeminiToolCallThoughtSignature) + } + upstream := []byte(`{"candidates":[{"content":{"parts":[` + part.String() + `]},"finishReason":"STOP"}]}`) + var message ojson.Result + if stream { + var param any + chunks := ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, upstream, ¶m) + if len(chunks) != 1 { + t.Fatalf("supported metadata part produced %d chunks", len(chunks)) + } + message = ojson.GetBytes(chunks[0], "choices.0.delta") + } else { + response := ConvertGeminiResponseToOpenAINonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream, nil) + message = ojson.GetBytes(response, "choices.0.message") + } + if tt.tool { + call := message.Get("tool_calls.0") + if call.Get("function.name").String() != "lookup" || call.Get("function.arguments").String() != `{}` { + t.Errorf("metadata dropped tool payload: %s", message.Raw) + } + if signed && call.Get("extra_content.google.thought_signature").String() != capturedGeminiToolCallThoughtSignature { + t.Errorf("metadata dropped tool signature: %s", message.Raw) + } + } else if message.Get("content").String() != "answer" { + t.Errorf("metadata dropped text payload: %s", message.Raw) + } + }) + } + } + } +} + +func TestGeminiOpenAIUnsupportedPayloadDoesNotRetargetSignature(t *testing.T) { + for _, tt := range []struct { + name string + parts string + }{ + {"file data", `{"fileData":{"mimeType":"image/png","fileUri":"gs://bucket/image"},"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}`}, + {"code", `{"executableCode":{"language":"PYTHON","code":"1"},"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}`}, + {"delayed file signature", `{"fileData":{"mimeType":"image/png","fileUri":"gs://bucket/image"}},{"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}`}, + {"delayed code signature", `{"codeExecutionResult":{"outcome":"OUTCOME_OK","output":"1"}},{"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}`}, + } { + for _, stream := range []bool{false, true} { + name := tt.name + "/nonstream" + if stream { + name = tt.name + "/stream" + } + t.Run(name, func(t *testing.T) { + upstream := []byte(`{"candidates":[{"content":{"parts":[{"functionCall":{"name":"lookup","args":{}}},` + tt.parts + `]},"finishReason":"STOP"}]}`) + var calls []ojson.Result + if stream { + var param any + for _, chunk := range ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, upstream, ¶m) { + calls = append(calls, ojson.GetBytes(chunk, "choices.0.delta.tool_calls").Array()...) + } + } else { + response := ConvertGeminiResponseToOpenAINonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream, nil) + calls = ojson.GetBytes(response, "choices.0.message.tool_calls").Array() + } + if len(calls) == 0 { + t.Fatal("unrelated tool call was removed") + } + for _, call := range calls { + if call.Get("extra_content.google.thought_signature").Exists() { + t.Errorf("unsupported payload signature was attached to preceding tool: %s", call.Raw) + } + } + }) + } + } +} + +func TestGeminiOpenAIStreamingLateToolSignature(t *testing.T) { + for _, tt := range []struct { + name string + part string + }{ + {"signature only", `{"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}`}, + {"empty text signature", `{"text":"","thought_signature":"` + capturedGeminiToolCallThoughtSignature + `"}`}, + {"empty function signature", `{"functionCall":{},"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}`}, + {"metadata only continuation", `{"functionCall":{"willContinue":true},"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}`}, + } { + t.Run(tt.name, func(t *testing.T) { + var param any + first := []byte(`{"candidates":[{"index":2,"content":{"parts":[{"functionCall":{"name":"lookup","partialArgs":[{"jsonPath":"$.q","stringValue":"Paris"}],"willContinue":true}}]}}]}`) + initial := ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, first, ¶m) + if len(initial) != 1 || ojson.GetBytes(initial[0], "choices.0.delta.tool_calls.0.index").Int() != 0 { + t.Fatalf("missing initial tool call: %s", initial) + } + late := []byte(`{"candidates":[{"index":2,"content":{"parts":[` + tt.part + `]}}]}`) + chunks := ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, late, ¶m) + if len(chunks) != 1 { + t.Fatalf("late signature must produce one delta, got %d", len(chunks)) + } + call := ojson.GetBytes(chunks[0], "choices.0.delta.tool_calls.0") + if ojson.GetBytes(chunks[0], "choices.0.index").Int() != 2 || !call.Get("index").Exists() || call.Get("index").Int() != 0 || call.Get("extra_content.google.thought_signature").String() != capturedGeminiToolCallThoughtSignature { + t.Fatalf("late signature lost tool/candidate association: %s", chunks[0]) + } + last := []byte(`{"candidates":[{"index":2,"content":{"parts":[{"functionCall":{}}]},"finishReason":"STOP"}]}`) + ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, last, ¶m) + done := ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, []byte("[DONE]"), ¶m) + if len(done) != 1 || ojson.GetBytes(done[0], "choices.0.finish_reason").String() != "tool_calls" { + t.Fatalf("late signature interrupted tool call completion: %s", done) + } + }) + } +} + +func TestGeminiOpenAIVertexInitialToolSignature(t *testing.T) { + upstream := []byte(`{"candidates":[{"index":1,"content":{"parts":[{"functionCall":{"name":"lookup","partialArgs":[{"jsonPath":"$.q","stringValue":"Paris"}],"willContinue":false},"thought_signature":"` + capturedGeminiToolCallThoughtSignature + `"}]}}]}`) + var param any + chunks := ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, upstream, ¶m) + if len(chunks) != 1 { + t.Fatalf("expected initial tool delta, got %s", chunks) + } + call := ojson.GetBytes(chunks[0], "choices.0.delta.tool_calls.0") + if call.Get("extra_content.google.thought_signature").String() != capturedGeminiToolCallThoughtSignature || call.Get("function.arguments").String() != `{"q":"Paris"}` { + t.Fatalf("signed Vertex call was not emitted intact: %s", chunks[0]) + } +} + +func TestGeminiOpenAILateSignatureDoesNotCrossText(t *testing.T) { + var param any + chunks := []string{ + `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"lookup","args":{}}}]}}]}`, + `{"candidates":[{"content":{"parts":[{"text":"answer"}]}}]}`, + `{"candidates":[{"content":{"parts":[{"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}]}}]}`, + } + for _, raw := range chunks { + for _, output := range ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, []byte(raw), ¶m) { + if ojson.GetBytes(output, "choices.0.delta.tool_calls.0.extra_content").Exists() { + t.Fatalf("text signature was attached to an earlier tool: %s", output) + } + } + } +} + +func TestGeminiOpenAINonStreamTrailingToolSignatureRoundTrip(t *testing.T) { + for _, tt := range []struct { + name string + between string + want string + }{ + {"adjacent", "", capturedGeminiToolCallThoughtSignature}, + {"empty text", `{"text":""},`, capturedGeminiToolCallThoughtSignature}, + {"text boundary", `{"text":"answer"},`, ""}, + {"image boundary", `{"inlineData":{"mimeType":"image/png","data":"eA=="}},`, ""}, + } { + t.Run(tt.name, func(t *testing.T) { + upstream := []byte(`{"candidates":[{"content":{"parts":[{"functionCall":{"name":"lookup","args":{}}},` + tt.between + `{"thoughtSignature":"` + capturedGeminiToolCallThoughtSignature + `"}]},"finishReason":"STOP"}]}`) + response := ConvertGeminiResponseToOpenAINonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream, nil) + call := ojson.GetBytes(response, "choices.0.message.tool_calls.0") + if got := call.Get("extra_content.google.thought_signature").String(); got != tt.want { + t.Fatalf("tail signature = %q, want %q; response=%s", got, tt.want, response) + } + request := ojson.NewDocString(`{"messages":[{"role":"assistant","tool_calls":[]},{"role":"tool","tool_call_id":"","content":"ok"}]}`) + _ = request.SetRaw("messages.0.tool_calls.0", call.Raw) + _ = request.Set("messages.1.tool_call_id", call.Get("id").String()) + output, errConvert := ConvertOpenAIRequestToGemini("gemini-4-carbon", request.Bytes(), false) + if errConvert != nil { + t.Fatal(errConvert) + } + want := tt.want + if want == "" { + want = "skip_thought_signature_validator" + } + if got := ojson.GetBytes(output, "contents.0.parts.0.thoughtSignature").String(); got != want { + t.Fatalf("replayed tail signature = %q, want %q; output=%s", got, want, output) + } + }) + } +} + +func TestGeminiOpenAIToolSignatureDoesNotExposeBypass(t *testing.T) { + for _, signature := range []string{"", "skip_thought_signature_validator", "gemini#skip_thought_signature_validator"} { + upstream := ojson.NewDocString(`{"candidates":[{"content":{"parts":[{"functionCall":{"name":"lookup","args":{}}}]}}]}`) + _ = upstream.Set("candidates.0.content.parts.0.thoughtSignature", signature) + response := ConvertGeminiResponseToOpenAINonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream.Bytes(), nil) + if ojson.GetBytes(response, "choices.0.message.tool_calls.0.extra_content").Exists() { + t.Fatalf("bypass must not be exposed as a real signature: %s", response) + } + var param any + for _, chunk := range ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, upstream.Bytes(), ¶m) { + if ojson.GetBytes(chunk, "choices.0.delta.tool_calls.0.extra_content").Exists() { + t.Fatalf("stream exposed bypass signature: %s", chunk) + } + } + } +} + +func TestGeminiOpenAIToolThoughtSignatureRoundTrip(t *testing.T) { + for _, stream := range []bool{false, true} { + name := "nonstream" + if stream { + name = "stream" + } + t.Run(name, func(t *testing.T) { + upstream := ojson.NewDocString(`{"candidates":[{"index":0,"content":{"role":"model","parts":[{"functionCall":{"name":"lookup","args":{"q":"Paris"}}}]},"finishReason":"STOP"}]}`) + _ = upstream.Set("candidates.0.content.parts.0.thoughtSignature", capturedGeminiToolCallThoughtSignature) + var toolCall ojson.Result + if stream { + var param any + chunks := ConvertGeminiResponseToOpenAI(context.Background(), "gemini-4-carbon", nil, nil, upstream.Bytes(), ¶m) + if len(chunks) != 1 { + t.Fatalf("expected one response chunk, got %d", len(chunks)) + } + toolCall = ojson.GetBytes(chunks[0], "choices.0.delta.tool_calls.0") + } else { + response := ConvertGeminiResponseToOpenAINonStream(context.Background(), "gemini-4-carbon", nil, nil, upstream.Bytes(), nil) + toolCall = ojson.GetBytes(response, "choices.0.message.tool_calls.0") + } + if got := toolCall.Get("extra_content.google.thought_signature").String(); got != capturedGeminiToolCallThoughtSignature { + t.Fatalf("tool call signature = %q, want %q; call=%s", got, capturedGeminiToolCallThoughtSignature, toolCall.Raw) + } + request := ojson.NewDocString(`{"messages":[{"role":"assistant","tool_calls":[]},{"role":"tool","tool_call_id":"","content":"ok"}]}`) + _ = request.SetRaw("messages.0.tool_calls.0", toolCall.Raw) + _ = request.Set("messages.1.tool_call_id", toolCall.Get("id").String()) + output, errConvert := ConvertOpenAIRequestToGemini("gemini-4-carbon", request.Bytes(), false) + if errConvert != nil { + t.Fatal(errConvert) + } + if got := ojson.GetBytes(output, "contents.0.parts.0.thoughtSignature").String(); got != capturedGeminiToolCallThoughtSignature { + t.Fatalf("replayed signature = %q, want original signature; output=%s", got, output) + } + }) + } +} diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_response.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_response.go index 24063d6bdb6..f90aaa707db 100644 --- a/internal/translator/gemini/openai/chat-completions/gemini_openai_response.go +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_response.go @@ -15,7 +15,9 @@ import ( "time" "github.com/MoeForge/moego/ojson" + sigcompat "github.com/router-for-me/CLIProxyAPI/v8/internal/signature" translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + geminicommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/gemini/common" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" log "github.com/sirupsen/logrus" ) @@ -35,11 +37,20 @@ type convertGeminiResponseToOpenAIChatParams struct { SanitizedNameMapResolved bool ActiveToolCall map[int]*translatorcommon.VertexStreamingToolCall HasIncompleteToolCall map[int]bool + LastToolCallIndex map[int]int } // functionCallIDCounter provides a process-wide unique counter for function call identifiers. var functionCallIDCounter uint64 +func geminiOpenAIToolThoughtSignature(raw string) string { + signature := strings.TrimSpace(raw) + if sigcompat.IsGeminiThoughtSignatureBypass(sigcompat.SignaturePayloadWithoutProviderPrefix(signature)) { + return "" + } + return signature +} + // ConvertGeminiResponseToOpenAI translates a single chunk of a streaming response from the // Gemini API format to the OpenAI Chat Completions streaming format. // It processes various Gemini event types and transforms them into OpenAI-compatible JSON responses. @@ -88,6 +99,9 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR if p.HasIncompleteToolCall == nil { p.HasIncompleteToolCall = make(map[int]bool) } + if p.LastToolCallIndex == nil { + p.LastToolCallIndex = make(map[int]int) + } if !p.SanitizedNameMapResolved { if p.SanitizedNameMap == nil { p.SanitizedNameMap = util.SanitizedToolNameMap(originalRequestRawJSON) @@ -213,6 +227,19 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR } } + appendToolSignature := func(signature string) { + index, exists := p.LastToolCallIndex[candidateIndex] + if signature == "" || !exists { + return + } + ensureToolCallsArray() + fcDoc := ojson.NewDocString(`{"index":0}`) + _ = fcDoc.Set("index", index) + _ = fcDoc.Set("extra_content.google.thought_signature", signature) + setAssistantRole() + _ = templateDoc.SetRawBytes("choices.0.delta.tool_calls.-1", fcDoc.Bytes()) + } + if partsResult.IsArray() { partResults := partsResult.Array() var textContent strings.Builder @@ -221,6 +248,15 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR hasReasoningContent := false for i := 0; i < len(partResults); i++ { partResult := partResults[i] + if geminicommon.HasUnsupportedPartPayload(partResult, "text", "functionCall", "inlineData", "inline_data", "audioTranscription") { + delete(p.LastToolCallIndex, candidateIndex) + if p.ActiveToolCall[candidateIndex] != nil { + p.HasIncompleteToolCall[candidateIndex] = true + p.ActiveToolCall[candidateIndex] = nil + } + sawNoopFunctionCall = true + continue + } partTextResult := partResult.Get("text") functionCallResult := partResult.Get("functionCall") inlineDataResult := partResult.Get("inlineData") @@ -243,8 +279,10 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR hasTextPayload := partTextResult.Exists() && partTextResult.String() != "" hasContentPayload := hasTextPayload || functionCallResult.Exists() || inlineDataResult.Exists() - // Skip pure thoughtSignature parts but keep any actual payload in the same part. + thoughtSignature := geminiOpenAIToolThoughtSignature(thoughtSignatureResult.String()) + // A late signature is still a tool delta even without argument bytes. if hasThoughtSignature && !hasContentPayload { + appendToolSignature(thoughtSignature) if p.ActiveToolCall[candidateIndex] != nil { sawNoopFunctionCall = true } @@ -253,6 +291,9 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR if partTextResult.Exists() { text := partTextResult.String() + if text != "" { + delete(p.LastToolCallIndex, candidateIndex) + } if p.ActiveToolCall[candidateIndex] != nil { if text == "" { sawNoopFunctionCall = true @@ -284,11 +325,16 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR if done { p.ActiveToolCall[candidateIndex] = nil } - if delta != "" { + if delta != "" || thoughtSignature != "" { ensureToolCallsArray() - fcDoc := ojson.NewDocString(`{"index":0,"function":{"arguments":""}}`) + fcDoc := ojson.NewDocString(`{"index":0}`) _ = fcDoc.Set("index", active.Index) - _ = translatorcommon.SetStringWithoutHTMLEscapeDoc(fcDoc, "function.arguments", delta) + if delta != "" { + _ = translatorcommon.SetStringWithoutHTMLEscapeDoc(fcDoc, "function.arguments", delta) + } + if thoughtSignature != "" { + _ = fcDoc.Set("extra_content.google.thought_signature", thoughtSignature) + } setAssistantRole() _ = templateDoc.SetRawBytes("choices.0.delta.tool_calls.-1", fcDoc.Bytes()) } else { @@ -321,6 +367,7 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR } p.SawToolCall[candidateIndex] = true p.FunctionIndex[candidateIndex]++ + p.LastToolCallIndex[candidateIndex] = functionCallIndex if !done { p.ActiveToolCall[candidateIndex] = active } @@ -332,6 +379,9 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR _ = fcDoc.Set("index", functionCallIndex) _ = fcDoc.Set("function.name", fcName) _ = translatorcommon.SetStringWithoutHTMLEscapeDoc(fcDoc, "function.arguments", delta) + if thoughtSignature != "" { + _ = fcDoc.Set("extra_content.google.thought_signature", thoughtSignature) + } setAssistantRole() _ = templateDoc.SetRawBytes("choices.0.delta.tool_calls.-1", fcDoc.Bytes()) } else { @@ -341,6 +391,7 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR } rawName := strings.TrimSpace(functionCallResult.Get("name").String()) if rawName == "" && !functionCallResult.Get("args").Exists() { + appendToolSignature(thoughtSignature) sawNoopFunctionCall = true continue } @@ -349,6 +400,7 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR // Retrieve the function index for this specific candidate. functionCallIndex := p.FunctionIndex[candidateIndex] p.FunctionIndex[candidateIndex]++ + p.LastToolCallIndex[candidateIndex] = functionCallIndex ensureToolCallsArray() @@ -364,10 +416,14 @@ func ConvertGeminiResponseToOpenAI(_ context.Context, _ string, originalRequestR if fcArgsResult := functionCallResult.Get("args"); fcArgsResult.Exists() { _ = fcDoc.Set("function.arguments", fcArgsResult.Raw) } + if thoughtSignature != "" { + _ = fcDoc.Set("extra_content.google.thought_signature", thoughtSignature) + } setAssistantRole() _ = templateDoc.SetRawBytes("choices.0.delta.tool_calls.-1", fcDoc.Bytes()) } } else if inlineDataResult.Exists() { + delete(p.LastToolCallIndex, candidateIndex) if p.ActiveToolCall[candidateIndex] != nil { p.HasIncompleteToolCall[candidateIndex] = true p.ActiveToolCall[candidateIndex] = nil @@ -513,7 +569,9 @@ func ConvertGeminiResponseToOpenAINonStream(_ context.Context, _ string, origina // Set finish reason. if finishReasonResult := candidate.Get("finishReason"); finishReasonResult.Exists() { finishReason := strings.ToLower(finishReasonResult.String()) - if isGeminiContentFilterFinishReason(finishReasonResult.String()) { + if strings.EqualFold(strings.TrimSpace(finishReasonResult.String()), "MAX_TOKENS") { + finishReason = "length" + } else if isGeminiContentFilterFinishReason(finishReasonResult.String()) { finishReason = "content_filter" } _ = choiceDoc.Set("finish_reason", finishReason) @@ -524,7 +582,8 @@ func ConvertGeminiResponseToOpenAINonStream(_ context.Context, _ string, origina hasFunctionCall := false if partsResult.IsArray() { partsResults := partsResult.Array() - var toolCalls [][]byte + var toolCallDocs []*ojson.Doc + var lastToolCall *ojson.Doc var images [][]byte var textContent strings.Builder var reasoningContent strings.Builder @@ -533,6 +592,10 @@ func ConvertGeminiResponseToOpenAINonStream(_ context.Context, _ string, origina for i := 0; i < len(partsResults); i++ { partResult := partsResults[i] + if geminicommon.HasUnsupportedPartPayload(partResult, "text", "functionCall", "inlineData", "inline_data", "audioTranscription") { + lastToolCall = nil + continue + } partTextResult := partResult.Get("text") functionCallResult := partResult.Get("functionCall") inlineDataResult := partResult.Get("inlineData") @@ -555,12 +618,18 @@ func ConvertGeminiResponseToOpenAINonStream(_ context.Context, _ string, origina hasTextPayload := partTextResult.Exists() && partTextResult.String() != "" hasContentPayload := hasTextPayload || functionCallResult.Exists() || inlineDataResult.Exists() - // Skip pure thoughtSignature parts but keep any actual payload in the same part. + // Keep a detached signature on its preceding tool, not across text or images. if hasThoughtSignature && !hasContentPayload { + if signature := geminiOpenAIToolThoughtSignature(thoughtSignatureResult.String()); signature != "" && lastToolCall != nil { + _ = lastToolCall.Set("extra_content.google.thought_signature", signature) + } continue } if partTextResult.Exists() { + if partTextResult.String() != "" { + lastToolCall = nil + } // Append text content, distinguishing between regular content and reasoning. if partResult.Get("thought").Bool() { hasReasoningContent = true @@ -583,8 +652,13 @@ func ConvertGeminiResponseToOpenAINonStream(_ context.Context, _ string, origina if fcArgsResult := functionCallResult.Get("args"); fcArgsResult.Exists() { _ = fcItemDoc.Set("function.arguments", fcArgsResult.Raw) } - toolCalls = append(toolCalls, fcItemDoc.Bytes()) + if signature := geminiOpenAIToolThoughtSignature(thoughtSignatureResult.String()); signature != "" { + _ = fcItemDoc.Set("extra_content.google.thought_signature", signature) + } + toolCallDocs = append(toolCallDocs, fcItemDoc) + lastToolCall = fcItemDoc } else if inlineDataResult.Exists() { + lastToolCall = nil data := inlineDataResult.Get("data").String() if data != "" { mimeType := inlineDataResult.Get("mimeType").String() @@ -609,7 +683,11 @@ func ConvertGeminiResponseToOpenAINonStream(_ context.Context, _ string, origina if hasReasoningContent { _ = choiceDoc.Set("message.reasoning_content", reasoningContent.String()) } - if len(toolCalls) > 0 { + if len(toolCallDocs) > 0 { + toolCalls := make([][]byte, len(toolCallDocs)) + for i, toolCallDoc := range toolCallDocs { + toolCalls[i] = toolCallDoc.Bytes() + } _ = choiceDoc.SetRawBytes("message.tool_calls", translatorcommon.JoinRawArray(toolCalls)) } if len(images) > 0 { @@ -639,7 +717,7 @@ func resolveGeminiOpenAIFinishReason(upstreamFinishReason string, sawToolCall bo case sawToolCall: finishReason = "tool_calls" case upstreamFinishReason == "MAX_TOKENS": - finishReason = "max_tokens" + finishReason = "length" case isGeminiContentFilterFinishReason(upstreamFinishReason): finishReason = "content_filter" default: diff --git a/internal/translator/gemini/openai/chat-completions/gemini_openai_response_test.go b/internal/translator/gemini/openai/chat-completions/gemini_openai_response_test.go index 211f72df397..da0a6239ba4 100644 --- a/internal/translator/gemini/openai/chat-completions/gemini_openai_response_test.go +++ b/internal/translator/gemini/openai/chat-completions/gemini_openai_response_test.go @@ -198,6 +198,12 @@ func TestConvertGeminiResponseToOpenAI_NonStopFinishReasonsMapToContentFilter(t wantFinishReason: "content_filter", wantNativeReason: "prohibited_content", }, + { + name: "MAX_TOKENS", + upstreamReason: "MAX_TOKENS", + wantFinishReason: "length", + wantNativeReason: "max_tokens", + }, } for _, tc := range cases { diff --git a/internal/translator/openai/claude/openai_claude_compat_test.go b/internal/translator/openai/claude/openai_claude_compat_test.go index ed908049f9e..1f3675cfea9 100644 --- a/internal/translator/openai/claude/openai_claude_compat_test.go +++ b/internal/translator/openai/claude/openai_claude_compat_test.go @@ -39,13 +39,97 @@ func TestConvertClaudeRequestToOpenAIWithCompatDoesNotAddReasoningWithoutThinkin result, _ := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) assistant := ojson.GetBytesNoCopy(result, "messages.0") if assistant.Get("reasoning_content").Exists() { - t.Fatalf("compatible translation added reasoning_content without thinking: %s", result) + t.Fatalf("compatible translation added reasoning_content without request thinking: %s", result) } if !assistant.Get("tool_calls").Exists() { t.Fatalf("tool_calls missing from compatible translation: %s", result) } } +func TestConvertClaudeRequestToOpenAIWithCompatDoesNotAddReasoningWhenThinkingDisabled(t *testing.T) { + for _, tc := range []struct { + name string + payload string + }{ + { + name: "thinking type disabled", + payload: `{"thinking":{"type":"disabled"},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + { + name: "thinking budget zero", + payload: `{"thinking":{"type":"enabled","budget_tokens":0},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + { + name: "output_config effort none", + payload: `{"output_config":{"effort":"none"},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + { + name: "model suffix none overrides enabled body", + payload: `{"model":"deepseek-v4(none)","thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + result, _ := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", []byte(tc.payload), false) + assistant := ojson.GetBytesNoCopy(result, "messages.0") + if assistant.Get("reasoning_content").Exists() { + t.Fatalf("compatible translation added reasoning_content when thinking disabled: %s", result) + } + if !assistant.Get("tool_calls").Exists() { + t.Fatalf("tool_calls missing from compatible translation: %s", result) + } + }) + } +} + +func TestConvertClaudeRequestToOpenAIWithCompatDoesNotAddReasoningWithoutThinkingForTextOnly(t *testing.T) { + payload := []byte(`{"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"assistant","content":[{"type":"text","text":"Plain answer without thinking."}]}]}`) + + result, _ := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", payload, false) + assistant := ojson.GetBytesNoCopy(result, "messages.0") + if assistant.Get("reasoning_content").Exists() { + t.Fatalf("compatible translation added reasoning_content to text-only assistant turn: %s", result) + } +} + +func TestConvertClaudeRequestToOpenAIWithCompatAddsPlaceholderReasoningForToolCallsWithoutThinking(t *testing.T) { + for _, tc := range []struct { + name string + payload string + }{ + { + name: "enabled thinking with absent thinking block", + payload: `{"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + { + name: "enabled thinking with whitespace-only thinking block", + payload: `{"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":" ","signature":""},{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + { + name: "adaptive thinking with absent thinking block", + payload: `{"thinking":{"type":"adaptive"},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + { + name: "standalone output_config effort with absent thinking block", + payload: `{"output_config":{"effort":"high"},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + { + name: "model suffix high overrides disabled body", + payload: `{"model":"deepseek-v4(high)","thinking":{"type":"disabled"},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + result, _ := ConvertClaudeRequestToOpenAIWithCompat("deepseek-v4", []byte(tc.payload), false) + assistant := ojson.GetBytesNoCopy(result, "messages.0") + if got := assistant.Get("reasoning_content").String(); got != " " { + t.Fatalf("reasoning_content = %q, want 1-char placeholder; output: %s", got, result) + } + if !assistant.Get("tool_calls").Exists() { + t.Fatalf("tool_calls missing from compatible translation: %s", result) + } + }) + } +} + func TestConvertClaudeRequestToOpenAIWithCompatPreservesIncompatibleThinking(t *testing.T) { payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":"claude#opaque"},{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`) @@ -60,10 +144,13 @@ func TestConvertClaudeRequestToOpenAIWithCompatPreservesIncompatibleThinking(t * } func TestConvertClaudeRequestToOpenAIWithoutCompatDoesNotAddReasoningForToolCalls(t *testing.T) { - payload := []byte(`{"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`) - - result, _ := ConvertClaudeRequestToOpenAI("deepseek-v4", payload, false) - if ojson.GetBytesNoCopy(result, "messages.0.reasoning_content").Exists() { - t.Fatalf("default translation added reasoning_content: %s", result) + for _, payload := range []string{ + `{"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + `{"thinking":{"type":"enabled","budget_tokens":1024},"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"Read","input":{}}]}]}`, + } { + result, _ := ConvertClaudeRequestToOpenAI("deepseek-v4", []byte(payload), false) + if ojson.GetBytesNoCopy(result, "messages.0.reasoning_content").Exists() { + t.Fatalf("default translation added reasoning_content: %s", result) + } } } diff --git a/internal/translator/openai/claude/openai_claude_request.go b/internal/translator/openai/claude/openai_claude_request.go index 6a9c93c6cf3..bcc122d4cb8 100644 --- a/internal/translator/openai/claude/openai_claude_request.go +++ b/internal/translator/openai/claude/openai_claude_request.go @@ -114,6 +114,8 @@ func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream _ = outDoc.Set("reasoning_effort", effort) } + reasoningActive := isClaudeRequestReasoningActive(outDoc.Get("reasoning_effort"), modelName, root.Get("model").String()) + // Process messages and system. messageCapacity := root.Get("messages.#").Int() if root.Get("system").Exists() { @@ -342,6 +344,11 @@ func convertClaudeRequestToOpenAI(modelName string, inputRawJSON []byte, stream // Add reasoning_content if present if hasReasoning { _ = msgDoc.Set("reasoning_content", reasoningContent) + } else if hasToolCalls && preserveThinkingBlocks && reasoningActive { + // Assistant turn with tool_calls but no replayable thinking text. + // Compat thinking upstreams (DeepSeek, Moonshot/Kimi) require + // reasoning_content to be present on such messages when reasoning is active. + _ = msgDoc.Set("reasoning_content", " ") } // Add tool_calls if present (in same message as content) @@ -545,6 +552,37 @@ func normalizeObjectSchemaProperties(schema any) any { } } +func isClaudeRequestReasoningActive(effortRes ojson.Result, modelName, payloadModel string) bool { + if active, ok := isThinkingSuffixActive(modelName); ok { + return active + } + if active, ok := isThinkingSuffixActive(payloadModel); ok { + return active + } + if !effortRes.Exists() { + return false + } + resolvedEffort := strings.ToLower(strings.TrimSpace(effortRes.String())) + return resolvedEffort != "" && resolvedEffort != string(thinking.LevelNone) && resolvedEffort != "0" && resolvedEffort != "false" +} + +func isThinkingSuffixActive(model string) (bool, bool) { + suffix := thinking.ParseSuffix(strings.TrimSpace(model)) + if !suffix.HasSuffix { + return false, false + } + if mode, ok := thinking.ParseSpecialSuffix(suffix.RawSuffix); ok { + return mode != thinking.ModeNone, true + } + if budget, ok := thinking.ParseNumericSuffix(suffix.RawSuffix); ok { + return budget > 0, true + } + if level, ok := thinking.ParseLevelSuffix(suffix.RawSuffix); ok { + return level != "" && level != thinking.LevelNone, true + } + return false, false +} + func shouldMapClaudeThinkingToGPTReasoning(part ojson.Result, preserveThinkingBlocks ...bool) bool { preserveThinking := len(preserveThinkingBlocks) > 0 && preserveThinkingBlocks[0] if preserveThinking { diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_response.go b/internal/translator/openai/openai/responses/openai_openai-responses_response.go index e3d2b42fa7a..e8f87f0c216 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_response.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_response.go @@ -19,6 +19,12 @@ type oaiToResponsesStateReasoning struct { ReasoningData string OutputIndex int } +type oaiToResponsesStateMessage struct { + MessageID string + Status string + Text string + OutputIndex int +} type oaiToResponsesState struct { translatorcommon.ApplyPatchErrorState ApplyPatchCalls map[string]*translatorcommon.ApplyPatchCallState @@ -39,6 +45,9 @@ type oaiToResponsesState struct { // aggregation buffers for response.output // Per-output message text buffers by index MsgTextBuf map[int]*strings.Builder + MsgCurrentID map[int]string + MsgSegCount map[int]int + Messages []oaiToResponsesStateMessage ReasoningBuf strings.Builder Reasonings []oaiToResponsesStateReasoning FuncArgsBuf map[string]*strings.Builder @@ -321,7 +330,7 @@ func buildResponsesCompletedEvent(st *oaiToResponsesState, nextSeq func() int) [ index int raw []byte } - outputItems := make([]completedOutputItem, 0, len(st.Reasonings)+len(st.MsgItemAdded)+len(st.FuncArgsBuf)) + outputItems := make([]completedOutputItem, 0, len(st.Reasonings)+len(st.Messages)+len(st.MsgItemAdded)+len(st.FuncArgsBuf)) if len(st.Reasonings) > 0 { for _, r := range st.Reasonings { itemDoc := ojson.NewDocString(`{"id":"","type":"reasoning","summary":[{"type":"summary_text","text":""}]}`) @@ -330,18 +339,33 @@ func buildResponsesCompletedEvent(st *oaiToResponsesState, nextSeq func() int) [ outputItems = append(outputItems, completedOutputItem{index: r.OutputIndex, raw: itemDoc.Bytes()}) } } + msgStatus := "completed" + if _, isInc := incompleteByFinishReason(st.FinishReason); isInc { + msgStatus = "incomplete" + } + for _, m := range st.Messages { + status := m.Status + if status == "" { + status = msgStatus + } + itemDoc := ojson.NewDocString(`{"id":"","type":"message","status":"completed","content":[{"type":"output_text","annotations":[],"logprobs":[],"text":""}],"role":"assistant"}`) + _ = itemDoc.Set("id", m.MessageID) + _ = itemDoc.Set("status", status) + _ = itemDoc.Set("content.0.text", m.Text) + outputItems = append(outputItems, completedOutputItem{index: m.OutputIndex, raw: itemDoc.Bytes()}) + } if len(st.MsgItemAdded) > 0 { for i := range st.MsgItemAdded { txt := "" if b := st.MsgTextBuf[i]; b != nil { txt = b.String() } - msgStatus := "completed" - if _, isInc := incompleteByFinishReason(st.FinishReason); isInc { - msgStatus = "incomplete" + msgID := st.MsgCurrentID[i] + if msgID == "" { + msgID = fmt.Sprintf("msg_%s_%d", st.ResponseID, i) } itemDoc := ojson.NewDocString(`{"id":"","type":"message","status":"completed","content":[{"type":"output_text","annotations":[],"logprobs":[],"text":""}],"role":"assistant"}`) - _ = itemDoc.Set("id", fmt.Sprintf("msg_%s_%d", st.ResponseID, i)) + _ = itemDoc.Set("id", msgID) _ = itemDoc.Set("status", msgStatus) _ = itemDoc.Set("content.0.text", txt) outputItems = append(outputItems, completedOutputItem{index: st.MsgOutputIx[i], raw: itemDoc.Bytes()}) @@ -434,6 +458,9 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, FuncArgsSent: make(map[string]int), MsgOutputIx: make(map[int]int), MsgTextBuf: make(map[int]*strings.Builder), + MsgCurrentID: make(map[int]string), + MsgSegCount: make(map[int]int), + Messages: make([]oaiToResponsesStateMessage, 0), MsgItemAdded: make(map[int]bool), MsgContentAdded: make(map[int]bool), MsgItemDone: make(map[int]bool), @@ -625,7 +652,11 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, st.Created = root.Get("created").Int() // reset aggregation state for a new streaming response st.MsgTextBuf = make(map[int]*strings.Builder) + st.MsgCurrentID = make(map[int]string) + st.MsgSegCount = make(map[int]int) + st.Messages = st.Messages[:0] st.ReasoningBuf.Reset() + st.Reasonings = st.Reasonings[:0] st.ReasoningID = "" st.ReasoningIndex = 0 st.ApplyPatchCalls = make(map[string]*translatorcommon.ApplyPatchCallState) @@ -708,6 +739,10 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, if !st.MsgItemAdded[idx] || st.MsgItemDone[idx] { return } + msgID := st.MsgCurrentID[idx] + if msgID == "" { + msgID = fmt.Sprintf("msg_%s_%d", st.ResponseID, idx) + } msgOutputIndex := st.MsgOutputIx[idx] fullText := "" if b := st.MsgTextBuf[idx]; b != nil { @@ -715,7 +750,7 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, } doneDoc := ojson.NewDocString(`{"type":"response.output_text.done","sequence_number":0,"item_id":"","output_index":0,"content_index":0,"text":"","logprobs":[]}`) _ = doneDoc.Set("sequence_number", nextSeq()) - _ = doneDoc.Set("item_id", fmt.Sprintf("msg_%s_%d", st.ResponseID, idx)) + _ = doneDoc.Set("item_id", msgID) _ = doneDoc.Set("output_index", msgOutputIndex) _ = doneDoc.Set("content_index", 0) _ = doneDoc.Set("text", fullText) @@ -723,7 +758,7 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, partDoneDoc := ojson.NewDocString(`{"type":"response.content_part.done","sequence_number":0,"item_id":"","output_index":0,"content_index":0,"part":{"type":"output_text","annotations":[],"logprobs":[],"text":""}}`) _ = partDoneDoc.Set("sequence_number", nextSeq()) - _ = partDoneDoc.Set("item_id", fmt.Sprintf("msg_%s_%d", st.ResponseID, idx)) + _ = partDoneDoc.Set("item_id", msgID) _ = partDoneDoc.Set("output_index", msgOutputIndex) _ = partDoneDoc.Set("content_index", 0) _ = partDoneDoc.Set("part.text", fullText) @@ -736,11 +771,23 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, itemDoneDoc := ojson.NewDocString(`{"type":"response.output_item.done","sequence_number":0,"output_index":0,"item":{"id":"","type":"message","status":"completed","content":[{"type":"output_text","annotations":[],"logprobs":[],"text":""}],"role":"assistant"}}`) _ = itemDoneDoc.Set("sequence_number", nextSeq()) _ = itemDoneDoc.Set("output_index", msgOutputIndex) - _ = itemDoneDoc.Set("item.id", fmt.Sprintf("msg_%s_%d", st.ResponseID, idx)) + _ = itemDoneDoc.Set("item.id", msgID) _ = itemDoneDoc.Set("item.status", msgStatus) _ = itemDoneDoc.Set("item.content.0.text", fullText) out = append(out, emitRespEvent("response.output_item.done", itemDoneDoc.Bytes())) - st.MsgItemDone[idx] = true + + st.Messages = append(st.Messages, oaiToResponsesStateMessage{ + MessageID: msgID, + Status: msgStatus, + Text: fullText, + OutputIndex: msgOutputIndex, + }) + delete(st.MsgItemAdded, idx) + delete(st.MsgContentAdded, idx) + delete(st.MsgItemDone, idx) + delete(st.MsgOutputIx, idx) + delete(st.MsgTextBuf, idx) + delete(st.MsgCurrentID, idx) } finalizeOpenItems := func() { @@ -917,7 +964,7 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, if hasActiveUnfinishedTool { return out } - if len(st.MsgItemAdded) == 0 && len(st.FuncItemAdded) == 0 { + if len(st.Messages) == 0 && len(st.MsgItemAdded) == 0 && len(st.FuncItemAdded) == 0 && (len(st.Reasonings) == 0 || st.FinishReason == "") { return out } st.CompletedEmitted = true @@ -927,81 +974,112 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponses(ctx context.Context, // choices[].delta content / tool_calls / reasoning_content if choices := root.Get("choices"); choices.Exists() && choices.IsArray() { + emitReasoningDelta := func(idx int, reasoningText string) { + if reasoningText == "" { + return + } + // Close any open assistant message item before starting a new reasoning block + // so interleaved message -> reasoning -> message segments remain sequential. + emitMessageItemDone(idx) + // On first appearance, add reasoning item and part + if st.ReasoningID == "" { + if len(st.Reasonings) == 0 { + st.ReasoningID = fmt.Sprintf("rs_%s_%d", st.ResponseID, idx) + } else { + st.ReasoningID = fmt.Sprintf("rs_%s_%d_%d", st.ResponseID, idx, len(st.Reasonings)) + } + st.ReasoningIndex = allocOutputIndex() + itemDoc := ojson.NewDocString(`{"type":"response.output_item.added","sequence_number":0,"output_index":0,"item":{"id":"","type":"reasoning","status":"in_progress","summary":[]}}`) + _ = itemDoc.Set("sequence_number", nextSeq()) + _ = itemDoc.Set("output_index", st.ReasoningIndex) + _ = itemDoc.Set("item.id", st.ReasoningID) + out = append(out, emitRespEvent("response.output_item.added", itemDoc.Bytes())) + partDoc := ojson.NewDocString(`{"type":"response.reasoning_summary_part.added","sequence_number":0,"item_id":"","output_index":0,"summary_index":0,"part":{"type":"summary_text","text":""}}`) + _ = partDoc.Set("sequence_number", nextSeq()) + _ = partDoc.Set("item_id", st.ReasoningID) + _ = partDoc.Set("output_index", st.ReasoningIndex) + out = append(out, emitRespEvent("response.reasoning_summary_part.added", partDoc.Bytes())) + } + // Append incremental text to reasoning buffer + st.ReasoningBuf.WriteString(reasoningText) + msgDoc := ojson.NewDocString(`{"type":"response.reasoning_summary_text.delta","sequence_number":0,"item_id":"","output_index":0,"summary_index":0,"delta":""}`) + _ = msgDoc.Set("sequence_number", nextSeq()) + _ = msgDoc.Set("item_id", st.ReasoningID) + _ = msgDoc.Set("output_index", st.ReasoningIndex) + _ = msgDoc.Set("delta", reasoningText) + out = append(out, emitRespEvent("response.reasoning_summary_text.delta", msgDoc.Bytes())) + } + + emitTextDelta := func(idx int, text string) { + if text == "" { + return + } + // Ensure the message item and its first content part are announced before any text deltas + if st.ReasoningID != "" { + stopReasoning(st.ReasoningBuf.String()) + st.ReasoningBuf.Reset() + } + if _, exists := st.MsgOutputIx[idx]; !exists { + st.MsgOutputIx[idx] = allocOutputIndex() + seg := st.MsgSegCount[idx] + st.MsgSegCount[idx] = seg + 1 + if seg == 0 { + st.MsgCurrentID[idx] = fmt.Sprintf("msg_%s_%d", st.ResponseID, idx) + } else { + st.MsgCurrentID[idx] = fmt.Sprintf("msg_%s_%d_%d", st.ResponseID, idx, seg) + } + } + msgID := st.MsgCurrentID[idx] + msgOutputIndex := st.MsgOutputIx[idx] + if !st.MsgItemAdded[idx] { + itemDoc := ojson.NewDocString(`{"type":"response.output_item.added","sequence_number":0,"output_index":0,"item":{"id":"","type":"message","status":"in_progress","content":[],"role":"assistant"}}`) + _ = itemDoc.Set("sequence_number", nextSeq()) + _ = itemDoc.Set("output_index", msgOutputIndex) + _ = itemDoc.Set("item.id", msgID) + out = append(out, emitRespEvent("response.output_item.added", itemDoc.Bytes())) + st.MsgItemAdded[idx] = true + } + if !st.MsgContentAdded[idx] { + partDoc := ojson.NewDocString(`{"type":"response.content_part.added","sequence_number":0,"item_id":"","output_index":0,"content_index":0,"part":{"type":"output_text","annotations":[],"logprobs":[],"text":""}}`) + _ = partDoc.Set("sequence_number", nextSeq()) + _ = partDoc.Set("item_id", msgID) + _ = partDoc.Set("output_index", msgOutputIndex) + _ = partDoc.Set("content_index", 0) + out = append(out, emitRespEvent("response.content_part.added", partDoc.Bytes())) + st.MsgContentAdded[idx] = true + } + + msgDoc := ojson.NewDocString(`{"type":"response.output_text.delta","sequence_number":0,"item_id":"","output_index":0,"content_index":0,"delta":"","logprobs":[]}`) + _ = msgDoc.Set("sequence_number", nextSeq()) + _ = msgDoc.Set("item_id", msgID) + _ = msgDoc.Set("output_index", msgOutputIndex) + _ = msgDoc.Set("content_index", 0) + _ = msgDoc.Set("delta", text) + out = append(out, emitRespEvent("response.output_text.delta", msgDoc.Bytes())) + // aggregate for response.output + if st.MsgTextBuf[idx] == nil { + st.MsgTextBuf[idx] = &strings.Builder{} + } + st.MsgTextBuf[idx].WriteString(text) + } + choices.ForEach(func(_, choice ojson.Result) bool { idx := int(choice.Get("index").Int()) delta := choice.Get("delta") if delta.Exists() { - // reasoning_content (OpenAI reasoning incremental text) - rc := delta.Get("reasoning_content") - if !rc.Exists() || rc.String() == "" { - rc = delta.Get("reasoning") - } - if rc.Exists() && rc.String() != "" { - // On first appearance, add reasoning item and part - if st.ReasoningID == "" { - st.ReasoningID = fmt.Sprintf("rs_%s_%d", st.ResponseID, idx) - st.ReasoningIndex = allocOutputIndex() - itemDoc := ojson.NewDocString(`{"type":"response.output_item.added","sequence_number":0,"output_index":0,"item":{"id":"","type":"reasoning","status":"in_progress","summary":[]}}`) - _ = itemDoc.Set("sequence_number", nextSeq()) - _ = itemDoc.Set("output_index", st.ReasoningIndex) - _ = itemDoc.Set("item.id", st.ReasoningID) - out = append(out, emitRespEvent("response.output_item.added", itemDoc.Bytes())) - partDoc := ojson.NewDocString(`{"type":"response.reasoning_summary_part.added","sequence_number":0,"item_id":"","output_index":0,"summary_index":0,"part":{"type":"summary_text","text":""}}`) - _ = partDoc.Set("sequence_number", nextSeq()) - _ = partDoc.Set("item_id", st.ReasoningID) - _ = partDoc.Set("output_index", st.ReasoningIndex) - out = append(out, emitRespEvent("response.reasoning_summary_part.added", partDoc.Bytes())) - } - // Append incremental text to reasoning buffer - st.ReasoningBuf.WriteString(rc.String()) - msgDoc := ojson.NewDocString(`{"type":"response.reasoning_summary_text.delta","sequence_number":0,"item_id":"","output_index":0,"summary_index":0,"delta":""}`) - _ = msgDoc.Set("sequence_number", nextSeq()) - _ = msgDoc.Set("item_id", st.ReasoningID) - _ = msgDoc.Set("output_index", st.ReasoningIndex) - _ = msgDoc.Set("delta", rc.String()) - out = append(out, emitRespEvent("response.reasoning_summary_text.delta", msgDoc.Bytes())) + // reasoning_content / reasoning / reasoning_details + for _, reasoningText := range collectOpenAIObjectReasoningTexts(delta) { + emitReasoningDelta(idx, reasoningText) } - if c := delta.Get("content"); c.Exists() && c.String() != "" { - // Ensure the message item and its first content part are announced before any text deltas - if st.ReasoningID != "" { - stopReasoning(st.ReasoningBuf.String()) - st.ReasoningBuf.Reset() - } - if _, exists := st.MsgOutputIx[idx]; !exists { - st.MsgOutputIx[idx] = allocOutputIndex() - } - msgOutputIndex := st.MsgOutputIx[idx] - if !st.MsgItemAdded[idx] { - itemDoc := ojson.NewDocString(`{"type":"response.output_item.added","sequence_number":0,"output_index":0,"item":{"id":"","type":"message","status":"in_progress","content":[],"role":"assistant"}}`) - _ = itemDoc.Set("sequence_number", nextSeq()) - _ = itemDoc.Set("output_index", msgOutputIndex) - _ = itemDoc.Set("item.id", fmt.Sprintf("msg_%s_%d", st.ResponseID, idx)) - out = append(out, emitRespEvent("response.output_item.added", itemDoc.Bytes())) - st.MsgItemAdded[idx] = true - } - if !st.MsgContentAdded[idx] { - partDoc := ojson.NewDocString(`{"type":"response.content_part.added","sequence_number":0,"item_id":"","output_index":0,"content_index":0,"part":{"type":"output_text","annotations":[],"logprobs":[],"text":""}}`) - _ = partDoc.Set("sequence_number", nextSeq()) - _ = partDoc.Set("item_id", fmt.Sprintf("msg_%s_%d", st.ResponseID, idx)) - _ = partDoc.Set("output_index", msgOutputIndex) - _ = partDoc.Set("content_index", 0) - out = append(out, emitRespEvent("response.content_part.added", partDoc.Bytes())) - st.MsgContentAdded[idx] = true - } - - msgDoc := ojson.NewDocString(`{"type":"response.output_text.delta","sequence_number":0,"item_id":"","output_index":0,"content_index":0,"delta":"","logprobs":[]}`) - _ = msgDoc.Set("sequence_number", nextSeq()) - _ = msgDoc.Set("item_id", fmt.Sprintf("msg_%s_%d", st.ResponseID, idx)) - _ = msgDoc.Set("output_index", msgOutputIndex) - _ = msgDoc.Set("content_index", 0) - _ = msgDoc.Set("delta", c.String()) - out = append(out, emitRespEvent("response.output_text.delta", msgDoc.Bytes())) - // aggregate for response.output - if st.MsgTextBuf[idx] == nil { - st.MsgTextBuf[idx] = &strings.Builder{} - } - st.MsgTextBuf[idx].WriteString(c.String()) + if c := delta.Get("content"); c.Exists() { + forEachOpenAIContentSegment(c, func(isReasoning bool, segText string) { + if isReasoning { + emitReasoningDelta(idx, segText) + } else { + emitTextDelta(idx, segText) + } + }) } // tool calls @@ -1130,21 +1208,45 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(_ context.Co // Build output list from choices[...] var outputItems [][]byte - // Detect and capture reasoning content if present (with fallback to reasoning) - rc := ojson.GetBytesNoCopy(rawJSON, "choices.0.message.reasoning_content") - if !rc.Exists() || rc.String() == "" { - rc = ojson.GetBytesNoCopy(rawJSON, "choices.0.message.reasoning") + type parsedChoiceContent struct { + reasoning string + text string + } + choices := root.Get("choices") + var choiceArr []ojson.Result + var parsedContents []parsedChoiceContent + if choices.Exists() && choices.IsArray() { + choiceArr = choices.Array() + parsedContents = make([]parsedChoiceContent, len(choiceArr)) + for i, choice := range choiceArr { + if msg := choice.Get("message"); msg.Exists() { + rText, vText := extractOpenAIMessageContent(msg.Get("content")) + parsedContents[i] = parsedChoiceContent{reasoning: rText, text: vText} + } + } + } + + rid := id + if strings.HasPrefix(rid, "resp_") { + rid = strings.TrimPrefix(rid, "resp_") + } + + // Detect and capture reasoning content if present (with fallback to reasoning / typed message.content) + var firstMsg ojson.Result + if len(choiceArr) > 0 { + firstMsg = choiceArr[0].Get("message") + } else { + firstMsg = root.Get("choices.0.message") + } + rcText := strings.Join(collectOpenAIObjectReasoningTexts(firstMsg), "") + if rcText == "" && len(parsedContents) > 0 { + rcText = parsedContents[0].reasoning } - rcText := rc.String() includeReasoning := rcText != "" if !includeReasoning { includeReasoning = echo.hasReasoning } if includeReasoning { - rid := id - if strings.HasPrefix(rid, "resp_") { - rid = strings.TrimPrefix(rid, "resp_") - } // Prefer summary_text from reasoning_content; encrypted_content is optional reasoningItemDoc := ojson.NewDocString(`{"id":"","type":"reasoning","encrypted_content":"","summary":[]}`) _ = reasoningItemDoc.Set("id", fmt.Sprintf("rs_%s", rid)) @@ -1155,87 +1257,101 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(_ context.Co outputItems = append(outputItems, reasoningItemDoc.Bytes()) } - if choices := root.Get("choices"); choices.Exists() && choices.IsArray() { - choices.ForEach(func(_, choice ojson.Result) bool { - msg := choice.Get("message") - if msg.Exists() { - // Text message part - if c := msg.Get("content"); c.Exists() && c.String() != "" { - itemStatus := "completed" - if isIncomplete { - itemStatus = "incomplete" - } - itemDoc := ojson.NewDocString(`{"id":"","type":"message","status":"completed","content":[{"type":"output_text","annotations":[],"logprobs":[],"text":""}],"role":"assistant"}`) - _ = itemDoc.Set("id", fmt.Sprintf("msg_%s_%d", id, int(choice.Get("index").Int()))) - _ = itemDoc.Set("status", itemStatus) - _ = itemDoc.Set("content.0.text", c.String()) - outputItems = append(outputItems, itemDoc.Bytes()) + for i, choice := range choiceArr { + msg := choice.Get("message") + if msg.Exists() { + choiceIdx := int(choice.Get("index").Int()) + if i > 0 { + extraRC := strings.Join(collectOpenAIObjectReasoningTexts(msg), "") + if extraRC == "" { + extraRC = parsedContents[i].reasoning } + if extraRC != "" { + reasoningItemDoc := ojson.NewDocString(`{"id":"","type":"reasoning","encrypted_content":"","summary":[]}`) + _ = reasoningItemDoc.Set("id", fmt.Sprintf("rs_%s_%d", rid, choiceIdx)) + _ = reasoningItemDoc.Set("summary.0.type", "summary_text") + _ = reasoningItemDoc.Set("summary.0.text", extraRC) + outputItems = append(outputItems, reasoningItemDoc.Bytes()) + } + } + // Text message part + if textContent := parsedContents[i].text; textContent != "" { + itemStatus := "completed" + if isIncomplete { + itemStatus = "incomplete" + } + itemDoc := ojson.NewDocString(`{"id":"","type":"message","status":"completed","content":[{"type":"output_text","annotations":[],"logprobs":[],"text":""}],"role":"assistant"}`) + _ = itemDoc.Set("id", fmt.Sprintf("msg_%s_%d", id, choiceIdx)) + _ = itemDoc.Set("status", itemStatus) + _ = itemDoc.Set("content.0.text", textContent) + outputItems = append(outputItems, itemDoc.Bytes()) + } - // Function/tool calls - if tcs := msg.Get("tool_calls"); tcs.Exists() && tcs.IsArray() { - customToolNames := toolIndex.custom - tcs.ForEach(func(tcIndex, tc ojson.Result) bool { - callID := tc.Get("id").String() - if callID == "" { - // Providers may omit tool_call ids; synthesize one so the - // function_call item stays usable for Codex round-trips. - callID = fmt.Sprintf("call_%s_%d_%d", id, choice.Get("index").Int(), tcIndex.Int()) - } - name := toolIndex.canonicalName(tc.Get("function.name").String()) - args := tc.Get("function.arguments").String() - toolStatus := "completed" - if isIncomplete { - toolStatus = "incomplete" + // Function/tool calls + if tcs := msg.Get("tool_calls"); tcs.Exists() && tcs.IsArray() { + customToolNames := toolIndex.custom + tcs.ForEach(func(tcIndex, tc ojson.Result) bool { + callID := tc.Get("id").String() + if callID == "" { + // Providers may omit tool_call ids; synthesize one so the + // function_call item stays usable for Codex round-trips. + callID = fmt.Sprintf("call_%s_%d_%d", id, choice.Get("index").Int(), tcIndex.Int()) + } + name := toolIndex.canonicalName(tc.Get("function.name").String()) + args := tc.Get("function.arguments").String() + toolStatus := "completed" + if isIncomplete { + toolStatus = "incomplete" + } + if toolIndex.isShell(name) { + item, errShellCallItem := shellCallItem(callID, args, toolStatus) + if errShellCallItem != nil { + st.SetToolInputError(errShellCallItem) + return false } - if toolIndex.isShell(name) { - item, errShellCallItem := shellCallItem(callID, args, toolStatus) - if errShellCallItem != nil { - st.SetToolInputError(errShellCallItem) + outputItems = append(outputItems, item) + return true + } + if toolIndex.isToolSearch(name) { + outputItems = append(outputItems, toolSearchCallItem(callID, args, toolStatus)) + return true + } + if _, isCustomTool := customToolNames[name]; isCustomTool { + itemDoc := ojson.NewDocString(`{"id":"","type":"custom_tool_call","status":"completed","input":"","call_id":"","name":""}`) + _ = itemDoc.Set("id", fmt.Sprintf("ctc_%s", callID)) + _ = itemDoc.Set("status", toolStatus) + input := "" + if toolIndex.isApplyPatch(name) { + patchCall := &translatorcommon.ApplyPatchCallState{} + _, fullInput, errFinishArguments := patchCall.FinishArguments(args) + if errFinishArguments != nil { + st.SetToolInputError(errFinishArguments) return false } - outputItems = append(outputItems, item) - return true + input = fullInput + } else { + input = unwrapCustomToolInput(args) } - if toolIndex.isToolSearch(name) { - outputItems = append(outputItems, toolSearchCallItem(callID, args, toolStatus)) - return true - } - if _, isCustomTool := customToolNames[name]; isCustomTool { - itemDoc := ojson.NewDocString(`{"id":"","type":"custom_tool_call","status":"completed","input":"","call_id":"","name":""}`) - _ = itemDoc.Set("id", fmt.Sprintf("ctc_%s", callID)) - _ = itemDoc.Set("status", toolStatus) - input := "" - if toolIndex.isApplyPatch(name) { - patchCall := &translatorcommon.ApplyPatchCallState{} - _, fullInput, errFinishArguments := patchCall.FinishArguments(args) - if errFinishArguments != nil { - st.SetToolInputError(errFinishArguments) - return false - } - input = fullInput - } else { - input = unwrapCustomToolInput(args) - } - _ = itemDoc.Set("input", input) - _ = itemDoc.Set("call_id", callID) - toolIndex.applyIdentityDoc(itemDoc, name, "") - outputItems = append(outputItems, itemDoc.Bytes()) - return true - } - itemDoc := ojson.NewDocString(`{"id":"","type":"function_call","status":"completed","arguments":"","call_id":"","name":""}`) - _ = itemDoc.Set("id", fmt.Sprintf("fc_%s", callID)) - _ = itemDoc.Set("status", toolStatus) - _ = translatorcommon.SetStringWithoutHTMLEscapeDoc(itemDoc, "arguments", args) + _ = itemDoc.Set("input", input) _ = itemDoc.Set("call_id", callID) toolIndex.applyIdentityDoc(itemDoc, name, "") outputItems = append(outputItems, itemDoc.Bytes()) return true - }) - } + } + itemDoc := ojson.NewDocString(`{"id":"","type":"function_call","status":"completed","arguments":"","call_id":"","name":""}`) + _ = itemDoc.Set("id", fmt.Sprintf("fc_%s", callID)) + _ = itemDoc.Set("status", toolStatus) + _ = translatorcommon.SetStringWithoutHTMLEscapeDoc(itemDoc, "arguments", args) + _ = itemDoc.Set("call_id", callID) + toolIndex.applyIdentityDoc(itemDoc, name, "") + outputItems = append(outputItems, itemDoc.Bytes()) + return true + }) } - return st.ToolInputError() == nil - }) + } + if st.ToolInputError() != nil { + break + } } if st.ToolInputError() != nil { return []byte(ojson.GetBytesNoCopy(responsesToolInputFailure(id, 0, st.ToolInputError()), "response").Raw) @@ -1271,7 +1387,7 @@ func ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(_ context.Co } func (st *oaiToResponsesState) canFinalizeResponse() bool { - if st.ToolInputError() != nil || st.FinishReason == "" || (len(st.MsgItemAdded) == 0 && len(st.FuncItemAdded) == 0) { + if st.ToolInputError() != nil || st.FinishReason == "" || (len(st.Messages) == 0 && len(st.MsgItemAdded) == 0 && len(st.FuncItemAdded) == 0 && len(st.Reasonings) == 0) { return false } for idx := range st.MsgItemAdded { @@ -1316,3 +1432,105 @@ func (st *oaiToResponsesState) FinalizeToolInput() [][]byte { st.Seq++ return [][]byte{emitRespEvent("response.failed", translatorcommon.ApplyPatchFailure(st.ResponseID, st.Seq))} } + +func collectOpenAIObjectReasoningTexts(obj ojson.Result) []string { + if !obj.Exists() { + return nil + } + for _, path := range []string{"reasoning_content", "reasoning", "reasoning_details"} { + if texts := collectOpenAIReasoningTexts(obj.Get(path)); len(texts) > 0 { + return texts + } + } + return nil +} + +func extractOpenAIContentPartThinkingText(part ojson.Result) string { + for _, field := range []string{"thinking", "reasoning", "reasoning_content", "text"} { + if texts := collectOpenAIReasoningTexts(part.Get(field)); len(texts) > 0 { + return strings.Join(texts, "") + } + } + return "" +} + +func collectOpenAIReasoningTexts(node ojson.Result) []string { + var texts []string + if !node.Exists() { + return texts + } + + if node.IsArray() { + node.ForEach(func(_, value ojson.Result) bool { + texts = append(texts, collectOpenAIReasoningTexts(value)...) + return true + }) + return texts + } + + switch node.Type { + case ojson.String: + if text := node.String(); text != "" { + texts = append(texts, text) + } + case ojson.JSON: + if text := node.Get("text"); text.Exists() { + if textStr := text.String(); textStr != "" { + texts = append(texts, textStr) + } + } else if raw := node.Raw; raw != "" && !strings.HasPrefix(raw, "{") && !strings.HasPrefix(raw, "[") { + texts = append(texts, raw) + } + } + + return texts +} + +func forEachOpenAIContentSegment(content ojson.Result, emit func(isReasoning bool, text string)) { + if !content.Exists() { + return + } + if content.IsArray() { + content.ForEach(func(_, part ojson.Result) bool { + if part.Type == ojson.String { + emit(false, part.String()) + return true + } + switch part.Get("type").String() { + case "thinking", "reasoning", "thought", "reasoning.text", "reasoning_text": + emit(true, extractOpenAIContentPartThinkingText(part)) + case "text", "output_text": + emit(false, part.Get("text").String()) + case "refusal": + refusalText := part.Get("refusal").String() + if refusalText == "" { + refusalText = part.Get("text").String() + } + emit(false, refusalText) + default: + emit(false, part.String()) + } + return true + }) + return + } + if content.Type == ojson.String { + emit(false, content.String()) + } +} + +func extractOpenAIMessageContent(content ojson.Result) (string, string) { + var reasoningBuilder strings.Builder + var textBuilder strings.Builder + forEachOpenAIContentSegment(content, func(isReasoning bool, text string) { + if text == "" { + return + } + if isReasoning { + reasoningBuilder.WriteString(text) + } else { + textBuilder.WriteString(text) + } + }) + return reasoningBuilder.String(), textBuilder.String() +} diff --git a/internal/translator/openai/openai/responses/openai_openai-responses_response_test.go b/internal/translator/openai/openai/responses/openai_openai-responses_response_test.go index af27634c221..fc0c8b9f70d 100644 --- a/internal/translator/openai/openai/responses/openai_openai-responses_response_test.go +++ b/internal/translator/openai/openai/responses/openai_openai-responses_response_test.go @@ -2152,3 +2152,385 @@ func TestConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream_MapsComp }) } } + +func TestConvertOpenAIChatCompletionsResponseToOpenAIResponses_DeltaContentTypedPartsArray(t *testing.T) { + t.Parallel() + + request := []byte(`{"model":"deepseek-v4-1-flash-1017"}`) + chunks := []string{ + `data: {"id":"bf39068555d24f22aaa60dc43231a002","object":"chat.completion.chunk","created":1794374142,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}`, + `data: {"id":"bf39068555d24f22aaa60dc43231a002","object":"chat.completion.chunk","created":1794374142,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"delta":{"index":0,"content":[{"type":"thinking","thinking":[{"type":"text","text":"The"}],"closed":true}]},"finish_reason":null}]}`, + `data: {"id":"bf39068555d24f22aaa60dc43231a002","object":"chat.completion.chunk","created":1794374142,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"delta":{"index":0,"content":[{"type":"thinking","thinking":[{"type":"text","text":"erse."}],"closed":true},{"type":"text","text":"收到,链路"}]},"finish_reason":null}]}`, + `data: {"id":"bf39068555d24f22aaa60dc43231a002","object":"chat.completion.chunk","created":1794374142,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"delta":{"index":0,"content":"正常"},"finish_reason":null}]}`, + `data: {"id":"bf39068555d24f22aaa60dc43231a002","object":"chat.completion.chunk","created":1794374142,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"delta":{"index":0,"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":31,"total_tokens":62,"completion_tokens":31,"completion_tokens_details":{"reasoning_tokens":21}}}`, + `data: [DONE]`, + } + + var param any + var itemTransitions []string + var reasoningDeltas []string + var textDeltas []string + var reasoningDoneText string + var textDoneText string + var completed ojson.Result + + for _, line := range chunks { + for _, chunk := range ConvertOpenAIChatCompletionsResponseToOpenAIResponses(context.Background(), "deepseek-v4-1-flash-1017", request, request, []byte(line), ¶m) { + event, data := parseOpenAIResponsesSSEEvent(t, chunk) + switch event { + case "response.output_item.added": + itemTransitions = append(itemTransitions, fmt.Sprintf("added:%s:%d", data.Get("item.type").String(), data.Get("output_index").Int())) + case "response.output_item.done": + itemTransitions = append(itemTransitions, fmt.Sprintf("done:%s:%d", data.Get("item.type").String(), data.Get("output_index").Int())) + case "response.reasoning_summary_text.delta": + reasoningDeltas = append(reasoningDeltas, data.Get("delta").String()) + case "response.reasoning_summary_text.done": + reasoningDoneText = data.Get("text").String() + case "response.output_text.delta": + textDeltas = append(textDeltas, data.Get("delta").String()) + case "response.output_text.done": + textDoneText = data.Get("text").String() + case "response.completed": + completed = data + } + } + } + + wantTransitions := []string{ + "added:reasoning:0", + "done:reasoning:0", + "added:message:1", + "done:message:1", + } + if strings.Join(itemTransitions, ",") != strings.Join(wantTransitions, ",") { + t.Fatalf("item transitions = %v, want %v", itemTransitions, wantTransitions) + } + if len(reasoningDeltas) != 2 || reasoningDeltas[0] != "The" || reasoningDeltas[1] != "erse." { + t.Fatalf("reasoning deltas = %v, want [The erse.]", reasoningDeltas) + } + if reasoningDoneText != "Theerse." { + t.Fatalf("reasoning_summary_text.done = %q, want %q", reasoningDoneText, "Theerse.") + } + if len(textDeltas) != 2 || textDeltas[0] != "收到,链路" || textDeltas[1] != "正常" { + t.Fatalf("output_text deltas = %v, want [收到,链路 正常]", textDeltas) + } + if textDoneText != "收到,链路正常" { + t.Fatalf("output_text.done = %q, want %q", textDoneText, "收到,链路正常") + } + if got := completed.Get("response.output.#").Int(); got != 2 { + t.Fatalf("response.output len = %d, want 2; completed=%s", got, completed.Raw) + } + if got := completed.Get("response.output.0.type").String(); got != "reasoning" { + t.Fatalf("response.output.0.type = %q, want reasoning", got) + } + if got := completed.Get("response.output.0.summary.0.text").String(); got != "Theerse." { + t.Fatalf("response.output.0.summary.0.text = %q, want %q", got, "Theerse.") + } + if got := completed.Get("response.output.1.type").String(); got != "message" { + t.Fatalf("response.output.1.type = %q, want message", got) + } + if got := completed.Get("response.output.1.content.0.text").String(); got != "收到,链路正常" { + t.Fatalf("response.output.1.content.0.text = %q, want %q", got, "收到,链路正常") + } + if got := completed.Get("response.usage.output_tokens_details.reasoning_tokens").Int(); got != 21 { + t.Fatalf("response.usage.output_tokens_details.reasoning_tokens = %d, want 21", got) + } +} + +func TestConvertOpenAIChatCompletionsResponseToOpenAIResponses_DeltaContentInterleavedTextThinkingText(t *testing.T) { + t.Parallel() + + request := []byte(`{"model":"zai-glm-5-3"}`) + chunks := []string{ + `data: {"id":"chatcmpl_interleaved","object":"chat.completion.chunk","created":1773896263,"model":"zai-glm-5-3","choices":[{"index":0,"delta":{"content":[{"type":"text","text":"First. "},{"type":"thinking","thinking":"Reconsidering..."},{"type":"text","text":"Second."}]},"finish_reason":"stop"}]}`, + `data: [DONE]`, + } + + var param any + var transitions []string + var addedIDs []string + var completed ojson.Result + + for _, line := range chunks { + for _, chunk := range ConvertOpenAIChatCompletionsResponseToOpenAIResponses(context.Background(), "zai-glm-5-3", request, request, []byte(line), ¶m) { + event, data := parseOpenAIResponsesSSEEvent(t, chunk) + switch event { + case "response.output_item.added": + transitions = append(transitions, fmt.Sprintf("added:%s:%d:%s", data.Get("item.type").String(), data.Get("output_index").Int(), data.Get("item.id").String())) + addedIDs = append(addedIDs, data.Get("item.id").String()) + case "response.output_item.done": + transitions = append(transitions, fmt.Sprintf("done:%s:%d:%s", data.Get("item.type").String(), data.Get("output_index").Int(), data.Get("item.id").String())) + case "response.completed": + completed = data + } + } + } + + wantTransitions := []string{ + "added:message:0:msg_chatcmpl_interleaved_0", + "done:message:0:msg_chatcmpl_interleaved_0", + "added:reasoning:1:rs_chatcmpl_interleaved_0", + "done:reasoning:1:rs_chatcmpl_interleaved_0", + "added:message:2:msg_chatcmpl_interleaved_0_1", + "done:message:2:msg_chatcmpl_interleaved_0_1", + } + if strings.Join(transitions, ",") != strings.Join(wantTransitions, ",") { + t.Fatalf("transitions = %v, want %v", transitions, wantTransitions) + } + if len(addedIDs) != 3 || addedIDs[0] == addedIDs[2] { + t.Fatalf("expected 3 distinct item IDs, got %v", addedIDs) + } + if got := completed.Get("response.output.#").Int(); got != 3 { + t.Fatalf("response.output len = %d, want 3; completed=%s", got, completed.Raw) + } + if got := completed.Get("response.output.0.content.0.text").String(); got != "First. " { + t.Fatalf("output.0 text = %q, want %q", got, "First. ") + } + if got := completed.Get("response.output.1.summary.0.text").String(); got != "Reconsidering..." { + t.Fatalf("output.1 summary = %q, want %q", got, "Reconsidering...") + } + if got := completed.Get("response.output.2.content.0.text").String(); got != "Second." { + t.Fatalf("output.2 text = %q, want %q", got, "Second.") + } +} + +func TestConvertOpenAIChatCompletionsResponseToOpenAIResponses_InterleavedTextThinkingTextTruncatedPreservesClosedMessageStatus(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + finishReason string + incompleteReason string + }{ + {name: "length", finishReason: "length", incompleteReason: "max_output_tokens"}, + {name: "content_filter", finishReason: "content_filter", incompleteReason: "content_filter"}, + } { + t.Run(tc.name, func(t *testing.T) { + request := []byte(`{"model":"zai-glm-5-3"}`) + chunks := []string{ + `data: {"id":"chatcmpl_trunc","object":"chat.completion.chunk","created":1773896263,"model":"zai-glm-5-3","choices":[{"index":0,"delta":{"content":[{"type":"text","text":"Completed prefix."},{"type":"thinking","thinking":"Thinking..."}]},"finish_reason":null}]}`, + fmt.Sprintf(`data: {"id":"chatcmpl_trunc","object":"chat.completion.chunk","created":1773896263,"model":"zai-glm-5-3","choices":[{"index":0,"delta":{"content":[{"type":"text","text":"Truncated tail"}]},"finish_reason":%q}]}`, tc.finishReason), + `data: [DONE]`, + } + + var param any + doneStatusByID := make(map[string]string) + var terminal ojson.Result + + for _, line := range chunks { + for _, chunk := range ConvertOpenAIChatCompletionsResponseToOpenAIResponses(context.Background(), "zai-glm-5-3", request, request, []byte(line), ¶m) { + event, data := parseOpenAIResponsesSSEEvent(t, chunk) + switch event { + case "response.output_item.done": + if data.Get("item.type").String() == "message" { + doneStatusByID[data.Get("item.id").String()] = data.Get("item.status").String() + } + case "response.incomplete": + terminal = data + } + } + } + + if !terminal.Exists() { + t.Fatalf("expected response.incomplete terminal event for finish_reason=%s", tc.finishReason) + } + if got := terminal.Get("response.incomplete_details.reason").String(); got != tc.incompleteReason { + t.Fatalf("incomplete_details.reason = %q, want %q", got, tc.incompleteReason) + } + if got := doneStatusByID["msg_chatcmpl_trunc_0"]; got != "completed" { + t.Fatalf("first message output_item.done status = %q, want completed", got) + } + if got := doneStatusByID["msg_chatcmpl_trunc_0_1"]; got != "incomplete" { + t.Fatalf("second message output_item.done status = %q, want incomplete", got) + } + if got := terminal.Get("response.output.0.status").String(); got != "completed" { + t.Fatalf("terminal response.output.0.status = %q, want completed (must match output_item.done)", got) + } + if got := terminal.Get("response.output.2.status").String(); got != "incomplete" { + t.Fatalf("terminal response.output.2.status = %q, want incomplete", got) + } + }) + } +} + +func TestConvertOpenAIChatCompletionsResponseToOpenAIResponses_DeltaContentPartVariants(t *testing.T) { + t.Parallel() + + request := []byte(`{"model":"zai-glm-5-3"}`) + chunks := []string{ + `data: {"id":"chatcmpl_variants","object":"chat.completion.chunk","created":1773896263,"model":"zai-glm-5-3","choices":[{"index":0,"delta":{"content":[]},"finish_reason":null}]}`, + `data: {"id":"chatcmpl_variants","object":"chat.completion.chunk","created":1773896263,"model":"zai-glm-5-3","choices":[{"index":0,"delta":{"content":[{"type":"thinking","thinking":"step 1"},{"type":"reasoning","text":" step 2"},{"type":"output_text","text":"answer: "},{"type":"refusal","refusal":"blocked "},"plain ",{"type":"custom_part","payload":"raw"}]},"finish_reason":null}]}`, + `data: {"id":"chatcmpl_variants","object":"chat.completion.chunk","created":1773896263,"model":"zai-glm-5-3","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, + `data: [DONE]`, + } + + var param any + var reasoningDeltas []string + var textDeltas []string + + for _, line := range chunks { + for _, chunk := range ConvertOpenAIChatCompletionsResponseToOpenAIResponses(context.Background(), "zai-glm-5-3", request, request, []byte(line), ¶m) { + event, data := parseOpenAIResponsesSSEEvent(t, chunk) + switch event { + case "response.reasoning_summary_text.delta": + reasoningDeltas = append(reasoningDeltas, data.Get("delta").String()) + case "response.output_text.delta": + textDeltas = append(textDeltas, data.Get("delta").String()) + } + } + } + + if got := strings.Join(reasoningDeltas, ""); got != "step 1 step 2" { + t.Fatalf("reasoning text = %q, want %q (deltas=%v)", got, "step 1 step 2", reasoningDeltas) + } + wantTextDeltas := []string{"answer: ", "blocked ", "plain ", `{"type":"custom_part","payload":"raw"}`} + if strings.Join(textDeltas, "|") != strings.Join(wantTextDeltas, "|") { + t.Fatalf("text deltas = %v, want %v", textDeltas, wantTextDeltas) + } +} + +func TestConvertOpenAIChatCompletionsResponseToOpenAIResponses_DeltaContentReasoningOnlyTermination(t *testing.T) { + t.Parallel() + + request := []byte(`{"model":"deepseek-v4-1-flash-1017"}`) + + t.Run("finish_reason length emits response.incomplete", func(t *testing.T) { + chunks := []string{ + `data: {"id":"chatcmpl_len_thinking","object":"chat.completion.chunk","created":1773896263,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"delta":{"index":0,"content":[{"type":"thinking","thinking":[{"type":"text","text":"exhausted budget"}],"closed":true}]},"finish_reason":null}]}`, + `data: {"id":"chatcmpl_len_thinking","object":"chat.completion.chunk","created":1773896263,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"delta":{},"finish_reason":"length"}],"usage":{"prompt_tokens":10,"completion_tokens":20,"total_tokens":30,"completion_tokens_details":{"reasoning_tokens":20}}}`, + } + + var param any + for _, line := range chunks { + for _, chunk := range ConvertOpenAIChatCompletionsResponseToOpenAIResponses(context.Background(), "deepseek-v4-1-flash-1017", request, request, []byte(line), ¶m) { + event, _ := parseOpenAIResponsesSSEEvent(t, chunk) + if event == "response.completed" { + t.Fatalf("reasoning-only stream with finish_reason=length emitted response.completed: %s", chunk) + } + } + } + + fin, ok := param.(interface{ CanFinalizeResponseStream() bool }) + if !ok || !fin.CanFinalizeResponseStream() { + t.Fatalf("expected CanFinalizeResponseStream() == true after explicit finish_reason=length") + } + + var incomplete ojson.Result + for _, chunk := range ConvertOpenAIChatCompletionsResponseToOpenAIResponses(context.Background(), "deepseek-v4-1-flash-1017", request, request, []byte("data: [DONE]"), ¶m) { + event, data := parseOpenAIResponsesSSEEvent(t, chunk) + if event == "response.incomplete" { + incomplete = data + } + } + + if !incomplete.Exists() { + t.Fatal("expected response.incomplete event on [DONE] for reasoning-only stream with finish_reason=length") + } + if got := incomplete.Get("response.status").String(); got != "incomplete" { + t.Fatalf("response.status = %q, want incomplete", got) + } + if got := incomplete.Get("response.incomplete_details.reason").String(); got != "max_output_tokens" { + t.Fatalf("response.incomplete_details.reason = %q, want max_output_tokens", got) + } + if got := incomplete.Get("response.output.#").Int(); got != 1 { + t.Fatalf("response.output len = %d, want 1; incomplete=%s", got, incomplete.Raw) + } + if got := incomplete.Get("response.output.0.type").String(); got != "reasoning" { + t.Fatalf("response.output.0.type = %q, want reasoning", got) + } + if got := incomplete.Get("response.output.0.summary.0.text").String(); got != "exhausted budget" { + t.Fatalf("response.output.0.summary.0.text = %q, want %q", got, "exhausted budget") + } + }) + + t.Run("missing finish_reason does not complete reasoning-only stream", func(t *testing.T) { + chunks := []string{ + `data: {"id":"chatcmpl_unfinished_thinking","object":"chat.completion.chunk","created":1773896263,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"delta":{"content":[{"type":"thinking","thinking":[{"type":"text","text":"still thinking"}],"closed":true}]},"finish_reason":null}]}`, + `data: [DONE]`, + } + + var param any + reasoningSeen := false + for _, line := range chunks { + for _, chunk := range ConvertOpenAIChatCompletionsResponseToOpenAIResponses(context.Background(), "deepseek-v4-1-flash-1017", request, request, []byte(line), ¶m) { + event, _ := parseOpenAIResponsesSSEEvent(t, chunk) + if event == "response.reasoning_summary_text.delta" { + reasoningSeen = true + } + if event == "response.completed" { + t.Fatalf("unfinished reasoning-only stream emitted response.completed: %s", chunk) + } + } + } + if !reasoningSeen { + t.Fatal("expected reasoning delta to be emitted before [DONE]") + } + }) +} + +func TestConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream_ContentPartsArray(t *testing.T) { + t.Parallel() + + t.Run("nested thinking array and text part", func(t *testing.T) { + request := []byte(`{"model":"deepseek-v4-1-flash-1017"}`) + raw := []byte(`{"id":"bd5377d8250c4022b9a1b4dcb258ec4b","object":"chat.completion","created":1773896263,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","tool_calls":null,"content":[{"type":"thinking","thinking":[{"type":"text","text":"We need answer to \"test\". "},{"type":"text","text":"Respond concise."}],"closed":true},{"type":"text","text":"Test received. How can I help?"}]}}]}`) + + resp := ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(context.Background(), "deepseek-v4-1-flash-1017", request, request, raw, nil) + data := util.ParseGJSONBytesNoCopy(resp) + + if got := data.Get("output.#").Int(); got != 2 { + t.Fatalf("output len = %d, want 2; resp=%s", got, resp) + } + if got := data.Get("output.0.type").String(); got != "reasoning" { + t.Fatalf("output.0.type = %q, want reasoning; resp=%s", got, resp) + } + if got := data.Get("output.0.summary.0.text").String(); got != `We need answer to "test". Respond concise.` { + t.Fatalf("output.0.summary.0.text = %q, want %q", got, `We need answer to "test". Respond concise.`) + } + if got := data.Get("output.1.type").String(); got != "message" { + t.Fatalf("output.1.type = %q, want message; resp=%s", got, resp) + } + if got := data.Get("output.1.content.0.text").String(); got != "Test received. How can I help?" { + t.Fatalf("output.1.content.0.text = %q, want %q", got, "Test received. How can I help?") + } + }) + + t.Run("top-level reasoning_content takes priority without leaking thinking part into message", func(t *testing.T) { + request := []byte(`{"model":"zai-glm-5-3"}`) + raw := []byte(`{"id":"chatcmpl_dedup","object":"chat.completion","created":1773896263,"model":"zai-glm-5-3","choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","reasoning_content":"top-level reasoning","content":[{"type":"thinking","thinking":"duplicate thinking"},{"type":"text","text":"Clean answer."}]}}]}`) + + resp := ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(context.Background(), "zai-glm-5-3", request, request, raw, nil) + data := util.ParseGJSONBytesNoCopy(resp) + + if got := data.Get("output.#").Int(); got != 2 { + t.Fatalf("output len = %d, want 2; resp=%s", got, resp) + } + if got := data.Get("output.0.summary.0.text").String(); got != "top-level reasoning" { + t.Fatalf("output.0.summary.0.text = %q, want %q", got, "top-level reasoning") + } + if got := data.Get("output.1.content.0.text").String(); got != "Clean answer." { + t.Fatalf("output.1.content.0.text = %q, want %q", got, "Clean answer.") + } + }) + + t.Run("thinking-only array with finish_reason length omits empty message item", func(t *testing.T) { + request := []byte(`{"model":"deepseek-v4-1-flash-1017"}`) + raw := []byte(`{"id":"chatcmpl_think_len","object":"chat.completion","created":1773896263,"model":"deepseek-v4-1-flash-1017","choices":[{"index":0,"finish_reason":"length","message":{"role":"assistant","content":[{"type":"thinking","thinking":[{"type":"text","text":"truncated thought"}],"closed":true}]}}]}`) + + resp := ConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream(context.Background(), "deepseek-v4-1-flash-1017", request, request, raw, nil) + data := util.ParseGJSONBytesNoCopy(resp) + + if got := data.Get("status").String(); got != "incomplete" { + t.Fatalf("status = %q, want incomplete; resp=%s", got, resp) + } + if got := data.Get("output.#").Int(); got != 1 { + t.Fatalf("output len = %d, want 1; resp=%s", got, resp) + } + if got := data.Get("output.0.type").String(); got != "reasoning" { + t.Fatalf("output.0.type = %q, want reasoning; resp=%s", got, resp) + } + if got := data.Get("output.0.summary.0.text").String(); got != "truncated thought" { + t.Fatalf("output.0.summary.0.text = %q, want %q", got, "truncated thought") + } + }) +} diff --git a/internal/tui/app.go b/internal/tui/app.go index 53e33b8930e..035a0d885f7 100644 --- a/internal/tui/app.go +++ b/internal/tui/app.go @@ -1,6 +1,7 @@ package tui import ( + "errors" "fmt" "io" "os" @@ -43,6 +44,11 @@ type App struct { client *Client + // fatalErr records a non-recoverable startup failure (e.g. the target does + // not expose a supported management API) so Run can exit non-zero after the + // Bubble Tea program ends. + fatalErr error + width int height int ready bool @@ -52,8 +58,9 @@ type App struct { } type authConnectMsg struct { - cfg map[string]any - err error + cfg map[string]any + err error + fatal error // non-nil when the server cannot serve the management API at all } // NewApp creates the root TUI application model targeting localhost on the given port. @@ -101,6 +108,9 @@ func NewAppWithBaseURL(baseURL string, secretKey string, hook *LogHook) App { } func (a App) Init() tea.Cmd { + if a.fatalErr != nil { + return tea.Quit + } if !a.authenticated { return textinput.Blink } @@ -135,6 +145,10 @@ func (a App) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case authConnectMsg: a.authConnecting = false + if msg.fatal != nil { + a.fatalErr = msg.fatal + return a, tea.Quit + } if msg.err != nil { a.authError = fmt.Sprintf(T("auth_gate_connect_fail"), msg.err.Error()) return a, nil @@ -484,7 +498,16 @@ func (a App) connectWithPassword(password string) tea.Cmd { return func() tea.Msg { a.client.SetSecretKey(password) cfg, errGetConfig := a.client.GetConfig() - return authConnectMsg{cfg: cfg, err: errGetConfig} + if errGetConfig == nil { + return authConnectMsg{cfg: cfg} + } + // A definitive unsupported server (both contracts absent) is fatal, not + // a retryable auth failure. Transient probe failures (503/429/network) + // are NOT fatal: they keep the previous retry behavior. + if errSupport := a.client.CheckManagementSupport(); errors.Is(errSupport, ErrManagementUnsupported) { + return authConnectMsg{err: errGetConfig, fatal: errSupport} + } + return authConnectMsg{err: errGetConfig} } } @@ -501,9 +524,24 @@ func RunWithBaseURL(baseURL string, secretKey string, hook *LogHook, output io.W output = os.Stdout } app := NewAppWithBaseURL(baseURL, secretKey, hook) + // Pre-flight the management contract in client mode so a target that + // definitively exposes neither v8 nor v0 fails fast with a non-zero exit. + // Transient probe failures (503/429/network) are not fatal here: they enter + // the normal auth-gate flow where the user can retry. + if hook == nil { + if err := app.client.CheckManagementSupport(); errors.Is(err, ErrManagementUnsupported) { + return err + } + } p := tea.NewProgram(app, tea.WithAltScreen(), tea.WithOutput(output)) - _, err := p.Run() - return err + final, err := p.Run() + if err != nil { + return err + } + if app2, ok := final.(App); ok { + return app2.fatalErr + } + return app.fatalErr } func (a App) broadcastToAllTabs(msg tea.Msg) (tea.Model, tea.Cmd) { diff --git a/internal/tui/client.go b/internal/tui/client.go index 7c688e117f2..c7f5d9442e4 100644 --- a/internal/tui/client.go +++ b/internal/tui/client.go @@ -8,14 +8,29 @@ import ( "net/url" "strconv" "strings" + "sync" "time" ) // Client wraps HTTP calls to the management API. +// +// The client prefers the v8 management contract and falls back to the +// deprecated /v0/management routes only when the v8 route is not implemented +// (404/405/501) by the target server. Configuration reads normalize the v8 +// tree-shaped document into the flat key set the TUI presents, so the tab +// models keep working on either contract. type Client struct { baseURL string secretKey string http *http.Client + + // probeMu guards the cached result of whether the target server exposes the + // v8 management contract, so a 404 on a missing config node is not mistaken + // for an absent route. Transient errors (network failure, 5xx) are not + // cached and are reported separately from a definitive "unsupported". + probeMu sync.Mutex + v8Probed bool + v8Supported bool } // NewClient creates a new management API client targeting localhost on the given port. @@ -54,11 +69,14 @@ func (c *Client) SetSecretKey(secretKey string) { c.secretKey = strings.TrimSpace(secretKey) } -func (c *Client) doRequest(method, path string, body io.Reader) ([]byte, int, error) { - url := c.baseURL + path - req, err := http.NewRequest(method, url, body) +func (c *Client) doRequest(method, path string, body io.Reader) ([]byte, int, http.Header, error) { + return c.doRequestHeaders(method, path, body, nil) +} + +func (c *Client) doRequestHeaders(method, path string, body io.Reader, headers http.Header) ([]byte, int, http.Header, error) { + req, err := http.NewRequest(method, c.baseURL+path, body) if err != nil { - return nil, 0, err + return nil, 0, nil, err } if c.secretKey != "" { req.Header.Set("Authorization", "Bearer "+c.secretKey) @@ -66,20 +84,79 @@ func (c *Client) doRequest(method, path string, body io.Reader) ([]byte, int, er if body != nil { req.Header.Set("Content-Type", "application/json") } + for k, vs := range headers { + // Set so a caller-supplied Content-Type replaces the JSON default. + req.Header.Del(k) + for _, v := range vs { + req.Header.Add(k, v) + } + } resp, err := c.http.Do(req) if err != nil { - return nil, 0, err + return nil, 0, nil, err } defer resp.Body.Close() data, err := io.ReadAll(resp.Body) if err != nil { - return nil, resp.StatusCode, err + return nil, resp.StatusCode, resp.Header, err + } + return data, resp.StatusCode, resp.Header, nil +} + +// isRouteUnsupported reports whether an HTTP status means the route does not +// exist on this server, so the caller may fall back to the other contract. +func isRouteUnsupported(code int) bool { + return code == http.StatusNotFound || code == http.StatusMethodNotAllowed || code == http.StatusNotImplemented +} + +// supportsV8 reports whether the target server implements the v8 management +// contract. The verdict is cached per client. A reachable /v8/management/config +// proves the contract exists; only an unimplemented root route (404/405/501) +// means the server predates v8. The second return value is false when the +// probe could not get a definitive answer (network error or 5xx), in which +// case the result is not cached and callers must not silently treat config +// reads as empty. +func (c *Client) supportsV8() (supported, definitive bool) { + c.probeMu.Lock() + defer c.probeMu.Unlock() + if c.v8Probed { + return c.v8Supported, true + } + _, code, err := c.getJSONStatus("/v8/management/config") + if err != nil && code == 0 { + // Transport-level failure: no definitive verdict, do not cache. + return false, false + } + switch { + case code == http.StatusNotFound || code == http.StatusMethodNotAllowed || code == http.StatusNotImplemented: + // Definitively unimplemented. + c.v8Probed = true + c.v8Supported = false + return false, true + case code == http.StatusOK: + if err != nil { + // Reachable route with an undecodable body: non-definitive. + return false, false + } + c.v8Probed = true + c.v8Supported = true + return true, true + case code == http.StatusUnauthorized || code == http.StatusForbidden: + // Auth-gated: the request was challenged before routing ran, so this + // does NOT prove the v8 contract exists (an auth-first proxy can 401 + // any path on a v0-only server). Report non-definitive and do not + // cache, so per-request fallback keeps working; the caller may still + // proceed to authentication on either contract. + return false, false + default: + // 429, 5xx, and any other status cannot prove the contract exists; + // treat as non-definitive and do not cache. + return false, false } - return data, resp.StatusCode, nil } func (c *Client) get(path string) ([]byte, error) { - data, code, err := c.doRequest("GET", path, nil) + data, code, _, err := c.doRequest("GET", path, nil) if err != nil { return nil, err } @@ -90,7 +167,7 @@ func (c *Client) get(path string) ([]byte, error) { } func (c *Client) put(path string, body io.Reader) ([]byte, error) { - data, code, err := c.doRequest("PUT", path, body) + data, code, _, err := c.doRequest("PUT", path, body) if err != nil { return nil, err } @@ -101,7 +178,7 @@ func (c *Client) put(path string, body io.Reader) ([]byte, error) { } func (c *Client) patch(path string, body io.Reader) ([]byte, error) { - data, code, err := c.doRequest("PATCH", path, body) + data, code, _, err := c.doRequest("PATCH", path, body) if err != nil { return nil, err } @@ -124,63 +201,345 @@ func (c *Client) getJSON(path string) (map[string]any, error) { return result, nil } -// postJSON sends a JSON body via POST and checks for errors. -func (c *Client) postJSON(path string, body any) error { - jsonBody, err := json.Marshal(body) +// getJSONStatus returns the decoded JSON object plus the HTTP status so callers +// can detect unsupported routes and fall back to the other contract. +func (c *Client) getJSONStatus(path string) (map[string]any, int, error) { + data, code, _, err := c.doRequest("GET", path, nil) if err != nil { - return err + return nil, code, err + } + if code >= 400 { + return nil, code, fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) } - _, code, err := c.doRequest("POST", path, strings.NewReader(string(jsonBody))) + var result map[string]any + if err := json.Unmarshal(data, &result); err != nil { + return nil, code, err + } + return result, code, nil +} + +// getJSONV8 fetches v8Path first and falls back to v0Path only when the v8 +// route is not implemented by the server. +func (c *Client) getJSONV8(v8Path, v0Path string) (map[string]any, error) { + result, code, err := c.getJSONStatus(v8Path) + if err == nil { + return result, nil + } + if isRouteUnsupported(code) { + return c.getJSON(v0Path) + } + return nil, err +} + +// ----- Config layout mapping ----- + +// flatToV8ConfigPath maps a flat v0 config field name used by the TUI to its +// path inside the v8 configuration tree. Fields not present here keep their +// own (already nested) path, so e.g. "quota-exceeded/switch-project" and +// "routing/strategy" resolve to the same v8 location. +var flatToV8ConfigPath = map[string]string{ + "debug": "observability/logs/debug", + "logging-to-file": "observability/logs/logging-to-file", + "logs-max-total-size-mb": "observability/logs/logs-max-total-size-mb", + "error-logs-max-files": "observability/logs/error-logs-max-files", + "request-log": "observability/logs/request-log", + "usage-statistics-enabled": "observability/usage/usage-statistics-enabled", + "proxy-url": "requests/proxy-url", + "request-retry": "routing/retry/request-retry", + "max-retry-interval": "routing/retry/max-retry-interval", + "max-retry-credentials": "routing/retry/max-retry-credentials", + "force-model-prefix": "routing/force-model-prefix", + "ws-auth": "oauth/providers/aistudio/ws-auth", + "routing/strategy": "routing/strategy", + "quota-exceeded/switch-project": "quota-exceeded/switch-project", + "quota-exceeded/switch-preview-model": "quota-exceeded/switch-preview-model", +} + +// v8ConfigPath resolves a TUI field path to its v8 config path. +func v8ConfigPath(flat string) string { + if p, ok := flatToV8ConfigPath[flat]; ok { + return p + } + return flat +} + +// errV8ConfigNodeMissing is returned by v8ConfigGet when the v8 contract is +// available but the requested config node does not exist (the server returns +// 404 {"error":"not_found"} for an absent field). Callers treat this as an +// empty value rather than falling back to v0. +var errV8ConfigNodeMissing = fmt.Errorf("v8 config node not set") + +// v8ConfigGet fetches a node from the v8 config tree. The returned value is the +// raw decoded JSON node at that path. A 404 on an existing contract maps to +// errV8ConfigNodeMissing; a 404 because the route itself is absent is returned +// as an HTTP status error so callers can still fall back to v0. +func (c *Client) v8ConfigGet(path string) (any, int, error) { + value, code, _, err := c.v8ConfigGetWithHeaders(path) + return value, code, err +} + +// v8ConfigGetWithHeaders is v8ConfigGet plus the response headers, so callers +// performing a read-modify-write can reuse the config ETag for If-Match. +func (c *Client) v8ConfigGetWithHeaders(path string) (any, int, http.Header, error) { + data, code, hdr, err := c.doRequest("GET", "/v8/management/config/"+path, nil) if err != nil { - return err + return nil, code, hdr, err + } + if code == http.StatusNotFound { + if supported, definitive := c.supportsV8(); definitive && supported { + // The v8 contract exists; the node itself is absent. When the node + // GET did not echo an ETag, fall back to the root config ETag so a + // create-on-missing-node write can still be conditional. + if hdr == nil || hdr.Get("ETag") == "" { + if rootHdr := c.rootConfigHeaders(); rootHdr != nil { + if hdr == nil { + hdr = http.Header{} + } + hdr.Set("ETag", rootHdr.Get("ETag")) + } + } + return nil, code, hdr, errV8ConfigNodeMissing + } } if code >= 400 { - return fmt.Errorf("HTTP %d", code) + return nil, code, hdr, fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) } - return nil + var result any + if err := json.Unmarshal(data, &result); err != nil { + return nil, code, hdr, err + } + return result, code, hdr, nil +} + +// rootConfigHeaders returns the response headers of a GET on the v8 root +// config document, used to obtain a config ETag for conditional writes when a +// child node does not yet exist. +func (c *Client) rootConfigHeaders() http.Header { + _, code, hdr, err := c.doRequest("GET", "/v8/management/config", nil) + if err != nil || code >= 400 { + return nil + } + return hdr +} + +// flattenV8Config converts the v8 tree-shaped configuration document into the +// flat key set the TUI tabs read. Fields the TUI displays are projected to +// their v8 location with server-aligned defaults; provider groups are kept +// under api-keys-providers for reference. Fields with no flat equivalent are +// not surfaced on the flat view. +func flattenV8Config(v8 map[string]any) map[string]any { + flat := make(map[string]any, len(v8)+16) + get := func(path ...string) any { + cur := any(v8) + for _, p := range path { + m, ok := cur.(map[string]any) + if !ok { + return nil + } + cur = m[p] + } + return cur + } + // setDef records the v8 value, or the supplied default when the field is + // absent from the persisted document. Defaults mirror internal/config + // runtime defaults so the TUI shows the effective value, not a zero value. + setDef := func(key string, v any, def any) { + if v == nil { + flat[key] = def + return + } + flat[key] = v + } + + // Numeric defaults use float64 because the TUI reads them via getFloat, + // which accepts only float64/json.Number. + setDef("port", get("server", "port"), float64(0)) + setDef("host", get("server", "host"), "") + setDef("debug", get("observability", "logs", "debug"), false) + setDef("proxy-url", get("requests", "proxy-url"), "") + setDef("request-retry", get("routing", "retry", "request-retry"), float64(0)) + setDef("max-retry-interval", get("routing", "retry", "max-retry-interval"), float64(0)) + setDef("force-model-prefix", get("routing", "force-model-prefix"), false) + setDef("logging-to-file", get("observability", "logs", "logging-to-file"), false) + setDef("logs-max-total-size-mb", get("observability", "logs", "logs-max-total-size-mb"), float64(0)) + setDef("error-logs-max-files", get("observability", "logs", "error-logs-max-files"), float64(10)) + setDef("usage-statistics-enabled", get("observability", "usage", "usage-statistics-enabled"), false) + setDef("request-log", get("observability", "logs", "request-log"), false) + if v := get("quota-exceeded"); v != nil { + flat["quota-exceeded"] = v + } + if v := get("routing"); v != nil { + flat["routing"] = v + } + setDef("ws-auth", get("oauth", "providers", "aistudio", "ws-auth"), true) + if v := get("access", "api-keys"); v != nil { + flat["api-keys"] = v + } + if v := get("api-keys"); v != nil { + flat["api-keys-providers"] = v + } + return flat } -// GetConfig fetches the parsed config. +// ErrManagementUnsupported is returned by CheckManagementSupport when neither +// the v8 nor the v0 management contract is reachable on the target server. +var ErrManagementUnsupported = fmt.Errorf("management API not supported by target server") + +// mgmtReachable classifies one management-config probe. +type mgmtReachable int + +const ( + mgmtUnreachable mgmtReachable = iota // transport failure / no verdict + mgmtUnsupported // definitive 404/405/501: route absent + mgmtAuthGated // 401/403: a management gate exists + mgmtOK // 200: contract served +) + +// probeManagement classifies a single config endpoint probe. +func (c *Client) probeManagement(path string) (mgmtReachable, error) { + _, code, err := c.getJSONStatus(path) + switch { + case err == nil: + return mgmtOK, nil + case code == 0: + return mgmtUnreachable, err + case code == http.StatusUnauthorized || code == http.StatusForbidden: + return mgmtAuthGated, nil + case isRouteUnsupported(code): + return mgmtUnsupported, nil + case code >= 500 || code == http.StatusTooManyRequests: + return mgmtUnreachable, err + default: + return mgmtUnreachable, err + } +} + +// CheckManagementSupport reports whether the target exposes a usable +// management API on either contract. It is definitive only when a contract is +// actually served or clearly absent; a transient failure on one contract does +// not get reported as "unsupported" while the other is merely unreachable. +func (c *Client) CheckManagementSupport() error { + v8, errV8 := c.probeManagement("/v8/management/config") + if v8 == mgmtOK || v8 == mgmtAuthGated { + return nil + } + v0, errV0 := c.probeManagement("/v0/management/config") + if v0 == mgmtOK || v0 == mgmtAuthGated { + return nil + } + // Only a definitive "route absent" on BOTH contracts is unsupported. + if v8 == mgmtUnsupported && v0 == mgmtUnsupported { + return ErrManagementUnsupported + } + // Otherwise we could not prove support (e.g. one unreachable, one absent): + // surface the most informative error without claiming "unsupported". + if errV8 != nil { + return fmt.Errorf("management API probe failed: %w", errV8) + } + if errV0 != nil { + return fmt.Errorf("management API probe failed: %w", errV0) + } + return ErrManagementUnsupported +} + +// GetConfig fetches the parsed config. It prefers the v8 document, normalized +// to the flat shape the TUI presents, and falls back to the legacy v0 config. func (c *Client) GetConfig() (map[string]any, error) { - return c.getJSON("/v0/management/config") + v8cfg, code, err := c.getJSONStatus("/v8/management/config") + if err == nil { + return flattenV8Config(v8cfg), nil + } + if isRouteUnsupported(code) { + return c.getJSON("/v0/management/config") + } + return nil, err } // GetConfigYAML fetches the raw config.yaml content. func (c *Client) GetConfigYAML() (string, error) { - data, err := c.get("/v0/management/config.yaml") + data, code, _, err := c.doRequest("GET", "/v8/management/config.yaml", nil) + if err == nil && code < 400 { + return string(data), nil + } + if isRouteUnsupported(code) { + data, err = c.get("/v0/management/config.yaml") + if err != nil { + return "", err + } + return string(data), nil + } if err != nil { return "", err } - return string(data), nil + return "", fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) } -// PutConfigYAML uploads new config.yaml content. +// PutConfigYAML uploads new config.yaml content, preferring the v8 endpoint. func (c *Client) PutConfigYAML(yamlContent string) error { - _, err := c.put("/v0/management/config.yaml", strings.NewReader(yamlContent)) - return err + data, code, _, err := c.doRequestHeaders("PUT", "/v8/management/config.yaml", strings.NewReader(yamlContent), http.Header{"Content-Type": {"application/yaml"}}) + if err == nil && code < 400 { + return nil + } + if isRouteUnsupported(code) { + _, err = c.put("/v0/management/config.yaml", strings.NewReader(yamlContent)) + return err + } + if err != nil { + return err + } + return fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) } +// ----- Credentials (auth files) ----- + // GetAuthFiles lists auth credential files. // API returns {"files": [...]}. func (c *Client) GetAuthFiles() ([]map[string]any, error) { - wrapper, err := c.getJSON("/v8/management/credentials") - if err != nil { - if strings.HasPrefix(err.Error(), "HTTP 404:") { - wrapper, err = c.getJSON("/v0/management/auth-files") - } + wrapper, code, err := c.getJSONStatus("/v8/management/credentials") + if err == nil { + return extractList(wrapper, "files") + } + if isRouteUnsupported(code) { + wrapper, err = c.getJSON("/v0/management/auth-files") if err != nil { return nil, err } + return extractList(wrapper, "files") } - return extractList(wrapper, "files") + return nil, err } // DeleteAuthFile deletes a single auth file by name. func (c *Client) DeleteAuthFile(name string) error { query := url.Values{} query.Set("name", name) - path := "/v0/management/auth-files?" + query.Encode() - _, code, err := c.doRequest("DELETE", path, nil) + v8Path := "/v8/management/credentials?" + query.Encode() + v0Path := "/v0/management/auth-files?" + query.Encode() + data, code, _, err := c.doRequest("DELETE", v8Path, nil) + if err == nil && code < 400 { + return nil + } + if isRouteUnsupported(code) { + if code != http.StatusNotFound { + return c.deleteV0(v0Path) + } + supported, definitive := c.supportsV8() + if definitive && supported { + return fmt.Errorf("delete failed (HTTP %d): %s", code, strings.TrimSpace(string(data))) + } + if !definitive { + return fmt.Errorf("v8 route unavailable and v8 support could not be determined (HTTP %d); not falling back", code) + } + return c.deleteV0(v0Path) + } + if err != nil { + return err + } + return fmt.Errorf("delete failed (HTTP %d)", code) +} + +func (c *Client) deleteV0(path string) error { + _, code, _, err := c.doRequest("DELETE", path, nil) if err != nil { return err } @@ -193,28 +552,81 @@ func (c *Client) DeleteAuthFile(name string) error { // ToggleAuthFile enables or disables an auth file. func (c *Client) ToggleAuthFile(name string, disabled bool) error { body, _ := json.Marshal(map[string]any{"name": name, "disabled": disabled}) - _, err := c.patch("/v0/management/auth-files/status", strings.NewReader(string(body))) - return err + return c.doV8ThenV0Write("PATCH", "/v8/management/credentials/status", body, "PATCH", "/v0/management/auth-files/status") } // PatchAuthFileFields updates editable fields on an auth file. func (c *Client) PatchAuthFileFields(name string, fields map[string]any) error { fields["name"] = name body, _ := json.Marshal(fields) - _, err := c.patch("/v0/management/auth-files/fields", strings.NewReader(string(body))) - return err + return c.doV8ThenV0Write("PATCH", "/v8/management/credentials/fields", body, "PATCH", "/v0/management/auth-files/fields") } // RefreshAuthFile triggers a forced refresh of a single auth credential. func (c *Client) RefreshAuthFile(name string) error { - return c.postJSON("/v0/management/auth-files/refresh", map[string]any{"name": name}) + return c.postJSONV8("/v8/management/credentials/refresh", "/v0/management/auth-files/refresh", map[string]any{"name": name}) } // RefreshAllAuthFiles triggers a forced refresh of all auth credentials. func (c *Client) RefreshAllAuthFiles() error { - return c.postJSON("/v0/management/auth-files/refresh", map[string]any{"all": true}) + return c.postJSONV8("/v8/management/credentials/refresh", "/v0/management/auth-files/refresh", map[string]any{"all": true}) } +func (c *Client) postJSONV8(v8Path, v0Path string, body any) error { + jsonBody, err := json.Marshal(body) + if err != nil { + return err + } + return c.doV8ThenV0Write("POST", v8Path, jsonBody, "POST", v0Path) +} + +// doV8ThenV0Write performs a write against a v8 route, falling back to the v0 +// route only when the v8 route is genuinely not implemented by this server. +// A business 404 (e.g. the named credential/field does not exist) on a +// reachable v8 route is returned as-is rather than retried against v0, which +// would both mask the real error and re-hit the deprecated contract. +func (c *Client) doV8ThenV0Write(v8Method, v8Path string, v8Body []byte, v0Method, v0Path string) error { + data, code, _, err := c.doRequest(v8Method, v8Path, strings.NewReader(string(v8Body))) + if err == nil && code < 400 { + return nil + } + if isRouteUnsupported(code) { + // 405/501 always mean this specific route is unimplemented -> v0. + // A 404 may mean either an unimplemented route or a missing resource; + // only fall back when v8 is definitively absent. When v8 is definitively + // present, surface the business error. When the probe cannot decide, + // do not guess a second protocol. + if code != http.StatusNotFound { + return c.writeV0(v0Method, v0Path, v8Body) + } + supported, definitive := c.supportsV8() + if definitive && supported { + return fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) + } + if !definitive { + return fmt.Errorf("v8 route unavailable and v8 support could not be determined (HTTP %d); not falling back", code) + } + return c.writeV0(v0Method, v0Path, v8Body) + } + if err != nil { + return err + } + return fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) +} + +func (c *Client) writeV0(method, path string, body []byte) error { + data, code, _, err := c.doRequest(method, path, strings.NewReader(string(body))) + if err != nil { + return err + } + if code >= 400 { + return fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) + } + return nil +} + +// ----- Logs ----- + // GetLogs fetches log lines from the server. func (c *Client) GetLogs(after int64, limit int) ([]string, int64, error) { query := url.Values{} @@ -225,13 +637,15 @@ func (c *Client) GetLogs(after int64, limit int) ([]string, int64, error) { query.Set("after", strconv.FormatInt(after, 10)) } - path := "/v0/management/logs" + v8Path := "/v8/management/observability/logs" + v0Path := "/v0/management/logs" encodedQuery := query.Encode() if encodedQuery != "" { - path += "?" + encodedQuery + v8Path += "?" + encodedQuery + v0Path += "?" + encodedQuery } - wrapper, err := c.getJSON(path) + wrapper, err := c.getJSONV8(v8Path, v0Path) if err != nil { return nil, after, err } @@ -269,100 +683,322 @@ func (c *Client) GetLogs(after int64, limit int) ([]string, int64, error) { return lines, latest, nil } +// ----- Client API keys (access.api-keys) ----- + // GetAPIKeys fetches the list of API keys. -// API returns {"api-keys": [...]}. +// API returns {"api-keys": [...]} on v0; the v8 equivalent is the bare array at +// /v8/management/config/access/api-keys. func (c *Client) GetAPIKeys() ([]string, error) { - wrapper, err := c.getJSON("/v0/management/api-keys") - if err != nil { - return nil, err + value, code, err := c.v8ConfigGet("access/api-keys") + if err == nil { + return stringSlice(value) } - arr, ok := wrapper["api-keys"] - if !ok { + if err == errV8ConfigNodeMissing { return nil, nil } - raw, err := json.Marshal(arr) + if isRouteUnsupported(code) { + wrapper, errGet := c.getJSON("/v0/management/api-keys") + if errGet != nil { + return nil, errGet + } + return stringSlice(wrapper["api-keys"]) + } + return nil, err +} + +// replaceAPIKeys writes the complete access.api-keys list through the v8 +// config endpoint. The ETag captured on the read is sent as If-Match so a +// write is rejected with 412 if another client saved after the read. A 405/501 +// write status means this specific route is unimplemented and falls back to +// the supplied v0 operation; 412 and other statuses are surfaced. +func (c *Client) replaceAPIKeys(keys []string, etag string, v0 func() error) error { + body, _ := json.Marshal(keys) + headers := http.Header{} + if etag != "" { + headers.Set("If-Match", etag) + } + data, code, _, err := c.doRequestHeaders("PUT", "/v8/management/config/access/api-keys", strings.NewReader(string(body)), headers) + if err == nil && code < 400 { + return nil + } + if code == http.StatusMethodNotAllowed || code == http.StatusNotImplemented { + return v0() + } if err != nil { - return nil, err + return err } - var result []string - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err + return fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) +} + +// mutateAPIKeys reads the current access.api-keys list, applies mutator, and +// writes it back conditionally so concurrent edits are not silently lost. +// It falls back to the v0 contract only when v8 is unsupported. +func (c *Client) mutateAPIKeys(mutator func(keys []string) ([]string, error), v0 func() error) error { + keys, etag, code, err := c.apiKeysV8() + if err == nil { + if etag == "" { + return fmt.Errorf("cannot modify api-keys: server returned no config version (ETag); refusing unconditional replace") + } + next, errMut := mutator(keys) + if errMut != nil { + return errMut + } + return c.replaceAPIKeys(next, etag, v0) } - return result, nil + if isRouteUnsupported(code) { + return v0() + } + return err } -// AddAPIKey adds a new API key by sending old=nil, new=key which appends. +// AddAPIKey adds a new API key. On v8 it appends to access.api-keys; on v0 it +// falls back to the legacy patch contract. func (c *Client) AddAPIKey(key string) error { - body := map[string]any{"old": nil, "new": key} - jsonBody, _ := json.Marshal(body) - _, err := c.patch("/v0/management/api-keys", strings.NewReader(string(jsonBody))) - return err + return c.mutateAPIKeys(func(keys []string) ([]string, error) { + return append(keys, key), nil + }, func() error { + body := map[string]any{"old": nil, "new": key} + jsonBody, _ := json.Marshal(body) + _, err := c.patch("/v0/management/api-keys", strings.NewReader(string(jsonBody))) + return err + }) } -// EditAPIKey replaces an API key at the given index. -func (c *Client) EditAPIKey(index int, newValue string) error { - body := map[string]any{"index": index, "value": newValue} - jsonBody, _ := json.Marshal(body) - _, err := c.patch("/v0/management/api-keys", strings.NewReader(string(jsonBody))) - return err +// EditAPIKey replaces an API key at the given index. expected is the key value +// the caller displayed when the user chose this index; if the server list no +// longer has that value at this position the write is refused instead of +// silently editing a shifted entry. +func (c *Client) EditAPIKey(index int, newValue string, expected ...string) error { + return c.mutateAPIKeys(func(keys []string) ([]string, error) { + if index < 0 || index >= len(keys) { + return nil, fmt.Errorf("index %d out of range", index) + } + if len(expected) > 0 && keys[index] != expected[0] { + return nil, fmt.Errorf("api-keys changed since selection (entry at index %d no longer matches); please refresh", index) + } + keys[index] = newValue + return keys, nil + }, func() error { + body := map[string]any{"index": index, "value": newValue} + jsonBody, _ := json.Marshal(body) + _, err := c.patch("/v0/management/api-keys", strings.NewReader(string(jsonBody))) + return err + }) } -// DeleteAPIKey deletes an API key by index. -func (c *Client) DeleteAPIKey(index int) error { - _, code, err := c.doRequest("DELETE", fmt.Sprintf("/v0/management/api-keys?index=%d", index), nil) +// DeleteAPIKey deletes an API key by index. expected optionally binds the key +// value shown to the user, so a concurrent reorder/delete is refused rather +// than removing the wrong entry. +func (c *Client) DeleteAPIKey(index int, expected ...string) error { + return c.mutateAPIKeys(func(keys []string) ([]string, error) { + if index < 0 || index >= len(keys) { + return nil, fmt.Errorf("index %d out of range", index) + } + if len(expected) > 0 && keys[index] != expected[0] { + return nil, fmt.Errorf("api-keys changed since selection (entry at index %d no longer matches); please refresh", index) + } + return append(keys[:index], keys[index+1:]...), nil + }, func() error { + _, code, _, err := c.doRequest("DELETE", fmt.Sprintf("/v0/management/api-keys?index=%d", index), nil) + if err != nil { + return err + } + if code >= 400 { + return fmt.Errorf("delete failed (HTTP %d)", code) + } + return nil + }) +} + +// apiKeysV8 reads the access.api-keys list together with the ETag of the exact +// config snapshot it came from, so a subsequent replace is conditional on that +// same version. Reading the root document (rather than the child node) keeps +// the list value and its version consistent even when the node is absent. +func (c *Client) apiKeysV8() ([]string, string, int, error) { + data, code, hdr, err := c.doRequest("GET", "/v8/management/config", nil) + etag := "" + if hdr != nil { + etag = hdr.Get("ETag") + } if err != nil { - return err + return nil, "", code, err } if code >= 400 { - return fmt.Errorf("delete failed (HTTP %d)", code) + return nil, "", code, fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) } - return nil + var doc map[string]any + if err := json.Unmarshal(data, &doc); err != nil { + return nil, "", code, err + } + var node any + if access, ok := doc["access"].(map[string]any); ok { + node = access["api-keys"] + } + keys, err := stringSlice(node) + return keys, etag, code, err +} + +func stringSlice(v any) ([]string, error) { + if v == nil { + return nil, nil + } + raw, err := json.Marshal(v) + if err != nil { + return nil, err + } + var out []string + if err := json.Unmarshal(raw, &out); err != nil { + return nil, err + } + return out, nil +} + +// ----- Provider upstream key lists (read-only display) ----- + +// providerV8ConfigKey maps a provider list identifier to its key under the v8 +// api-keys tree. +var providerV8ConfigKey = map[string]string{ + "gemini": "gemini", + "interactions": "interactions", + "claude": "claude", + "codex": "codex", + "xai": "xai", + "meta": "meta", + "vertex": "vertex", + "openai-compatibility": "openai-compatibility", } // GetGeminiKeys fetches Gemini API keys. // API returns {"gemini-api-key": [...]}. func (c *Client) GetGeminiKeys() ([]map[string]any, error) { - return c.getWrappedKeyList("/v0/management/gemini-api-key", "gemini-api-key") + return c.getProviderKeyList("gemini", "/v0/management/gemini-api-key", "gemini-api-key") } // GetInteractionsKeys fetches native Interactions API keys. // API returns {"interactions-api-key": [...]}. func (c *Client) GetInteractionsKeys() ([]map[string]any, error) { - return c.getWrappedKeyList("/v0/management/interactions-api-key", "interactions-api-key") + return c.getProviderKeyList("interactions", "/v0/management/interactions-api-key", "interactions-api-key") } // GetClaudeKeys fetches Claude API keys. +// API returns {"claude-api-key": [...]}. func (c *Client) GetClaudeKeys() ([]map[string]any, error) { - return c.getWrappedKeyList("/v0/management/claude-api-key", "claude-api-key") + return c.getProviderKeyList("claude", "/v0/management/claude-api-key", "claude-api-key") } // GetCodexKeys fetches Codex API keys. +// API returns {"codex-api-key": [...]}. func (c *Client) GetCodexKeys() ([]map[string]any, error) { - return c.getWrappedKeyList("/v0/management/codex-api-key", "codex-api-key") + return c.getProviderKeyList("codex", "/v0/management/codex-api-key", "codex-api-key") } // GetXAIKeys fetches xAI API keys. +// API returns {"xai-api-key": [...]}. func (c *Client) GetXAIKeys() ([]map[string]any, error) { - return c.getWrappedKeyList("/v0/management/xai-api-key", "xai-api-key") + return c.getProviderKeyList("xai", "/v0/management/xai-api-key", "xai-api-key") } // GetVertexKeys fetches Vertex API keys. +// API returns {"vertex-api-key": [...]}. func (c *Client) GetVertexKeys() ([]map[string]any, error) { - return c.getWrappedKeyList("/v0/management/vertex-api-key", "vertex-api-key") + return c.getProviderKeyList("vertex", "/v0/management/vertex-api-key", "vertex-api-key") } // GetOpenAICompat fetches OpenAI compatibility entries. +// API returns {"openai-compatibility": [...]}. func (c *Client) GetOpenAICompat() ([]map[string]any, error) { - return c.getWrappedKeyList("/v0/management/openai-compatibility", "openai-compatibility") + return c.getProviderKeyList("openai-compatibility", "/v0/management/openai-compatibility", "openai-compatibility") } -// getWrappedKeyList fetches a wrapped list from the API. -func (c *Client) getWrappedKeyList(path, key string) ([]map[string]any, error) { - wrapper, err := c.getJSON(path) - if err != nil { - return nil, err +// getProviderKeyList fetches a provider upstream-key list, preferring the v8 +// config tree (api-keys/) and normalizing its grouped shape to the +// flat legacy list the TUI renders. It falls back to the v0 wrapped list. +func (c *Client) getProviderKeyList(provider, v0Path, v0WrapKey string) ([]map[string]any, error) { + v8Key := providerV8ConfigKey[provider] + value, code, err := c.v8ConfigGet("api-keys/" + v8Key) + if err == nil { + return flattenProviderKeyList(provider, value), nil + } + if err == errV8ConfigNodeMissing { + return nil, nil + } + if isRouteUnsupported(code) { + wrapper, errGet := c.getJSON(v0Path) + if errGet != nil { + return nil, errGet + } + return extractList(wrapper, v0WrapKey) + } + return nil, err +} + +// flattenProviderKeyList converts the v8 api-keys. value into the +// flat legacy list the TUI renders. For key-grouped providers the groups each +// carry a keys array; group-level prefix/base-url/proxy-url are inherited by +// each key that does not override them. The openai-compatibility provider is a +// list of upstream entries (name/base-url/prefix/api-key-entries), not a keys +// list, so its groups are returned unchanged. +func flattenProviderKeyList(provider string, value any) []map[string]any { + groups, ok := value.([]any) + if !ok || len(groups) == 0 { + return nil + } + if provider == "openai-compatibility" { + out := make([]map[string]any, 0, len(groups)) + for _, g := range groups { + if group, ok := g.(map[string]any); ok { + out = append(out, group) + } + } + return out } - return extractList(wrapper, key) + out := make([]map[string]any, 0, len(groups)) + for _, g := range groups { + group, ok := g.(map[string]any) + if !ok { + continue + } + groupPrefix := group["prefix"] + groupBase := group["base-url"] + groupProxy := group["proxy-url"] + keys, hasKeys := group["keys"].([]any) + if hasKeys && len(keys) == 0 { + // A group with an explicit empty keys list yields no credentials. + continue + } + if len(keys) == 0 { + // Legacy flat entry without a keys array: only counts when it + // carries a real api-key, not just a group name. + if apiKey, ok := group["api-key"].(string); ok && apiKey != "" { + out = append(out, map[string]any{"api-key": apiKey}) + } + continue + } + for _, k := range keys { + keyMap, ok := k.(map[string]any) + if !ok { + continue + } + entry := make(map[string]any, len(keyMap)+3) + for k2, v2 := range keyMap { + entry[k2] = v2 + } + // v8 treats an explicit per-key null the same as an absent field: + // both inherit the group value. + inherit := func(field string, groupVal any) { + if v, exists := entry[field]; !exists || v == nil { + if groupVal != nil { + entry[field] = groupVal + } + } + } + inherit("prefix", groupPrefix) + inherit("base-url", groupBase) + inherit("proxy-url", groupProxy) + out = append(out, entry) + } + } + return out } // extractList pulls an array of maps from a wrapper object by key. @@ -384,16 +1020,78 @@ func extractList(wrapper map[string]any, key string) ([]map[string]any, error) { // GetDebug fetches the current debug setting. func (c *Client) GetDebug() (bool, error) { - wrapper, err := c.getJSON("/v0/management/debug") - if err != nil { - return false, err - } - if v, ok := wrapper["debug"]; ok { - if b, ok := v.(bool); ok { + value, code, err := c.v8ConfigGet("observability/logs/debug") + if err == nil { + if b, ok := value.(bool); ok { return b, nil } + return false, nil + } + if err == errV8ConfigNodeMissing { + return false, nil + } + if isRouteUnsupported(code) { + wrapper, errGet := c.getJSON("/v0/management/debug") + if errGet != nil { + return false, errGet + } + if v, ok := wrapper["debug"]; ok { + if b, ok := v.(bool); ok { + return b, nil + } + } + return false, nil + } + return false, err +} + +// ----- OAuth session ----- + +// oauthV8Provider maps a legacy provider auth-url path segment to its v8 +// provider identifier. +var oauthV8Provider = map[string]string{ + "anthropic-auth-url": "claude", + "codex-auth-url": "codex", + "antigravity-auth-url": "antigravity", + "kimi-auth-url": "kimi", + "kimi-ai-auth-url": "kimi-ai", + "xai-auth-url": "xai", + "devin-auth-url": "devin", + "meta-auth-url": "meta", +} + +// StartOAuthFlow begins an OAuth login for the given provider. It prefers the +// shared v8 endpoint and falls back to the provider-specific v0 route. +// legacyAPIPath is the v0 path segment (e.g. "codex-auth-url"). +func (c *Client) StartOAuthFlow(legacyAPIPath string) (map[string]any, error) { + provider := oauthV8Provider[strings.TrimPrefix(legacyAPIPath, "/v0/management/")] + if provider == "" { + provider = strings.TrimSuffix(strings.TrimPrefix(legacyAPIPath, "/v0/management/"), "-auth-url") } - return false, nil + query := url.Values{} + query.Set("provider", provider) + query.Set("is_webui", "true") + v8Path := "/v8/management/oauth/auth-url?" + query.Encode() + wrapper, code, err := c.getJSONStatus(v8Path) + if err == nil { + return wrapper, nil + } + if isRouteUnsupported(code) { + return c.getJSON("/v0/management/" + legacyAPIPath + "?is_webui=true") + } + return nil, err +} + +// SubmitOAuthCallback posts a callback URL to the management server, preferring +// the v8 callback endpoint. +func (c *Client) SubmitOAuthCallback(providerKey, redirectURL, state string) error { + body := map[string]string{ + "provider": providerKey, + "redirect_url": redirectURL, + "state": state, + } + jsonBody, _ := json.Marshal(body) + return c.doV8ThenV0Write("POST", "/v8/management/oauth/callback", jsonBody, "POST", "/v0/management/oauth-callback") } // GetAuthStatus polls the OAuth session status. @@ -401,10 +1099,17 @@ func (c *Client) GetDebug() (bool, error) { func (c *Client) GetAuthStatus(state string) (string, string, error) { query := url.Values{} query.Set("state", state) - path := "/v0/management/get-auth-status?" + query.Encode() - wrapper, err := c.getJSON(path) + v8Path := "/v8/management/oauth/status?" + query.Encode() + wrapper, code, err := c.getJSONStatus(v8Path) if err != nil { - return "", "", err + if isRouteUnsupported(code) { + wrapper, err = c.getJSON("/v0/management/get-auth-status?" + query.Encode()) + if err != nil { + return "", "", err + } + } else { + return "", "", err + } } status := getString(wrapper, "status") errMsg := getString(wrapper, "error") @@ -419,42 +1124,94 @@ func (c *Client) CancelAuthSession(state string) error { } query := url.Values{} query.Set("state", state) - path := "/v0/management/oauth-session?" + query.Encode() - _, code, err := c.doRequest("DELETE", path, nil) + v8Path := "/v8/management/oauth/session?" + query.Encode() + _, code, _, err := c.doRequest("DELETE", v8Path, nil) + if err == nil && code < 400 { + return nil + } + if isRouteUnsupported(code) { + _, code, _, err = c.doRequest("DELETE", "/v0/management/oauth-session?"+query.Encode(), nil) + if err != nil { + return err + } + if code >= 400 { + return fmt.Errorf("HTTP %d", code) + } + return nil + } if err != nil { return err } - if code >= 400 { - return fmt.Errorf("HTTP %d", code) - } - return nil + return fmt.Errorf("HTTP %d", code) } // ----- Config field update methods ----- +// putConfigField writes a single config field, preferring the v8 path-based +// config endpoint with the raw value, and falling back to the v0 {value:...} +// envelope contract. +func (c *Client) putConfigField(flatPath string, value any) error { + v8Path := "/v8/management/config/" + v8ConfigPath(flatPath) + v8Body, _ := json.Marshal(value) + data, code, _, err := c.doRequest("PUT", v8Path, strings.NewReader(string(v8Body))) + if err == nil && code < 400 { + return nil + } + if isRouteUnsupported(code) { + v0Body, _ := json.Marshal(map[string]any{"value": value}) + _, err = c.put("/v0/management/"+flatPath, strings.NewReader(string(v0Body))) + return err + } + if err != nil { + return err + } + return fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) +} + // PutBoolField updates a boolean config field. func (c *Client) PutBoolField(path string, value bool) error { - body, _ := json.Marshal(map[string]any{"value": value}) - _, err := c.put("/v0/management/"+path, strings.NewReader(string(body))) - return err + return c.putConfigField(path, value) } // PutIntField updates an integer config field. func (c *Client) PutIntField(path string, value int) error { - body, _ := json.Marshal(map[string]any{"value": value}) - _, err := c.put("/v0/management/"+path, strings.NewReader(string(body))) - return err + return c.putConfigField(path, value) } // PutStringField updates a string config field. func (c *Client) PutStringField(path string, value string) error { - body, _ := json.Marshal(map[string]any{"value": value}) - _, err := c.put("/v0/management/"+path, strings.NewReader(string(body))) - return err + return c.putConfigField(path, value) } -// DeleteField sends a DELETE request for a config field. +// DeleteField sends a DELETE request for a config field, preferring v8. func (c *Client) DeleteField(path string) error { - _, _, err := c.doRequest("DELETE", "/v0/management/"+path, nil) - return err + v8Path := "/v8/management/config/" + v8ConfigPath(path) + data, code, _, err := c.doRequest("DELETE", v8Path, nil) + if err == nil && code < 400 { + return nil + } + if code == http.StatusNotFound { + supported, definitive := c.supportsV8() + if definitive && supported { + // v8 exists but the field is absent: nothing to delete. + return nil + } + if !definitive { + return fmt.Errorf("v8 route returned 404 and v8 support could not be determined; not falling back") + } + } + if isRouteUnsupported(code) { + _, code, _, err = c.doRequest("DELETE", "/v0/management/"+path, nil) + if err != nil { + return err + } + if code >= 400 { + return fmt.Errorf("delete failed (HTTP %d)", code) + } + return nil + } + if err != nil { + return err + } + return fmt.Errorf("delete failed (HTTP %d): %s", code, strings.TrimSpace(string(data))) } diff --git a/internal/tui/client_test.go b/internal/tui/client_test.go index ead3947b7c0..70e75b9a458 100644 --- a/internal/tui/client_test.go +++ b/internal/tui/client_test.go @@ -76,15 +76,13 @@ func TestClient_RemoteServerInteraction(t *testing.T) { defer ts.Close() client := NewClientWithBaseURL(ts.URL, "remote-secret-key") - cfg, err := client.GetConfig() + _, err := client.GetConfig() if err != nil { t.Fatalf("unexpected error: %v", err) } - if cfg["status"] != "ok" { - t.Fatalf("expected status ok, got %v", cfg["status"]) - } - if requestedPath != "/v0/management/config" { - t.Fatalf("expected path /v0/management/config, got %q", requestedPath) + // The client prefers the v8 contract; it must reach the v8 config route. + if requestedPath != "/v8/management/config" { + t.Fatalf("expected path /v8/management/config, got %q", requestedPath) } if authHeader != "Bearer remote-secret-key" { t.Fatalf("expected Authorization Bearer remote-secret-key, got %q", authHeader) diff --git a/internal/tui/client_v8_test.go b/internal/tui/client_v8_test.go new file mode 100644 index 00000000000..90f5a13b265 --- /dev/null +++ b/internal/tui/client_v8_test.go @@ -0,0 +1,844 @@ +package tui + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +// v8OnlyManagementServer is a test server that only implements the +// /v8/management contract. Every /v0/management request returns 404, matching +// a deployment where the deprecated routes were removed or blocked. +type v8OnlyManagementServer struct { + *httptest.Server + v0Requests int32 + config map[string]any +} + +func newV8OnlyManagementServer(t *testing.T) *v8OnlyManagementServer { + t.Helper() + srv := &v8OnlyManagementServer{ + config: map[string]any{ + "observability": map[string]any{ + "logs": map[string]any{"debug": false}, + "usage": map[string]any{"usage-statistics-enabled": false}, + }, + "routing": map[string]any{"strategy": "round-robin"}, + "requests": map[string]any{"proxy-url": ""}, + }, + } + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&srv.v0Requests, 1) + http.NotFound(w, r) + }) + handle := func(pattern string, fn http.HandlerFunc) { + mux.HandleFunc(pattern, fn) + } + handle("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "method", http.StatusMethodNotAllowed) + return + } + writeJSON(t, w, srv.config) + }) + mux.HandleFunc("/v8/management/config/access/api-keys", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []string{"client-key-1"}) + }) + mux.HandleFunc("/v8/management/config/api-keys/gemini", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []any{ + map[string]any{"name": "g1", "keys": []any{map[string]any{"api-key": "AIzaSyTestKey01"}}}, + }) + }) + mux.HandleFunc("/v8/management/credentials", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, map[string]any{"files": []any{map[string]any{"name": "a.json"}}}) + }) + mux.HandleFunc("/v8/management/oauth/status", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, map[string]any{"status": "wait"}) + }) + mux.HandleFunc("/v8/management/oauth/auth-url", func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.Query().Get("provider"); got != "codex" { + http.Error(w, "provider", http.StatusBadRequest) + return + } + writeJSON(t, w, map[string]any{"url": "https://auth.example.com/x", "state": "st-1"}) + }) + mux.HandleFunc("/v8/management/observability/logs", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, map[string]any{"lines": []string{"l1"}, "latest-timestamp": 5}) + }) + mux.HandleFunc("/v8/management/config/observability/logs/debug", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPut { + w.WriteHeader(http.StatusOK) + return + } + writeJSON(t, w, true) + }) + srv.Server = httptest.NewServer(mux) + t.Cleanup(srv.Close) + return srv +} + +func writeJSON(t *testing.T, w http.ResponseWriter, v any) { + t.Helper() + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode(v); err != nil { + t.Fatalf("encode: %v", err) + } +} + +func (s *v8OnlyManagementServer) assertNoV0(t *testing.T) { + t.Helper() + if n := atomic.LoadInt32(&s.v0Requests); n != 0 { + t.Fatalf("expected 0 v0 requests against a v8-only server, got %d", n) + } +} + +// TestClient_V8OnlyServer exercises every management surface the TUI uses +// against a server that no longer exposes /v0/management. The TUI client must +// reach the v8 routes instead of failing. +func TestClient_V8OnlyServer(t *testing.T) { + srv := newV8OnlyManagementServer(t) + client := NewClientWithBaseURL(srv.URL, "secret") + + t.Run("GetConfig", func(t *testing.T) { + cfg, err := client.GetConfig() + if err != nil { + t.Fatalf("GetConfig: %v", err) + } + if cfg["status"] == nil && cfg["observability"] == nil && cfg["debug"] == nil { + t.Fatalf("GetConfig returned empty/invalid config: %v", cfg) + } + }) + + t.Run("GetAPIKeys", func(t *testing.T) { + keys, err := client.GetAPIKeys() + if err != nil { + t.Fatalf("GetAPIKeys: %v", err) + } + if len(keys) == 0 { + t.Fatalf("expected at least one api key") + } + }) + + t.Run("GetGeminiKeys", func(t *testing.T) { + keys, err := client.GetGeminiKeys() + if err != nil { + t.Fatalf("GetGeminiKeys: %v", err) + } + if len(keys) == 0 { + t.Fatalf("expected gemini keys") + } + }) + + t.Run("GetAuthFiles", func(t *testing.T) { + files, err := client.GetAuthFiles() + if err != nil { + t.Fatalf("GetAuthFiles: %v", err) + } + if len(files) == 0 { + t.Fatalf("expected auth files") + } + }) + + t.Run("GetAuthStatus", func(t *testing.T) { + status, _, err := client.GetAuthStatus("st-1") + if err != nil { + t.Fatalf("GetAuthStatus: %v", err) + } + if status != "wait" { + t.Fatalf("status = %q, want wait", status) + } + }) + + t.Run("GetLogs", func(t *testing.T) { + lines, latest, err := client.GetLogs(0, 10) + if err != nil { + t.Fatalf("GetLogs: %v", err) + } + if len(lines) == 0 || latest == 0 { + t.Fatalf("expected log lines, got lines=%v latest=%d", lines, latest) + } + }) + + t.Run("PutBoolField", func(t *testing.T) { + if err := client.PutBoolField("debug", true); err != nil { + t.Fatalf("PutBoolField: %v", err) + } + }) + + t.Run("StartOAuth", func(t *testing.T) { + data, err := client.getJSON("/v8/management/oauth/auth-url?provider=codex&is_webui=true") + if err != nil { + t.Fatalf("oauth auth-url: %v", err) + } + if getString(data, "url") == "" { + t.Fatalf("expected auth url") + } + }) + + srv.assertNoV0(t) +} + +// TestClient_V0Fallback verifies the client still works against a legacy server +// that only exposes /v0/management (no v8 routes): each call must fall back. +func TestClient_V0Fallback(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/v8/") { + http.NotFound(w, r) + return + } + switch { + case r.URL.Path == "/v0/management/config": + writeJSON(t, w, map[string]any{"debug": true, "port": 8317}) + case r.URL.Path == "/v0/management/api-keys": + writeJSON(t, w, map[string]any{"api-keys": []string{"k1"}}) + case r.URL.Path == "/v0/management/gemini-api-key": + writeJSON(t, w, map[string]any{"gemini-api-key": []any{map[string]any{"api-key": "G1"}}}) + case r.URL.Path == "/v0/management/get-auth-status": + writeJSON(t, w, map[string]any{"status": "wait"}) + case r.URL.Path == "/v0/management/logs": + writeJSON(t, w, map[string]any{"lines": []string{"x"}, "latest-timestamp": 3}) + case r.URL.Path == "/v0/management/debug": + writeJSON(t, w, map[string]any{"debug": true}) + case r.URL.Path == "/v0/management/auth-files": + writeJSON(t, w, map[string]any{"files": []any{map[string]any{"name": "a"}}}) + default: + http.NotFound(w, r) + } + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + if cfg, err := client.GetConfig(); err != nil || getBool(cfg, "debug") != true { + t.Fatalf("GetConfig fallback: cfg=%v err=%v", cfg, err) + } + if keys, err := client.GetAPIKeys(); err != nil || len(keys) != 1 { + t.Fatalf("GetAPIKeys fallback: keys=%v err=%v", keys, err) + } + if keys, err := client.GetGeminiKeys(); err != nil || len(keys) != 1 { + t.Fatalf("GetGeminiKeys fallback: keys=%v err=%v", keys, err) + } + if status, _, err := client.GetAuthStatus("s"); err != nil || status != "wait" { + t.Fatalf("GetAuthStatus fallback: status=%q err=%v", status, err) + } + if lines, latest, err := client.GetLogs(0, 5); err != nil || len(lines) == 0 || latest == 0 { + t.Fatalf("GetLogs fallback: lines=%v latest=%d err=%v", lines, latest, err) + } + if dbg, err := client.GetDebug(); err != nil || !dbg { + t.Fatalf("GetDebug fallback: dbg=%v err=%v", dbg, err) + } + if files, err := client.GetAuthFiles(); err != nil || len(files) != 1 { + t.Fatalf("GetAuthFiles fallback: files=%v err=%v", files, err) + } +} + +// TestClient_V8OAuthStartPrefersSharedEndpoint ensures OAuth start goes to the +// shared v8 route with the canonical provider parameter, not the legacy path. +func TestClient_V8OAuthStartPrefersSharedEndpoint(t *testing.T) { + var gotPath, gotProvider string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotProvider = r.URL.Query().Get("provider") + writeJSON(t, w, map[string]any{"url": "https://x", "state": "s"}) + })) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + data, err := client.StartOAuthFlow("anthropic-auth-url") + if err != nil { + t.Fatalf("StartOAuthFlow: %v", err) + } + if gotPath != "/v8/management/oauth/auth-url" { + t.Fatalf("path = %q, want /v8/management/oauth/auth-url", gotPath) + } + if gotProvider != "claude" { + t.Fatalf("provider = %q, want claude", gotProvider) + } + if getString(data, "url") == "" { + t.Fatalf("expected url") + } +} + +// TestClient_V8MissingNodeWrites verifies that an absent config node is treated +// as an empty value on the v8 contract (not a missing route), so the TUI can +// create the first access.api-keys entry and reads empty provider lists. +func TestClient_V8MissingNodeWrites(t *testing.T) { + var v0Requests int32 + var ifMatchSeen string + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&v0Requests, 1) + http.NotFound(w, r) + }) + // Root config exists (proves the v8 contract), child nodes may 404. + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"root-etag"`) + writeJSON(t, w, map[string]any{"server": map[string]any{"port": 8317}}) + }) + _ = ifMatchSeen + mux.HandleFunc("/v8/management/config/access/api-keys", func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + // Node not set on the server. + http.Error(w, `{"error":"not_found"}`, http.StatusNotFound) + case http.MethodPut: + ifMatchSeen = r.Header.Get("If-Match") + w.WriteHeader(http.StatusOK) + default: + http.Error(w, "method", http.StatusMethodNotAllowed) + } + }) + _ = ifMatchSeen + mux.HandleFunc("/v8/management/config/api-keys/codex", func(w http.ResponseWriter, r *http.Request) { + http.Error(w, `{"error":"not_found"}`, http.StatusNotFound) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + keys, err := client.GetAPIKeys() + if err != nil { + t.Fatalf("GetAPIKeys on missing node: %v", err) + } + if len(keys) != 0 { + t.Fatalf("expected empty list for missing node, got %v", keys) + } + + codex, err := client.GetCodexKeys() + if err != nil { + t.Fatalf("GetCodexKeys on missing node: %v", err) + } + if len(codex) != 0 { + t.Fatalf("expected empty provider list, got %v", codex) + } + + if err := client.AddAPIKey("first-key"); err != nil { + t.Fatalf("AddAPIKey creating first key: %v", err) + } + if atomic.LoadInt32(&v0Requests) != 0 { + t.Fatalf("v0 fallback used on v8-only server: %d requests", v0Requests) + } + // A create on a missing node must still be conditional: the root config + // ETag guards the write so a concurrent creator is not silently overwritten. + if ifMatchSeen != `"root-etag"` { + t.Fatalf("If-Match on missing-node create = %q, want %q", ifMatchSeen, `"root-etag"`) + } +} + +// TestClient_V8APIKeyConditionalWrite ensures the config ETag captured on read +// is sent as If-Match on the subsequent replace, guarding concurrent edits. +func TestClient_V8APIKeyConditionalWrite(t *testing.T) { + var ifMatch string + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }) + // Read path now goes through the root config document so the list value and + // its ETag share one versioned snapshot. + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"abc123"`) + writeJSON(t, w, map[string]any{"access": map[string]any{"api-keys": []string{"k1"}}}) + }) + mux.HandleFunc("/v8/management/config/access/api-keys", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPut { + ifMatch = r.Header.Get("If-Match") + w.WriteHeader(http.StatusOK) + return + } + http.Error(w, "method", http.StatusMethodNotAllowed) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + if err := client.EditAPIKey(0, "k1-new"); err != nil { + t.Fatalf("EditAPIKey: %v", err) + } + if ifMatch != `"abc123"` { + t.Fatalf("If-Match = %q, want %q", ifMatch, `"abc123"`) + } +} + +// TestClient_V8OpenAICompatPreservesGroups verifies openai-compatibility +// upstream entries are returned intact (name/base-url/prefix kept), not +// expanded into per-key rows. +func TestClient_V8OpenAICompatPreservesGroups(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, map[string]any{}) + }) + mux.HandleFunc("/v8/management/config/api-keys/openai-compatibility", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []any{ + map[string]any{ + "name": "custom-upstream", + "base-url": "https://api.example.com", + "prefix": "cu", + "keys": []any{ + map[string]any{"api-key": "k1"}, + map[string]any{"api-key": "k2"}, + }, + }, + }) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + entries, err := client.GetOpenAICompat() + if err != nil { + t.Fatalf("GetOpenAICompat: %v", err) + } + if len(entries) != 1 { + t.Fatalf("expected 1 upstream entry, got %d: %v", len(entries), entries) + } + if getString(entries[0], "name") != "custom-upstream" { + t.Fatalf("name lost: %v", entries[0]) + } + if getString(entries[0], "base-url") != "https://api.example.com" { + t.Fatalf("base-url lost: %v", entries[0]) + } +} + +// TestClient_V8Business404NotFallback ensures a resource-level 404 on a +// reachable v8 route is surfaced to the caller, not silently retried on v0. +func TestClient_V8Business404NotFallback(t *testing.T) { + var v0Calls int32 + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&v0Calls, 1) + w.WriteHeader(http.StatusOK) // would wrongly "succeed" if retried + }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, map[string]any{}) + }) + mux.HandleFunc("/v8/management/credentials/status", func(w http.ResponseWriter, r *http.Request) { + http.Error(w, `{"error":"credential not found"}`, http.StatusNotFound) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + err := client.ToggleAuthFile("missing.json", true) + if err == nil { + t.Fatalf("expected error for missing credential") + } + if atomic.LoadInt32(&v0Calls) != 0 { + t.Fatalf("business 404 was retried on v0 (%d calls)", v0Calls) + } +} + +// TestClient_ProbeFailureNotCached verifies a transient probe failure does not +// poison the client into treating all v8 config reads as empty. +func TestClient_ProbeFailureNotCached(t *testing.T) { + var configCalls int32 + failFirst := true + mux := http.NewServeMux() + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&configCalls, 1) + if failFirst { + failFirst = false + w.WriteHeader(http.StatusServiceUnavailable) + return + } + writeJSON(t, w, map[string]any{"access": map[string]any{"api-keys": []string{"k"}}}) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + // First probe fails transiently; must not be cached as definitive. + keys, err := client.GetAPIKeys() + if err == nil && len(keys) == 0 { + t.Fatalf("transient probe failure turned into an empty key list") + } + // A second call after recovery should now read real keys. + keys, err = client.GetAPIKeys() + if err != nil { + t.Fatalf("GetAPIKeys after recovery: %v", err) + } +} + +// TestClient_V8DeleteAuthFileBusiness404 ensures a credential-not-found 404 on +// a reachable v8 route does not trigger a v0 delete. +func TestClient_V8DeleteAuthFileBusiness404(t *testing.T) { + var v0Calls int32 + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&v0Calls, 1) + w.WriteHeader(http.StatusOK) + }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, map[string]any{}) + }) + mux.HandleFunc("/v8/management/credentials", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + http.Error(w, `{"error":"credential not found"}`, http.StatusNotFound) + return + } + writeJSON(t, w, map[string]any{"files": []any{}}) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + err := client.DeleteAuthFile("missing.json") + if err == nil { + t.Fatalf("expected error for missing credential") + } + if atomic.LoadInt32(&v0Calls) != 0 { + t.Fatalf("business 404 delete was retried on v0 (%d calls)", v0Calls) + } +} + +// TestClient_V8ProviderKeyNullInheritsGroup verifies a per-key null field +// inherits the group value, matching v8 semantics. +func TestClient_V8ProviderKeyNullInheritsGroup(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, map[string]any{}) + }) + mux.HandleFunc("/v8/management/config/api-keys/gemini", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []any{ + map[string]any{ + "name": "g1", + "prefix": "grp", + "base-url": "https://g.example.com", + "proxy-url": "socks5://p", + "keys": []any{ + map[string]any{"api-key": "k1", "prefix": nil}, + map[string]any{"api-key": "k2"}, + }, + }, + }) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + keys, err := client.GetGeminiKeys() + if err != nil { + t.Fatalf("GetGeminiKeys: %v", err) + } + if len(keys) != 2 { + t.Fatalf("expected 2 keys, got %v", keys) + } + // k1 has explicit null prefix -> inherits "grp"; k2 absent prefix -> inherits too. + if getString(keys[0], "prefix") != "grp" { + t.Fatalf("null prefix did not inherit group: %v", keys[0]) + } + if getString(keys[0], "base-url") != "https://g.example.com" { + t.Fatalf("base-url not inherited: %v", keys[0]) + } +} + +// TestClient_V8MissingETagRefusesWrite ensures an api-keys write is refused +// rather than sent unconditionally when the server supplies no ETag. +func TestClient_V8MissingETagRefusesWrite(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + // No ETag header at all. + writeJSON(t, w, map[string]any{"access": map[string]any{"api-keys": []string{"k1"}}}) + }) + mux.HandleFunc("/v8/management/config/access/api-keys", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + if err := client.EditAPIKey(0, "x"); err == nil { + t.Fatalf("expected refusal to write without a config version") + } +} + +// TestClient_ProbeIndeterminateBlocksFallback ensures a transient probe failure +// prevents a v0 write rather than silently switching protocols. +func TestClient_ProbeIndeterminateBlocksFallback(t *testing.T) { + var v0Calls int32 + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&v0Calls, 1) + w.WriteHeader(http.StatusOK) + }) + // Root config probe fails transiently (503): v8 support cannot be decided. + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + }) + mux.HandleFunc("/v8/management/credentials", func(w http.ResponseWriter, r *http.Request) { + http.Error(w, `{"error":"x"}`, http.StatusNotFound) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + err := client.DeleteAuthFile("f.json") + if err == nil { + t.Fatalf("expected error when v8 support is indeterminate") + } + if atomic.LoadInt32(&v0Calls) != 0 { + t.Fatalf("write fell back to v0 with indeterminate v8 support") + } +} + +// TestCheckManagementSupport exercises the pre-flight compatibility probe. +func TestCheckManagementSupport(t *testing.T) { + t.Run("v8 present", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v8/management/config" { + writeJSON(t, w, map[string]any{}) + return + } + http.NotFound(w, r) + })) + defer srv.Close() + if err := NewClientWithBaseURL(srv.URL, "x").CheckManagementSupport(); err != nil { + t.Fatalf("v8 server should be supported: %v", err) + } + }) + + t.Run("v0 only", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v0/management/config" { + writeJSON(t, w, map[string]any{}) + return + } + http.NotFound(w, r) + })) + defer srv.Close() + if err := NewClientWithBaseURL(srv.URL, "x").CheckManagementSupport(); err != nil { + t.Fatalf("v0-only server should be supported: %v", err) + } + }) + + t.Run("neither", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NotFound(w, r) + })) + defer srv.Close() + err := NewClientWithBaseURL(srv.URL, "x").CheckManagementSupport() + if err == nil { + t.Fatalf("expected unsupported-server error") + } + }) +} + +// TestClient_V8IndexGuardPreventsStaleDelete ensures a selection made on an +// older snapshot cannot delete the wrong entry after a concurrent reorder. +func TestClient_V8IndexGuardPreventsStaleDelete(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }) + // Server list has since changed: A removed, B is now at index 0. + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"e2"`) + writeJSON(t, w, map[string]any{"access": map[string]any{"api-keys": []string{"B", "C"}}}) + }) + mux.HandleFunc("/v8/management/config/access/api-keys", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + // User selected index 1 when the displayed list was [A,B,C] and value B. + // On the server it is now [B,C]; index 1 holds C, so the guard must refuse. + err := client.DeleteAPIKey(1, "B") + if err == nil { + t.Fatalf("expected stale-selection refusal") + } +} + +// TestClient_V8StaleSelectionAfterRefresh simulates pressing edit on index 1 +// (value B) and, before submit, a background refresh swapping the list. The +// guard uses the value captured at intent time, so the write must be refused. +func TestClient_V8StaleSelectionAfterRefresh(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"e3"`) + // Refreshed list: A removed; index 1 now holds C, not the B the user picked. + writeJSON(t, w, map[string]any{"access": map[string]any{"api-keys": []string{"B", "C"}}}) + }) + mux.HandleFunc("/v8/management/config/access/api-keys", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + // pendingValue captured at intent time was "B"; index 1 now holds "C". + if err := client.EditAPIKey(1, "B-edited", "B"); err == nil { + t.Fatalf("expected refusal editing a shifted entry") + } +} + +// TestClient_V8PreconditionFailedNotRetried ensures a 412 from a concurrent +// write is surfaced and NOT retried or turned into a v0 request. +func TestClient_V8PreconditionFailedNotRetried(t *testing.T) { + var v0Calls, putCalls int32 + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&v0Calls, 1) + w.WriteHeader(http.StatusOK) + }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"old"`) + writeJSON(t, w, map[string]any{"access": map[string]any{"api-keys": []string{"k"}}}) + }) + mux.HandleFunc("/v8/management/config/access/api-keys", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPut { + atomic.AddInt32(&putCalls, 1) + http.Error(w, `{"error":"precondition_failed"}`, http.StatusPreconditionFailed) + return + } + http.Error(w, "method", http.StatusMethodNotAllowed) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + err := client.AddAPIKey("k2") + if err == nil { + t.Fatalf("expected 412 to surface") + } + if atomic.LoadInt32(&v0Calls) != 0 { + t.Fatalf("412 must not fall back to v0") + } +} + +// TestClient_V8EmptyKeysGroupYieldsNoEntry ensures a provider group with an +// explicit empty keys list produces no phantom key in the TUI. +func TestClient_V8EmptyKeysGroupYieldsNoEntry(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/v0/", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, map[string]any{}) + }) + mux.HandleFunc("/v8/management/config/api-keys/claude", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []any{map[string]any{"name": "empty-group", "keys": []any{}}}) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + client := NewClientWithBaseURL(srv.URL, "secret") + + keys, err := client.GetClaudeKeys() + if err != nil { + t.Fatalf("GetClaudeKeys: %v", err) + } + if len(keys) != 0 { + t.Fatalf("empty keys group rendered a phantom entry: %v", keys) + } +} + +// TestRunWithBaseURLUnsupportedExitsNonZero drives RunWithBaseURL against a +// server that exposes neither contract and asserts a non-nil error (non-zero +// exit) is returned rather than silently rendering and exiting 0. +func TestRunWithBaseURLUnsupportedExitsNonZero(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NotFound(w, r) + })) + defer srv.Close() + + // hook == nil -> client mode -> pre-flight support check runs. + err := RunWithBaseURL(srv.URL, "secret", nil, io.Discard) + if err == nil { + t.Fatalf("expected non-nil error for unsupported server") + } +} + +// TestApp_AuthThenUnsupportedExitsNonZero simulates the auth-then-404 flow: an +// auth-gated probe admits the user, credentials fail at runtime with both +// contracts absent, and the resulting fatal error must propagate through the +// final model so Run returns non-zero. +func TestApp_AuthThenUnsupportedExitsNonZero(t *testing.T) { + var authed int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") == "" { + w.WriteHeader(http.StatusUnauthorized) + return + } + atomic.AddInt32(&authed, 1) + http.NotFound(w, r) + })) + defer srv.Close() + + // Pre-flight sees 401 (auth-gated) => supported, so we get past it. + app := NewAppWithBaseURL(srv.URL, "", nil) + if app.fatalErr != nil { + t.Fatalf("pre-flight should not mark an auth-gated server fatal") + } + // Simulate entering a password then the connect discovering unsupported. + cmd := app.connectWithPassword("pw") + msg := cmd() + acm, ok := msg.(authConnectMsg) + if !ok { + t.Fatalf("expected authConnectMsg, got %T", msg) + } + if acm.fatal == nil { + t.Fatalf("expected fatal error when both contracts are absent after auth") + } + // Feed through Update to confirm fatalErr + quit propagation. + next, _ := app.Update(acm) + if nextApp, ok := next.(App); !ok || nextApp.fatalErr == nil { + t.Fatalf("fatal error did not propagate to the app model") + } +} + +// TestApp_AuthTransientProbeStaysRetryable ensures a transient support-probe +// failure (e.g. 503) after a wrong/absent credential is NOT fatal: the user +// keeps the retryable auth-gate error instead of being exited. +func TestApp_AuthTransientProbeStaysRetryable(t *testing.T) { + var calls int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&calls, 1) + switch r.URL.Path { + case "/v8/management/config": + w.WriteHeader(http.StatusServiceUnavailable) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + + app := NewAppWithBaseURL(srv.URL, "", nil) + msg := app.connectWithPassword("pw")() + acm, ok := msg.(authConnectMsg) + if !ok { + t.Fatalf("expected authConnectMsg, got %T", msg) + } + // v8 503 is transient, v0 404 is absent: not a definitive unsupported. + if acm.fatal != nil { + t.Fatalf("transient probe failure must not be fatal, got %v", acm.fatal) + } + if acm.err == nil { + t.Fatalf("expected a retryable auth error") + } +} + +// TestRunWithBaseURLTransientProbeNotFatal asserts the startup pre-flight only +// exits on a definitive unsupported server, not on a transient probe failure. +func TestRunWithBaseURLTransientProbeNotFatal(t *testing.T) { + // v8 -> 503 (transient), v0 -> 404. Not definitively unsupported. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v8/management/config" { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + http.NotFound(w, r) + })) + defer srv.Close() + + // Pre-flight must NOT return a fatal error; it falls through to Bubble Tea, + // which runs until its window closes. We therefore assert CheckManagement + // Support alone does not classify this as ErrManagementUnsupported. + err := NewClientWithBaseURL(srv.URL, "x").CheckManagementSupport() + if errors.Is(err, ErrManagementUnsupported) { + t.Fatalf("transient v8 failure must not be reported as ErrManagementUnsupported") + } +} diff --git a/internal/tui/keys_tab.go b/internal/tui/keys_tab.go index 90ef2ddddea..633c889c596 100644 --- a/internal/tui/keys_tab.go +++ b/internal/tui/keys_tab.go @@ -36,6 +36,9 @@ type keysTabModel struct { adding bool editIdx int editInput textinput.Model + // pendingValue binds the key the user targeted when they pressed e/d, so a + // background refresh cannot make a later write hit a shifted entry. + pendingValue string } type keysDataMsg struct { @@ -151,7 +154,7 @@ func (m keysTabModel) Update(msg tea.Msg) (keysTabModel, tea.Cmd) { } } return m, func() tea.Msg { - err := m.client.EditAPIKey(editIdx, value) + err := m.client.EditAPIKey(editIdx, value, m.pendingValue) if err != nil { return keyActionMsg{err: err} } @@ -176,9 +179,10 @@ func (m keysTabModel) Update(msg tea.Msg) (keysTabModel, tea.Cmd) { switch msg.String() { case "y", "Y": idx := m.confirm + expected := m.pendingValue m.confirm = -1 return m, func() tea.Msg { - err := m.client.DeleteAPIKey(idx) + err := m.client.DeleteAPIKey(idx, expected) if err != nil { return keyActionMsg{err: err} } @@ -221,6 +225,7 @@ func (m keysTabModel) Update(msg tea.Msg) (keysTabModel, tea.Cmd) { m.editing = true m.adding = false m.editIdx = m.cursor + m.pendingValue = m.keys[m.cursor] m.editInput.SetValue(m.keys[m.cursor]) m.editInput.Prompt = T("edit_key_prompt") m.editInput.Focus() @@ -232,6 +237,7 @@ func (m keysTabModel) Update(msg tea.Msg) (keysTabModel, tea.Cmd) { // Delete selected key if m.cursor < len(m.keys) { m.confirm = m.cursor + m.pendingValue = m.keys[m.cursor] m.viewport.SetContent(m.renderContent()) } return m, nil diff --git a/internal/tui/oauth_tab.go b/internal/tui/oauth_tab.go index f13e4983704..545ccee1746 100644 --- a/internal/tui/oauth_tab.go +++ b/internal/tui/oauth_tab.go @@ -14,7 +14,7 @@ import ( // oauthProvider represents an OAuth provider option. type oauthProvider struct { name string - apiPath string // management API path + apiPath string // legacy v0 management path segment (e.g. "codex-auth-url") emoji string deviceFlow bool // true for RFC 8628 device-code providers } @@ -45,6 +45,7 @@ type oauthTabModel struct { authURL string // auth URL to display authState string // OAuth state parameter providerName string // current provider name + providerKey string // v8 provider identifier for the callback userCode string // device-code user_code (optional) deviceFlow bool // true when waiting on device authorization expiresIn int // device-code / poll timeout in seconds @@ -77,6 +78,7 @@ type oauthStartMsg struct { url string state string providerName string + providerKey string userCode string deviceFlow bool expiresIn int @@ -134,6 +136,7 @@ func (m oauthTabModel) Update(msg tea.Msg) (oauthTabModel, tea.Cmd) { m.authURL = msg.url m.authState = msg.state m.providerName = msg.providerName + m.providerKey = msg.providerKey m.userCode = msg.userCode m.deviceFlow = msg.deviceFlow m.expiresIn = msg.expiresIn @@ -281,8 +284,8 @@ func (m oauthTabModel) Update(msg tea.Msg) (oauthTabModel, tea.Cmd) { func (m oauthTabModel) startOAuth(provider oauthProvider, generation int) tea.Cmd { return func() tea.Msg { - // Call the auth URL endpoint with is_webui=true - data, err := m.client.getJSON("/v0/management/" + provider.apiPath + "?is_webui=true") + // Call the shared v8 auth-url endpoint (falls back to the v0 route). + data, err := m.client.StartOAuthFlow(provider.apiPath) if err != nil { return oauthStartMsg{generation: generation, err: fmt.Errorf("failed to start %s login: %w", provider.name, err)} } @@ -305,6 +308,7 @@ func (m oauthTabModel) startOAuth(provider oauthProvider, generation int) tea.Cm url: authURL, state: state, providerName: provider.name, + providerKey: oauthV8Provider[provider.apiPath], userCode: userCode, deviceFlow: deviceFlow, expiresIn: expiresIn, @@ -344,37 +348,19 @@ func (m oauthTabModel) cancelOAuthSession(state string) tea.Cmd { func (m oauthTabModel) submitCallback(callbackURL string) tea.Cmd { return func() tea.Msg { - // Determine provider from current context - providerKey := "" - for _, p := range oauthProviders { - if p.name == m.providerName { - // Map provider name to the canonical key the API expects - switch p.apiPath { - case "anthropic-auth-url": - providerKey = "anthropic" - case "codex-auth-url": - providerKey = "codex" - case "antigravity-auth-url": - providerKey = "antigravity" - case "kimi-auth-url": - providerKey = "kimi" - case "kimi-ai-auth-url": - providerKey = "kimi-ai" - case "xai-auth-url": - providerKey = "xai" - case "meta-auth-url": - providerKey = "meta" + // The v8 provider key recorded when the flow started; derive it from the + // provider list as a fallback for sessions started before this field. + providerKey := m.providerKey + if providerKey == "" { + for _, p := range oauthProviders { + if p.name == m.providerName { + providerKey = oauthV8Provider[p.apiPath] + break } - break } } - body := map[string]string{ - "provider": providerKey, - "redirect_url": callbackURL, - "state": m.authState, - } - err := m.client.postJSON("/v0/management/oauth-callback", body) + err := m.client.SubmitOAuthCallback(providerKey, callbackURL, m.authState) if err != nil { return oauthCallbackSubmitMsg{err: err} } diff --git a/internal/util/nocopy_invariant_test.go b/internal/util/nocopy_invariant_test.go index 368e68c6e92..a96ddb47c78 100644 --- a/internal/util/nocopy_invariant_test.go +++ b/internal/util/nocopy_invariant_test.go @@ -116,6 +116,7 @@ var reviewedInPlaceByteWrites = map[string]reviewedInPlaceByteWrite{ "internal/client/codex/live/tcp_proxy.go": {1, "copies header and payload into a freshly allocated frame"}, "internal/home/client.go": {1, "zeroes a secret buffer after json.Unmarshal has copied every value out"}, "internal/pluginstore/auth.go": {1, "zeroes a locally built credential buffer after base64 encoding copied it out"}, + "sdk/cliproxy/auth/selector_weighted.go": {2, "shifts weightedPoolMember bookkeeping structs when inserting or removing members; no byte of any JSON payload is rewritten"}, } // TestInPlaceByteWritesAreReviewed keeps the set of in-place byte writes small diff --git a/internal/util/provider.go b/internal/util/provider.go index 810a9cb2d0b..e29e5c1e5a1 100644 --- a/internal/util/provider.go +++ b/internal/util/provider.go @@ -215,7 +215,7 @@ func MaskAuthorizationHeader(value string) string { // // Behavior by header key (case-insensitive): // - "Authorization": Preserve the auth type prefix (e.g., "Bearer ") and mask only the credential part. -// - Headers containing "api-key": Mask the entire value using HideAPIKey. +// - Headers containing "api-key", "apikey", "token", "secret", or "cookie": Mask the entire value using HideAPIKey. // - Others: Return the original value unchanged. // // Parameters: @@ -232,7 +232,8 @@ func MaskSensitiveHeaderValue(key, value string) string { case strings.Contains(lowerKey, "api-key"), strings.Contains(lowerKey, "apikey"), strings.Contains(lowerKey, "token"), - strings.Contains(lowerKey, "secret"): + strings.Contains(lowerKey, "secret"), + strings.Contains(lowerKey, "cookie"): return HideAPIKey(value) default: return value diff --git a/internal/util/provider_test.go b/internal/util/provider_test.go index daf45c8db6d..24665d6415a 100644 --- a/internal/util/provider_test.go +++ b/internal/util/provider_test.go @@ -37,3 +37,25 @@ func TestMaskSensitiveQueryMasksValue(t *testing.T) { } }) } + +func TestMaskSensitiveHeaderValueMasksCookiesAndSecrets(t *testing.T) { + for _, tc := range []struct { + key string + value string + wantLeak string + }{ + {key: "Authorization", value: "Bearer super-secret-token-value", wantLeak: "super-secret-token-value"}, + {key: "X-Api-Key", value: "sk-super-secret-api-key", wantLeak: "sk-super-secret-api-key"}, + {key: "Cookie", value: "session=super-secret-cookie", wantLeak: "super-secret-cookie"}, + {key: "Set-Cookie", value: "__cf_bm=super-secret-cf-cookie; Path=/; HttpOnly", wantLeak: "super-secret-cf-cookie"}, + } { + masked := util.MaskSensitiveHeaderValue(tc.key, tc.value) + if strings.Contains(masked, tc.wantLeak) { + t.Fatalf("MaskSensitiveHeaderValue(%q) leaked %q in %q", tc.key, tc.wantLeak, masked) + } + } + + if got := util.MaskSensitiveHeaderValue("X-Request-Id", "req-plain-123"); got != "req-plain-123" { + t.Fatalf("MaskSensitiveHeaderValue(X-Request-Id) = %q, want unchanged", got) + } +} diff --git a/internal/watcher/auth_file_snapshot.go b/internal/watcher/auth_file_snapshot.go index 4162e6060db..10c56971dae 100644 --- a/internal/watcher/auth_file_snapshot.go +++ b/internal/watcher/auth_file_snapshot.go @@ -18,7 +18,7 @@ func (w *Watcher) SnapshotAuthFile(path string) ([]*coreauth.Auth, error) { } w.clientsMutex.RLock() cfg := w.config - authDir := w.authDir + authDir := w.currentAuthDirLocked() parser := w.pluginAuthParser w.clientsMutex.RUnlock() if cfg == nil || authDir == "" { diff --git a/internal/watcher/clients.go b/internal/watcher/clients.go index 98bf690dfde..e8ddbccebe8 100644 --- a/internal/watcher/clients.go +++ b/internal/watcher/clients.go @@ -94,7 +94,7 @@ func (w *Watcher) reloadClients(rescanAuth bool, affectedOAuthProviders []string parser := w.pluginAuthParser w.clientsMutex.RUnlock() - if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir); errResolveAuthDir != nil { + if resolvedAuthDir, errResolveAuthDir := w.resolveAuthDirForConfig(cfg); errResolveAuthDir != nil { log.Errorf("failed to resolve auth directory for hash cache: %v", errResolveAuthDir) } else if resolvedAuthDir != "" { entries, errReadDir := os.ReadDir(resolvedAuthDir) @@ -254,7 +254,7 @@ func (w *Watcher) rereadDiscardedFileSnapshot(auth *coreauth.Auth) { w.clientsMutex.Lock() existing := w.currentAuths[auth.ID] - if existing == nil || !existing.SameFileSnapshot(auth) { + if existing == nil || !existing.SameFileSnapshot(auth) || !w.isPathInCurrentAuthDirLocked(path) { w.clientsMutex.Unlock() return } @@ -312,6 +312,9 @@ func (w *Watcher) invalidateAuthFileHashLocked(path string) string { } func (w *Watcher) addOrUpdateClientLocked(path string) { + if !w.isPathInCurrentAuthDir(path) { + return + } w.observeAuthFile(path) data, errRead := os.ReadFile(path) if errRead != nil { @@ -341,12 +344,13 @@ func (w *Watcher) addOrUpdateClientLocked(path string) { w.clientsMutex.Unlock() return } + if !w.isPathInCurrentAuthDirLocked(normalized) { + w.clientsMutex.Unlock() + return + } cfg := w.config - authDir := w.authDir + authDir := w.currentAuthDirLocked() parser := w.pluginAuthParser - if w.fileAuthsByPath == nil { - w.fileAuthsByPath = make(map[string]map[string]*coreauth.Auth) - } if prev, ok := w.lastAuthHashes[normalized]; ok && prev == curHash { log.Debugf("auth file unchanged (hash match), skipping reload: %s", filepath.Base(path)) w.clientsMutex.Unlock() @@ -360,23 +364,6 @@ func (w *Watcher) addOrUpdateClientLocked(path string) { oldAuth = cached.Clone() } } - - // Update caches - if w.lastAuthHashes == nil { - w.lastAuthHashes = make(map[string]string) - } - w.lastAuthHashes[normalized] = curHash - if cacheAuthContents { - if w.lastAuthContents == nil { - w.lastAuthContents = make(map[string]*coreauth.Auth) - } - w.lastAuthContents[normalized] = &newAuth - } - - oldByID := make(map[string]*coreauth.Auth, len(w.fileAuthsByPath[normalized])) - for id, a := range w.fileAuthsByPath[normalized] { - oldByID[id] = a - } w.clientsMutex.Unlock() // Compute and log field changes @@ -403,6 +390,27 @@ func (w *Watcher) addOrUpdateClientLocked(path string) { } newByID := authSliceToMap(generated) w.clientsMutex.Lock() + if w.config == nil || !w.isPathInCurrentAuthDirLocked(normalized) || (authDir != "" && !w.sameNormalizedAuthPath(authDir, w.currentAuthDirLocked())) { + w.clientsMutex.Unlock() + return + } + if w.fileAuthsByPath == nil { + w.fileAuthsByPath = make(map[string]map[string]*coreauth.Auth) + } + if w.lastAuthHashes == nil { + w.lastAuthHashes = make(map[string]string) + } + w.lastAuthHashes[normalized] = curHash + if cacheAuthContents { + if w.lastAuthContents == nil { + w.lastAuthContents = make(map[string]*coreauth.Auth) + } + w.lastAuthContents[normalized] = &newAuth + } + oldByID := make(map[string]*coreauth.Auth, len(w.fileAuthsByPath[normalized])) + for id, a := range w.fileAuthsByPath[normalized] { + oldByID[id] = a + } if len(newByID) > 0 { w.fileAuthsByPath[normalized] = authIDSet(newByID) } else { @@ -426,9 +434,16 @@ func (w *Watcher) removeClient(path string) { } func (w *Watcher) removeClientLocked(path string) { + if !w.isPathInCurrentAuthDir(path) { + return + } w.observeAuthFile(path) normalized := w.normalizeAuthPath(path) w.clientsMutex.Lock() + if !w.isPathInCurrentAuthDirLocked(normalized) { + w.clientsMutex.Unlock() + return + } oldByID := make(map[string]*coreauth.Auth, len(w.fileAuthsByPath[normalized])) for id, a := range w.fileAuthsByPath[normalized] { oldByID[id] = a @@ -504,11 +519,22 @@ func authIDSet(auths map[string]*coreauth.Auth) map[string]*coreauth.Auth { return set } +func (w *Watcher) resolveAuthDirForConfig(cfg *config.Config) (string, error) { + raw := "" + if cfg != nil { + raw = strings.TrimSpace(cfg.AuthDir) + } + if raw == "" { + raw = w.currentAuthDir() + } + return util.ResolveAuthDir(raw) +} + func (w *Watcher) loadFileClients(cfg *config.Config) int { authFileCount := 0 successfulAuthCount := 0 - authDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir) + authDir, errResolveAuthDir := w.resolveAuthDirForConfig(cfg) if errResolveAuthDir != nil { log.Errorf("failed to resolve auth directory: %v", errResolveAuthDir) return 0 diff --git a/internal/watcher/config_reload.go b/internal/watcher/config_reload.go index b9d5aabbfe0..5738909d67b 100644 --- a/internal/watcher/config_reload.go +++ b/internal/watcher/config_reload.go @@ -7,6 +7,7 @@ import ( "encoding/hex" "os" "reflect" + "strings" "time" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" @@ -102,22 +103,32 @@ func (w *Watcher) reloadConfig() bool { return false } + resolvedNewAuthDir := "" if w.mirroredAuthDir != "" { newConfig.AuthDir = w.mirroredAuthDir + resolvedNewAuthDir = w.mirroredAuthDir } else { if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(newConfig.AuthDir); errResolveAuthDir != nil { log.Errorf("failed to resolve auth directory from config: %v", errResolveAuthDir) } else { newConfig.AuthDir = resolvedAuthDir + resolvedNewAuthDir = resolvedAuthDir } } + w.authRescanMu.Lock() w.clientsMutex.Lock() var oldConfig *config.Config _ = yaml.Unmarshal(w.oldConfigYaml, &oldConfig) + prevAuthDir := w.authDir w.oldConfigYaml, _ = yaml.Marshal(newConfig) w.config = newConfig + if strings.TrimSpace(resolvedNewAuthDir) != "" { + w.authDir = resolvedNewAuthDir + } + curAuthDir := w.authDir w.clientsMutex.Unlock() + w.authRescanMu.Unlock() var affectedOAuthProviders []string if oldConfig != nil { @@ -141,7 +152,10 @@ func (w *Watcher) reloadConfig() bool { } } - authDirChanged := oldConfig == nil || oldConfig.AuthDir != newConfig.AuthDir + authDirChanged := oldConfig == nil || oldConfig.AuthDir != newConfig.AuthDir || prevAuthDir != curAuthDir + if authDirChanged { + w.syncAuthDirWatch() + } retryConfigChanged := oldConfig != nil && (oldConfig.RequestRetry != newConfig.RequestRetry || oldConfig.MaxRetryInterval != newConfig.MaxRetryInterval || oldConfig.MaxRetryCredentials != newConfig.MaxRetryCredentials) forceAuthRefresh := oldConfig != nil && (oldConfig.ForceModelPrefix != newConfig.ForceModelPrefix || !reflect.DeepEqual(oldConfig.OAuthModelAlias, newConfig.OAuthModelAlias) || !reflect.DeepEqual(oldConfig.OAuthSettings, newConfig.OAuthSettings) || retryConfigChanged) diff --git a/internal/watcher/diff/config_diff.go b/internal/watcher/diff/config_diff.go index 5ae60d3aeb8..29afaca3488 100644 --- a/internal/watcher/diff/config_diff.go +++ b/internal/watcher/diff/config_diff.go @@ -117,9 +117,21 @@ func BuildConfigChangeDetails(oldCfg, newCfg *config.Config) []string { if !reflect.DeepEqual(oldCfg.Antigravity.SensitiveWords, newCfg.Antigravity.SensitiveWords) { changes = append(changes, fmt.Sprintf("antigravity.sensitive-words: %d -> %d", len(oldCfg.Antigravity.SensitiveWords), len(newCfg.Antigravity.SensitiveWords))) } + if !equalStringMap(oldCfg.Antigravity.SensitiveWordsReplace, newCfg.Antigravity.SensitiveWordsReplace) { + changes = append(changes, fmt.Sprintf("antigravity.sensitive-words-replace: %d -> %d", len(oldCfg.Antigravity.SensitiveWordsReplace), len(newCfg.Antigravity.SensitiveWordsReplace))) + } + if !equalSensitivePatternRules(oldCfg.Antigravity.SensitivePatternsReplace, newCfg.Antigravity.SensitivePatternsReplace) { + changes = append(changes, fmt.Sprintf("antigravity.sensitive-patterns-replace: %d -> %d", len(oldCfg.Antigravity.SensitivePatternsReplace), len(newCfg.Antigravity.SensitivePatternsReplace))) + } if !reflect.DeepEqual(oldCfg.Devin.SensitiveWords, newCfg.Devin.SensitiveWords) { changes = append(changes, fmt.Sprintf("devin.sensitive-words: %d -> %d", len(oldCfg.Devin.SensitiveWords), len(newCfg.Devin.SensitiveWords))) } + if !equalStringMap(oldCfg.Devin.SensitiveWordsReplace, newCfg.Devin.SensitiveWordsReplace) { + changes = append(changes, fmt.Sprintf("devin.sensitive-words-replace: %d -> %d", len(oldCfg.Devin.SensitiveWordsReplace), len(newCfg.Devin.SensitiveWordsReplace))) + } + if !equalSensitivePatternRules(oldCfg.Devin.SensitivePatternsReplace, newCfg.Devin.SensitivePatternsReplace) { + changes = append(changes, fmt.Sprintf("devin.sensitive-patterns-replace: %d -> %d", len(oldCfg.Devin.SensitivePatternsReplace), len(newCfg.Devin.SensitivePatternsReplace))) + } oldEnabled := "" if oldCfg.Antigravity.ConnectionPool.Enabled != nil { oldEnabled = fmt.Sprintf("%t", *oldCfg.Antigravity.ConnectionPool.Enabled) @@ -173,6 +185,9 @@ func BuildConfigChangeDetails(oldCfg, newCfg *config.Config) []string { if oldCfg.Claude.ToolSearch != newCfg.Claude.ToolSearch { changes = append(changes, fmt.Sprintf("claude.tool-search: %t -> %t", oldCfg.Claude.ToolSearch, newCfg.Claude.ToolSearch)) } + if oldCfg.Claude.ServerSideFallback != newCfg.Claude.ServerSideFallback { + changes = append(changes, fmt.Sprintf("claude.server-side-fallback: %t -> %t", oldCfg.Claude.ServerSideFallback, newCfg.Claude.ServerSideFallback)) + } if oldCfg.XAI.InjectXSearch != newCfg.XAI.InjectXSearch { changes = append(changes, fmt.Sprintf("xai.inject-x-search: %t -> %t", oldCfg.XAI.InjectXSearch, newCfg.XAI.InjectXSearch)) } @@ -330,16 +345,28 @@ func BuildConfigChangeDetails(oldCfg, newCfg *config.Config) []string { changes = append(changes, fmt.Sprintf("claude[%d].fingerprint-profile: %s -> %s", i, strings.TrimSpace(o.FingerprintProfile), strings.TrimSpace(n.FingerprintProfile))) } changes = appendOptionalIntChange(changes, fmt.Sprintf("claude[%d].request-retry", i), o.RequestRetry, n.RequestRetry) - if o.Cloak != nil && n.Cloak != nil { + switch { + case o.Cloak == nil && n.Cloak != nil: + changes = append(changes, fmt.Sprintf("claude[%d].cloak: added", i)) + case o.Cloak != nil && n.Cloak == nil: + changes = append(changes, fmt.Sprintf("claude[%d].cloak: removed", i)) + case o.Cloak != nil && n.Cloak != nil: if strings.TrimSpace(o.Cloak.Mode) != strings.TrimSpace(n.Cloak.Mode) { changes = append(changes, fmt.Sprintf("claude[%d].cloak.mode: %s -> %s", i, o.Cloak.Mode, n.Cloak.Mode)) } if o.Cloak.StrictMode != n.Cloak.StrictMode { changes = append(changes, fmt.Sprintf("claude[%d].cloak.strict-mode: %t -> %t", i, o.Cloak.StrictMode, n.Cloak.StrictMode)) } - if len(o.Cloak.SensitiveWords) != len(n.Cloak.SensitiveWords) { + if !reflect.DeepEqual(o.Cloak.SensitiveWords, n.Cloak.SensitiveWords) { changes = append(changes, fmt.Sprintf("claude[%d].cloak.sensitive-words: %d -> %d", i, len(o.Cloak.SensitiveWords), len(n.Cloak.SensitiveWords))) } + if !equalStringMap(o.Cloak.SensitiveWordsReplace, n.Cloak.SensitiveWordsReplace) { + changes = append(changes, fmt.Sprintf("claude[%d].cloak.sensitive-words-replace: %d -> %d", i, len(o.Cloak.SensitiveWordsReplace), len(n.Cloak.SensitiveWordsReplace))) + } + if !equalSensitivePatternRules(o.Cloak.SensitivePatternsReplace, n.Cloak.SensitivePatternsReplace) { + changes = append(changes, fmt.Sprintf("claude[%d].cloak.sensitive-patterns-replace: %d -> %d", i, len(o.Cloak.SensitivePatternsReplace), len(n.Cloak.SensitivePatternsReplace))) + } + changes = appendOptionalBoolChange(changes, fmt.Sprintf("claude[%d].cloak.cache-user-id", i), o.Cloak.CacheUserID, n.Cloak.CacheUserID) } } } @@ -688,7 +715,19 @@ func equalStringMap(a, b map[string]string) bool { return false } for k, v := range a { - if b[k] != v { + if bv, ok := b[k]; !ok || bv != v { + return false + } + } + return true +} + +func equalSensitivePatternRules(a, b []config.SensitivePatternRule) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { return false } } diff --git a/internal/watcher/diff/config_diff_test.go b/internal/watcher/diff/config_diff_test.go index 963a704cc1c..17037d53e55 100644 --- a/internal/watcher/diff/config_diff_test.go +++ b/internal/watcher/diff/config_diff_test.go @@ -469,7 +469,7 @@ func TestBuildConfigChangeDetails_FlagsAndKeys(t *testing.T) { }, }, XAI: config.XAIConfig{InjectXSearch: true}, - Claude: config.ClaudeConfig{ToolSearch: true}, + Claude: config.ClaudeConfig{ToolSearch: true, ServerSideFallback: true}, ClaudeKey: []config.ClaudeKey{ {APIKey: "c1", BaseURL: "http://new", ProxyURL: "http://p", Headers: map[string]string{"H": "1"}, ExcludedModels: []string{"a"}}, {APIKey: "c2"}, @@ -522,6 +522,7 @@ func TestBuildConfigChangeDetails_FlagsAndKeys(t *testing.T) { expectContains(t, details, `antigravity.connection-pool.idle-conn-timeout: "30s" -> "10s"`) expectContains(t, details, "xai.inject-x-search: false -> true") expectContains(t, details, "claude.tool-search: false -> true") + expectContains(t, details, "claude.server-side-fallback: false -> true") expectContains(t, details, "api-keys count: 1 -> 2") expectContains(t, details, "claude-api-key count: 1 -> 2") expectContains(t, details, "codex-api-key count: 1 -> 2") @@ -839,3 +840,108 @@ func TestBuildConfigChangeDetails_KVStore(t *testing.T) { t.Fatalf("whitespace-only path difference produced changes: %v", unchanged) } } + +func TestBuildConfigChangeDetails_SensitiveWordsReplace(t *testing.T) { + oldCfg := &config.Config{ + Antigravity: config.AntigravityConfig{ + SensitiveWordsReplace: map[string]string{"Codex": "Assistant"}, + }, + ClaudeKey: []config.ClaudeKey{{ + APIKey: "k1", + Cloak: &config.CloakConfig{SensitiveWordsReplace: map[string]string{"a": "b"}}, + }}, + } + newCfg := &config.Config{ + Antigravity: config.AntigravityConfig{ + SensitiveWordsReplace: map[string]string{"Codex": "Assistant", "GPT-5": "Model"}, + }, + Devin: config.DevinConfig{ + SensitiveWordsReplace: map[string]string{"Claude Code": "Devin"}, + }, + ClaudeKey: []config.ClaudeKey{{ + APIKey: "k1", + Cloak: &config.CloakConfig{SensitiveWordsReplace: map[string]string{"a": "c"}}, + }}, + } + changes := BuildConfigChangeDetails(oldCfg, newCfg) + expectContains(t, changes, "antigravity.sensitive-words-replace: 1 -> 2") + expectContains(t, changes, "devin.sensitive-words-replace: 0 -> 1") + expectContains(t, changes, "claude[0].cloak.sensitive-words-replace: 1 -> 1") + + emptyA := &config.Config{ClaudeKey: []config.ClaudeKey{{APIKey: "k1", Cloak: &config.CloakConfig{}}}} + emptyB := &config.Config{ + Antigravity: config.AntigravityConfig{SensitiveWordsReplace: map[string]string{}}, + Devin: config.DevinConfig{SensitiveWordsReplace: map[string]string{}}, + ClaudeKey: []config.ClaudeKey{{APIKey: "k1", Cloak: &config.CloakConfig{SensitiveWordsReplace: map[string]string{}}}}, + } + if noDiff := BuildConfigChangeDetails(emptyA, emptyB); len(noDiff) != 0 { + t.Fatalf("expected no diff between nil and empty SensitiveWordsReplace maps, got %v", noDiff) + } + + emptyValOld := &config.Config{ + Antigravity: config.AntigravityConfig{SensitiveWordsReplace: map[string]string{"Codex": ""}}, + Devin: config.DevinConfig{SensitiveWordsReplace: map[string]string{"Codex": ""}}, + ClaudeKey: []config.ClaudeKey{{APIKey: "k1", Cloak: &config.CloakConfig{SensitiveWordsReplace: map[string]string{"Codex": ""}}}}, + } + emptyValNew := &config.Config{ + Antigravity: config.AntigravityConfig{SensitiveWordsReplace: map[string]string{"GPT-5": ""}}, + Devin: config.DevinConfig{SensitiveWordsReplace: map[string]string{"GPT-5": ""}}, + ClaudeKey: []config.ClaudeKey{{APIKey: "k1", Cloak: &config.CloakConfig{SensitiveWordsReplace: map[string]string{"GPT-5": ""}}}}, + } + emptyValChanges := BuildConfigChangeDetails(emptyValOld, emptyValNew) + expectContains(t, emptyValChanges, "antigravity.sensitive-words-replace: 1 -> 1") + expectContains(t, emptyValChanges, "devin.sensitive-words-replace: 1 -> 1") + expectContains(t, emptyValChanges, "claude[0].cloak.sensitive-words-replace: 1 -> 1") + + nilCloakOld := &config.Config{ClaudeKey: []config.ClaudeKey{{APIKey: "k1"}}} + addedCloakNew := &config.Config{ClaudeKey: []config.ClaudeKey{{ + APIKey: "k1", + Cloak: &config.CloakConfig{SensitiveWords: []string{"API"}, SensitiveWordsReplace: map[string]string{"a": "b"}}, + }}} + expectContains(t, BuildConfigChangeDetails(nilCloakOld, addedCloakNew), "claude[0].cloak: added") + expectContains(t, BuildConfigChangeDetails(addedCloakNew, nilCloakOld), "claude[0].cloak: removed") + + sameLenWordsNew := &config.Config{ClaudeKey: []config.ClaudeKey{{ + APIKey: "k1", + Cloak: &config.CloakConfig{SensitiveWords: []string{"proxy"}, SensitiveWordsReplace: map[string]string{"a": "b"}}, + }}} + expectContains(t, BuildConfigChangeDetails(addedCloakNew, sameLenWordsNew), "claude[0].cloak.sensitive-words: 1 -> 1") +} + +func TestBuildConfigChangeDetails_SensitivePatternsReplace(t *testing.T) { + oldCfg := &config.Config{ + Antigravity: config.AntigravityConfig{ + SensitivePatternsReplace: []config.SensitivePatternRule{{Pattern: "a", Replacement: ""}}, + }, + ClaudeKey: []config.ClaudeKey{{ + APIKey: "k1", + Cloak: &config.CloakConfig{SensitivePatternsReplace: []config.SensitivePatternRule{{Pattern: "c", Replacement: ""}}}, + }}, + } + newCfg := &config.Config{ + Antigravity: config.AntigravityConfig{ + SensitivePatternsReplace: []config.SensitivePatternRule{{Pattern: "a", Replacement: ""}, {Pattern: "b", Replacement: "x"}}, + }, + Devin: config.DevinConfig{ + SensitivePatternsReplace: []config.SensitivePatternRule{{Pattern: "d", Replacement: ""}}, + }, + ClaudeKey: []config.ClaudeKey{{ + APIKey: "k1", + Cloak: &config.CloakConfig{SensitivePatternsReplace: []config.SensitivePatternRule{{Pattern: "c", Replacement: "y"}}}, + }}, + } + changes := BuildConfigChangeDetails(oldCfg, newCfg) + expectContains(t, changes, "antigravity.sensitive-patterns-replace: 1 -> 2") + expectContains(t, changes, "devin.sensitive-patterns-replace: 0 -> 1") + expectContains(t, changes, "claude[0].cloak.sensitive-patterns-replace: 1 -> 1") + + emptyA := &config.Config{ClaudeKey: []config.ClaudeKey{{APIKey: "k1", Cloak: &config.CloakConfig{}}}} + emptyB := &config.Config{ + Antigravity: config.AntigravityConfig{SensitivePatternsReplace: []config.SensitivePatternRule{}}, + Devin: config.DevinConfig{SensitivePatternsReplace: []config.SensitivePatternRule{}}, + ClaudeKey: []config.ClaudeKey{{APIKey: "k1", Cloak: &config.CloakConfig{SensitivePatternsReplace: []config.SensitivePatternRule{}}}}, + } + if noDiff := BuildConfigChangeDetails(emptyA, emptyB); len(noDiff) != 0 { + t.Fatalf("expected no diff between nil and empty SensitivePatternsReplace slices, got %v", noDiff) + } +} diff --git a/internal/watcher/dispatcher.go b/internal/watcher/dispatcher.go index e9e3cf31e7e..b8be4d400b5 100644 --- a/internal/watcher/dispatcher.go +++ b/internal/watcher/dispatcher.go @@ -147,17 +147,35 @@ func (w *Watcher) dispatchPersistedAuthUpdateWithRevision(update *AuthUpdate) (b } func (w *Watcher) refreshAuthState(force bool) { - w.clientsMutex.Lock() - w.activeAuthScans++ - cfg := w.config - authDir := w.authDir - parser := w.pluginAuthParser - previous := maps.Clone(w.authRevisions) - previousFiles := maps.Clone(w.fileObservations) - w.clientsMutex.Unlock() - auths, incompleteFiles := snapshotCoreAuthsFunc(cfg, authDir, parser) - w.clientsMutex.Lock() - w.activeAuthScans-- + var ( + cfg *config.Config + authDir string + parser synthesizer.PluginAuthParser + previous map[string]uint64 + previousFiles map[string]uint64 + auths []*coreauth.Auth + incompleteFiles map[string]struct{} + ) + for { + w.clientsMutex.Lock() + w.activeAuthScans++ + cfg = w.config + authDir = w.currentAuthDirLocked() + parser = w.pluginAuthParser + previous = maps.Clone(w.authRevisions) + previousFiles = maps.Clone(w.fileObservations) + w.clientsMutex.Unlock() + + auths, incompleteFiles = snapshotCoreAuthsFunc(cfg, authDir, parser) + + w.clientsMutex.Lock() + w.activeAuthScans-- + currentAuthDir := w.currentAuthDirLocked() + if authDir == currentAuthDir || w.sameNormalizedAuthPath(authDir, currentAuthDir) { + break + } + w.clientsMutex.Unlock() + } var incompletePaths map[string]struct{} if len(incompleteFiles) > 0 { incompletePaths = make(map[string]struct{}, len(incompleteFiles)*2) @@ -267,6 +285,16 @@ func (w *Watcher) refreshAuthState(force bool) { source := auth.Attributes[coreauth.AttributeSource] return source != "" && !strings.HasPrefix(source, "config:") } + belongsToCurrentAuthDir := func(auth *coreauth.Auth) bool { + if !isFileBackedAuth(auth) || authDir == "" { + return true + } + rawPath := fileBackedAuthPath(auth) + if rawPath == "" || filepath.Dir(w.normalizeAuthPath(rawPath)) == "." { + return true + } + return w.isPathInAuthDir(rawPath, authDir) + } for index, auth := range auths { if auth != nil && (changedDuringScan(auth) || incompleteDuringScan(auth)) { auths[index] = nil @@ -282,7 +310,7 @@ func (w *Watcher) refreshAuthState(force bool) { } } for id, auth := range providerReloadAuths { - if auth == nil || previous[id] != w.authRevisions[id] { + if auth == nil || previous[id] != w.authRevisions[id] || !belongsToCurrentAuthDir(auth) { continue } if _, exists := w.currentAuths[id]; exists { @@ -306,7 +334,7 @@ func (w *Watcher) refreshAuthState(force bool) { var rereadPaths []string rereadSeen := make(map[string]struct{}) for _, auth := range w.currentAuths { - if auth == nil { + if auth == nil || !belongsToCurrentAuthDir(auth) { continue } if !changedDuringScan(auth) && !incompleteDuringScan(auth) { @@ -346,9 +374,9 @@ func (w *Watcher) refreshAuthState(force bool) { } } -func (w *Watcher) indexFileBackedAuthLocked(auth *coreauth.Auth) { - if auth == nil || auth.ID == "" || len(auth.Attributes) == 0 { - return +func fileBackedAuthPath(auth *coreauth.Auth) string { + if auth == nil || len(auth.Attributes) == 0 { + return "" } path := auth.Attributes[coreauth.AttributePath] if path == "" { @@ -357,7 +385,14 @@ func (w *Watcher) indexFileBackedAuthLocked(auth *coreauth.Auth) { path = source } } - normalized := w.normalizeAuthPath(path) + return path +} + +func (w *Watcher) indexFileBackedAuthLocked(auth *coreauth.Auth) { + if auth == nil || auth.ID == "" { + return + } + normalized := w.normalizeAuthPath(fileBackedAuthPath(auth)) if normalized == "" { return } @@ -414,7 +449,12 @@ func (w *Watcher) prepareAuthUpdatesLocked(auths []*coreauth.Auth, force bool) [ } for path, pathAuths := range w.fileAuthsByPath { for id := range pathAuths { - if _, ok := newState[id]; !ok { + auth, ok := newState[id] + if !ok { + delete(pathAuths, id) + continue + } + if authPath := fileBackedAuthPath(auth); authPath != "" && !w.sameNormalizedAuthPath(path, authPath) { delete(pathAuths, id) } } diff --git a/internal/watcher/events.go b/internal/watcher/events.go index 10908a2b26c..bedab7a61bf 100644 --- a/internal/watcher/events.go +++ b/internal/watcher/events.go @@ -41,11 +41,17 @@ func (w *Watcher) start(ctx context.Context) error { return errAddConfigDir } - if errAddAuthDir := w.watcher.Add(w.authDir); errAddAuthDir != nil { - log.Errorf("failed to watch auth directory %s: %v", w.authDir, errAddAuthDir) + w.watchMu.Lock() + authDir := w.currentAuthDir() + if errAddAuthDir := w.watcher.Add(authDir); errAddAuthDir != nil { + w.watchMu.Unlock() + log.Errorf("failed to watch auth directory %s: %v", authDir, errAddAuthDir) return errAddAuthDir } - log.Debugf("watching auth directory: %s", w.authDir) + w.started = true + w.watchedAuthDir = authDir + w.watchMu.Unlock() + log.Debugf("watching auth directory: %s", authDir) go w.processEvents(ctx) @@ -53,6 +59,42 @@ func (w *Watcher) start(ctx context.Context) error { return nil } +func (w *Watcher) syncAuthDirWatch() { + if w == nil || w.watcher == nil || w.stopped.Load() { + return + } + w.watchMu.Lock() + defer w.watchMu.Unlock() + if !w.started || w.stopped.Load() { + return + } + target := strings.TrimSpace(w.currentAuthDir()) + oldWatched := strings.TrimSpace(w.watchedAuthDir) + if oldWatched == target { + return + } + if oldWatched != "" && !w.sameNormalizedAuthPath(oldWatched, w.configPath) && !w.sameNormalizedAuthPath(oldWatched, target) { + if errRemove := w.watcher.Remove(oldWatched); errRemove != nil { + log.Debugf("failed to remove previous auth directory watch %s: %v", oldWatched, errRemove) + } + w.watchedAuthDir = "" + } + if target == "" { + w.watchedAuthDir = "" + return + } + if w.watchedAuthDir != "" && w.sameNormalizedAuthPath(w.watchedAuthDir, target) { + w.watchedAuthDir = target + return + } + if errAdd := w.watcher.Add(target); errAdd != nil { + log.Errorf("failed to watch auth directory %s: %v", target, errAdd) + return + } + w.watchedAuthDir = target + log.Debugf("watching auth directory: %s", target) +} + func (w *Watcher) processEvents(ctx context.Context) { for { select { @@ -77,7 +119,7 @@ func (w *Watcher) handleEvent(event fsnotify.Event) { configOps := fsnotify.Write | fsnotify.Create | fsnotify.Rename normalizedName := w.normalizeAuthPath(event.Name) normalizedConfigPath := w.normalizeAuthPath(w.configPath) - normalizedAuthDir := w.normalizeAuthPath(w.authDir) + normalizedAuthDir := w.normalizeAuthPath(w.currentAuthDir()) isConfigEvent := normalizedName == normalizedConfigPath && event.Op&configOps != 0 authOps := fsnotify.Create | fsnotify.Write | fsnotify.Remove | fsnotify.Rename isAuthJSON := filepath.Dir(normalizedName) == normalizedAuthDir && strings.HasSuffix(normalizedName, ".json") && event.Op&authOps != 0 @@ -99,6 +141,9 @@ func (w *Watcher) handleEvent(event fsnotify.Event) { // Handle auth directory changes incrementally (.json only) w.authRescanMu.Lock() defer w.authRescanMu.Unlock() + if !w.isPathInAuthDir(normalizedName, w.currentAuthDir()) { + return + } w.observeAuthFile(event.Name) if event.Op&(fsnotify.Remove|fsnotify.Rename) != 0 { @@ -109,6 +154,9 @@ func (w *Watcher) handleEvent(event fsnotify.Event) { // Atomic replace on some platforms may surface as Rename (or Remove) before the new file is ready. // Wait briefly; if the path exists again, treat as an update instead of removal. time.Sleep(replaceCheckDelay) + if !w.isPathInAuthDir(normalizedName, w.currentAuthDir()) { + return + } statSucceeded := false if _, statErr := os.Stat(event.Name); statErr == nil { statSucceeded = true @@ -118,6 +166,9 @@ func (w *Watcher) handleEvent(event fsnotify.Event) { // before treating a known auth file as permanently removed. for attempt := 0; attempt < 3; attempt++ { time.Sleep(25 * time.Millisecond) + if !w.isPathInAuthDir(normalizedName, w.currentAuthDir()) { + return + } if _, retryErr := os.Stat(event.Name); retryErr == nil { statSucceeded = true break @@ -160,6 +211,9 @@ func (w *Watcher) observeAuthFile(path string) { } w.clientsMutex.Lock() defer w.clientsMutex.Unlock() + if !w.isPathInCurrentAuthDirLocked(normalized) { + return + } if w.fileObservations == nil { w.fileObservations = make(map[string]uint64) } diff --git a/internal/watcher/snapshot_traffic_test.go b/internal/watcher/snapshot_traffic_test.go index e6aa9c01c46..09a869d68ce 100644 --- a/internal/watcher/snapshot_traffic_test.go +++ b/internal/watcher/snapshot_traffic_test.go @@ -3,6 +3,7 @@ package watcher import ( "context" "encoding/json" + "maps" "os" "path/filepath" "testing" @@ -146,7 +147,7 @@ func TestRefreshAuthStateSnapshotKeepsRequestRuntimeState(t *testing.T) { got, _ := manager.GetByID(trafficAuthFile) if got.Status != want.Status || got.StatusMessage != want.StatusMessage || got.Unavailable != want.Unavailable || !got.NextRetryAfter.Equal(want.NextRetryAfter) || - got.LastError == nil || *got.LastError != *want.LastError || got.Failed != want.Failed { + got.LastError == nil || !trafficErrorsEqual(got.LastError, want.LastError) || got.Failed != want.Failed { t.Fatalf("auth state = %q %q unavailable=%v retry=%v lastError=%v failed=%d, want %q %q unavailable=%v retry=%v lastError=%v failed=%d", got.Status, got.StatusMessage, got.Unavailable, got.NextRetryAfter, got.LastError, got.Failed, want.Status, want.StatusMessage, want.Unavailable, want.NextRetryAfter, want.LastError, want.Failed) @@ -157,7 +158,7 @@ func TestRefreshAuthStateSnapshotKeepsRequestRuntimeState(t *testing.T) { for model, wantState := range want.ModelStates { gotState := got.ModelStates[model] if gotState == nil || gotState.Status != wantState.Status || gotState.Unavailable != wantState.Unavailable || - !gotState.NextRetryAfter.Equal(wantState.NextRetryAfter) || gotState.LastError == nil || *gotState.LastError != *wantState.LastError || + !gotState.NextRetryAfter.Equal(wantState.NextRetryAfter) || gotState.LastError == nil || !trafficErrorsEqual(gotState.LastError, wantState.LastError) || gotState.Quota.Exceeded != wantState.Quota.Exceeded || !gotState.Quota.NextRecoverAt.Equal(wantState.Quota.NextRecoverAt) { t.Fatalf("model state %s = %+v, want %+v", model, gotState, wantState) } @@ -345,3 +346,11 @@ func TestRefreshAuthStateRereadsAuthPersistedDuringScan(t *testing.T) { }) } } + +func trafficErrorsEqual(a, b *coreauth.Error) bool { + if a == nil || b == nil { + return a == b + } + return a.Code == b.Code && a.Message == b.Message && a.Retryable == b.Retryable && + a.HTTPStatus == b.HTTPStatus && maps.Equal(a.Metadata, b.Metadata) +} diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.go index 60a5f68f242..bca9c0a6f95 100644 --- a/internal/watcher/watcher.go +++ b/internal/watcher/watcher.go @@ -4,6 +4,7 @@ package watcher import ( "context" + "path/filepath" "strings" "sync" "sync/atomic" @@ -11,6 +12,7 @@ import ( "github.com/fsnotify/fsnotify" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/util" "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher/synthesizer" "gopkg.in/yaml.v3" @@ -33,6 +35,9 @@ type authDirProvider interface { type Watcher struct { configPath string authDir string + watchMu sync.Mutex + started bool + watchedAuthDir string config *config.Config clientsMutex sync.RWMutex authRescanMu sync.Mutex @@ -169,9 +174,76 @@ func (w *Watcher) Stop() error { func (w *Watcher) SetConfig(cfg *config.Config) { cloned := cfg.CloneForRuntime() w.clientsMutex.Lock() - defer w.clientsMutex.Unlock() + if cloned != nil { + if w.mirroredAuthDir != "" { + cloned.AuthDir = w.mirroredAuthDir + w.authDir = w.mirroredAuthDir + } else if trimmedAuthDir := strings.TrimSpace(cloned.AuthDir); trimmedAuthDir != "" { + if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(trimmedAuthDir); errResolveAuthDir == nil && resolvedAuthDir != "" { + cloned.AuthDir = resolvedAuthDir + w.authDir = resolvedAuthDir + } else if w.authDir == "" { + w.authDir = trimmedAuthDir + } + } + } w.config = cloned w.oldConfigYaml, _ = yaml.Marshal(cloned) + w.clientsMutex.Unlock() + w.syncAuthDirWatch() +} + +func (w *Watcher) currentAuthDirLocked() string { + if w == nil { + return "" + } + if authDir := strings.TrimSpace(w.authDir); authDir != "" { + return authDir + } + if w.config != nil { + if cfgAuthDir := strings.TrimSpace(w.config.AuthDir); cfgAuthDir != "" { + if resolved, errResolve := util.ResolveAuthDir(cfgAuthDir); errResolve == nil && resolved != "" { + return resolved + } + return cfgAuthDir + } + } + return "" +} + +func (w *Watcher) currentAuthDir() string { + if w == nil { + return "" + } + w.clientsMutex.RLock() + defer w.clientsMutex.RUnlock() + return w.currentAuthDirLocked() +} + +func (w *Watcher) isPathInAuthDir(path, authDir string) bool { + normalizedPath := w.normalizeAuthPath(path) + normalizedDir := w.normalizeAuthPath(authDir) + if normalizedPath == "" || normalizedDir == "" { + return false + } + return w.sameNormalizedAuthPath(filepath.Dir(normalizedPath), normalizedDir) +} + +func (w *Watcher) isPathInCurrentAuthDirLocked(path string) bool { + authDir := w.currentAuthDirLocked() + if authDir == "" { + return true + } + return w.isPathInAuthDir(path, authDir) +} + +func (w *Watcher) isPathInCurrentAuthDir(path string) bool { + if w == nil { + return false + } + w.clientsMutex.RLock() + defer w.clientsMutex.RUnlock() + return w.isPathInCurrentAuthDirLocked(path) } // SetPluginAuthParser updates the plugin auth parser used for file auth synthesis. @@ -215,7 +287,7 @@ func (w *Watcher) RereadDiscardedFileSnapshot(auth *coreauth.Auth) { func (w *Watcher) SnapshotCoreAuths() []*coreauth.Auth { w.clientsMutex.RLock() cfg := w.config - authDir := w.authDir + authDir := w.currentAuthDirLocked() parser := w.pluginAuthParser w.clientsMutex.RUnlock() return snapshotCoreAuths(cfg, authDir, parser) diff --git a/internal/watcher/watcher_test.go b/internal/watcher/watcher_test.go index 97123ff8226..d1aa04a9487 100644 --- a/internal/watcher/watcher_test.go +++ b/internal/watcher/watcher_test.go @@ -20,6 +20,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher/synthesizer" sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" "gopkg.in/yaml.v3" ) @@ -1935,3 +1936,361 @@ func TestScheduleProcessEventsStopsOnContextDone(t *testing.T) { func hexString(data []byte) string { return strings.ToLower(fmt.Sprintf("%x", data)) } + +func TestReloadConfigUpdatesAuthDirWatchAndSnapshots(t *testing.T) { + tmpDir := t.TempDir() + dirA := filepath.Join(tmpDir, "auth-a") + dirB := filepath.Join(tmpDir, "auth-b") + if errMkdirA := os.MkdirAll(dirA, 0o755); errMkdirA != nil { + t.Fatalf("failed to create auth dir A: %v", errMkdirA) + } + if errMkdirB := os.MkdirAll(dirB, 0o755); errMkdirB != nil { + t.Fatalf("failed to create auth dir B: %v", errMkdirB) + } + + credAPath := filepath.Join(dirA, "cred-a.json") + if errWriteA := os.WriteFile(credAPath, []byte(`{"type":"codex","email":"a@example.com"}`), 0o600); errWriteA != nil { + t.Fatalf("failed to write cred-a.json: %v", errWriteA) + } + sharedAPath := filepath.Join(dirA, "shared.json") + if errWriteSharedA := os.WriteFile(sharedAPath, []byte(`{"type":"codex","email":"shared-a@example.com"}`), 0o600); errWriteSharedA != nil { + t.Fatalf("failed to write shared.json in dirA: %v", errWriteSharedA) + } + credBPath := filepath.Join(dirB, "cred-b.json") + if errWriteB := os.WriteFile(credBPath, []byte(`{"type":"codex","email":"b@example.com"}`), 0o600); errWriteB != nil { + t.Fatalf("failed to write cred-b.json: %v", errWriteB) + } + sharedBPath := filepath.Join(dirB, "shared.json") + if errWriteSharedB := os.WriteFile(sharedBPath, []byte(`{"type":"codex","email":"shared-b@example.com"}`), 0o600); errWriteSharedB != nil { + t.Fatalf("failed to write shared.json in dirB: %v", errWriteSharedB) + } + + configPath := filepath.Join(tmpDir, "config.yaml") + writeConfig := func(authDir string) { + t.Helper() + cfg := &config.Config{ + AuthDir: authDir, + CredentialInFlight: config.DefaultCredentialInFlightConfig(), + } + data, errMarshal := yaml.Marshal(cfg) + if errMarshal != nil { + t.Fatalf("failed to marshal config: %v", errMarshal) + } + if errWriteCfg := os.WriteFile(configPath, data, 0o600); errWriteCfg != nil { + t.Fatalf("failed to write config: %v", errWriteCfg) + } + } + writeConfig(dirA) + + w, errNewWatcher := NewWatcher(configPath, dirA, nil) + if errNewWatcher != nil { + t.Fatalf("NewWatcher failed: %v", errNewWatcher) + } + defer func() { + if errStop := w.Stop(); errStop != nil { + t.Errorf("failed to stop watcher: %v", errStop) + } + }() + + queue := make(chan AuthUpdate, 16) + w.SetAuthUpdateQueue(queue) + w.SetConfig(&config.Config{ + AuthDir: dirA, + CredentialInFlight: config.DefaultCredentialInFlightConfig(), + }) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + if errStart := w.Start(ctx); errStart != nil { + t.Fatalf("Start failed: %v", errStart) + } + + initialSeen := make(map[string]bool) + for len(initialSeen) < 2 { + select { + case initial := <-queue: + if initial.Action != AuthUpdateActionAdd { + t.Fatalf("unexpected initial auth update: %+v", initial) + } + initialSeen[initial.ID] = true + case <-time.After(2 * time.Second): + t.Fatalf("timed out waiting for initial updates, got %v", initialSeen) + } + } + if !initialSeen["cred-a.json"] || !initialSeen["shared.json"] { + t.Fatalf("expected cred-a.json and shared.json in initial updates, got %v", initialSeen) + } + + // Switch auth-dir from dirA to dirB at runtime. + writeConfig(dirB) + w.ReloadConfigIfChanged() + + seenAddB := false + seenModifyShared := false + seenDeleteA := false + for !seenAddB || !seenModifyShared || !seenDeleteA { + select { + case update := <-queue: + if update.ID == "cred-b.json" && update.Action == AuthUpdateActionAdd { + seenAddB = true + } + if update.ID == "shared.json" && update.Action == AuthUpdateActionModify && update.Auth != nil && update.Auth.Label == "shared-b@example.com" { + seenModifyShared = true + } + if update.ID == "cred-a.json" && update.Action == AuthUpdateActionDelete { + seenDeleteA = true + } + case <-time.After(2 * time.Second): + t.Fatalf("timed out waiting for auth-dir switch updates (seenAddB=%v, seenModifyShared=%v, seenDeleteA=%v)", seenAddB, seenModifyShared, seenDeleteA) + } + } + + snapshot := w.SnapshotCoreAuths() + if len(snapshot) != 2 { + t.Fatalf("expected SnapshotCoreAuths to return 2 entries from dirB, got %+v", snapshot) + } + w.clientsMutex.RLock() + _, staleSharedIndexed := w.fileAuthsByPath[w.normalizeAuthPath(sharedAPath)] + _, newSharedIndexed := w.fileAuthsByPath[w.normalizeAuthPath(sharedBPath)] + w.clientsMutex.RUnlock() + if staleSharedIndexed || !newSharedIndexed { + t.Fatalf("expected fileAuthsByPath to drop dirA shared.json (%v) and keep dirB shared.json (%v)", staleSharedIndexed, newSharedIndexed) + } + + fileSnapshot, errSnapshotFile := w.SnapshotAuthFile(credBPath) + if errSnapshotFile != nil { + t.Fatalf("SnapshotAuthFile(credBPath) failed: %v", errSnapshotFile) + } + if len(fileSnapshot) != 1 || fileSnapshot[0].ID != "cred-b.json" { + t.Fatalf("expected SnapshotAuthFile(credBPath) ID=cred-b.json, got %+v", fileSnapshot) + } + + // Events for the old directory must be ignored, while events in the new directory must be processed. + credA2Path := filepath.Join(dirA, "cred-a2.json") + if errWriteA2 := os.WriteFile(credA2Path, []byte(`{"type":"codex","email":"a2@example.com"}`), 0o600); errWriteA2 != nil { + t.Fatalf("failed to write cred-a2.json: %v", errWriteA2) + } + w.handleEvent(fsnotify.Event{Name: credA2Path, Op: fsnotify.Create}) + + credB2Path := filepath.Join(dirB, "cred-b2.json") + if errWriteB2 := os.WriteFile(credB2Path, []byte(`{"type":"codex","email":"b2@example.com"}`), 0o600); errWriteB2 != nil { + t.Fatalf("failed to write cred-b2.json: %v", errWriteB2) + } + + select { + case update := <-queue: + if update.Action != AuthUpdateActionAdd || update.ID != "cred-b2.json" { + t.Fatalf("expected add update for cred-b2.json, got %+v", update) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for fsnotify update from new auth-dir dirB") + } +} + +func TestSetConfigUpdatesAuthDir(t *testing.T) { + tmpDir := t.TempDir() + dirA := filepath.Join(tmpDir, "auth-a") + dirB := filepath.Join(tmpDir, "auth-b") + if errMkdirA := os.MkdirAll(dirA, 0o755); errMkdirA != nil { + t.Fatalf("failed to create auth dir A: %v", errMkdirA) + } + if errMkdirB := os.MkdirAll(dirB, 0o755); errMkdirB != nil { + t.Fatalf("failed to create auth dir B: %v", errMkdirB) + } + credBPath := filepath.Join(dirB, "cred-b.json") + if errWriteB := os.WriteFile(credBPath, []byte(`{"type":"codex","email":"b@example.com"}`), 0o600); errWriteB != nil { + t.Fatalf("failed to write cred-b.json: %v", errWriteB) + } + + w, errNewWatcher := NewWatcher(filepath.Join(tmpDir, "config.yaml"), dirA, nil) + if errNewWatcher != nil { + t.Fatalf("NewWatcher failed: %v", errNewWatcher) + } + defer func() { + if errStop := w.Stop(); errStop != nil { + t.Errorf("failed to stop watcher: %v", errStop) + } + }() + + w.SetConfig(&config.Config{AuthDir: dirB}) + + snapshot := w.SnapshotCoreAuths() + if len(snapshot) != 1 || snapshot[0].ID != "cred-b.json" { + t.Fatalf("expected SnapshotCoreAuths to return cred-b.json from dirB, got %+v", snapshot) + } + fileSnapshot, errSnapshotFile := w.SnapshotAuthFile(credBPath) + if errSnapshotFile != nil { + t.Fatalf("SnapshotAuthFile failed: %v", errSnapshotFile) + } + if len(fileSnapshot) != 1 || fileSnapshot[0].ID != "cred-b.json" { + t.Fatalf("expected SnapshotAuthFile ID=cred-b.json, got %+v", fileSnapshot) + } +} + +type blockingAuthDirSwitchParser struct { + blockPath string + entered chan struct{} + release chan struct{} + once sync.Once +} + +func (p *blockingAuthDirSwitchParser) ParseAuth(_ context.Context, req pluginapi.AuthParseRequest) (*coreauth.Auth, bool, error) { + if filepath.Clean(req.Path) == filepath.Clean(p.blockPath) { + p.once.Do(func() { + close(p.entered) + }) + <-p.release + } + return nil, false, nil +} + +func TestAddOrUpdateClientDiscardsStaleDirEventAcrossAuthDirSwitch(t *testing.T) { + tmpDir := t.TempDir() + dirA := filepath.Join(tmpDir, "auth-a") + dirB := filepath.Join(tmpDir, "auth-b") + if errMkdirA := os.MkdirAll(dirA, 0o755); errMkdirA != nil { + t.Fatalf("failed to create auth dir A: %v", errMkdirA) + } + if errMkdirB := os.MkdirAll(dirB, 0o755); errMkdirB != nil { + t.Fatalf("failed to create auth dir B: %v", errMkdirB) + } + + lateAPath := filepath.Join(dirA, "late-a.json") + if errWriteLateA := os.WriteFile(lateAPath, []byte(`{"type":"codex","email":"late-a@example.com"}`), 0o600); errWriteLateA != nil { + t.Fatalf("failed to write late-a.json: %v", errWriteLateA) + } + credBPath := filepath.Join(dirB, "cred-b.json") + if errWriteB := os.WriteFile(credBPath, []byte(`{"type":"codex","email":"b@example.com"}`), 0o600); errWriteB != nil { + t.Fatalf("failed to write cred-b.json: %v", errWriteB) + } + + parser := &blockingAuthDirSwitchParser{ + blockPath: lateAPath, + entered: make(chan struct{}), + release: make(chan struct{}), + } + + queue := make(chan AuthUpdate, 16) + w := &Watcher{ + authDir: dirA, + lastAuthHashes: make(map[string]string), + fileAuthsByPath: make(map[string]map[string]*coreauth.Auth), + pluginAuthParser: parser, + } + w.SetConfig(&config.Config{AuthDir: dirA}) + w.SetAuthUpdateQueue(queue) + defer w.stopDispatch() + + done := make(chan struct{}) + go func() { + w.addOrUpdateClientLocked(lateAPath) + close(done) + }() + + select { + case <-parser.entered: + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for addOrUpdateClientLocked to reach synthesis") + } + + // Switch auth-dir to dirB while the dirA event is paused mid-synthesis. + w.SetConfig(&config.Config{AuthDir: dirB}) + w.refreshAuthState(false) + + select { + case update := <-queue: + if update.Action != AuthUpdateActionAdd || update.ID != "cred-b.json" { + t.Fatalf("expected add update for cred-b.json, got %+v", update) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for cred-b.json update") + } + + close(parser.release) + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for paused addOrUpdateClientLocked to finish") + } + + w.clientsMutex.RLock() + currentCount := len(w.currentAuths) + _, hasCredB := w.currentAuths["cred-b.json"] + _, hasLateA := w.lastAuthHashes[w.normalizeAuthPath(lateAPath)] + w.clientsMutex.RUnlock() + if currentCount != 1 || !hasCredB || hasLateA { + t.Fatalf("stale dirA event polluted state after switch: currentCount=%d, hasCredB=%v, hasLateA=%v", currentCount, hasCredB, hasLateA) + } +} + +func TestConcurrentSetConfigKeepsWatchedAuthDirOnLatestConfig(t *testing.T) { + tmpDir := t.TempDir() + dirA := filepath.Join(tmpDir, "auth-a") + dirB := filepath.Join(tmpDir, "auth-b") + dirC := filepath.Join(tmpDir, "auth-c") + for _, dir := range []string{dirA, dirB, dirC} { + if errMkdir := os.MkdirAll(dir, 0o755); errMkdir != nil { + t.Fatalf("failed to create auth dir %s: %v", dir, errMkdir) + } + } + configPath := filepath.Join(tmpDir, "config.yaml") + if errWriteCfg := os.WriteFile(configPath, []byte("auth_dir: "+dirA+"\n"), 0o600); errWriteCfg != nil { + t.Fatalf("failed to write config: %v", errWriteCfg) + } + + w, errNewWatcher := NewWatcher(configPath, dirA, nil) + if errNewWatcher != nil { + t.Fatalf("NewWatcher failed: %v", errNewWatcher) + } + defer func() { + if errStop := w.Stop(); errStop != nil { + t.Errorf("failed to stop watcher: %v", errStop) + } + }() + + queue := make(chan AuthUpdate, 16) + w.SetAuthUpdateQueue(queue) + w.SetConfig(&config.Config{AuthDir: dirA}) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if errStart := w.Start(ctx); errStart != nil { + t.Fatalf("Start failed: %v", errStart) + } + + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(2) + go func() { + defer wg.Done() + w.SetConfig(&config.Config{AuthDir: dirB}) + }() + go func() { + defer wg.Done() + w.SetConfig(&config.Config{AuthDir: dirC}) + }() + } + wg.Wait() + w.SetConfig(&config.Config{AuthDir: dirC}) + + w.watchMu.Lock() + watched := w.watchedAuthDir + w.watchMu.Unlock() + if !w.sameNormalizedAuthPath(watched, dirC) || !w.sameNormalizedAuthPath(w.currentAuthDir(), dirC) { + t.Fatalf("expected watchedAuthDir=%q and currentAuthDir=%q to match dirC=%q", watched, w.currentAuthDir(), dirC) + } + + credCPath := filepath.Join(dirC, "cred-c.json") + if errWriteC := os.WriteFile(credCPath, []byte(`{"type":"codex","email":"c@example.com"}`), 0o600); errWriteC != nil { + t.Fatalf("failed to write cred-c.json: %v", errWriteC) + } + select { + case update := <-queue: + if update.Action != AuthUpdateActionAdd || update.ID != "cred-c.json" { + t.Fatalf("expected add update for cred-c.json, got %+v", update) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for fsnotify update from dirC") + } +} diff --git a/internal/wstunnel/close_race_regression_test.go b/internal/wstunnel/close_race_regression_test.go new file mode 100644 index 00000000000..e658bc8cb7f --- /dev/null +++ b/internal/wstunnel/close_race_regression_test.go @@ -0,0 +1,171 @@ +package wstunnel + +import ( + "errors" + "net/http/httptest" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +// TestPeerClose_CloseFrameWrittenBeforeSocketClose proves that a close frame +// requested through close() reaches the wire before the transport is +// reclaimed, even when the writeLoop goroutine is descheduled on a busy +// builder. +// +// Regression: on the unpatched peer.go, writeLoop emitted the Close frame +// without holding writeMu while a concurrent finishClose() could reclaim the +// underlying socket before the writer goroutine finished. The client then +// observed an abnormal 1006 closure instead of the expected close code. +func TestPeerClose_CloseFrameWrittenBeforeSocketClose(t *testing.T) { + for _, tc := range []struct { + name string + closeCode int + reason string + triggerClose func(p *peer) + }{ + { + name: "policy violation close is delivered", + closeCode: websocket.ClosePolicyViolation, + reason: "api key revoked", + triggerClose: func(p *peer) { + p.close(websocket.ClosePolicyViolation, "api key revoked", true) + }, + }, + { + name: "protocol error close is delivered", + closeCode: websocket.CloseProtocolError, + reason: "", + triggerClose: func(p *peer) { + p.close(websocket.CloseProtocolError, "", true) + }, + }, + { + name: "server shutdown close is delivered", + closeCode: websocket.CloseGoingAway, + reason: "server shutting down", + triggerClose: func(p *peer) { + p.close(websocket.CloseGoingAway, "server shutting down", true) + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + hub := NewHub(Options{PingInterval: 0}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + + client := dialRole(t, srv.URL, "key", RoleClient, "device", "Device") + _ = readTextJSONFrame(t, client) + + p := lookupTunnelPeer(t, hub, "key", "device") + + // Trigger the close from the hub side. The close path spawns + // awaitClose which calls finishClose on timeout; on the unpatched + // code finishClose could race the writeLoop close frame and reset + // the socket first. + tc.triggerClose(p) + + // The client must see the peer's close frame with the requested + // code, not a bare TCP reset. + _, _, errRead := readTunnelTestMessage(client) + var closeErr *websocket.CloseError + if !errors.As(errRead, &closeErr) { + t.Fatalf("close = %v, want CloseError with code %d", errRead, tc.closeCode) + } + if closeErr.Code != tc.closeCode { + t.Fatalf("close code = %d, want %d", closeErr.Code, tc.closeCode) + } + }) + } +} + +// TestPeerClose_ProtocolErrorReclaimsPermanentlyBlockedWriter drives the +// busy-writer branch of onProtocolError: an in-flight data write parks inside +// the gated transport holding writeMu, and the protocol-error callback must +// still reclaim the socket (unblocking the writer) without deadlocking on a +// close frame that can never be flushed. +// +// Regression coverage for issue #7504: a permanently blocked writer cannot +// deliver 1002, so the bounded wait must give up and close the transport. +func TestPeerClose_ProtocolErrorReclaimsPermanentlyBlockedWriter(t *testing.T) { + forceClose := make(chan time.Time) + hub := NewHub(Options{PingInterval: 0}) + hub.testForceClose = forceClose + t.Cleanup(func() { close(forceClose) }) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newGatedTunnelServer(t, hub) + + client := dialRole(t, srv.URL, "key", RoleClient, "device", "Device") + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "device") + guarded := p.conn.UnderlyingConn().(*deadlineGuardConn) + transport := guarded.Conn.(*gatedTunnelConn) + + // Arm the transport so the in-flight data write stays parked inside the + // socket Write call holding writeMu. + transport.arm() + if !p.tryEnqueueData([]byte("in-flight write holds writeMu")) { + t.Fatal("could not enqueue active write") + } + waitTunnelSignal(t, transport.blocked, "active write holding writeMu") + if p.writeMu.TryLock() { + p.writeMu.Unlock() + t.Fatal("expected writeMu to be held by the active write") + } + + // Fire the protocol-error callback while writeMu is genuinely busy. + guarded.onProtocolError() + + // The bounded wait gives up, reclaims the raw socket, unblocks the gated + // write, and lets writeLoop exit. + waitTunnelSignal(t, transport.closed, "raw transport close") + waitTunnelSignal(t, p.writerDone, "blocked writer exit") + waitTunnelSignal(t, p.done, "socket reclamation") +} + +// TestPeerClose_ProtocolErrorDeliversCloseAfterWriterReleases verifies that +// when the busy writer is transient (the write finishes promptly), the +// protocol-error close frame is emitted on the wire before the transport is +// reclaimed — the 1002-vs-1006 ordering that issue #7504 reported as flaky. +func TestPeerClose_ProtocolErrorDeliversCloseAfterWriterReleases(t *testing.T) { + forceClose := make(chan time.Time) + hub := NewHub(Options{PingInterval: 0}) + hub.testForceClose = forceClose + t.Cleanup(func() { close(forceClose) }) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newGatedTunnelServer(t, hub) + + client := dialRole(t, srv.URL, "key", RoleClient, "device", "Device") + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "device") + guarded := p.conn.UnderlyingConn().(*deadlineGuardConn) + transport := guarded.Conn.(*gatedTunnelConn) + + // Park the writer, fire the busy-writer protocol-error path, then release + // the gate so writeLoop can still flush the queued close frame inside the + // bounded grace window. + transport.arm() + if !p.tryEnqueueData([]byte("transient busy write")) { + t.Fatal("could not enqueue active write") + } + waitTunnelSignal(t, transport.blocked, "active write holding writeMu") + guarded.onProtocolError() + close(transport.gate) + + // The released in-flight data frame is flushed first; the protocol-error + // close frame must follow it before the transport is reclaimed. + _, _, errRead := readTunnelTestMessage(client) + if errRead != nil { + t.Fatalf("expected the released data frame first, got %v", errRead) + } + _, _, errRead = readTunnelTestMessage(client) + var closeErr *websocket.CloseError + if !errors.As(errRead, &closeErr) || closeErr.Code != websocket.CloseProtocolError { + t.Fatalf("close = %v, want CloseError code %d", errRead, websocket.CloseProtocolError) + } + waitTunnelSignal(t, p.writerDone, "writer exit") + waitTunnelSignal(t, p.done, "socket reclamation") +} diff --git a/internal/wstunnel/control_review_test.go b/internal/wstunnel/control_review_test.go new file mode 100644 index 00000000000..db9e93ac1e6 --- /dev/null +++ b/internal/wstunnel/control_review_test.go @@ -0,0 +1,203 @@ +package wstunnel + +import ( + "errors" + "fmt" + "io" + "net" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +type deadlineTrackingTunnelConn struct { + net.Conn + monitoring atomic.Bool + deadlineCalls atomic.Int64 + deadlines atomic.Int64 + readDeadlines atomic.Int64 + writeDeadlines atomic.Int64 +} + +func (c *deadlineTrackingTunnelConn) SetDeadline(deadline time.Time) error { + c.deadlineCalls.Add(1) + if c.monitoring.Load() && !deadline.IsZero() { + c.deadlines.Add(1) + } + return c.Conn.SetDeadline(deadline) +} + +func (c *deadlineTrackingTunnelConn) SetReadDeadline(deadline time.Time) error { + c.deadlineCalls.Add(1) + if c.monitoring.Load() && !deadline.IsZero() { + c.readDeadlines.Add(1) + } + return c.Conn.SetReadDeadline(deadline) +} + +func (c *deadlineTrackingTunnelConn) SetWriteDeadline(deadline time.Time) error { + c.deadlineCalls.Add(1) + if c.monitoring.Load() && !deadline.IsZero() { + c.writeDeadlines.Add(1) + } + return c.Conn.SetWriteDeadline(deadline) +} + +type deadlineTrackingTunnelListener struct{ net.Listener } + +func (l deadlineTrackingTunnelListener) Accept() (net.Conn, error) { + conn, errAccept := l.Listener.Accept() + if errAccept != nil { + return nil, errAccept + } + return &deadlineTrackingTunnelConn{Conn: conn}, nil +} + +func newDeadlineTrackingTunnelServer(t *testing.T, hub *Hub) *httptest.Server { + t.Helper() + srv := httptest.NewUnstartedServer(hub) + srv.Listener = deadlineTrackingTunnelListener{srv.Listener} + srv.Start() + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + return srv +} + +func assertNoFiniteTunnelDeadlines(t *testing.T, transport *deadlineTrackingTunnelConn) { + t.Helper() + if all, reads, writes := transport.deadlines.Load(), transport.readDeadlines.Load(), transport.writeDeadlines.Load(); all != 0 || reads != 0 || writes != 0 { + t.Fatalf("finite post-upgrade deadlines: all=%d reads=%d writes=%d, want zero", all, reads, writes) + } +} + +func TestPeerControl_PingAndCloseNeverSetFiniteDeadlines(t *testing.T) { + hub := NewHub(Options{PingInterval: time.Hour}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newDeadlineTrackingTunnelServer(t, hub) + client := dialRole(t, srv.URL, "key", RoleClient, "device", "Device") + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "device") + transport := p.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*deadlineTrackingTunnelConn) + transport.monitoring.Store(true) + pongs := make(chan string, 1) + client.SetPongHandler(func(payload string) error { + pongs <- payload + return nil + }) + client.SetCloseHandler(func(int, string) error { return nil }) + readDone := make(chan error, 1) + go func() { + _, _, errRead := client.ReadMessage() + readDone <- errRead + }() + for _, payload := range []string{"", "matching-pong", strings.Repeat("p", 125)} { + if errWrite := client.WriteControl(websocket.PingMessage, []byte(payload), time.Time{}); errWrite != nil { + t.Fatal(errWrite) + } + select { + case got := <-pongs: + if got != payload { + t.Fatalf("pong payload = %q, want %q", got, payload) + } + case errRead := <-readDone: + t.Fatalf("connection ended before pong: %v", errRead) + case <-time.After(5 * time.Second): + t.Fatal("missing pong response") + } + } + if errWrite := client.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "client close"), time.Time{}); errWrite != nil { + t.Fatal(errWrite) + } + select { + case errRead := <-readDone: + var closeErr *websocket.CloseError + if !errors.As(errRead, &closeErr) || closeErr.Code != websocket.CloseNormalClosure || closeErr.Text != "" { + t.Fatalf("close response = %v, want 1000 with empty reason", errRead) + } + case <-time.After(5 * time.Second): + t.Fatal("missing close response") + } + waitTunnelSignal(t, p.writerDone, "close response and writer exit") + assertNoFiniteTunnelDeadlines(t, transport) +} + +func TestPeerControl_EmptyCloseReceivesReplyWithoutFiniteDeadlines(t *testing.T) { + forceClose := make(chan time.Time) + hub := NewHub(Options{PingInterval: time.Hour}) + hub.testForceClose = forceClose + t.Cleanup(func() { close(forceClose) }) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newDeadlineTrackingTunnelServer(t, hub) + client := dialRole(t, srv.URL, "key", RoleClient, "device", "Device") + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "device") + transport := p.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*deadlineTrackingTunnelConn) + transport.monitoring.Store(true) + client.SetCloseHandler(func(int, string) error { return nil }) + + if errWrite := client.WriteControl(websocket.CloseMessage, []byte{}, time.Time{}); errWrite != nil { + t.Fatal(errWrite) + } + assertTunnelClose(t, client, websocket.CloseNoStatusReceived) + waitTunnelSignal(t, p.done, "empty close transport exit") + waitTunnelSignal(t, p.writerDone, "empty close response and writer exit") + assertNoFiniteTunnelDeadlines(t, transport) +} + +func TestPeerControl_PendingPongIsBoundedAndKeepsLatestPayload(t *testing.T) { + p := &peer{pongCh: make(chan string, 1), sendCh: make(chan outboundFrame)} + p.requestPong("first") + latest := strings.Repeat("p", 125) + p.requestPong(latest) + p.requestPong(strings.Repeat("x", 126)) + select { + case got := <-p.pongCh: + if got != latest { + t.Fatalf("pending pong = %q, want latest valid payload", got) + } + default: + t.Fatal("missing pending pong") + } + p.shutdownAndDrainQueue() + p.requestPong("after close") + if len(p.pongCh) != 0 { + t.Fatal("closing peer accepted another pong") + } +} + +func TestPeerControl_UnknownWebSocketOpcodeIsFatalProtocolError(t *testing.T) { + for _, opcode := range []byte{0x3, 0x7, 0xb, 0xf} { + t.Run(fmt.Sprintf("opcode=%x", opcode), func(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newDeadlineTrackingTunnelServer(t, hub) + client := dialRole(t, srv.URL, "key", RoleClient, "device", "Device") + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "device") + transport := p.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*deadlineTrackingTunnelConn) + transport.monitoring.Store(true) + // Send a final, masked, empty frame using a reserved data/control opcode. + raw := []byte{0x80 | opcode, 0x80, 0, 0, 0, 0} + if n, errWrite := client.UnderlyingConn().Write(raw); errWrite != nil { + t.Fatal(errWrite) + } else if n != len(raw) { + t.Fatal(io.ErrShortWrite) + } + // No non-fatal JSON error may precede the transport close. + assertTunnelClose(t, client, websocket.CloseProtocolError) + waitTunnelSignal(t, p.done, "protocol error transport close") + waitTunnelSignal(t, p.writerDone, "protocol error writer exit") + assertNoFiniteTunnelDeadlines(t, transport) + hub.mu.RLock() + _, registered := hub.realms["key"] + hub.mu.RUnlock() + if registered { + t.Fatal("protocol error left the peer registered") + } + }) + } +} diff --git a/internal/wstunnel/frame_inspector.go b/internal/wstunnel/frame_inspector.go new file mode 100644 index 00000000000..5eceffd8045 --- /dev/null +++ b/internal/wstunnel/frame_inspector.go @@ -0,0 +1,143 @@ +package wstunnel + +import ( + "encoding/binary" + "unicode/utf8" + + "github.com/gorilla/websocket" +) + +// frameInspector checks client framing before Gorilla can synchronously write a +// protocol-error close. Data payloads are skipped; only Close payloads are kept. +// Compression is disabled, so no RSV bits are permitted. +type frameInspector struct { + header [14]byte + headerBytes int + headerSize int + remaining uint64 + opcode byte + fragmented bool + closePayload []byte + failed bool + stopped bool +} + +func (s *frameInspector) inspect(raw []byte) bool { + if s.failed { + return false + } + if s.headerSize == 0 { + s.headerSize = 2 + } + for len(raw) > 0 && !s.stopped { + if s.headerBytes < s.headerSize { + s.header[s.headerBytes] = raw[0] + s.headerBytes++ + raw = raw[1:] + if s.headerBytes == 2 { + if !s.inspectHeader() { + s.failed = true + return false + } + } + if s.headerBytes == s.headerSize { + switch s.header[1] & 0x7f { + case 126: + s.remaining = uint64(binary.BigEndian.Uint16(s.header[2:4])) + case 127: + s.remaining = binary.BigEndian.Uint64(s.header[2:10]) + // Gorilla rejects lengths that overflow its signed counter. + if s.remaining>>63 != 0 { + s.failed = true + return false + } + default: + s.remaining = uint64(s.header[1] & 0x7f) + } + if s.remaining == 0 { + s.finishFrame() + } + } + continue + } + + size := min(uint64(len(raw)), s.remaining) + if s.opcode == websocket.CloseMessage { + for _, b := range raw[:size] { + mask := s.header[s.headerSize-4+len(s.closePayload)%4] + s.closePayload = append(s.closePayload, b^mask) + } + } + raw = raw[size:] + s.remaining -= size + if s.remaining == 0 && !s.finishFrame() { + s.failed = true + return false + } + } + return true +} + +func (s *frameInspector) inspectHeader() bool { + first, second := s.header[0], s.header[1] + if first&0x70 != 0 || second&0x80 == 0 { + return false + } + s.opcode = first & 0x0f + final := first&0x80 != 0 + switch s.opcode { + case websocket.TextMessage, websocket.BinaryMessage: + if s.fragmented { + return false + } + s.fragmented = !final + case 0: + if !s.fragmented { + return false + } + s.fragmented = !final + case websocket.CloseMessage, websocket.PingMessage, websocket.PongMessage: + if !final || second&0x7f > 125 { + return false + } + default: + return false + } + s.headerSize = 6 // Two base bytes and the mandatory four-byte client mask. + switch second & 0x7f { + case 126: + s.headerSize += 2 + case 127: + s.headerSize += 8 + } + return true +} + +func (s *frameInspector) finishFrame() bool { + if s.opcode == websocket.CloseMessage { + // RFC 6455 also forbids a one-byte Close payload, which Gorilla accepts. + if len(s.closePayload) == 1 { + return false + } + if len(s.closePayload) >= 2 { + code := int(binary.BigEndian.Uint16(s.closePayload)) + // Match Gorilla v1.5.3's received-code allowlist, not all 1xxx codes. + switch code { + case 1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013: + default: + if code < 3000 || code > 4999 { + return false + } + } + if !utf8.Valid(s.closePayload[2:]) { + return false + } + } + // Gorilla stops reading at a valid Close; trailing bytes are irrelevant. + s.stopped = true + } + s.headerBytes = 0 + s.headerSize = 2 + s.closePayload = s.closePayload[:0] + return true +} diff --git a/internal/wstunnel/frame_inspector_test.go b/internal/wstunnel/frame_inspector_test.go new file mode 100644 index 00000000000..19d7425a3d7 --- /dev/null +++ b/internal/wstunnel/frame_inspector_test.go @@ -0,0 +1,121 @@ +package wstunnel + +import ( + "encoding/binary" + "fmt" + "testing" +) + +func maskedTunnelFrame(first byte, payload []byte, lengthBytes int) []byte { + raw := []byte{first, 0x80 | byte(len(payload))} + switch lengthBytes { + case 2: + raw[1] = 0xfe + raw = binary.BigEndian.AppendUint16(raw, uint16(len(payload))) + case 8: + raw[1] = 0xff + raw = binary.BigEndian.AppendUint64(raw, uint64(len(payload))) + } + mask := [4]byte{0x12, 0x34, 0x56, 0x78} + raw = append(raw, mask[:]...) + for i, b := range payload { + raw = append(raw, b^mask[i%4]) + } + return raw +} + +func TestFrameInspector_RejectsFatalFramesAtEveryReadBoundary(t *testing.T) { + tests := []struct { + name string + raw []byte + }{ + {"RSV1", []byte{0xc2, 0x80}}, + {"RSV2", []byte{0xa2, 0x80}}, + {"RSV3", []byte{0x92, 0x80}}, + {"unmasked", []byte{0x82, 0}}, + {"unexpected continuation", []byte{0x80, 0x80}}, + {"fragmented close", []byte{0x08, 0x80}}, + {"fragmented ping", []byte{0x09, 0x80}}, + {"fragmented pong", []byte{0x0a, 0x80}}, + {"extended close length", []byte{0x88, 0xfe}}, + {"extended ping length", []byte{0x89, 0xff}}, + {"extended pong length", []byte{0x8a, 0xfe}}, + {"one-byte close", maskedTunnelFrame(0x88, []byte{0}, 0)}, + {"invalid UTF-8 close reason", maskedTunnelFrame(0x88, []byte{0x03, 0xe8, 0xff}, 0)}, + {"truncated UTF-8 close reason", maskedTunnelFrame(0x88, []byte{0x03, 0xe8, 0xe4, 0xb8}, 0)}, + {"signed length overflow", []byte{0x82, 0xff, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, + } + for _, opcode := range []byte{3, 4, 5, 6, 7, 11, 12, 13, 14, 15} { + tests = append(tests, struct { + name string + raw []byte + }{fmt.Sprintf("reserved opcode %d", opcode), []byte{0x80 | opcode, 0x80}}) + } + for _, first := range []byte{0x81, 0x82} { + raw := append(maskedTunnelFrame(0x01, []byte("fragment"), 0), first, 0x80) + tests = append(tests, struct { + name string + raw []byte + }{fmt.Sprintf("new data before FIN %d", first), raw}) + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + for split := 0; split <= len(tc.raw); split++ { + var inspector frameInspector + if inspector.inspect(tc.raw[:split]) && inspector.inspect(tc.raw[split:]) { + t.Fatalf("accepted fatal frame with split at byte %d: %x", split, tc.raw) + } + if !inspector.failed || inspector.inspect(nil) { + t.Fatal("fatal framing error was not permanent") + } + } + }) + } +} + +func TestFrameInspector_CloseCodeAllowlistMatchesGorilla(t *testing.T) { + for code := 0; code <= 65535; code++ { + payload := binary.BigEndian.AppendUint16(nil, uint16(code)) + var inspector frameInspector + got := inspector.inspect(maskedTunnelFrame(0x88, payload, 0)) + want := code >= 3000 && code <= 4999 + switch code { + case 1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013: + want = true + } + if got != want { + t.Fatalf("close code %d: accepted=%t, want %t", code, got, want) + } + } +} + +func TestFrameInspector_ValidFragmentationAndControlAtEveryReadBoundary(t *testing.T) { + raw := maskedTunnelFrame(0x01, []byte("first fragment"), 0) + raw = append(raw, maskedTunnelFrame(0x89, []byte("ping"), 0)...) + raw = append(raw, maskedTunnelFrame(0x00, nil, 0)...) + raw = append(raw, maskedTunnelFrame(0x8a, []byte("pong"), 0)...) + raw = append(raw, maskedTunnelFrame(0x80, []byte("final fragment"), 0)...) + // Gorilla accepts non-minimal extended encodings for data frames. + raw = append(raw, maskedTunnelFrame(0x82, []byte{0x83, 0x00, 0xff}, 2)...) + raw = append(raw, maskedTunnelFrame(0x82, make([]byte, 65536), 8)...) + raw = append(raw, maskedTunnelFrame(0x88, []byte{0x03, 0xe8, 0xe4, 0xb8, 0xad}, 0)...) + // A valid Close ends Gorilla's reader; subsequent bytes must not be inspected. + raw = append(raw, 0x83, 0x00) + for _, size := range []int{1, 2, 3, 4, 5, 6, 7, 8, 13, 14, 127, 4096, len(raw)} { + t.Run(fmt.Sprintf("read size %d", size), func(t *testing.T) { + var inspector frameInspector + for offset := 0; offset < len(raw); offset += size { + if !inspector.inspect(raw[offset:min(offset+size, len(raw))]) { + t.Fatalf("rejected valid input at offset %d", offset) + } + } + if !inspector.stopped || cap(inspector.closePayload) > 256 { + t.Fatal("valid Close did not stop inspection with bounded storage") + } + }) + } + var emptyClose frameInspector + if !emptyClose.inspect(maskedTunnelFrame(0x88, nil, 0)) || !emptyClose.stopped { + t.Fatal("empty Close was rejected") + } +} diff --git a/internal/wstunnel/handler.go b/internal/wstunnel/handler.go new file mode 100644 index 00000000000..e74129591cd --- /dev/null +++ b/internal/wstunnel/handler.go @@ -0,0 +1,164 @@ +package wstunnel + +import ( + "net/http" + "net/url" + "strings" + + "github.com/MoeForge/moego/ojson" + log "github.com/sirupsen/logrus" +) + +const ( + headerTunnelRole = "X-Tunnel-Role" + headerTunnelUUID = "X-Tunnel-UUID" + headerTunnelName = "X-Tunnel-Name" + headerTunnelType = "X-Tunnel-Type" +) + +// ServeHTTP authenticates access.api-keys, validates device identity, upgrades +// the HTTP connection to WebSocket, and registers the peer in its isolated realm. +func (h *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h == nil { + writeJSONError(w, http.StatusServiceUnavailable, "tunnel hub unavailable") + return + } + if r == nil { + writeJSONError(w, http.StatusBadRequest, "invalid request") + return + } + if !strings.EqualFold(r.Method, http.MethodGet) { + w.Header().Set("Allow", http.MethodGet) + writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed") + return + } + + var query url.Values + if r.URL != nil { + query = r.URL.Query() + } + + apiKey, authStatus := h.authenticateRequest(r, query) + if authStatus == http.StatusServiceUnavailable { + writeJSONError(w, http.StatusServiceUnavailable, "tunnel hub is closed") + return + } + if authStatus != 0 { + writeJSONError(w, http.StatusUnauthorized, "invalid or missing api key") + return + } + + role, errRole := NormalizeAndValidateRole(firstNonEmptyTrimmed(query.Get("role"), r.Header.Get(headerTunnelRole))) + if errRole != nil { + writeJSONError(w, http.StatusBadRequest, errRole.Error()) + return + } + uuid, errUUID := NormalizeAndValidateUUID(firstNonEmptyTrimmed(query.Get("uuid"), r.Header.Get(headerTunnelUUID))) + if errUUID != nil { + writeJSONError(w, http.StatusBadRequest, errUUID.Error()) + return + } + name, errName := NormalizeAndValidateName(firstNonEmptyTrimmed(query.Get("name"), r.Header.Get(headerTunnelName))) + if errName != nil { + writeJSONError(w, http.StatusBadRequest, errName.Error()) + return + } + var serverType string + if role == RoleServer { + var errType error + serverType, errType = NormalizeAndValidateType(firstNonEmptyTrimmed(query.Get("type"), r.Header.Get(headerTunnelType))) + if errType != nil { + writeJSONError(w, http.StatusBadRequest, errType.Error()) + return + } + } + + reservation, reserveStatus := h.reserveUUID(apiKey, uuid) + if reserveStatus != 0 { + switch reserveStatus { + case http.StatusServiceUnavailable: + writeJSONError(w, http.StatusServiceUnavailable, "tunnel hub is closed") + case http.StatusUnauthorized: + writeJSONError(w, http.StatusUnauthorized, "invalid or missing api key") + default: + writeJSONError(w, http.StatusConflict, "device uuid already connected") + } + return + } + + h.mu.RLock() + afterReserve := h.testOnAfterReserve + h.mu.RUnlock() + if afterReserve != nil { + afterReserve() + } + + guardedWriter := &deadlineGuardResponseWriter{ResponseWriter: w} + conn, errUpgrade := h.upgrader.Upgrade(guardedWriter, r, nil) + if errUpgrade != nil { + h.releaseReservation(apiKey, uuid, reservation) + log.Debugf("wstunnel: websocket upgrade failed: %v", errUpgrade) + return + } + + guardedWriter.conn.postUpgrade.Store(true) + p := newPeer(h, apiKey, uuid, name, serverType, role, conn, h.sendQueueSize, h.maxPeerQueuedBytes) + h.commitPeer(p, reservation) +} + +func (h *Hub) authenticateRequest(r *http.Request, query url.Values) (string, int) { + candidates := [5]string{ + extractBearerToken(r.Header.Get("Authorization")), + strings.TrimSpace(r.Header.Get("X-Goog-Api-Key")), + strings.TrimSpace(r.Header.Get("X-Api-Key")), + strings.TrimSpace(query.Get("key")), + strings.TrimSpace(query.Get("auth_token")), + } + + h.mu.RLock() + defer h.mu.RUnlock() + + if h.closed { + return "", http.StatusServiceUnavailable + } + if len(h.allowedKeys) == 0 { + return "", http.StatusUnauthorized + } + + for _, candidate := range candidates { + if candidate == "" { + continue + } + if _, ok := h.allowedKeys[candidate]; ok { + return candidate, 0 + } + } + return "", http.StatusUnauthorized +} + +func extractBearerToken(header string) string { + trimmed := strings.TrimSpace(header) + if trimmed == "" { + return "" + } + parts := strings.SplitN(trimmed, " ", 2) + if len(parts) == 2 && strings.EqualFold(parts[0], "bearer") { + return strings.TrimSpace(parts[1]) + } + return trimmed +} + +func firstNonEmptyTrimmed(primary, fallback string) string { + if strings.TrimSpace(primary) != "" { + return primary + } + return fallback +} + +func writeJSONError(w http.ResponseWriter, statusCode int, message string) { + doc := ojson.NewDocString("{}") + _ = doc.Set("error", message) + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(statusCode) + _, _ = w.Write(doc.Bytes()) +} diff --git a/internal/wstunnel/handshake_review_test.go b/internal/wstunnel/handshake_review_test.go new file mode 100644 index 00000000000..455a02ef660 --- /dev/null +++ b/internal/wstunnel/handshake_review_test.go @@ -0,0 +1,104 @@ +package wstunnel + +import ( + "net/http" + "net/http/httptest" + "net/url" + "sync" + "sync/atomic" + "testing" + + "github.com/gorilla/websocket" +) + +func TestHubAuth_StaleReservationReleasePreservesReplacement(t *testing.T) { + hub := NewHub(Options{}) + t.Cleanup(hub.Close) + hub.UpdateAllowedAPIKeys([]string{"key"}) + stale, status := hub.reserveUUID("key", "device") + if status != 0 { + t.Fatalf("initial reservation status = %d", status) + } + hub.UpdateAllowedAPIKeys(nil) + if len(stale.realm.reserved) != 0 || len(hub.realms) != 0 { + t.Fatal("revocation retained pending reservations") + } + hub.UpdateAllowedAPIKeys([]string{"key"}) + replacement, replacementStatus := hub.reserveUUID("key", "device") + if replacementStatus != 0 { + t.Fatalf("replacement reservation status = %d, want success", replacementStatus) + } + hub.releaseReservation("key", "device", stale) + if hub.realms["key"].reserved["device"] != replacement { + t.Fatal("stale release deleted the replacement reservation") + } + if _, duplicateStatus := hub.reserveUUID("key", "device"); duplicateStatus != http.StatusConflict { + t.Fatalf("duplicate reservation status = %d, want 409", duplicateStatus) + } + hub.releaseReservation("key", "device", replacement) + if len(hub.realms) != 0 { + t.Fatal("matching release did not reclaim the empty realm") + } +} + +func TestHubAuth_PreRevocationHandshakeCannotCommitAfterKeyIsReadded(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + reserved := make(chan struct{}) + resume := make(chan struct{}) + var reservations atomic.Int32 + hub.testOnAfterReserve = func() { + if reservations.Add(1) == 1 { + close(reserved) + <-resume + } + } + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + var resumeOnce sync.Once + resumeHandshake := func() { resumeOnce.Do(func() { close(resume) }) } + staleDone := make(chan struct{}) + var stale *websocket.Conn + var errDial error + go func() { + var resp *http.Response + stale, resp, errDial = websocket.DefaultDialer.Dial(dialTunnelURL(srv.URL, url.Values{ + "key": {"key"}, "role": {"client"}, "uuid": {"device"}, "name": {"Stale"}, + }), nil) + closeHTTPResponseBody(t, resp) + close(staleDone) + }() + t.Cleanup(func() { + resumeHandshake() + waitTunnelSignal(t, staleDone, "stale handshake completion") + if stale != nil { + if errClose := stale.Close(); errClose != nil { + t.Logf("stale connection close error: %v", errClose) + } + } + }) + waitTunnelSignal(t, reserved, "pre-revocation reservation") + hub.UpdateAllowedAPIKeys(nil) + hub.UpdateAllowedAPIKeys([]string{"key"}) + + // The new connection must succeed while the stale handshake is still paused. + current := dialRole(t, srv.URL, "key", RoleClient, "device", "Current") + _ = readTextJSONFrame(t, current) + currentPeer := lookupTunnelPeer(t, hub, "key", "device") + resumeHandshake() + waitTunnelSignal(t, staleDone, "stale WebSocket upgrade") + if errDial != nil { + t.Fatalf("stale upgrade failed before commit: %v", errDial) + } + assertTunnelClose(t, stale, websocket.ClosePolicyViolation) + if lookupTunnelPeer(t, hub, "key", "device") != currentPeer { + t.Fatal("stale commit clobbered the replacement peer") + } + if errWrite := current.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"still-current"}`)); errWrite != nil { + t.Fatal(errWrite) + } + if got := readTextJSONFrame(t, current); got.Get("request_id").String() != "still-current" { + t.Fatalf("replacement connection stopped working: %s", got.Raw) + } +} diff --git a/internal/wstunnel/hub.go b/internal/wstunnel/hub.go new file mode 100644 index 00000000000..b09c54b00e6 --- /dev/null +++ b/internal/wstunnel/hub.go @@ -0,0 +1,484 @@ +package wstunnel + +import ( + "net/http" + "sort" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/gorilla/websocket" +) + +// Options configures a WebSocket tunnel Hub. +type Options struct { + // SendQueueSize sets the per-peer outbound frame buffer capacity (default 256). + SendQueueSize int + // MaxPeerQueuedBytes caps all outbound bytes queued/in-flight for a single peer (default 64 MiB + 512). + MaxPeerQueuedBytes int64 + // MaxTenantQueuedBytes caps all outbound bytes queued/in-flight per API-key tenant. + // It defaults to the larger of 256 MiB and MaxPeerQueuedBytes. + MaxTenantQueuedBytes int64 + // PingInterval sets the periodic WebSocket Ping interval (default 30s). + PingInterval time.Duration + // PingTrigger optionally triggers immediate WebSocket Ping frames across active peers. + PingTrigger <-chan struct{} +} + +// uuidReservation binds a handshake to its original tenant generation. +type uuidReservation struct { + realm *realm +} + +type realm struct { + reserved map[string]*uuidReservation + peers map[string]*peer + queuedBytes atomic.Int64 +} + +func newRealm() *realm { + return &realm{ + reserved: make(map[string]*uuidReservation), + peers: make(map[string]*peer), + } +} + +func (r *realm) isEmpty() bool { + return r == nil || (len(r.reserved) == 0 && len(r.peers) == 0 && r.queuedBytes.Load() == 0) +} + +func (r *realm) sortedServers() []ServerInfo { + if r == nil || len(r.peers) == 0 { + return nil + } + servers := make([]ServerInfo, 0) + for _, p := range r.peers { + if p.role == RoleServer { + servers = append(servers, ServerInfo{ + UUID: p.uuid, + Name: p.name, + Type: p.serverType, + }) + } + } + sort.Slice(servers, func(i, j int) bool { + return servers[i].UUID < servers[j].UUID + }) + return servers +} + +// Hub coordinates multi-tenant WebSocket tunnel realms isolated by access.api-keys. +type Hub struct { + mu sync.RWMutex + closed bool + allowedKeys map[string]struct{} + realms map[string]*realm + + sendQueueSize int + maxPeerQueuedBytes int64 + maxTenantQueuedBytes int64 + pingInterval time.Duration + stopCh chan struct{} + stopOnce sync.Once + upgrader websocket.Upgrader + + testForceClose <-chan time.Time + testOnAfterReserve func() + testOnPeerUnregistered func(apiKey, uuid string) + testBeforeListServersEnqueue func() + testBeforeProtocolErrorReturn func() +} + +// NewHub constructs an initialized WebSocket tunnel Hub. +func NewHub(opts Options) *Hub { + queueSize := opts.SendQueueSize + if queueSize <= 0 { + queueSize = defaultSendQueueSize + } + maxPeerBytes := opts.MaxPeerQueuedBytes + if maxPeerBytes <= 0 { + maxPeerBytes = defaultMaxPeerQueuedBytes + } + maxTenantBytes := opts.MaxTenantQueuedBytes + if maxTenantBytes <= 0 { + maxTenantBytes = defaultMaxTenantQueuedBytes + if maxTenantBytes < maxPeerBytes { + maxTenantBytes = maxPeerBytes + } + } + pingInterval := opts.PingInterval + if pingInterval <= 0 { + pingInterval = defaultPingInterval + } + + h := &Hub{ + allowedKeys: make(map[string]struct{}), + realms: make(map[string]*realm), + sendQueueSize: queueSize, + maxPeerQueuedBytes: maxPeerBytes, + maxTenantQueuedBytes: maxTenantBytes, + pingInterval: pingInterval, + stopCh: make(chan struct{}), + upgrader: websocket.Upgrader{ + ReadBufferSize: 4096, + WriteBufferSize: 4096, + CheckOrigin: func(*http.Request) bool { + return true + }, + }, + } + + if opts.PingTrigger != nil { + go h.watchPingTrigger(opts.PingTrigger) + } + return h +} + +func (h *Hub) watchPingTrigger(trigger <-chan struct{}) { + for { + select { + case <-h.stopCh: + return + case _, ok := <-trigger: + if !ok { + return + } + h.broadcastPing() + } + } +} + +func (h *Hub) broadcastPing() { + h.mu.RLock() + var targets []*peer + for _, rlm := range h.realms { + for _, p := range rlm.peers { + targets = append(targets, p) + } + } + h.mu.RUnlock() + + for _, p := range targets { + p.requestPing() + } +} + +// UpdateAllowedAPIKeys atomically updates the allowed access.api-keys set and +// immediately disconnects all peers belonging to revoked keys. +func (h *Hub) UpdateAllowedAPIKeys(keys []string) { + if h == nil { + return + } + normalized := make(map[string]struct{}, len(keys)) + for _, raw := range keys { + trimmed := strings.TrimSpace(raw) + if trimmed == "" { + continue + } + normalized[trimmed] = struct{}{} + } + + var evicted []*peer + h.mu.Lock() + if h.closed { + h.mu.Unlock() + return + } + h.allowedKeys = normalized + for apiKey, rlm := range h.realms { + if _, ok := normalized[apiKey]; ok { + continue + } + for _, p := range rlm.peers { + evicted = append(evicted, p) + } + clear(rlm.reserved) + clear(rlm.peers) + if rlm.isEmpty() { + delete(h.realms, apiKey) + } + } + h.mu.Unlock() + + for _, p := range evicted { + p.close(websocket.ClosePolicyViolation, "api key revoked", false) + } +} + +// Close shuts down the Hub and closes all active tunnel connections. +func (h *Hub) Close() { + if h == nil { + return + } + h.stopOnce.Do(func() { + close(h.stopCh) + + var evicted []*peer + h.mu.Lock() + h.closed = true + for _, rlm := range h.realms { + for _, p := range rlm.peers { + evicted = append(evicted, p) + } + } + h.realms = make(map[string]*realm) + h.allowedKeys = make(map[string]struct{}) + h.mu.Unlock() + + for _, p := range evicted { + p.close(websocket.CloseGoingAway, "server shutting down", false) + } + }) +} + +func (h *Hub) reserveUUID(apiKey, uuid string) (*uuidReservation, int) { + h.mu.Lock() + defer h.mu.Unlock() + + if h.closed { + return nil, http.StatusServiceUnavailable + } + if _, ok := h.allowedKeys[apiKey]; !ok { + return nil, http.StatusUnauthorized + } + rlm := h.realms[apiKey] + if rlm == nil { + rlm = newRealm() + h.realms[apiKey] = rlm + } + if _, exists := rlm.peers[uuid]; exists { + return nil, http.StatusConflict + } + if _, reserved := rlm.reserved[uuid]; reserved { + return nil, http.StatusConflict + } + reservation := &uuidReservation{realm: rlm} + rlm.reserved[uuid] = reservation + return reservation, 0 +} + +func (h *Hub) releaseReservation(apiKey, uuid string, reservation *uuidReservation) { + h.mu.Lock() + defer h.mu.Unlock() + + rlm := h.realms[apiKey] + if rlm == nil || reservation == nil || rlm.reserved[uuid] != reservation { + return + } + delete(rlm.reserved, uuid) + if rlm.isEmpty() { + delete(h.realms, apiKey) + } +} + +func (h *Hub) pruneRealm(apiKey string, rlm *realm) { + h.mu.Lock() + defer h.mu.Unlock() + + if h.realms[apiKey] == rlm && rlm.isEmpty() { + delete(h.realms, apiKey) + } +} + +func (h *Hub) commitPeer(p *peer, reservation *uuidReservation) bool { + var overflowClients []*peer + + h.mu.Lock() + rlm := h.realms[p.apiKey] + reservationValid := rlm != nil && reservation != nil && reservation.realm == rlm && rlm.reserved[p.uuid] == reservation + if reservationValid { + delete(rlm.reserved, p.uuid) + } + _, keyAllowed := h.allowedKeys[p.apiKey] + if h.closed || !keyAllowed || !reservationValid { + closeCode := websocket.ClosePolicyViolation + reason := "api key revoked" + if h.closed { + closeCode = websocket.CloseGoingAway + reason = "server shutting down" + } + if rlm != nil && rlm.isEmpty() { + delete(h.realms, p.apiKey) + } + h.mu.Unlock() + + go p.writeLoop(0) + p.close(closeCode, reason, false) + return false + } + + p.tenant = rlm + if p.role == RoleClient { + rawList, errEncode := EncodeServerListFrame("", rlm.sortedServers()) + if errEncode == nil { + if !p.tryEnqueueControl(outboundFrame{ + messageType: websocket.TextMessage, + data: rawList, + }) { + overflowClients = append(overflowClients, p) + } + } + rlm.peers[p.uuid] = p + } else { + rlm.peers[p.uuid] = p + rawOnline, errEncode := EncodeServerEventFrame(ControlTypeServerOnline, ServerInfo{ + UUID: p.uuid, + Name: p.name, + Type: p.serverType, + }) + if errEncode == nil { + frame := outboundFrame{ + messageType: websocket.TextMessage, + data: rawOnline, + } + for _, member := range rlm.peers { + if member.role != RoleClient { + continue + } + if !member.tryEnqueueControl(frame) { + overflowClients = append(overflowClients, member) + } + } + } + } + h.mu.Unlock() + + for _, slow := range overflowClients { + slow.close(websocket.ClosePolicyViolation, "control queue overflow", true) + } + + go p.writeLoop(h.pingInterval) + go p.readLoop() + return true +} + +func (h *Hub) unregisterPeer(p *peer, notifyRealm bool) { + if h == nil || p == nil { + return + } + + var ( + removed bool + overflowClients []*peer + ) + + h.mu.Lock() + rlm := h.realms[p.apiKey] + if rlm != nil { + if existing := rlm.peers[p.uuid]; existing == p { + delete(rlm.peers, p.uuid) + removed = true + if notifyRealm && p.role == RoleServer && !h.closed { + rawOffline, errEncode := EncodeServerEventFrame(ControlTypeServerOffline, ServerInfo{ + UUID: p.uuid, + Name: p.name, + Type: p.serverType, + }) + if errEncode == nil { + frame := outboundFrame{ + messageType: websocket.TextMessage, + data: rawOffline, + } + for _, member := range rlm.peers { + if member.role != RoleClient { + continue + } + if !member.tryEnqueueControl(frame) { + overflowClients = append(overflowClients, member) + } + } + } + } + } + if rlm.isEmpty() { + delete(h.realms, p.apiKey) + } + } + onUnregistered := h.testOnPeerUnregistered + h.mu.Unlock() + + for _, slow := range overflowClients { + slow.close(websocket.ClosePolicyViolation, "control queue overflow", true) + } + if removed && onUnregistered != nil { + onUnregistered(p.apiKey, p.uuid) + } +} + +func (h *Hub) handleControlMessage(sender *peer, raw []byte) { + req, errCode, errParse := ParseControlFrame(raw) + if errParse != nil { + sender.sendError(errCode, errParse.Error(), "", "") + return + } + + switch req.Type { + case ControlTypeListServers: + if sender.role != RoleClient { + sender.sendError(ErrCodeUnsupportedRoleAction, "only client peers can request server_list", "", req.RequestID) + return + } + // Hold RLock across snapshot + enqueue so list_servers cannot overtake concurrent server_online/server_offline broadcasts. + h.mu.RLock() + rlm := h.realms[sender.apiKey] + if rlm == nil || rlm.peers[sender.uuid] != sender { + h.mu.RUnlock() + return + } + servers := rlm.sortedServers() + rawList, errEncode := EncodeServerListFrame(req.RequestID, servers) + if errEncode != nil { + h.mu.RUnlock() + return + } + if hook := h.testBeforeListServersEnqueue; hook != nil && req.RequestID == "race-snapshot" { + hook() + } + enqueued := sender.tryEnqueueControl(outboundFrame{ + messageType: websocket.TextMessage, + data: rawList, + }) + h.mu.RUnlock() + if !enqueued { + sender.close(websocket.ClosePolicyViolation, "control queue overflow", true) + } + } +} + +func (h *Hub) handleDataMessage(sender *peer, rawFrame []byte) { + view, errCode, errParse := ParseDataFrameHeader(rawFrame) + if errParse != nil { + sender.sendError(errCode, errParse.Error(), "", "") + return + } + if view.SrcUUID != sender.uuid { + sender.sendError(ErrCodeSourceUUIDMismatch, "frame source uuid does not match authenticated device uuid", "", "") + return + } + + h.mu.RLock() + rlm := h.realms[sender.apiKey] + if rlm == nil || rlm.peers[sender.uuid] != sender { + h.mu.RUnlock() + return + } + target := rlm.peers[view.DstUUID] + if target == nil { + h.mu.RUnlock() + sender.sendError(ErrCodeTargetNotFound, "target peer is not connected", view.DstUUID, "") + return + } + if target.role == sender.role { + h.mu.RUnlock() + sender.sendError(ErrCodeInvalidTargetRole, "cannot route data between peers of the same role", view.DstUUID, "") + return + } + + // Keep membership validation and enqueue atomic with respect to revocation. + enqueued := target.tryEnqueueData(rawFrame) + h.mu.RUnlock() + if !enqueued { + sender.sendError(ErrCodeTargetBufferFull, "target peer send buffer is full", view.DstUUID, "") + } +} diff --git a/internal/wstunnel/hub_auth_test.go b/internal/wstunnel/hub_auth_test.go new file mode 100644 index 00000000000..4012ff6fe86 --- /dev/null +++ b/internal/wstunnel/hub_auth_test.go @@ -0,0 +1,471 @@ +package wstunnel + +import ( + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gorilla/websocket" +) + +func dialTunnelURL(serverURL string, query url.Values) string { + wsBase := "ws" + strings.TrimPrefix(serverURL, "http") + "/v1/tunnel" + if len(query) > 0 { + wsBase += "?" + query.Encode() + } + return wsBase +} + +func closeHTTPResponseBody(t *testing.T, resp *http.Response) { + t.Helper() + if resp == nil || resp.Body == nil { + return + } + if errClose := resp.Body.Close(); errClose != nil { + t.Logf("response body close error: %v", errClose) + } +} + +func registerCleanupConn(t *testing.T, conn *websocket.Conn) { + t.Helper() + t.Cleanup(func() { + if conn != nil { + _ = conn.Close() + } + }) +} + +func readTextJSONFrame(t *testing.T, conn *websocket.Conn) ojson.Result { + t.Helper() + msgType, raw, errRead := readTunnelTestMessage(conn) + if errRead != nil { + t.Fatalf("ReadMessage() error = %v", errRead) + } + if msgType != websocket.TextMessage { + t.Fatalf("message type = %d, want TextMessage (%d)", msgType, websocket.TextMessage) + } + if !ojson.ValidBytes(raw) { + t.Fatalf("invalid json frame: %s", string(raw)) + } + return ojson.ParseBytes(raw) +} + +// waitServersVisible drains control frames on conn until every uuid in want +// has been observed on the client (via an initial server_list or incremental +// server_online events). The WebSocket handshake completing does not guarantee +// commitPeer has published a concurrently-dialing server, and a server already +// present in the initial list produces no server_online, so all pending uuids +// must be collected across a single drain rather than one frame per uuid. +func waitServersVisible(t *testing.T, conn *websocket.Conn, want ...string) { + t.Helper() + pending := make(map[string]struct{}, len(want)) + for _, uuid := range want { + pending[uuid] = struct{}{} + } + deadline := time.Now().Add(5 * time.Second) + for len(pending) > 0 && time.Now().Before(deadline) { + frame := readTextJSONFrame(t, conn) + switch frame.Get("type").String() { + case ControlTypeServerList: + count := int(frame.Get("servers.#").Int()) + for i := 0; i < count; i++ { + delete(pending, frame.Get(fmt.Sprintf("servers.%d.uuid", i)).String()) + } + case ControlTypeServerOnline: + delete(pending, frame.Get("server.uuid").String()) + } + } + if len(pending) > 0 { + t.Fatalf("timed out waiting for servers to become visible: %v", pending) + } +} + +func TestHubAuth_MethodAndCredentials(t *testing.T) { + hub := NewHub(Options{}) + t.Cleanup(hub.Close) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + t.Run("non-GET method returns 405 with Allow GET", func(t *testing.T) { + req, errReq := http.NewRequest(http.MethodPost, srv.URL+"/v1/tunnel", nil) + if errReq != nil { + t.Fatalf("NewRequest error = %v", errReq) + } + resp, errDo := http.DefaultClient.Do(req) + if errDo != nil { + t.Fatalf("Do error = %v", errDo) + } + defer closeHTTPResponseBody(t, resp) + if resp.StatusCode != http.StatusMethodNotAllowed { + t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusMethodNotAllowed) + } + if gotAllow := resp.Header.Get("Allow"); gotAllow != http.MethodGet { + t.Fatalf("Allow = %q, want %q", gotAllow, http.MethodGet) + } + }) + + t.Run("empty allowedKeys rejects even with credential", func(t *testing.T) { + q := url.Values{"role": {"client"}, "uuid": {"c1"}, "name": {"Client 1"}, "key": {"any-key"}} + _, resp, errDial := websocket.DefaultDialer.Dial(dialTunnelURL(srv.URL, q), nil) + defer closeHTTPResponseBody(t, resp) + if errDial == nil { + t.Fatal("Dial succeeded with empty allowedKeys, want 401") + } + if resp == nil || resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("status = %v, want 401", resp) + } + body, _ := io.ReadAll(resp.Body) + if ojson.GetBytes(body, "error").String() != "invalid or missing api key" { + t.Fatalf("error body = %s, want invalid or missing api key", string(body)) + } + }) + + hub.UpdateAllowedAPIKeys([]string{" key-alpha ", "", "key-beta", "key-alpha"}) + + t.Run("missing or wrong credential returns 401", func(t *testing.T) { + for _, badKey := range []string{"", "wrong-key"} { + q := url.Values{"role": {"client"}, "uuid": {"c1"}, "name": {"Client 1"}} + if badKey != "" { + q.Set("key", badKey) + } + _, resp, errDial := websocket.DefaultDialer.Dial(dialTunnelURL(srv.URL, q), nil) + closeHTTPResponseBody(t, resp) + if errDial == nil || resp == nil || resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("Dial(key=%q) = (%v, %v), want 401", badKey, resp, errDial) + } + } + }) + + t.Run("all five credential sources and multi-candidate fallback work", func(t *testing.T) { + cases := []struct { + name string + headers http.Header + query url.Values + uuid string + }{ + { + name: "Authorization Bearer", + headers: http.Header{"Authorization": {"Bearer key-alpha"}}, + query: url.Values{"role": {"server"}, "uuid": {"u-auth-bearer"}, "name": {"S1"}, "type": {"s"}}, + uuid: "u-auth-bearer", + }, + { + name: "X-Goog-Api-Key", + headers: http.Header{"X-Goog-Api-Key": {"key-alpha"}}, + query: url.Values{"role": {"server"}, "uuid": {"u-goog"}, "name": {"S2"}, "type": {"type-2"}}, + uuid: "u-goog", + }, + { + name: "X-Api-Key", + headers: http.Header{"X-Api-Key": {"key-alpha"}}, + query: url.Values{"role": {"server"}, "uuid": {"u-xapi"}, "name": {"S3"}, "type": {"type-3"}}, + uuid: "u-xapi", + }, + { + name: "query key", + query: url.Values{"key": {"key-alpha"}, "role": {"server"}, "uuid": {"u-qkey"}, "name": {"S4"}, "type": {"type-4"}}, + uuid: "u-qkey", + }, + { + name: "query auth_token", + query: url.Values{"auth_token": {"key-alpha"}, "role": {"server"}, "uuid": {"u-qtoken"}, "name": {"S5"}, "type": {"type-5"}}, + uuid: "u-qtoken", + }, + { + name: "invalid Authorization falls back to valid query key", + headers: http.Header{"Authorization": {"Bearer invalid-first"}}, + query: url.Values{"key": {"key-beta"}, "role": {"client"}, "uuid": {"u-fallback"}, "name": {"C-Fallback"}}, + uuid: "u-fallback", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + conn, resp, errDial := websocket.DefaultDialer.Dial(dialTunnelURL(srv.URL, tc.query), tc.headers) + closeHTTPResponseBody(t, resp) + if errDial != nil { + t.Fatalf("Dial() error = %v", errDial) + } + registerCleanupConn(t, conn) + if tc.query.Get("role") == "client" { + frame := readTextJSONFrame(t, conn) + if frame.Get("type").String() != ControlTypeServerList || frame.Get("servers.#").Int() != 0 { + t.Fatalf("fallback client expected empty key-beta server_list, got %s", frame.Raw) + } + } + }) + } + }) + + t.Run("header fallback for role uuid name type and 400 validation errors", func(t *testing.T) { + headers := http.Header{ + "Authorization": {"Bearer key-beta"}, + "X-Tunnel-Role": {"SERVER"}, + "X-Tunnel-UUID": {"hdr-srv-1"}, + "X-Tunnel-Name": {"Header Server"}, + "X-Tunnel-Type": {" Header-Type-01 "}, + } + // Blank query type must fall back to X-Tunnel-Type; non-blank query type overrides header. + conn, resp, errDial := websocket.DefaultDialer.Dial(dialTunnelURL(srv.URL, url.Values{"type": {" "}}), headers) + closeHTTPResponseBody(t, resp) + if errDial != nil { + t.Fatalf("Dial with X-Tunnel-* headers error = %v", errDial) + } + registerCleanupConn(t, conn) + + overrideConn, overResp, errOver := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"server"}, "uuid": {"hdr-srv-2"}, "name": {"Override Server"}, "type": {"Query-Type"}}), + http.Header{"Authorization": {"Bearer key-beta"}, "X-Tunnel-Type": {"Ignored-Header-Type"}}, + ) + closeHTTPResponseBody(t, overResp) + if errOver != nil { + t.Fatalf("Dial with query type override error = %v", errOver) + } + registerCleanupConn(t, overrideConn) + + // Client role ignores type (both omitted and blank/arbitrary values allowed). + cliCheck, cliResp, errCli := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"client"}, "uuid": {"hdr-cli-check"}, "name": {"Client Check"}}), + http.Header{"Authorization": {"Bearer key-beta"}}, + ) + closeHTTPResponseBody(t, cliResp) + if errCli != nil { + t.Fatalf("Dial client without type error = %v", errCli) + } + registerCleanupConn(t, cliCheck) + listFrame := readTextJSONFrame(t, cliCheck) + if listFrame.Get("servers.#").Int() != 2 || + listFrame.Get("servers.0.uuid").String() != "hdr-srv-1" || + listFrame.Get("servers.0.type").String() != "Header-Type-01" || + listFrame.Get("servers.1.uuid").String() != "hdr-srv-2" || + listFrame.Get("servers.1.type").String() != "Query-Type" { + t.Fatalf("unexpected server_list types: %s", listFrame.Raw) + } + + cliWithBlankType, cliBlankResp, errCliBlank := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"client"}, "uuid": {"hdr-cli-blank-type"}, "name": {"Client Blank Type"}, "type": {""}}), + http.Header{"Authorization": {"Bearer key-beta"}}, + ) + closeHTTPResponseBody(t, cliBlankResp) + if errCliBlank != nil { + t.Fatalf("Dial client with empty type error = %v", errCliBlank) + } + registerCleanupConn(t, cliWithBlankType) + _ = readTextJSONFrame(t, cliWithBlankType) + + badCases := []struct { + query url.Values + wantErr string + }{ + {url.Values{"role": {"invalid"}, "uuid": {"u1"}, "name": {"n1"}}, "invalid or missing role: must be client or server"}, + {url.Values{"role": {"client"}, "uuid": {"bad uuid"}, "name": {"n1"}}, "invalid or missing uuid"}, + {url.Values{"role": {"client"}, "uuid": {"u1"}, "name": {" "}}, "invalid or missing name"}, + {url.Values{"role": {"server"}, "uuid": {"u-no-type"}, "name": {"n1"}}, "invalid or missing type"}, + {url.Values{"role": {"server"}, "uuid": {"u-no-type"}, "name": {"n1"}, "type": {""}}, "invalid or missing type"}, + {url.Values{"role": {"server"}, "uuid": {"u-no-type"}, "name": {"n1"}, "type": {" "}}, "invalid or missing type"}, + {url.Values{"role": {"server"}, "uuid": {"u-no-type"}, "name": {"n1"}, "type": {"bad\ttype"}}, "invalid or missing type"}, + {url.Values{"role": {"server"}, "uuid": {"u-no-type"}, "name": {"n1"}, "type": {strings.Repeat("t", MaxServerTypeLen+1)}}, "invalid or missing type"}, + } + for _, bc := range badCases { + _, badResp, errBad := websocket.DefaultDialer.Dial(dialTunnelURL(srv.URL, bc.query), http.Header{"Authorization": {"Bearer key-beta"}}) + var errBody []byte + if badResp != nil && badResp.Body != nil { + errBody, _ = io.ReadAll(badResp.Body) + } + closeHTTPResponseBody(t, badResp) + if errBad == nil || badResp == nil || badResp.StatusCode != http.StatusBadRequest { + t.Fatalf("Dial(%v) = (%v, %v), want 400", bc.query, badResp, errBad) + } + if gotErr := ojson.GetBytes(errBody, "error").String(); gotErr != bc.wantErr { + t.Fatalf("Dial(%v) error = %q, want %q", bc.query, gotErr, bc.wantErr) + } + } + + // Failed server type validation must not reserve the UUID; single-character type succeeds. + afterRejectConn, afterRejectResp, errAfterReject := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"server"}, "uuid": {"u-no-type"}, "name": {"Recovered"}, "type": {"x"}}), + http.Header{"Authorization": {"Bearer key-beta"}}, + ) + closeHTTPResponseBody(t, afterRejectResp) + if errAfterReject != nil { + t.Fatalf("Dial after 400 type rejection failed (UUID leaked?): %v", errAfterReject) + } + registerCleanupConn(t, afterRejectConn) + }) +} + +func TestHubAuth_UUIDUniquenessConcurrencyAndDuplicateNames(t *testing.T) { + unregisteredCh := make(chan string, 16) + hub := NewHub(Options{}) + hub.testOnPeerUnregistered = func(_, uuid string) { + select { + case unregisteredCh <- uuid: + default: + } + } + hub.UpdateAllowedAPIKeys([]string{"key-1"}) + t.Cleanup(hub.Close) + + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + authHdr := http.Header{"Authorization": {"Bearer key-1"}} + + t.Run("cross-role and same-role duplicate uuid rejected with 409, reconnect allowed after disconnect", func(t *testing.T) { + srvConn, resp, errDial := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"server"}, "uuid": {"dup-uuid"}, "name": {"Shared Name"}, "type": {"shared-type"}}), + authHdr, + ) + closeHTTPResponseBody(t, resp) + if errDial != nil { + t.Fatalf("initial server dial error = %v", errDial) + } + + for _, role := range []string{"server", "client"} { + dupQuery := url.Values{"role": {role}, "uuid": {"dup-uuid"}, "name": {"Another"}} + if role == "server" { + dupQuery.Set("type", "another-type") + } + _, dupResp, errDup := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, dupQuery), + authHdr, + ) + closeHTTPResponseBody(t, dupResp) + if errDup == nil || dupResp == nil || dupResp.StatusCode != http.StatusConflict { + t.Fatalf("duplicate uuid with role=%s got (%v, %v), want 409", role, dupResp, errDup) + } + } + + _ = srvConn.Close() + select { + case gotUUID := <-unregisteredCh: + if gotUUID != "dup-uuid" { + t.Fatalf("unregistered uuid = %q, want dup-uuid", gotUUID) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for dup-uuid unregister") + } + + reConn, reResp, errReDial := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"client"}, "uuid": {"dup-uuid"}, "name": {"Reconnected"}}), + authHdr, + ) + closeHTTPResponseBody(t, reResp) + if errReDial != nil { + t.Fatalf("reconnect after disconnect error = %v", errReDial) + } + registerCleanupConn(t, reConn) + _ = readTextJSONFrame(t, reConn) + }) + + t.Run("16 concurrent dials with same uuid admit exactly 1 and reject 15 with 409", func(t *testing.T) { + const workers = 16 + var ( + wg sync.WaitGroup + startGate = make(chan struct{}) + okCount atomic.Int32 + conflict atomic.Int32 + winnerMu sync.Mutex + winner *websocket.Conn + ) + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-startGate + c, resp, errDial := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"server"}, "uuid": {"race-uuid"}, "name": {"RaceNode"}, "type": {"race-type"}}), + authHdr, + ) + closeHTTPResponseBody(t, resp) + if errDial == nil { + okCount.Add(1) + winnerMu.Lock() + winner = c + winnerMu.Unlock() + return + } + if resp != nil && resp.StatusCode == http.StatusConflict { + conflict.Add(1) + } + }() + } + close(startGate) + wg.Wait() + if winner != nil { + registerCleanupConn(t, winner) + } + if okCount.Load() != 1 || conflict.Load() != workers-1 { + t.Fatalf("concurrent race results: ok=%d conflict=%d, want ok=1 conflict=%d", okCount.Load(), conflict.Load(), workers-1) + } + }) + + t.Run("duplicate device names and server types with distinct uuids coexist", func(t *testing.T) { + for _, id := range []string{"same-name-srv-1", "same-name-srv-2"} { + c, resp, errDial := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"server"}, "uuid": {id}, "name": {"Identical Name"}, "type": {"Identical Type"}}), + authHdr, + ) + closeHTTPResponseBody(t, resp) + if errDial != nil { + t.Fatalf("dial server %s error = %v", id, errDial) + } + registerCleanupConn(t, c) + } + for _, id := range []string{"same-name-cli-1", "same-name-cli-2"} { + c, resp, errDial := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"client"}, "uuid": {id}, "name": {"Identical Name"}}), + authHdr, + ) + closeHTTPResponseBody(t, resp) + if errDial != nil { + t.Fatalf("dial client %s error = %v", id, errDial) + } + registerCleanupConn(t, c) + _ = readTextJSONFrame(t, c) + } + }) +} + +func TestHubAuth_PreCommitKeyRevocationAndClosedHub(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"ephemeral-key"}) + hub.testOnAfterReserve = func() { + hub.UpdateAllowedAPIKeys(nil) + } + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + conn, resp, errDial := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"client"}, "uuid": {"revoked-mid-upgrade"}, "name": {"Client"}}), + http.Header{"Authorization": {"Bearer ephemeral-key"}}, + ) + closeHTTPResponseBody(t, resp) + if errDial == nil { + registerCleanupConn(t, conn) + + _, _, errRead := readTunnelTestMessage(conn) + var closeErr *websocket.CloseError + if !errors.As(errRead, &closeErr) || closeErr.Code != websocket.ClosePolicyViolation { + t.Fatalf("expected ClosePolicyViolation (1008) on pre-commit key revocation, got %v", errRead) + } + } + + hub.Close() + _, closedResp, errClosedDial := websocket.DefaultDialer.Dial( + dialTunnelURL(srv.URL, url.Values{"role": {"client"}, "uuid": {"after-close"}, "name": {"Client"}}), + http.Header{"Authorization": {"Bearer ephemeral-key"}}, + ) + closeHTTPResponseBody(t, closedResp) + if errClosedDial == nil || closedResp == nil || closedResp.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("Dial after Hub.Close() = (%v, %v), want 503", closedResp, errClosedDial) + } +} diff --git a/internal/wstunnel/hub_exchange_test.go b/internal/wstunnel/hub_exchange_test.go new file mode 100644 index 00000000000..0a116edfa2b --- /dev/null +++ b/internal/wstunnel/hub_exchange_test.go @@ -0,0 +1,625 @@ +package wstunnel + +import ( + "bytes" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gorilla/websocket" +) + +func dialRole(t *testing.T, serverURL, apiKey string, role Role, uuid, name string) *websocket.Conn { + t.Helper() + serverType := "" + if role == RoleServer { + serverType = "test-server" + } + return dialRoleWithType(t, serverURL, apiKey, role, uuid, name, serverType) +} + +func dialRoleWithType(t *testing.T, serverURL, apiKey string, role Role, uuid, name, serverType string) *websocket.Conn { + t.Helper() + q := url.Values{ + "role": {string(role)}, + "uuid": {uuid}, + "name": {name}, + } + if serverType != "" { + q.Set("type", serverType) + } + conn, resp, errDial := websocket.DefaultDialer.Dial( + dialTunnelURL(serverURL, q), + http.Header{"Authorization": {"Bearer " + apiKey}}, + ) + closeHTTPResponseBody(t, resp) + if errDial != nil { + t.Fatalf("dialRole(%s, %s) error = %v", role, uuid, errDial) + } + registerCleanupConn(t, conn) + return conn +} + +func readBinaryDataFrame(t *testing.T, conn *websocket.Conn) DataFrameView { + t.Helper() + msgType, raw, errRead := readTunnelTestMessage(conn) + if errRead != nil { + t.Fatalf("ReadMessage() error = %v", errRead) + } + if msgType != websocket.BinaryMessage { + t.Fatalf("message type = %d (%s), want BinaryMessage", msgType, string(raw)) + } + view, code, errParse := ParseDataFrameHeader(raw) + if errParse != nil || code != "" { + t.Fatalf("ParseDataFrameHeader() = (%+v, %q, %v)", view, code, errParse) + } + return view +} + +func TestHubExchange_TenantIsolation(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key-1", "key-2"}) + t.Cleanup(hub.Close) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + // Same UUIDs registered under two distinct api-keys must not collide or leak. + srv1 := dialRole(t, srv.URL, "key-1", RoleServer, "shared-srv-uuid", "Tenant1-Server") + srv2 := dialRole(t, srv.URL, "key-2", RoleServer, "shared-srv-uuid", "Tenant2-Server") + _ = dialRole(t, srv.URL, "key-2", RoleServer, "only-in-tenant-2", "Secret-Server-2") + + cli1 := dialRole(t, srv.URL, "key-1", RoleClient, "shared-cli-uuid", "Tenant1-Client") + cli2 := dialRole(t, srv.URL, "key-2", RoleClient, "shared-cli-uuid", "Tenant2-Client") + + // The client Dial returns as soon as the WebSocket handshake finishes, but + // commitPeer may not yet have published every registered server. Drain the + // topology stream until each expected server is observable; an initial + // server_list is followed only by incremental server_online events, so each + // uuid must be awaited rather than assuming one snapshot has all of them. + waitServersVisible(t, cli1, "shared-srv-uuid") + waitServersVisible(t, cli2, "shared-srv-uuid", "only-in-tenant-2") + + // Verify no cross-tenant leak with explicit list_servers snapshots. + if errWrite := cli1.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"t1"}`)); errWrite != nil { + t.Fatalf("cli1 list_servers error = %v", errWrite) + } + list1 := readTextJSONFrame(t, cli1) + if list1.Get("servers.#").Int() != 1 || list1.Get("servers.0.name").String() != "Tenant1-Server" { + t.Fatalf("tenant 1 server_list leaked or wrong: %s", list1.Raw) + } + if errWrite := cli2.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"t2"}`)); errWrite != nil { + t.Fatalf("cli2 list_servers error = %v", errWrite) + } + list2 := readTextJSONFrame(t, cli2) + if list2.Get("servers.#").Int() != 2 { + t.Fatalf("tenant 2 server_list count = %d, want 2 (%s)", list2.Get("servers.#").Int(), list2.Raw) + } + + // Sending to shared-srv-uuid from cli1 must reach srv1 and never srv2. + pkt1, errEncode := EncodeDataFrame(PayloadTypeText, "shared-cli-uuid", "shared-srv-uuid", []byte("hello-tenant-1")) + if errEncode != nil { + t.Fatalf("EncodeDataFrame error = %v", errEncode) + } + if errWrite := cli1.WriteMessage(websocket.BinaryMessage, pkt1); errWrite != nil { + t.Fatalf("cli1 WriteMessage error = %v", errWrite) + } + got1 := readBinaryDataFrame(t, srv1) + if got1.SrcUUID != "shared-cli-uuid" || string(got1.Payload) != "hello-tenant-1" { + t.Fatalf("srv1 got unexpected packet: %+v", got1) + } + + // Attempting to address a UUID that exists only in key-2 from key-1 must return target_not_found. + crossPkt, errCross := EncodeDataFrame(PayloadTypeBinary, "shared-cli-uuid", "only-in-tenant-2", []byte{1, 2, 3}) + if errCross != nil { + t.Fatalf("EncodeDataFrame error = %v", errCross) + } + if errWrite := cli1.WriteMessage(websocket.BinaryMessage, crossPkt); errWrite != nil { + t.Fatalf("cli1 WriteMessage error = %v", errWrite) + } + errFrame := readTextJSONFrame(t, cli1) + if errFrame.Get("type").String() != ControlTypeError || errFrame.Get("code").String() != ErrCodeTargetNotFound { + t.Fatalf("expected target_not_found across tenants, got %s", errFrame.Raw) + } + _ = srv2 +} + +func TestHubExchange_DiscoveryEventsAndControlCommands(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key-disc"}) + t.Cleanup(hub.Close) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + // Connect servers out of lexicographical order to verify deterministic sorting and custom types. + srvB := dialRoleWithType(t, srv.URL, "key-disc", RoleServer, "srv-b", "Server B", "linux-builder") + _ = dialRoleWithType(t, srv.URL, "key-disc", RoleServer, "srv-a", "Server A", "cpa-desktop") + + cli := dialRole(t, srv.URL, "key-disc", RoleClient, "cli-1", "Client 1") + // Drain the topology stream until both pre-connected servers are visible; + // their commitPeer may not have run before the client's snapshot was taken. + waitServersVisible(t, cli, "srv-a", "srv-b") + if errWrite := cli.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"init"}`)); errWrite != nil { + t.Fatalf("cli list_servers error = %v", errWrite) + } + initial := readTextJSONFrame(t, cli) + if initial.Get("type").String() != ControlTypeServerList || + initial.Get("servers.#").Int() != 2 || + initial.Get("servers.0.uuid").String() != "srv-a" || + initial.Get("servers.0.type").String() != "cpa-desktop" || + initial.Get("servers.1.uuid").String() != "srv-b" || + initial.Get("servers.1.type").String() != "linux-builder" { + t.Fatalf("unexpected initial server_list: %s", initial.Raw) + } + + // Dynamic server_online push when srv-c joins with arbitrary custom type. + srvC := dialRoleWithType(t, srv.URL, "key-disc", RoleServer, "srv-c", "Server C", "GPU 节点 🚀") + online := readTextJSONFrame(t, cli) + if online.Get("type").String() != ControlTypeServerOnline || + online.Get("server.uuid").String() != "srv-c" || + online.Get("server.name").String() != "Server C" || + online.Get("server.type").String() != "GPU 节点 🚀" { + t.Fatalf("unexpected server_online: %s", online.Raw) + } + + // Explicit list_servers query with request_id echo. + if errWrite := cli.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"req-sync-1"}`)); errWrite != nil { + t.Fatalf("WriteMessage(list_servers) error = %v", errWrite) + } + refreshed := readTextJSONFrame(t, cli) + if refreshed.Get("type").String() != ControlTypeServerList || + refreshed.Get("request_id").String() != "req-sync-1" || + refreshed.Get("servers.#").Int() != 3 || + refreshed.Get("servers.2.uuid").String() != "srv-c" || + refreshed.Get("servers.2.type").String() != "GPU 节点 🚀" { + t.Fatalf("unexpected refreshed server_list: %s", refreshed.Raw) + } + + // Server role attempting list_servers gets unsupported_role_action without disconnecting. + if errWrite := srvB.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers"}`)); errWrite != nil { + t.Fatalf("srvB WriteMessage error = %v", errWrite) + } + srvErr := readTextJSONFrame(t, srvB) + if srvErr.Get("code").String() != ErrCodeUnsupportedRoleAction { + t.Fatalf("expected unsupported_role_action for server list_servers, got %s", srvErr.Raw) + } + + // Dynamic server_offline push when srv-c disconnects. + _ = srvC.Close() + offline := readTextJSONFrame(t, cli) + if offline.Get("type").String() != ControlTypeServerOffline || + offline.Get("server.uuid").String() != "srv-c" || + offline.Get("server.name").String() != "Server C" || + offline.Get("server.type").String() != "GPU 节点 🚀" { + t.Fatalf("unexpected server_offline: %s", offline.Raw) + } +} + +func TestHubExchange_InvalidUTF8ControlNeverExecutesListServers(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + t.Cleanup(hub.Close) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + client := dialRole(t, srv.URL, "key", RoleClient, "client", "Client") + _ = readTextJSONFrame(t, client) + for _, tc := range []struct { + name string + raw string + }{ + {"extra string", "{\"type\":\"list_servers\",\"extra\":\"\xff\"}"}, + {"field name", "{\"type\":\"list_servers\",\"\xff\":\"ignored\"}"}, + {"nested extra string", "{\"type\":\"list_servers\",\"extra\":{\"name\":\"\xc0\xaf\"}}"}, + } { + t.Run(tc.name, func(t *testing.T) { + if errWrite := client.WriteMessage(websocket.TextMessage, []byte(tc.raw)); errWrite != nil { + t.Fatal(errWrite) + } + frame := readTextJSONFrame(t, client) + if frame.Get("type").String() != ControlTypeError || frame.Get("code").String() != ErrCodeInvalidControlFrame { + t.Fatalf("invalid UTF-8 control executed instead of returning invalid_control_frame: %s", frame.Raw) + } + // A valid barrier proves rejection is non-fatal and left no list response queued. + if errWrite := client.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"after-invalid-utf8"}`)); errWrite != nil { + t.Fatal(errWrite) + } + barrier := readTextJSONFrame(t, client) + if barrier.Get("type").String() != ControlTypeServerList || barrier.Get("request_id").String() != "after-invalid-utf8" { + t.Fatalf("unexpected response after invalid UTF-8 control: %s", barrier.Raw) + } + }) + } +} + +func TestHubExchange_ManyToManyFullDuplexMultiplexing(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key-mesh"}) + t.Cleanup(hub.Close) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + const numPeers = 3 + servers := make([]*websocket.Conn, numPeers) + serverWriteMu := make([]sync.Mutex, numPeers) + for s := 0; s < numPeers; s++ { + servers[s] = dialRole(t, srv.URL, "key-mesh", RoleServer, fmt.Sprintf("srv-%d", s), fmt.Sprintf("Server %d", s)) + } + + clients := make([]*websocket.Conn, numPeers) + clientWriteMu := make([]sync.Mutex, numPeers) + for c := 0; c < numPeers; c++ { + clients[c] = dialRole(t, srv.URL, "key-mesh", RoleClient, fmt.Sprintf("cli-%d", c), fmt.Sprintf("Client %d", c)) + initList := readTextJSONFrame(t, clients[c]) + if initList.Get("servers.#").Int() != numPeers { + t.Fatalf("client %d saw %d servers, want %d", c, initList.Get("servers.#").Int(), numPeers) + } + } + + // Each server reads 2*numPeers packets (one binary + one empty/text from each client) and replies back to the sender client. + var srvWG sync.WaitGroup + errCh := make(chan error, 32) + for s := 0; s < numPeers; s++ { + srvIdx := s + srvUUID := fmt.Sprintf("srv-%d", srvIdx) + srvWG.Add(1) + go func() { + defer srvWG.Done() + for i := 0; i < numPeers*2; i++ { + + msgType, raw, errRead := readTunnelTestMessage(servers[srvIdx]) + if errRead != nil { + errCh <- fmt.Errorf("server %d read: %w", srvIdx, errRead) + return + } + if msgType != websocket.BinaryMessage { + errCh <- fmt.Errorf("server %d unexpected msgType %d", srvIdx, msgType) + return + } + view, code, errParse := ParseDataFrameHeader(raw) + if errParse != nil || code != "" { + errCh <- fmt.Errorf("server %d parse: %s %v", srvIdx, code, errParse) + return + } + if view.DstUUID != srvUUID { + errCh <- fmt.Errorf("server %d got DstUUID %q", srvIdx, view.DstUUID) + return + } + var replyPayload []byte + if len(view.Payload) > 0 { + replyPayload = append([]byte("ack:"+srvUUID+":"), view.Payload...) + } + replyFrame, errEnc := EncodeDataFrame(view.PayloadType, srvUUID, view.SrcUUID, replyPayload) + if errEnc != nil { + errCh <- errEnc + return + } + serverWriteMu[srvIdx].Lock() + errWrite := servers[srvIdx].WriteMessage(websocket.BinaryMessage, replyFrame) + serverWriteMu[srvIdx].Unlock() + if errWrite != nil { + errCh <- errWrite + return + } + } + }() + } + + var cliReadWG sync.WaitGroup + received := make([]map[string][]byte, numPeers) + var receivedMu sync.Mutex + for c := 0; c < numPeers; c++ { + received[c] = make(map[string][]byte) + cliIdx := c + cliUUID := fmt.Sprintf("cli-%d", cliIdx) + cliReadWG.Add(1) + go func() { + defer cliReadWG.Done() + for i := 0; i < numPeers*2; i++ { + + msgType, raw, errRead := readTunnelTestMessage(clients[cliIdx]) + if errRead != nil { + errCh <- fmt.Errorf("client %d read: %w", cliIdx, errRead) + return + } + if msgType != websocket.BinaryMessage { + errCh <- fmt.Errorf("client %d unexpected msgType %d: %s", cliIdx, msgType, string(raw)) + return + } + view, _, errParse := ParseDataFrameHeader(raw) + if errParse != nil { + errCh <- errParse + return + } + if view.DstUUID != cliUUID { + errCh <- fmt.Errorf("client %d got DstUUID %q", cliIdx, view.DstUUID) + return + } + key := fmt.Sprintf("%s:%d", view.SrcUUID, view.PayloadType) + receivedMu.Lock() + received[cliIdx][key] = append([]byte(nil), view.Payload...) + receivedMu.Unlock() + } + }() + } + + var cliSendWG sync.WaitGroup + for c := 0; c < numPeers; c++ { + for s := 0; s < numPeers; s++ { + cliIdx, srvIdx := c, s + cliSendWG.Add(1) + go func() { + defer cliSendWG.Done() + cliUUID := fmt.Sprintf("cli-%d", cliIdx) + srvUUID := fmt.Sprintf("srv-%d", srvIdx) + + binBody := []byte{0x00, byte(cliIdx), byte(srvIdx), 0xff} + binFrame, errEnc1 := EncodeDataFrame(PayloadTypeBinary, cliUUID, srvUUID, binBody) + if errEnc1 != nil { + errCh <- errEnc1 + return + } + emptyFrame, errEnc2 := EncodeDataFrame(PayloadTypeText, cliUUID, srvUUID, nil) + if errEnc2 != nil { + errCh <- errEnc2 + return + } + + clientWriteMu[cliIdx].Lock() + errW1 := clients[cliIdx].WriteMessage(websocket.BinaryMessage, binFrame) + errW2 := clients[cliIdx].WriteMessage(websocket.BinaryMessage, emptyFrame) + clientWriteMu[cliIdx].Unlock() + if errW1 != nil { + errCh <- errW1 + } + if errW2 != nil { + errCh <- errW2 + } + }() + } + } + + cliSendWG.Wait() + srvWG.Wait() + cliReadWG.Wait() + close(errCh) + for errItem := range errCh { + if errItem != nil { + t.Fatalf("mesh error: %v", errItem) + } + } + + for c := 0; c < numPeers; c++ { + for s := 0; s < numPeers; s++ { + srvUUID := fmt.Sprintf("srv-%d", s) + wantBin := append([]byte("ack:"+srvUUID+":"), 0x00, byte(c), byte(s), 0xff) + gotBin := received[c][fmt.Sprintf("%s:%d", srvUUID, PayloadTypeBinary)] + if !bytes.Equal(gotBin, wantBin) { + t.Fatalf("client %d <- %s binary payload = %x, want %x", c, srvUUID, gotBin, wantBin) + } + gotEmpty, exists := received[c][fmt.Sprintf("%s:%d", srvUUID, PayloadTypeText)] + if !exists || len(gotEmpty) != 0 { + t.Fatalf("client %d <- %s empty payload = (%v, len=%d), want empty", c, srvUUID, exists, len(gotEmpty)) + } + } + } +} + +func TestHubExchange_SecurityGuardsAndBackpressureIsolation(t *testing.T) { + // A tight per-peer byte budget plus a gated transport make the flood hit + // target_buffer_full deterministically: srv-slow's socket write stays + // parked so its queued bytes are never released back to the budget. The + // send-queue slot count stays large so the client's own control queue is + // not overflowed by the target_buffer_full error frames it must also + // carry back to the test. + hub := NewHub(Options{ + SendQueueSize: 64, + MaxPeerQueuedBytes: 1 << 20, + MaxTenantQueuedBytes: 2 << 20, + }) + hub.UpdateAllowedAPIKeys([]string{"key-sec"}) + t.Cleanup(hub.Close) + srv := newGatedTunnelServer(t, hub) + + srvSlow := dialRole(t, srv.URL, "key-sec", RoleServer, "srv-slow", "Slow Server") + srvFast := dialRole(t, srv.URL, "key-sec", RoleServer, "srv-fast", "Fast Server") + cli1 := dialRole(t, srv.URL, "key-sec", RoleClient, "cli-1", "Client 1") + cli2 := dialRole(t, srv.URL, "key-sec", RoleClient, "cli-2", "Client 2") + // Drain the topology stream until both servers are observable so a delayed + // server_online cannot be mistaken for the error/data frames read below. + waitServersVisible(t, cli1, "srv-slow", "srv-fast") + waitServersVisible(t, cli2, "srv-slow", "srv-fast") + + // Park srv-slow's socket write so the byte budget cannot drain, making the + // target_buffer_full rejection deterministic rather than dependent on + // kernel send-buffer saturation. + slowPeer := lookupTunnelPeer(t, hub, "key-sec", "srv-slow") + slowPeer.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*gatedTunnelConn).arm() + + // 1. Source UUID spoofing rejected. + spoof, _ := EncodeDataFrame(PayloadTypeBinary, "cli-2", "srv-fast", []byte("spoof")) + if errWrite := cli1.WriteMessage(websocket.BinaryMessage, spoof); errWrite != nil { + t.Fatalf("WriteMessage(spoof) error = %v", errWrite) + } + spoofErr := readTextJSONFrame(t, cli1) + if spoofErr.Get("code").String() != ErrCodeSourceUUIDMismatch { + t.Fatalf("expected source_uuid_mismatch, got %s", spoofErr.Raw) + } + + // 2. Same-role routing (client->client and server->server) rejected. + c2c, _ := EncodeDataFrame(PayloadTypeBinary, "cli-1", "cli-2", []byte("hi")) + if errWrite := cli1.WriteMessage(websocket.BinaryMessage, c2c); errWrite != nil { + t.Fatalf("WriteMessage(c2c) error = %v", errWrite) + } + if got := readTextJSONFrame(t, cli1).Get("code").String(); got != ErrCodeInvalidTargetRole { + t.Fatalf("client->client code = %q, want %q", got, ErrCodeInvalidTargetRole) + } + + s2s, _ := EncodeDataFrame(PayloadTypeBinary, "srv-fast", "srv-slow", []byte("hi")) + if errWrite := srvFast.WriteMessage(websocket.BinaryMessage, s2s); errWrite != nil { + t.Fatalf("WriteMessage(s2s) error = %v", errWrite) + } + if got := readTextJSONFrame(t, srvFast).Get("code").String(); got != ErrCodeInvalidTargetRole { + t.Fatalf("server->server code = %q, want %q", got, ErrCodeInvalidTargetRole) + } + + // 3. Slow peer backpressure: flood srvSlow (without reading from it) until target_buffer_full arrives. + gotBufferFull := make(chan struct{}) + syncDone := make(chan error, 1) + go func() { + var once sync.Once + for { + // Read raw frames so a read failure is reported on syncDone instead + // of terminating this goroutine via t.Fatalf and leaving the main + // test blocked on the barrier forever. + msgType, raw, errRead := readTunnelTestMessage(cli1) + if errRead != nil { + syncDone <- errRead + return + } + if msgType != websocket.TextMessage || !ojson.ValidBytes(raw) { + continue + } + frame := ojson.ParseBytes(raw) + if frame.Get("type").String() == ControlTypeError && frame.Get("code").String() == ErrCodeTargetBufferFull { + once.Do(func() { close(gotBufferFull) }) + continue + } + if frame.Get("type").String() == ControlTypeServerList && frame.Get("request_id").String() == "post-flood-barrier" { + syncDone <- nil + return + } + } + }() + + largeChunk := bytes.Repeat([]byte("z"), 256*1024) + floodDone := false + for i := 0; i < 64 && !floodDone; i++ { + pkt, _ := EncodeDataFrame(PayloadTypeBinary, "cli-1", "srv-slow", largeChunk) + if errWrite := cli1.WriteMessage(websocket.BinaryMessage, pkt); errWrite != nil { + t.Fatalf("WriteMessage(flood %d) error = %v", i, errWrite) + } + select { + case <-gotBufferFull: + floodDone = true + default: + } + } + select { + case <-gotBufferFull: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for target_buffer_full from slow server") + } + + // Barrier sync via list_servers to deterministically drain all in-flight error frames on cli1. + if errWrite := cli1.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"post-flood-barrier"}`)); errWrite != nil { + t.Fatalf("WriteMessage(barrier) error = %v", errWrite) + } + select { + case errSync := <-syncDone: + if errSync != nil { + t.Fatalf("barrier sync error = %v", errSync) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for post-flood barrier server_list") + } + + // Verify srvFast still exchanges traffic with cli1 without being blocked by srvSlow. + fastPkt, _ := EncodeDataFrame(PayloadTypeText, "cli-1", "srv-fast", []byte("fast-ok")) + if errWrite := cli1.WriteMessage(websocket.BinaryMessage, fastPkt); errWrite != nil { + t.Fatalf("WriteMessage(srvFast) error = %v", errWrite) + } + gotFast := readBinaryDataFrame(t, srvFast) + if string(gotFast.Payload) != "fast-ok" { + t.Fatalf("srvFast payload = %q, want fast-ok", string(gotFast.Payload)) + } + _ = srvSlow +} + +func TestHubExchange_ControllablePingAndKeyRevocation(t *testing.T) { + pingTrig := make(chan struct{}, 1) + hub := NewHub(Options{ + PingInterval: time.Hour, + PingTrigger: pingTrig, + }) + hub.UpdateAllowedAPIKeys([]string{"key-revoke", "key-keep"}) + t.Cleanup(hub.Close) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + cliRevoke := dialRole(t, srv.URL, "key-revoke", RoleClient, "c-rev", "Revoke Client") + _ = readTextJSONFrame(t, cliRevoke) + + srvKeep := dialRole(t, srv.URL, "key-keep", RoleServer, "s-keep", "Keep Server") + cliKeep := dialRole(t, srv.URL, "key-keep", RoleClient, "c-keep", "Keep Client") + _ = readTextJSONFrame(t, cliKeep) + + pingReceived := make(chan struct{}, 4) + cliKeep.SetPingHandler(func(appData string) error { + select { + case pingReceived <- struct{}{}: + default: + } + return cliKeep.WriteControl(websocket.PongMessage, []byte(appData), time.Time{}) + }) + + // Read loop in background on cliKeep to process control frames and receive data frames. + keepReadCh := make(chan DataFrameView, 1) + keepErrCh := make(chan error, 1) + go func() { + for { + + msgType, raw, errRead := readTunnelTestMessage(cliKeep) + if errRead != nil { + keepErrCh <- errRead + return + } + if msgType == websocket.BinaryMessage { + view, _, errP := ParseDataFrameHeader(raw) + if errP != nil { + keepErrCh <- errP + return + } + keepReadCh <- view + return + } + } + }() + + // Deterministically trigger Ping without wall-clock sleep. + pingTrig <- struct{}{} + select { + case <-pingReceived: + case <-time.After(5 * time.Second): + t.Fatal("did not receive triggered WebSocket Ping frame") + } + + // Revoke key-revoke via UpdateAllowedAPIKeys while keeping key-keep. + hub.UpdateAllowedAPIKeys([]string{"key-keep"}) + + _, _, errRevoked := readTunnelTestMessage(cliRevoke) + var closeErr *websocket.CloseError + if !errors.As(errRevoked, &closeErr) || closeErr.Code != websocket.ClosePolicyViolation { + t.Fatalf("expected revoked key connection to close with 1008, got %v", errRevoked) + } + + // Also connect a server under key-revoke before another revocation check below, and verify key-keep bidirectional traffic. + pkt, _ := EncodeDataFrame(PayloadTypeText, "s-keep", "c-keep", []byte("still-alive")) + if errWrite := srvKeep.WriteMessage(websocket.BinaryMessage, pkt); errWrite != nil { + t.Fatalf("srvKeep WriteMessage error = %v", errWrite) + } + select { + case got := <-keepReadCh: + if got.SrcUUID != "s-keep" || string(got.Payload) != "still-alive" { + t.Fatalf("unexpected frame on surviving tenant: %+v", got) + } + case errRead := <-keepErrCh: + t.Fatalf("surviving tenant read error = %v", errRead) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for packet on surviving tenant") + } +} diff --git a/internal/wstunnel/hub_review_regression_test.go b/internal/wstunnel/hub_review_regression_test.go new file mode 100644 index 00000000000..d9b84fb6d59 --- /dev/null +++ b/internal/wstunnel/hub_review_regression_test.go @@ -0,0 +1,424 @@ +package wstunnel + +import ( + "bytes" + "fmt" + "net/http/httptest" + "runtime" + "sync" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gorilla/websocket" +) + +func TestHubReview_CloseAndRevokeDoNotBlockOnBlockedWriteWhenQueueNotFull(t *testing.T) { + hub := NewHub(Options{ + SendQueueSize: 256, + }) + hub.UpdateAllowedAPIKeys([]string{"key-revoke", "key-keep"}) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + srvStalled := dialRole(t, srv.URL, "key-revoke", RoleServer, "srv-stalled", "Stalled Server") + cliRevoke := dialRole(t, srv.URL, "key-revoke", RoleClient, "cli-revoke", "Revoke Client") + // Drain the topology stream until srv-stalled is observable so its + // server_online cannot be mistaken for the barrier server_list below. + waitServersVisible(t, cliRevoke, "srv-stalled") + + srvKeep := dialRole(t, srv.URL, "key-keep", RoleServer, "srv-keep", "Keep Server") + cliKeep := dialRole(t, srv.URL, "key-keep", RoleClient, "cli-keep", "Keep Client") + // The client handshake can complete before srvKeep's commitPeer publishes + // it; srvKeep's server_online may then arrive after cliKeep's initial + // server_list. Drain the topology stream until srv-keep is observable so a + // stale control frame cannot be mistaken for the data frame read below. + waitServersVisible(t, cliKeep, "srv-keep") + + // Send two 8 MiB frames to srvStalled without reading from srvStalled: + // frame 1 blocks inside WriteMessage (filling OS socket buffers) while len(sendCh) == 1 << 256. + huge := bytes.Repeat([]byte("x"), 8<<20) + for i := 0; i < 2; i++ { + pkt, errEnc := EncodeDataFrame(PayloadTypeBinary, "cli-revoke", "srv-stalled", huge) + if errEnc != nil { + t.Fatalf("EncodeDataFrame error = %v", errEnc) + } + if errWrite := cliRevoke.WriteMessage(websocket.BinaryMessage, pkt); errWrite != nil { + t.Fatalf("cliRevoke WriteMessage(%d) error = %v", i, errWrite) + } + } + // Barrier via list_servers on cliRevoke ensures cliRevoke's readLoop has processed both 8 MiB frames into srvStalled. + if errWrite := cliRevoke.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"enqueued-8mb"}`)); errWrite != nil { + t.Fatalf("WriteMessage(list_servers) error = %v", errWrite) + } + barrier := readTextJSONFrame(t, cliRevoke) + if barrier.Get("request_id").String() != "enqueued-8mb" { + t.Fatalf("unexpected barrier frame: %s", barrier.Raw) + } + + revokeDone := make(chan struct{}) + go func() { + hub.UpdateAllowedAPIKeys([]string{"key-keep"}) + close(revokeDone) + }() + + select { + case <-revokeDone: + case <-time.After(1500 * time.Millisecond): + _ = srvStalled.Close() + hub.Close() + t.Fatal("UpdateAllowedAPIKeys deadlocked while peer WriteMessage was blocked with non-full sendCh") + } + + // Surviving tenant must still exchange packets bidirectionally. + c2s, _ := EncodeDataFrame(PayloadTypeText, "cli-keep", "srv-keep", []byte("ping-keep")) + if errWrite := cliKeep.WriteMessage(websocket.BinaryMessage, c2s); errWrite != nil { + t.Fatalf("cliKeep WriteMessage error = %v", errWrite) + } + gotC2S := readBinaryDataFrame(t, srvKeep) + if string(gotC2S.Payload) != "ping-keep" { + t.Fatalf("srvKeep got %q, want ping-keep", string(gotC2S.Payload)) + } + + s2c, _ := EncodeDataFrame(PayloadTypeText, "srv-keep", "cli-keep", []byte("pong-keep")) + if errWrite := srvKeep.WriteMessage(websocket.BinaryMessage, s2c); errWrite != nil { + t.Fatalf("srvKeep WriteMessage error = %v", errWrite) + } + gotS2C := readBinaryDataFrame(t, cliKeep) + if string(gotS2C.Payload) != "pong-keep" { + t.Fatalf("cliKeep got %q, want pong-keep", string(gotS2C.Payload)) + } + + closeDone := make(chan struct{}) + go func() { + hub.Close() + close(closeDone) + }() + select { + case <-closeDone: + case <-time.After(1500 * time.Millisecond): + t.Fatal("Hub.Close() blocked") + } +} + +func TestHubBudget_ReconnectRetainsInFlightTenantBudget(t *testing.T) { + for _, revoke := range []bool{false, true} { + for _, drainWithPeers := range []bool{false, true} { + t.Run(fmt.Sprintf("revoke=%t/drainWithPeers=%t", revoke, drainWithPeers), func(t *testing.T) { + hub := NewHub(Options{ + MaxPeerQueuedBytes: 4096, + MaxTenantQueuedBytes: 4096, + PingInterval: time.Hour, + }) + forceClose := make(chan time.Time) + hub.testForceClose = forceClose + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newGatedTunnelServer(t, hub) + t.Cleanup(func() { close(forceClose) }) + oldConn := dialRole(t, srv.URL, "key", RoleClient, "client", "Old Client") + _ = readTextJSONFrame(t, oldConn) + old := lookupTunnelPeer(t, hub, "key", "client") + tenant := old.tenant + transport := old.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*gatedTunnelConn) + transport.arm() + if !old.tryEnqueueData(make([]byte, 3072)) { + t.Fatal("could not enqueue blocked write") + } + waitTunnelSignal(t, transport.blocked, "in-flight write holding tenant budget") + + if revoke { + hub.UpdateAllowedAPIKeys(nil) + hub.UpdateAllowedAPIKeys([]string{"key"}) + } else { + old.close(websocket.CloseNormalClosure, "", true) + } + assertRetained := func(wantPeers int) { + t.Helper() + hub.mu.RLock() + defer hub.mu.RUnlock() + if hub.realms["key"] != tenant || len(tenant.peers) != wantPeers || len(tenant.reserved) != 0 { + t.Fatal("in-flight tenant realm was replaced or has unexpected membership") + } + } + assertRetained(0) + if remaining := tenant.queuedBytes.Load(); remaining != 3072 { + t.Fatalf("disconnected tenant budget = %d, want 3072", remaining) + } + + // A failed upgrade must not discard the retained in-flight budget either. + reservation, statusReserve := hub.reserveUUID("key", "aborted") + if statusReserve != 0 || reservation.realm != tenant { + t.Fatalf("reconnect reservation did not reuse tenant: status=%d", statusReserve) + } + hub.releaseReservation("key", "aborted", reservation) + assertRetained(0) + + client := dialRole(t, srv.URL, "key", RoleClient, "client", "Replacement Client") + _ = readTextJSONFrame(t, client) + server := dialRole(t, srv.URL, "key", RoleServer, "server", "Replacement Server") + if online := readTextJSONFrame(t, client); online.Get("type").String() != ControlTypeServerOnline { + t.Fatalf("unexpected topology event: %s", online.Raw) + } + currentClient := lookupTunnelPeer(t, hub, "key", "client") + currentServer := lookupTunnelPeer(t, hub, "key", "server") + if currentClient.tenant != tenant || currentServer.tenant != tenant { + t.Fatal("reconnected peers received a fresh tenant byte budget") + } + raw, errEncode := EncodeDataFrame(PayloadTypeBinary, "client", "server", make([]byte, 2048)) + if errEncode != nil { + t.Fatal(errEncode) + } + if errWrite := client.WriteMessage(websocket.BinaryMessage, raw); errWrite != nil { + t.Fatal(errWrite) + } + if got := readTextJSONFrame(t, client); got.Get("code").String() != ErrCodeTargetBufferFull || got.Get("target_uuid").String() != "server" { + t.Fatalf("retained in-flight budget did not apply backpressure: %s", got.Raw) + } + select { + case <-old.writerDone: + t.Fatal("blocked write exited before its gate was released") + default: + } + + if !drainWithPeers { + currentClient.close(0, "", false) + currentServer.close(0, "", false) + waitTunnelSignal(t, currentClient.writerDone, "replacement client exit") + waitTunnelSignal(t, currentServer.writerDone, "replacement server exit") + if revoke { + hub.UpdateAllowedAPIKeys(nil) + } + assertRetained(0) + } + + // Release the write, not the grace reaper, to reclaim its byte reservation. + close(transport.gate) + waitTunnelSignal(t, old.writerDone, "old writer exit and budget release") + if remaining := old.queuedBytes.Load(); remaining != 0 { + t.Fatalf("old peer budget = %d, want 0", remaining) + } + if drainWithPeers { + assertRetained(2) + if errWrite := client.WriteMessage(websocket.BinaryMessage, raw); errWrite != nil { + t.Fatal(errWrite) + } + if got := readBinaryDataFrame(t, server); len(got.Payload) != 2048 { + t.Fatal("reconnected peers could not use the released tenant budget") + } + currentClient.close(0, "", false) + currentServer.close(0, "", false) + waitTunnelSignal(t, currentClient.writerDone, "replacement client exit") + waitTunnelSignal(t, currentServer.writerDone, "replacement server exit") + } + hub.mu.RLock() + _, retained := hub.realms["key"] + hub.mu.RUnlock() + if retained || tenant.queuedBytes.Load() != 0 { + t.Fatal("drained idle or revoked tenant leaked its realm or byte budget") + } + }) + } + } +} + +func TestHubReview_ByteBudgetBackpressureAndReclaim(t *testing.T) { + // High frame slot count (256), tight byte budget (32 KiB per peer, 64 KiB tenant-wide). + hub := NewHub(Options{ + SendQueueSize: 256, + MaxPeerQueuedBytes: 32 * 1024, + MaxTenantQueuedBytes: 64 * 1024, + }) + hub.UpdateAllowedAPIKeys([]string{"key-mem"}) + t.Cleanup(hub.Close) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + srvSlow := dialRole(t, srv.URL, "key-mem", RoleServer, "srv-mem-slow", "Slow Mem Server") + srvClean := dialRole(t, srv.URL, "key-mem", RoleServer, "srv-mem-clean", "Clean Mem Server") + cli := dialRole(t, srv.URL, "key-mem", RoleClient, "cli-mem", "Mem Client") + _ = readTextJSONFrame(t, cli) + + gotFull := make(chan struct{}) + barrierCh := make(chan error, 1) + go func() { + var once sync.Once + for { + // Report read failures on barrierCh instead of terminating this + // goroutine via t.Fatalf, which would leave the main test blocked. + msgType, raw, errRead := readTunnelTestMessage(cli) + if errRead != nil { + barrierCh <- errRead + return + } + if msgType != websocket.TextMessage || !ojson.ValidBytes(raw) { + continue + } + frame := ojson.ParseBytes(raw) + if frame.Get("type").String() == ControlTypeError && frame.Get("code").String() == ErrCodeTargetBufferFull { + once.Do(func() { close(gotFull) }) + continue + } + if frame.Get("type").String() == ControlTypeServerList && frame.Get("request_id").String() == "mem-sync" { + barrierCh <- nil + return + } + } + }() + + // Send 24 x 16 KiB = 384 KiB (only 24 frames << 256 slot limit, or enough to fill loopback + 32 KiB budget). + // Wait: even 64 x 64 KiB = 4 MiB is only 64 frames (far below 256 slots!) so without byte-budget enforcement + // 64 frames NEVER hit SendQueueSize=256! + chunk := bytes.Repeat([]byte("m"), 64*1024) + for i := 0; i < 64; i++ { + pkt, _ := EncodeDataFrame(PayloadTypeBinary, "cli-mem", "srv-mem-slow", chunk) + if errWrite := cli.WriteMessage(websocket.BinaryMessage, pkt); errWrite != nil { + t.Fatalf("WriteMessage(%d) error = %v", i, errWrite) + } + select { + case <-gotFull: + i = 64 + default: + } + } + + select { + case <-gotFull: + case <-time.After(1500 * time.Millisecond): + t.Fatal("expected target_buffer_full from MaxPeerQueuedBytes before reaching 256 frame slots") + } + + if errWrite := cli.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"mem-sync"}`)); errWrite != nil { + t.Fatalf("WriteMessage(mem-sync) error = %v", errWrite) + } + select { + case errBarrier := <-barrierCh: + if errBarrier != nil { + t.Fatalf("mem-sync barrier read error = %v", errBarrier) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for mem-sync barrier server_list") + } + + // Close srvSlow so all its queued/in-flight bytes are reclaimed from the hub budget, then verify srvClean works. + _ = srvSlow.Close() + for { + ev := readTextJSONFrame(t, cli) + if ev.Get("type").String() == ControlTypeServerOffline && ev.Get("server.uuid").String() == "srv-mem-slow" { + break + } + } + + okPkt, _ := EncodeDataFrame(PayloadTypeBinary, "cli-mem", "srv-mem-clean", bytes.Repeat([]byte("k"), 16*1024)) + if errWrite := cli.WriteMessage(websocket.BinaryMessage, okPkt); errWrite != nil { + t.Fatalf("WriteMessage(srvClean) error = %v", errWrite) + } + gotClean := readBinaryDataFrame(t, srvClean) + if len(gotClean.Payload) != 16*1024 { + t.Fatalf("srvClean payload len = %d, want %d", len(gotClean.Payload), 16*1024) + } + hub.mu.RLock() + tenant := hub.realms["key-mem"] + peers := make([]*peer, 0, len(tenant.peers)) + for _, p := range tenant.peers { + peers = append(peers, p) + } + hub.mu.RUnlock() + hub.Close() + for _, p := range peers { + waitTunnelSignal(t, p.writerDone, "writer exit and budget reclamation") + } + if rem := tenant.queuedBytes.Load(); rem != 0 { + t.Fatalf("tenant.queuedBytes after Close = %d, want 0", rem) + } +} + +func TestHubReview_ListServersLinearizableWithServerOffline(t *testing.T) { + unregistered := make(chan string, 64) + hub := NewHub(Options{}) + hub.testOnPeerUnregistered = func(_, uuid string) { + unregistered <- uuid + } + hub.UpdateAllowedAPIKeys([]string{"key-lin"}) + t.Cleanup(hub.Close) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + + cli := dialRole(t, srv.URL, "key-lin", RoleClient, "cli-lin", "Linearizable Client") + initFrame := readTextJSONFrame(t, cli) + if initFrame.Get("servers.#").Int() != 0 { + t.Fatalf("expected initial empty server_list, got %s", initFrame.Raw) + } + + localServers := make(map[string]ServerInfo) + doneReading := make(chan struct{}) + go func() { + defer close(doneReading) + for { + frame := readTextJSONFrame(t, cli) + switch frame.Get("type").String() { + case ControlTypeServerList: + if frame.Get("request_id").String() == "final-drain" { + return + } + clear(localServers) + count := int(frame.Get("servers.#").Int()) + for i := 0; i < count; i++ { + id := frame.Get(fmt.Sprintf("servers.%d.uuid", i)).String() + name := frame.Get(fmt.Sprintf("servers.%d.name", i)).String() + srvType := frame.Get(fmt.Sprintf("servers.%d.type", i)).String() + localServers[id] = ServerInfo{UUID: id, Name: name, Type: srvType} + } + case ControlTypeServerOnline: + id := frame.Get("server.uuid").String() + localServers[id] = ServerInfo{ + UUID: id, + Name: frame.Get("server.name").String(), + Type: frame.Get("server.type").String(), + } + case ControlTypeServerOffline: + delete(localServers, frame.Get("server.uuid").String()) + } + } + }() + + var writeMu sync.Mutex + sendListReq := func(reqID string) { + writeMu.Lock() + defer writeMu.Unlock() + _ = cli.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"list_servers","request_id":%q}`, reqID))) + } + + sConn := dialRole(t, srv.URL, "key-lin", RoleServer, "ephemeral-srv-0", "Ephemeral") + hookEntered := make(chan struct{}) + var hookOnce sync.Once + hub.testBeforeListServersEnqueue = func() { + hookOnce.Do(func() { + close(hookEntered) + // Trigger server disconnect concurrently while list_servers has already captured its snapshot. + _ = sConn.Close() + // Give unregisterPeer a non-blocking yield window if Hub unlocked too early; if Hub holds RLock, + // unregisterPeer will block on Lock() until server_list is enqueued first. + for i := 0; i < 4000; i++ { + runtime.Gosched() + select { + case id := <-unregistered: + unregistered <- id + return + default: + } + } + }) + } + sendListReq("race-snapshot") + <-hookEntered + <-unregistered + + // Send one non-list_servers marker? Wait: to test whether prior poll responses left a ghost server WITHOUT + // overwriting localServers on final-drain, only exit on final-drain BEFORE clearing localServers! + sendListReq("final-drain") + <-doneReading + + if len(localServers) != 0 { + t.Fatalf("stale server_list overwrote newer server_offline; ghost servers remaining: %+v", localServers) + } +} diff --git a/internal/wstunnel/peer.go b/internal/wstunnel/peer.go new file mode 100644 index 00000000000..cfce3e688e4 --- /dev/null +++ b/internal/wstunnel/peer.go @@ -0,0 +1,423 @@ +package wstunnel + +import ( + "io" + "sync" + "sync/atomic" + "time" + + "github.com/gorilla/websocket" + log "github.com/sirupsen/logrus" +) + +const ( + defaultSendQueueSize = 256 + defaultPingInterval = 30 * time.Second + defaultMaxPeerQueuedBytes = int64(MaxInboundFrameBytes) + defaultMaxTenantQueuedBytes = int64(256 << 20) + // closeGracePeriod bounds local socket reclamation, not network I/O. + closeGracePeriod = time.Second + // protocolErrorCloseGrace bounds how long the busy-writer protocol-error + // path waits for writeLoop to emit the protocol-error close frame before + // reclaiming the transport and unblocking the stalled writer. + protocolErrorCloseGrace = 100 * time.Millisecond +) + +type outboundFrame struct { + messageType int + data []byte + accountedBytes int64 +} + +type peer struct { + hub *Hub + tenant *realm + apiKey string + uuid string + name string + serverType string + role Role + + conn *websocket.Conn + sendCh chan outboundFrame + pingCh chan struct{} + pongCh chan string + closed chan struct{} + done chan struct{} + writerDone chan struct{} + closeOnce sync.Once + transportOnce sync.Once + closePayload []byte + // writerFinished closes when writeLoop stops performing writes (before it + // reclaims the transport and reports writerDone); it lets finishClose wait + // for the close frame to be attempted without watching the full teardown. + writerFinished chan struct{} + writerFinishOnce sync.Once + writeMu sync.Mutex + enqueueMu sync.Mutex + enqueueClosed bool + maxQueuedBytes int64 + queuedBytes atomic.Int64 +} + +func newPeer(hub *Hub, apiKey, uuid, name, serverType string, role Role, conn *websocket.Conn, queueSize int, maxQueuedBytes int64) *peer { + if queueSize <= 0 { + queueSize = defaultSendQueueSize + } + if maxQueuedBytes <= 0 { + maxQueuedBytes = defaultMaxPeerQueuedBytes + } + p := &peer{ + hub: hub, + apiKey: apiKey, + uuid: uuid, + name: name, + serverType: serverType, + role: role, + conn: conn, + sendCh: make(chan outboundFrame, queueSize), + pingCh: make(chan struct{}, 1), + pongCh: make(chan string, 1), + closed: make(chan struct{}), + done: make(chan struct{}), + writerDone: make(chan struct{}), + writerFinished: make(chan struct{}), + maxQueuedBytes: maxQueuedBytes, + } + if guardedConn, okGuarded := conn.UnderlyingConn().(*deadlineGuardConn); okGuarded { + // Inspect before Gorilla sees fatal bytes, even while its write token is held. + guardedConn.onProtocolError = func() { + // Holding the idle writer lock prevents a new data/control write from + // starting between this check and the close request. Never wait for it. + idleWriter := p.writeMu.TryLock() + p.close(websocket.CloseProtocolError, "", true) + if idleWriter { + p.writeMu.Unlock() + } else { + // A malformed peer must not hold an active writer indefinitely; the + // short bounded wait lets writeLoop emit the close frame first. + go p.finishClose(protocolErrorCloseGrace) + } + if hub != nil && hub.testBeforeProtocolErrorReturn != nil { + hub.testBeforeProtocolErrorReturn() + } + } + } + conn.SetPingHandler(func(payload string) error { + p.requestPong(payload) + return nil + }) + conn.SetCloseHandler(func(code int, _ string) error { + p.close(code, "", true) + return nil + }) + return p +} + +func tryReserveBudget(counter *atomic.Int64, delta, limit int64) bool { + if delta <= 0 { + return true + } + for { + cur := counter.Load() + if delta > limit-cur { + return false + } + if counter.CompareAndSwap(cur, cur+delta) { + return true + } + } +} + +func (p *peer) releaseBytes(n int64) { + if p == nil || n <= 0 { + return + } + p.queuedBytes.Add(-n) + if p.tenant != nil && p.tenant.queuedBytes.Add(-n) == 0 && p.hub != nil { + select { + case <-p.closed: + // Only a closed peer can retain in-flight bytes after unregistration. + p.hub.pruneRealm(p.apiKey, p.tenant) + default: + // Unregistration prunes open peers after queue draining, without + // inverting the Hub-to-enqueue lock order during enqueue rollback. + } + } +} + +func (p *peer) tryEnqueueControl(frame outboundFrame) bool { + return p.tryEnqueue(frame) +} + +func (p *peer) tryEnqueueData(rawFrame []byte) bool { + return p.tryEnqueue(outboundFrame{messageType: websocket.BinaryMessage, data: rawFrame}) +} + +func (p *peer) tryEnqueue(frame outboundFrame) bool { + if p == nil { + return false + } + p.enqueueMu.Lock() + defer p.enqueueMu.Unlock() + if p.enqueueClosed { + return false + } + size := int64(len(frame.data)) + if !tryReserveBudget(&p.queuedBytes, size, p.maxQueuedBytes) { + return false + } + if p.tenant != nil && !tryReserveBudget(&p.tenant.queuedBytes, size, p.hub.maxTenantQueuedBytes) { + p.queuedBytes.Add(-size) + return false + } + frame.accountedBytes = size + select { + case p.sendCh <- frame: + return true + default: + p.releaseBytes(size) + return false + } +} + +func (p *peer) shutdownAndDrainQueue() { + if p == nil { + return + } + p.enqueueMu.Lock() + defer p.enqueueMu.Unlock() + p.enqueueClosed = true + for { + select { + case rem := <-p.sendCh: + p.releaseBytes(rem.accountedBytes) + default: + return + } + } +} + +func (p *peer) sendError(code, message, targetUUID, requestID string) { + if p == nil { + return + } + raw, errEncode := EncodeErrorFrame(code, message, targetUUID, requestID) + if errEncode != nil { + return + } + _ = p.tryEnqueueControl(outboundFrame{ + messageType: websocket.TextMessage, + data: raw, + }) +} + +func (p *peer) requestPing() { + if p == nil { + return + } + select { + case <-p.closed: + return + default: + } + select { + case p.pingCh <- struct{}{}: + default: + } +} + +func (p *peer) requestPong(payload string) { + p.enqueueMu.Lock() + defer p.enqueueMu.Unlock() + if p.enqueueClosed || len(payload) > 125 { + return + } + // Coalesce pending pings to the latest payload without blocking the reader. + select { + case <-p.pongCh: + default: + } + select { + case p.pongCh <- payload: + default: + } +} + +func (p *peer) writeFrame(frame outboundFrame) error { + defer p.releaseBytes(frame.accountedBytes) + p.writeMu.Lock() + defer p.writeMu.Unlock() + select { + case <-p.closed: + return websocket.ErrCloseSent + default: + } + return p.conn.WriteMessage(frame.messageType, frame.data) +} + +func (p *peer) writeControl(messageType int, payload []byte) error { + p.writeMu.Lock() + defer p.writeMu.Unlock() + select { + case <-p.closed: + return websocket.ErrCloseSent + default: + } + return p.conn.WriteControl(messageType, payload, time.Time{}) +} + +func (p *peer) readLoop() { + defer p.close(0, "", true) + for { + select { + case <-p.closed: + return + default: + } + msgType, reader, errNextReader := p.conn.NextReader() + if errNextReader != nil { + return + } + limit := MaxInboundFrameBytes + reason := "binary frame exceeds maximum allowed size" + if msgType == websocket.TextMessage { + limit = MaxControlFrameBytes + reason = "control frame exceeds 4096 bytes" + } + // Bound reassembled messages without Gorilla writing a close from this reader. + raw, errRead := io.ReadAll(io.LimitReader(reader, int64(limit)+1)) + if len(raw) > limit { + p.close(websocket.CloseMessageTooBig, reason, true) + return + } + if errRead != nil { + return + } + select { + case <-p.closed: + return + default: + } + switch msgType { + case websocket.TextMessage: + p.hub.handleControlMessage(p, raw) + case websocket.BinaryMessage: + p.hub.handleDataMessage(p, raw) + } + } +} + +func (p *peer) writeLoop(pingInterval time.Duration) { + defer func() { + p.close(0, "", true) + p.writerFinishOnce.Do(func() { close(p.writerFinished) }) + p.finishClose(closeGracePeriod) + close(p.writerDone) + }() + + var tickerCh <-chan time.Time + if pingInterval > 0 { + ticker := time.NewTicker(pingInterval) + defer ticker.Stop() + tickerCh = ticker.C + } + + for { + // A pending close always takes priority over queued data and pings. + select { + case <-p.closed: + // A non-nil empty payload still requests a Close frame without a status code. + if p.closePayload != nil { + p.writeMu.Lock() + _ = p.conn.WriteControl(websocket.CloseMessage, p.closePayload, time.Time{}) + p.writeMu.Unlock() + } + return + default: + } + var errWrite error + select { + case <-p.closed: + continue + case frame := <-p.sendCh: + errWrite = p.writeFrame(frame) + case <-tickerCh: + errWrite = p.writeControl(websocket.PingMessage, nil) + case <-p.pingCh: + errWrite = p.writeControl(websocket.PingMessage, nil) + case payload := <-p.pongCh: + errWrite = p.writeControl(websocket.PongMessage, []byte(payload)) + } + if errWrite != nil && errWrite != websocket.ErrCloseSent { + return + } + } +} + +// finishClose reclaims the transport after giving writeLoop a grace window to +// finish, which lets a queued close frame be written first. writerFinished and +// writerDone both close once writeLoop exits; a permanently blocked writer +// holds writeMu and stalls that exit, so the wait is capped by grace and +// reclaiming the socket then unblocks the stalled writer. A zero grace closes +// the transport immediately. +func (p *peer) finishClose(grace time.Duration) { + p.transportOnce.Do(func() { + if grace > 0 && p.closePayload != nil { + timer := time.NewTimer(grace) + defer timer.Stop() + select { + case <-p.writerFinished: + case <-p.writerDone: + case <-timer.C: + } + } + if p.conn != nil { + // The WebSocket close frame is sufficient; never block on TLS close_notify. + if conn := rawTransportConn(p.conn.UnderlyingConn()); conn != nil { + if errClose := conn.Close(); errClose != nil { + log.Debugf("wstunnel: socket close error: %v", errClose) + } + } + } + close(p.done) + }) +} + +func (p *peer) awaitClose() { + // This timer only forces reclamation of an already closing local socket. + // No read/write deadlines are installed on an upgraded connection. + timer := time.NewTimer(closeGracePeriod) + defer timer.Stop() + forceClose := timer.C + if p.hub != nil && p.hub.testForceClose != nil { + forceClose = p.hub.testForceClose + } + select { + case <-p.done: + case <-forceClose: + p.finishClose(0) + } +} + +func (p *peer) close(closeCode int, reason string, notifyRealm bool) { + if p == nil { + return + } + p.closeOnce.Do(func() { + if closeCode > 0 { + p.closePayload = websocket.FormatCloseMessage(closeCode, reason) + } + p.shutdownAndDrainQueue() + close(p.closed) + if p.hub != nil { + p.hub.unregisterPeer(p, notifyRealm) + } + if closeCode == 0 || p.conn == nil { + go p.finishClose(closeGracePeriod) + } else { + // Only writeLoop writes the close frame; callers never perform socket I/O. + go p.awaitClose() + } + }) +} diff --git a/internal/wstunnel/peer_review_test.go b/internal/wstunnel/peer_review_test.go new file mode 100644 index 00000000000..78f694fe33e --- /dev/null +++ b/internal/wstunnel/peer_review_test.go @@ -0,0 +1,524 @@ +package wstunnel + +import ( + "bytes" + "errors" + "fmt" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gorilla/websocket" +) + +func readTunnelTestMessage(conn *websocket.Conn) (int, []byte, error) { + type result struct { + messageType int + raw []byte + err error + } + ch := make(chan result, 1) + go func() { + messageType, raw, errRead := conn.ReadMessage() + ch <- result{messageType, raw, errRead} + }() + select { + case res := <-ch: + return res.messageType, res.raw, res.err + case <-time.After(10 * time.Second): + _ = conn.Close() + return 0, nil, errors.New("test message read did not complete") + } +} + +func waitTunnelSignal(t *testing.T, ch <-chan struct{}, description string) { + t.Helper() + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Fatalf("timed out waiting for %s", description) + } +} + +// gatedTunnelConn deterministically models a saturated transport send buffer. +// Arming it after a successful write leaves the WebSocket writer idle while +// the next socket write blocks, independently of OS buffer sizing or scheduling. +type gatedTunnelConn struct { + net.Conn + mu sync.Mutex + gate chan struct{} + blocked chan struct{} + closed chan struct{} + once sync.Once +} + +func (c *gatedTunnelConn) arm() { + c.mu.Lock() + defer c.mu.Unlock() + c.gate = make(chan struct{}) + c.blocked = make(chan struct{}, 1) +} + +func (c *gatedTunnelConn) Write(raw []byte) (int, error) { + c.mu.Lock() + gate, blocked := c.gate, c.blocked + c.mu.Unlock() + if gate != nil { + select { + case blocked <- struct{}{}: + default: + } + select { + case <-gate: + case <-c.closed: + return 0, net.ErrClosed + } + } + return c.Conn.Write(raw) +} + +func (c *gatedTunnelConn) Close() error { + c.once.Do(func() { close(c.closed) }) + return c.Conn.Close() +} + +type gatedTunnelListener struct{ net.Listener } + +func (l gatedTunnelListener) Accept() (net.Conn, error) { + conn, errAccept := l.Listener.Accept() + if errAccept != nil { + return nil, errAccept + } + return &gatedTunnelConn{Conn: conn, closed: make(chan struct{})}, nil +} + +func newGatedTunnelServer(t *testing.T, hub *Hub) *httptest.Server { + t.Helper() + srv := httptest.NewUnstartedServer(hub) + srv.Listener = gatedTunnelListener{srv.Listener} + srv.Start() + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + return srv +} + +func lookupTunnelPeer(t *testing.T, hub *Hub, key, uuid string) *peer { + t.Helper() + hub.mu.RLock() + defer hub.mu.RUnlock() + tenant := hub.realms[key] + if tenant == nil || tenant.peers[uuid] == nil { + t.Fatalf("missing peer %s", uuid) + } + return tenant.peers[uuid] +} + +func assertTunnelClose(t *testing.T, conn *websocket.Conn, code int) { + t.Helper() + _, _, errRead := readTunnelTestMessage(conn) + var closeErr *websocket.CloseError + if !errors.As(errRead, &closeErr) || closeErr.Code != code { + t.Fatalf("close = %v, want code %d", errRead, code) + } +} + +func TestPeerClose_SaturatedTransportNeverBlocksCallers(t *testing.T) { + for _, tc := range []struct{ shutdown, active bool }{{false, false}, {true, false}, {false, true}, {true, true}} { + t.Run(fmt.Sprintf("shutdown=%t/active=%t", tc.shutdown, tc.active), func(t *testing.T) { + forceClose := make(chan time.Time) + hub := NewHub(Options{}) + hub.testForceClose = forceClose + var forceOnce sync.Once + reclaim := func() { forceOnce.Do(func() { close(forceClose) }) } + t.Cleanup(reclaim) + hub.UpdateAllowedAPIKeys([]string{"key", "keep"}) + srv := newGatedTunnelServer(t, hub) + stalled := dialRole(t, srv.URL, "key", RoleClient, "stalled", "Stalled") + _ = readTextJSONFrame(t, stalled) + healthy := dialRole(t, srv.URL, "key", RoleClient, "healthy", "Healthy") + _ = readTextJSONFrame(t, healthy) + keep := dialRole(t, srv.URL, "keep", RoleClient, "keep", "Keep") + _ = readTextJSONFrame(t, keep) + + p := lookupTunnelPeer(t, hub, "key", "stalled") + transport := p.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*gatedTunnelConn) + transport.arm() + if tc.active { + if !p.tryEnqueueData([]byte("blocked active write")) { + t.Fatal("failed to start blocked write") + } + waitTunnelSignal(t, transport.blocked, "blocked active write") + } + // Without an active write, the close write itself must stall. + returned := make(chan struct{}) + go func() { + if tc.shutdown { + hub.Close() + } else { + hub.UpdateAllowedAPIKeys([]string{"keep"}) + } + close(returned) + }() + waitTunnelSignal(t, returned, "non-blocking revoke/shutdown") + if !tc.active { + waitTunnelSignal(t, transport.blocked, "close write on saturated transport") + } + wantCode := websocket.ClosePolicyViolation + if tc.shutdown { + wantCode = websocket.CloseGoingAway + } + assertTunnelClose(t, healthy, wantCode) + hub.mu.RLock() + tenant := hub.realms["key"] + registered := tenant != nil && (len(tenant.peers) != 0 || len(tenant.reserved) != 0) + hub.mu.RUnlock() + if registered { + t.Fatal("revoked peers or reservations remain registered") + } + if !tc.shutdown { + if errWrite := keep.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers"}`)); errWrite != nil { + t.Fatal(errWrite) + } + _ = readTextJSONFrame(t, keep) + returnedClose := make(chan struct{}) + go func() { hub.Close(); close(returnedClose) }() + waitTunnelSignal(t, returnedClose, "shutdown after revocation") + } + // Advance the local reclamation clock without waiting for wall time. + reclaim() + waitTunnelSignal(t, p.done, "forced socket reclamation") + waitTunnelSignal(t, p.writerDone, "stalled writer exit") + }) + } +} + +func TestPeerClose_ActiveWriteAndQueuedFramesReceivePolicyClose(t *testing.T) { + for _, revoke := range []bool{false, true} { + t.Run(fmt.Sprintf("revoke=%t", revoke), func(t *testing.T) { + hub := NewHub(Options{SendQueueSize: 1}) + forceClose := make(chan time.Time) + hub.testForceClose = forceClose + t.Cleanup(func() { close(forceClose) }) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newGatedTunnelServer(t, hub) + client := dialRole(t, srv.URL, "key", RoleClient, "client", "Client") + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "client") + transport := p.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*gatedTunnelConn) + transport.arm() + if !p.tryEnqueueData([]byte("active")) { + t.Fatal("failed to enqueue active write") + } + waitTunnelSignal(t, transport.blocked, "active write") + if !p.tryEnqueueData([]byte("queued")) { + t.Fatal("failed to enqueue waiting frame") + } + if revoke { + hub.UpdateAllowedAPIKeys(nil) + } else { + // A topology event cannot fit behind the active and queued frames. + _ = dialRole(t, srv.URL, "key", RoleServer, "server", "Server") + } + waitTunnelSignal(t, p.closed, "policy close request") + close(transport.gate) + kind, raw, errRead := readTunnelTestMessage(client) + if errRead != nil || kind != websocket.BinaryMessage || string(raw) != "active" { + t.Fatalf("active write = (%d, %q, %v)", kind, raw, errRead) + } + // The close frame must precede the discarded queued frame. + assertTunnelClose(t, client, websocket.ClosePolicyViolation) + waitTunnelSignal(t, p.writerDone, "graceful writer exit") + if p.queuedBytes.Load() != 0 || p.tenant.queuedBytes.Load() != 0 { + t.Fatal("policy close leaked queued bytes") + } + }) + } +} + +func TestPeerClose_TLSConnectionReceivesPolicyCloseAndReclaimsSocket(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := httptest.NewTLSServer(hub) + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + dialer := websocket.Dialer{TLSClientConfig: srv.Client().Transport.(*http.Transport).TLSClientConfig} + client, resp, errDial := dialer.Dial(dialTunnelURL(srv.URL, url.Values{ + "key": {"key"}, "role": {"client"}, "uuid": {"client"}, "name": {"Client"}, + }), nil) + closeHTTPResponseBody(t, resp) + if errDial != nil { + t.Fatal(errDial) + } + registerCleanupConn(t, client) + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "client") + hub.UpdateAllowedAPIKeys(nil) + assertTunnelClose(t, client, websocket.ClosePolicyViolation) + waitTunnelSignal(t, p.done, "TLS socket reclamation") + waitTunnelSignal(t, p.writerDone, "TLS writer exit") +} + +func newBudgetTestPeer(hub *Hub, tenant *realm, uuid string, role Role) *peer { + return &peer{ + hub: hub, tenant: tenant, apiKey: "a", uuid: uuid, role: role, + sendCh: make(chan outboundFrame, 256), closed: make(chan struct{}), done: make(chan struct{}), + maxQueuedBytes: hub.maxPeerQueuedBytes, + } +} + +func TestPeerBudget_ControlAndDataSharePeerAndTenantLimits(t *testing.T) { + hub := NewHub(Options{MaxPeerQueuedBytes: 100, MaxTenantQueuedBytes: 150}) + tenant := newRealm() + first := newBudgetTestPeer(hub, tenant, "first", RoleClient) + second := newBudgetTestPeer(hub, tenant, "second", RoleClient) + for i := 0; i < 2; i++ { + if !first.tryEnqueueControl(outboundFrame{messageType: websocket.TextMessage, data: make([]byte, 50)}) { + t.Fatal("control frame unexpectedly rejected") + } + } + if first.tryEnqueueData([]byte("x")) || first.tryEnqueueControl(outboundFrame{data: []byte("x")}) { + t.Fatal("control/data bypassed per-peer byte budget") + } + if !second.tryEnqueueControl(outboundFrame{data: make([]byte, 50)}) || tenant.queuedBytes.Load() != 150 { + t.Fatal("control frames not accounted against tenant budget") + } + if second.tryEnqueueControl(outboundFrame{data: []byte("x")}) || second.queuedBytes.Load() != 50 { + t.Fatal("tenant exhaustion failed to roll back peer reservation") + } + first.shutdownAndDrainQueue() + second.shutdownAndDrainQueue() + if tenant.queuedBytes.Load() != 0 || first.queuedBytes.Load() != 0 || second.queuedBytes.Load() != 0 { + t.Fatal("draining control frames leaked byte reservations") + } + if first.tryEnqueueControl(outboundFrame{data: []byte("x")}) { + t.Fatal("closed peer accepted control frame") + } +} + +func TestHubBudget_ExhaustedTenantDoesNotStarveAnotherTenant(t *testing.T) { + hub := NewHub(Options{MaxPeerQueuedBytes: 1024, MaxTenantQueuedBytes: 2048}) + hub.UpdateAllowedAPIKeys([]string{"a", "b"}) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + serverB := dialRole(t, srv.URL, "b", RoleServer, "s", "Server") + clientB := dialRole(t, srv.URL, "b", RoleClient, "c", "Client") + _ = readTextJSONFrame(t, clientB) + + // Paused writers make exact exhaustion independent of TCP buffer sizes. + tenantA := newRealm() + slow := newBudgetTestPeer(hub, tenantA, "slow", RoleServer) + healthy := newBudgetTestPeer(hub, tenantA, "healthy", RoleServer) + senderA := newBudgetTestPeer(hub, tenantA, "sender", RoleClient) + tenantA.peers[slow.uuid] = slow + tenantA.peers[healthy.uuid] = healthy + tenantA.peers[senderA.uuid] = senderA + hub.mu.Lock() + hub.realms["a"] = tenantA + hub.mu.Unlock() + routeA := func(target string, payloadBytes int) { + t.Helper() + raw, errEncode := EncodeDataFrame(PayloadTypeBinary, senderA.uuid, target, make([]byte, payloadBytes)) + if errEncode != nil { + t.Fatal(errEncode) + } + hub.handleDataMessage(senderA, raw) + } + routeA(slow.uuid, 1024-MinBinaryFrameHeaderLen-len(senderA.uuid)-len(slow.uuid)) + if slow.queuedBytes.Load() != 1024 || slow.tryEnqueueData([]byte("full")) { + t.Fatal("expected slow peer budget exhaustion") + } + routeA(healthy.uuid, 16) + select { + case frame := <-healthy.sendCh: + healthy.releaseBytes(frame.accountedBytes) + default: + t.Fatal("slow peer starved healthy peer in same tenant") + } + routeA(healthy.uuid, 1024-MinBinaryFrameHeaderLen-len(senderA.uuid)-len(healthy.uuid)) + if tenantA.queuedBytes.Load() != 2048 { + t.Fatal("tenant A budget not completely exhausted") + } + if healthy.tryEnqueueData([]byte("full")) { + t.Fatal("tenant-wide budget was not enforced") + } + for _, direction := range []bool{false, true} { + src, dst, sender, receiver := "c", "s", clientB, serverB + if direction { + src, dst, sender, receiver = "s", "c", serverB, clientB + } + raw, errEncode := EncodeDataFrame(PayloadTypeText, src, dst, []byte("tenant-b-healthy")) + if errEncode != nil { + t.Fatal(errEncode) + } + if errWrite := sender.WriteMessage(websocket.BinaryMessage, raw); errWrite != nil { + t.Fatal(errWrite) + } + if got := readBinaryDataFrame(t, receiver); string(got.Payload) != "tenant-b-healthy" { + t.Fatal("exhausted tenant A starved tenant B") + } + } +} + +func TestControlFrame_LimitsAndBoundedErrors(t *testing.T) { + for _, tc := range []struct { + name string + raw string + ok bool + }{ + {"frame boundary", `{"type":"list_servers"}` + strings.Repeat(" ", MaxControlFrameBytes-len(`{"type":"list_servers"}`)), true}, + {"oversized frame", strings.Repeat(" ", MaxControlFrameBytes+1), false}, + {"unknown type", `{"type":"` + strings.Repeat("x", MaxControlTypeLen) + `"}`, false}, + {"oversized type", `{"type":"` + strings.Repeat("x", MaxControlTypeLen+1) + `"}`, false}, + {"request id boundary", `{"type":"list_servers","request_id":"` + strings.Repeat("r", MaxRequestIDLen) + `"}`, true}, + {"oversized request id", `{"type":"list_servers","request_id":"` + strings.Repeat("r", MaxRequestIDLen+1) + `"}`, false}, + } { + t.Run(tc.name, func(t *testing.T) { + _, code, errParse := ParseControlFrame([]byte(tc.raw)) + if tc.ok { + if errParse != nil || code != "" { + t.Fatalf("valid control rejected: %s %v", code, errParse) + } + } else if errParse == nil || code != ErrCodeInvalidControlFrame || len(errParse.Error()) > 100 || strings.Contains(errParse.Error(), strings.Repeat("x", 64)) { + t.Fatalf("invalid control produced unbounded or missing error: %s %v", code, errParse) + } + }) + } +} + +func TestHubLimits_ControlSizeAndFragmentation(t *testing.T) { + for _, oversized := range []bool{false, true} { + t.Run(fmt.Sprintf("oversized=%t", oversized), func(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + client := dialRole(t, srv.URL, "key", RoleClient, "c", "Client") + _ = readTextJSONFrame(t, client) + raw := append([]byte(`{"type":"list_servers"}`), bytes.Repeat([]byte(" "), MaxControlFrameBytes-len(`{"type":"list_servers"}`))...) + if oversized { + raw = append(raw, ' ') + } + writer, errNextWriter := client.NextWriter(websocket.TextMessage) + if errNextWriter != nil { + t.Fatal(errNextWriter) + } + if _, errWrite := writer.Write(raw[:2048]); errWrite != nil { + t.Fatal(errWrite) + } + if _, errWrite := writer.Write(raw[2048:]); errWrite != nil { + t.Fatal(errWrite) + } + if errClose := writer.Close(); errClose != nil { + t.Fatal(errClose) + } + if oversized { + assertTunnelClose(t, client, websocket.CloseMessageTooBig) + } else if got := readTextJSONFrame(t, client); got.Get("type").String() != ControlTypeServerList { + t.Fatalf("boundary control rejected: %s", got.Raw) + } + }) + } +} + +func TestHubLimits_BinaryPayloadAndTransportBoundaries(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + server := dialRole(t, srv.URL, "key", RoleServer, "s", "Server") + client := dialRole(t, srv.URL, "key", RoleClient, "c", "Client") + _ = readTextJSONFrame(t, client) + for _, size := range []int{MaxRawPayloadBytes, MaxRawPayloadBytes + 1, MaxInboundFrameBytes - 6, MaxInboundFrameBytes - 5} { + raw := append([]byte{ProtocolVersion1, PayloadTypeBinary, 1, 1, 'c', 's'}, make([]byte, size)...) + written := make(chan error, 1) + go func() { written <- client.WriteMessage(websocket.BinaryMessage, raw) }() + if len(raw) > MaxInboundFrameBytes { + assertTunnelClose(t, client, websocket.CloseMessageTooBig) + select { + case <-written: + case <-time.After(5 * time.Second): + t.Fatal("oversized transport writer did not exit") + } + continue + } + if errWrite := <-written; errWrite != nil { + t.Fatal(errWrite) + } + if size == MaxRawPayloadBytes { + if got := readBinaryDataFrame(t, server); len(got.Payload) != MaxRawPayloadBytes { + t.Fatalf("payload boundary length = %d", len(got.Payload)) + } + continue + } + if got := readTextJSONFrame(t, client); got.Get("code").String() != ErrCodeInvalidDataFrame { + t.Fatalf("protocol overflow = %s", got.Raw) + } + if errWrite := client.WriteMessage(websocket.TextMessage, []byte(`{"type":"list_servers","request_id":"alive"}`)); errWrite != nil { + t.Fatal(errWrite) + } + if got := readTextJSONFrame(t, client); got.Get("request_id").String() != "alive" { + t.Fatal("protocol payload overflow terminated connection") + } + } +} + +func TestHubClose_RevokedSessionCannotRouteAfterKeyIsReadded(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"a"}) + t.Cleanup(hub.Close) + oldTenant := newRealm() + stale := newBudgetTestPeer(hub, oldTenant, "client", RoleClient) + oldTenant.peers[stale.uuid] = stale + hub.realms["a"] = oldTenant + hub.UpdateAllowedAPIKeys(nil) + hub.UpdateAllowedAPIKeys([]string{"a"}) + newTenant := newRealm() + current := newBudgetTestPeer(hub, newTenant, "client", RoleClient) + target := newBudgetTestPeer(hub, newTenant, "server", RoleServer) + newTenant.peers[current.uuid] = current + newTenant.peers[target.uuid] = target + hub.realms["a"] = newTenant + raw, errEncode := EncodeDataFrame(PayloadTypeText, "client", "server", []byte("not authorized")) + if errEncode != nil { + t.Fatal(errEncode) + } + hub.handleDataMessage(stale, raw) + hub.handleControlMessage(stale, []byte(`{"type":"list_servers"}`)) + if len(target.sendCh) != 0 || len(stale.sendCh) != 0 { + t.Fatal("revoked session accessed a new tenant generation") + } + hub.handleDataMessage(current, raw) + if len(target.sendCh) != 1 { + t.Fatal("current authorized session could not route") + } +} + +func TestHubControl_UnknownTypeErrorDoesNotEchoInput(t *testing.T) { + hub := NewHub(Options{}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := httptest.NewServer(hub) + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + client := dialRole(t, srv.URL, "key", RoleClient, "c", "Client") + _ = readTextJSONFrame(t, client) + doc := ojson.NewDocString("{}") + if errSet := doc.Set("type", strings.Repeat("x", MaxControlTypeLen)); errSet != nil { + t.Fatal(errSet) + } + if errWrite := client.WriteMessage(websocket.TextMessage, doc.Bytes()); errWrite != nil { + t.Fatal(errWrite) + } + got := readTextJSONFrame(t, client) + if got.Get("code").String() != ErrCodeInvalidControlFrame || len(got.Raw) > 200 || strings.Contains(got.Raw, strings.Repeat("x", MaxControlTypeLen)) { + t.Fatalf("unknown type amplified into error: %s", got.Raw) + } +} diff --git a/internal/wstunnel/protocol.go b/internal/wstunnel/protocol.go new file mode 100644 index 00000000000..7046a7b8308 --- /dev/null +++ b/internal/wstunnel/protocol.go @@ -0,0 +1,351 @@ +// Package wstunnel implements an access.api-keys authenticated, multi-tenant, +// many-to-many WebSocket tunnel between client and server devices. +package wstunnel + +import ( + "errors" + "fmt" + "strconv" + "strings" + "unicode/utf8" + + "github.com/MoeForge/moego/ojson" +) + +// Role identifies the declared endpoint role of a connected tunnel device. +type Role string + +const ( + // RoleClient identifies a client device that discovers and exchanges packets with servers. + RoleClient Role = "client" + // RoleServer identifies a server device that accepts and sends packets with clients. + RoleServer Role = "server" +) + +const ( + // ProtocolVersion1 is the binary data-frame wire format version. + ProtocolVersion1 byte = 0x01 + + // PayloadTypeBinary indicates an opaque binary payload. + PayloadTypeBinary byte = 0x00 + // PayloadTypeText indicates a UTF-8 text payload. + PayloadTypeText byte = 0x01 + + // MinBinaryFrameHeaderLen is the fixed prefix length before SrcUUID and DstUUID bytes. + MinBinaryFrameHeaderLen = 4 + // MaxUUIDLen is the maximum byte length of a device UUID. + MaxUUIDLen = 128 + // MaxDeviceNameLen is the maximum UTF-8 byte length of a device name. + MaxDeviceNameLen = 256 + // MaxServerTypeLen is the maximum UTF-8 byte length of a server type. + MaxServerTypeLen = 256 + // MaxControlFrameBytes caps inbound JSON text messages before allocation and parsing. + MaxControlFrameBytes = 4096 + // MaxControlTypeLen caps the byte length of an inbound control type. + MaxControlTypeLen = 64 + // MaxRequestIDLen is the maximum byte length of an optional control request_id. + MaxRequestIDLen = 128 + // MaxRawPayloadBytes is the maximum raw business payload size per binary data frame (64 MiB). + MaxRawPayloadBytes = 64 << 20 + // MaxInboundFrameBytes is the WebSocket read limit covering header overhead plus MaxRawPayloadBytes. + MaxInboundFrameBytes = MaxRawPayloadBytes + 512 +) + +const ( + // ControlTypeServerList delivers the online server snapshot to a client. + ControlTypeServerList = "server_list" + // ControlTypeListServers requests an up-to-date server_list snapshot from a client. + ControlTypeListServers = "list_servers" + // ControlTypeServerOnline notifies online clients that a server joined the tenant realm. + ControlTypeServerOnline = "server_online" + // ControlTypeServerOffline notifies online clients that a server left the tenant realm. + ControlTypeServerOffline = "server_offline" + // ControlTypeError reports a non-fatal protocol or routing error to the sender. + ControlTypeError = "error" +) + +const ( + // ErrCodeInvalidControlFrame indicates malformed JSON or an unsupported control message. + ErrCodeInvalidControlFrame = "invalid_control_frame" + // ErrCodeUnsupportedRoleAction indicates a control action not permitted for the peer role. + ErrCodeUnsupportedRoleAction = "unsupported_role_action" + // ErrCodeInvalidDataFrame indicates a malformed or out-of-bounds binary data frame. + ErrCodeInvalidDataFrame = "invalid_data_frame" + // ErrCodeUnsupportedVersion indicates an unknown binary frame protocol version. + ErrCodeUnsupportedVersion = "unsupported_version" + // ErrCodeSourceUUIDMismatch indicates the frame's SrcUUID does not match the authenticated peer UUID. + ErrCodeSourceUUIDMismatch = "source_uuid_mismatch" + // ErrCodeTargetNotFound indicates the target DstUUID is not online in the same api-key realm. + ErrCodeTargetNotFound = "target_not_found" + // ErrCodeInvalidTargetRole indicates an attempt to route client->client or server->server. + ErrCodeInvalidTargetRole = "invalid_target_role" + // ErrCodeTargetBufferFull indicates the target peer's outbound send buffer is full. + ErrCodeTargetBufferFull = "target_buffer_full" +) + +// ServerInfo describes an online server device within the caller's api-key realm. +type ServerInfo struct { + UUID string + Name string + Type string +} + +// ControlRequest represents a parsed inbound text control frame. +type ControlRequest struct { + Type string + RequestID string +} + +// DataFrameView provides zero-copy slices into a validated binary data frame. +type DataFrameView struct { + Version byte + PayloadType byte + SrcUUID string + DstUUID string + Payload []byte +} + +// NormalizeAndValidateRole trims, lowercases, and validates a declared tunnel role. +func NormalizeAndValidateRole(raw string) (Role, error) { + normalized := strings.ToLower(strings.TrimSpace(raw)) + switch Role(normalized) { + case RoleClient: + return RoleClient, nil + case RoleServer: + return RoleServer, nil + default: + return "", errors.New("invalid or missing role: must be client or server") + } +} + +// NormalizeAndValidateUUID trims and validates a device UUID (1..128 printable non-space ASCII bytes). +func NormalizeAndValidateUUID(raw string) (string, error) { + trimmed := strings.TrimSpace(raw) + if !isValidUUIDBytes([]byte(trimmed)) { + return "", errors.New("invalid or missing uuid") + } + return trimmed, nil +} + +func isValidUUIDBytes(b []byte) bool { + if len(b) < 1 || len(b) > MaxUUIDLen { + return false + } + for i := 0; i < len(b); i++ { + if b[i] < 0x21 || b[i] > 0x7e { + return false + } + } + return true +} + +// NormalizeAndValidateName validates UTF-8 and control-character constraints on raw input, +// then trims surrounding spaces and checks the 1..256 byte length bound. +func NormalizeAndValidateName(raw string) (string, error) { + if !utf8.ValidString(raw) || hasASCIIControlChar(raw) { + return "", errors.New("invalid or missing name") + } + trimmed := strings.TrimSpace(raw) + if len(trimmed) < 1 || len(trimmed) > MaxDeviceNameLen { + return "", errors.New("invalid or missing name") + } + return trimmed, nil +} + +// NormalizeAndValidateType validates UTF-8 and control-character constraints on raw input, +// then trims surrounding spaces and checks the 1..256 byte length bound. +func NormalizeAndValidateType(raw string) (string, error) { + if !utf8.ValidString(raw) || hasASCIIControlChar(raw) { + return "", errors.New("invalid or missing type") + } + trimmed := strings.TrimSpace(raw) + if len(trimmed) < 1 || len(trimmed) > MaxServerTypeLen { + return "", errors.New("invalid or missing type") + } + return trimmed, nil +} + +func hasASCIIControlChar(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] < 0x20 || s[i] == 0x7f { + return true + } + } + return false +} + +// EncodeDataFrame encapsulates an opaque payload into a tunnel binary frame. +func EncodeDataFrame(payloadType byte, srcUUID, dstUUID string, payload []byte) ([]byte, error) { + if !isValidUUIDBytes([]byte(srcUUID)) { + return nil, errors.New("invalid source uuid") + } + if !isValidUUIDBytes([]byte(dstUUID)) { + return nil, errors.New("invalid destination uuid") + } + if len(payload) > MaxRawPayloadBytes { + return nil, fmt.Errorf("payload exceeds maximum size of %d bytes", MaxRawPayloadBytes) + } + + totalLen := MinBinaryFrameHeaderLen + len(srcUUID) + len(dstUUID) + len(payload) + buf := make([]byte, 0, totalLen) + buf = append(buf, ProtocolVersion1, payloadType, byte(len(srcUUID)), byte(len(dstUUID))) + buf = append(buf, srcUUID...) + buf = append(buf, dstUUID...) + buf = append(buf, payload...) + return buf, nil +} + +// ParseDataFrameHeader validates a tunnel binary frame header and returns a zero-copy view. +func ParseDataFrameHeader(rawFrame []byte) (DataFrameView, string, error) { + if len(rawFrame) < MinBinaryFrameHeaderLen { + return DataFrameView{}, ErrCodeInvalidDataFrame, errors.New("binary frame shorter than 4-byte header") + } + version := rawFrame[0] + if version != ProtocolVersion1 { + return DataFrameView{}, ErrCodeUnsupportedVersion, fmt.Errorf("unsupported binary frame version 0x%02x", version) + } + payloadType := rawFrame[1] + srcLen := int(rawFrame[2]) + dstLen := int(rawFrame[3]) + if srcLen < 1 || srcLen > MaxUUIDLen || dstLen < 1 || dstLen > MaxUUIDLen { + return DataFrameView{}, ErrCodeInvalidDataFrame, errors.New("binary frame uuid length out of bounds") + } + headerLen := MinBinaryFrameHeaderLen + srcLen + dstLen + if len(rawFrame) < headerLen { + return DataFrameView{}, ErrCodeInvalidDataFrame, errors.New("binary frame truncated before uuid fields") + } + payload := rawFrame[headerLen:] + if len(payload) > MaxRawPayloadBytes { + return DataFrameView{}, ErrCodeInvalidDataFrame, errors.New("binary frame payload exceeds maximum allowed size") + } + srcBytes := rawFrame[MinBinaryFrameHeaderLen : MinBinaryFrameHeaderLen+srcLen] + dstBytes := rawFrame[MinBinaryFrameHeaderLen+srcLen : headerLen] + if !isValidUUIDBytes(srcBytes) || !isValidUUIDBytes(dstBytes) { + return DataFrameView{}, ErrCodeInvalidDataFrame, errors.New("binary frame contains invalid uuid bytes") + } + + return DataFrameView{ + Version: version, + PayloadType: payloadType, + SrcUUID: string(srcBytes), + DstUUID: string(dstBytes), + Payload: payload, + }, "", nil +} + +// EncodeServerListFrame builds a JSON server_list control message using single-exit ojson.Doc serialization. +func EncodeServerListFrame(requestID string, servers []ServerInfo) ([]byte, error) { + doc := ojson.NewDocString("{}") + if errSet := doc.Set("type", ControlTypeServerList); errSet != nil { + return nil, errSet + } + if requestID != "" { + if errSet := doc.Set("request_id", requestID); errSet != nil { + return nil, errSet + } + } + if errSetRaw := doc.SetRaw("servers", "[]"); errSetRaw != nil { + return nil, errSetRaw + } + for i, srv := range servers { + idx := strconv.Itoa(i) + if errSet := doc.Set("servers."+idx+".uuid", srv.UUID); errSet != nil { + return nil, errSet + } + if errSet := doc.Set("servers."+idx+".name", srv.Name); errSet != nil { + return nil, errSet + } + if errSet := doc.Set("servers."+idx+".type", srv.Type); errSet != nil { + return nil, errSet + } + } + return doc.Bytes(), nil +} + +// EncodeServerEventFrame builds a server_online or server_offline JSON control message. +func EncodeServerEventFrame(eventType string, server ServerInfo) ([]byte, error) { + if eventType != ControlTypeServerOnline && eventType != ControlTypeServerOffline { + return nil, fmt.Errorf("unsupported server event type %q", eventType) + } + doc := ojson.NewDocString("{}") + if errSet := doc.Set("type", eventType); errSet != nil { + return nil, errSet + } + if errSet := doc.Set("server.uuid", server.UUID); errSet != nil { + return nil, errSet + } + if errSet := doc.Set("server.name", server.Name); errSet != nil { + return nil, errSet + } + if errSet := doc.Set("server.type", server.Type); errSet != nil { + return nil, errSet + } + return doc.Bytes(), nil +} + +// EncodeErrorFrame builds a non-fatal JSON error control message. +func EncodeErrorFrame(code, message, targetUUID, requestID string) ([]byte, error) { + doc := ojson.NewDocString("{}") + if errSet := doc.Set("type", ControlTypeError); errSet != nil { + return nil, errSet + } + if errSet := doc.Set("code", code); errSet != nil { + return nil, errSet + } + if targetUUID != "" { + if errSet := doc.Set("target_uuid", targetUUID); errSet != nil { + return nil, errSet + } + } + if requestID != "" { + if errSet := doc.Set("request_id", requestID); errSet != nil { + return nil, errSet + } + } + if errSet := doc.Set("message", message); errSet != nil { + return nil, errSet + } + return doc.Bytes(), nil +} + +// ParseControlFrame validates and parses an inbound JSON text control frame. +func ParseControlFrame(raw []byte) (ControlRequest, string, error) { + if len(raw) > MaxControlFrameBytes { + return ControlRequest{}, ErrCodeInvalidControlFrame, errors.New("control frame exceeds maximum allowed size") + } + if len(raw) == 0 || !utf8.Valid(raw) || !ojson.ValidBytes(raw) { + return ControlRequest{}, ErrCodeInvalidControlFrame, errors.New("malformed control json") + } + parsed := ojson.ParseBytes(raw) + if !parsed.IsObject() { + return ControlRequest{}, ErrCodeInvalidControlFrame, errors.New("control frame must be a json object") + } + typeRes := parsed.Get("type") + if typeRes.Type != ojson.String { + return ControlRequest{}, ErrCodeInvalidControlFrame, errors.New("control frame missing string type") + } + msgType := typeRes.String() + if len(msgType) > MaxControlTypeLen { + return ControlRequest{}, ErrCodeInvalidControlFrame, errors.New("control type exceeds maximum allowed size") + } + if msgType != ControlTypeListServers { + return ControlRequest{}, ErrCodeInvalidControlFrame, errors.New("unsupported control message type") + } + + var reqID string + reqIDRes := parsed.Get("request_id") + if reqIDRes.Exists() { + if reqIDRes.Type != ojson.String { + return ControlRequest{}, ErrCodeInvalidControlFrame, errors.New("request_id must be a string") + } + reqID = reqIDRes.String() + if len(reqID) > MaxRequestIDLen || !utf8.ValidString(reqID) || hasASCIIControlChar(reqID) { + return ControlRequest{}, ErrCodeInvalidControlFrame, errors.New("invalid request_id") + } + } + + return ControlRequest{ + Type: msgType, + RequestID: reqID, + }, "", nil +} diff --git a/internal/wstunnel/protocol_test.go b/internal/wstunnel/protocol_test.go new file mode 100644 index 00000000000..22703fb9146 --- /dev/null +++ b/internal/wstunnel/protocol_test.go @@ -0,0 +1,388 @@ +package wstunnel + +import ( + "bytes" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" +) + +func TestValidateHandshakeParams(t *testing.T) { + t.Run("role normalization and validation", func(t *testing.T) { + roleClient, errClient := NormalizeAndValidateRole(" CLIENT ") + if errClient != nil || roleClient != RoleClient { + t.Fatalf("NormalizeAndValidateRole(CLIENT) = (%q, %v), want (%q, nil)", roleClient, errClient, RoleClient) + } + roleServer, errServer := NormalizeAndValidateRole("\tSeRvEr\n") + if errServer != nil || roleServer != RoleServer { + t.Fatalf("NormalizeAndValidateRole(server) = (%q, %v), want (%q, nil)", roleServer, errServer, RoleServer) + } + for _, bad := range []string{"", " ", "admin", "peer", "client2"} { + if _, errBad := NormalizeAndValidateRole(bad); errBad == nil { + t.Fatalf("NormalizeAndValidateRole(%q) succeeded, want error", bad) + } + } + }) + + t.Run("uuid validation", func(t *testing.T) { + for _, okVal := range []string{ + "a", + " 550e8400-e29b-41d4-a716-446655440000 ", + strings.Repeat("x", MaxUUIDLen), + } { + got, errUUID := NormalizeAndValidateUUID(okVal) + if errUUID != nil { + t.Fatalf("NormalizeAndValidateUUID(%q) error = %v", okVal, errUUID) + } + if got != strings.TrimSpace(okVal) { + t.Fatalf("NormalizeAndValidateUUID(%q) = %q, want %q", okVal, got, strings.TrimSpace(okVal)) + } + } + + for _, badVal := range []string{ + "", + " ", + "has space", + "has\ttab", + "has\nnewline", + "非ASCII", + "bad\x7fdel", + strings.Repeat("x", MaxUUIDLen+1), + } { + if _, errBad := NormalizeAndValidateUUID(badVal); errBad == nil { + t.Fatalf("NormalizeAndValidateUUID(%q) succeeded, want error", badVal) + } + } + }) + + t.Run("name validation", func(t *testing.T) { + validNames := []string{ + " Office Mac Studio ", + "研发构建机-01 🚀", + `Quote "A" \ Slash`, + strings.Repeat("a", MaxDeviceNameLen), + strings.Repeat("测", MaxDeviceNameLen/3), + } + for _, raw := range validNames { + got, errName := NormalizeAndValidateName(raw) + if errName != nil { + t.Fatalf("NormalizeAndValidateName(%q) error = %v", raw, errName) + } + if got != strings.TrimSpace(raw) { + t.Fatalf("NormalizeAndValidateName(%q) = %q, want %q", raw, got, strings.TrimSpace(raw)) + } + } + + invalidNames := []string{ + "", + " ", + "\nLeadingNewline", + "TrailingCR\r", + "\tTabWrapped\t", + "line1\nline2", + "line1\rline2", + "tab\there", + "null\x00byte", + "del\x7fbyte", + string([]byte{0xff, 0xfe, 0xfd}), + strings.Repeat("a", MaxDeviceNameLen+1), + } + for _, raw := range invalidNames { + if _, errBad := NormalizeAndValidateName(raw); errBad == nil { + t.Fatalf("NormalizeAndValidateName(%q) succeeded, want error", raw) + } + } + }) + + t.Run("type validation", func(t *testing.T) { + validTypes := []string{ + "a", + "测", + " cpa-desktop ", + "研发服务端类型-01 🚀", + `Custom "Type" \ v2`, + strings.Repeat("t", MaxServerTypeLen), + strings.Repeat("类", MaxServerTypeLen/3), + } + for _, raw := range validTypes { + got, errType := NormalizeAndValidateType(raw) + if errType != nil { + t.Fatalf("NormalizeAndValidateType(%q) error = %v", raw, errType) + } + if got != strings.TrimSpace(raw) { + t.Fatalf("NormalizeAndValidateType(%q) = %q, want %q", raw, got, strings.TrimSpace(raw)) + } + } + + invalidTypes := []string{ + "", + " ", + " ", + "\u00a0", + "\u3000", + "\nLeadingNewline", + "TrailingCR\r", + "\tTabWrapped\t", + "line1\nline2", + "line1\rline2", + "tab\there", + "null\x00byte", + "del\x7fbyte", + string([]byte{0xff, 0xfe, 0xfd}), + strings.Repeat("t", MaxServerTypeLen+1), + } + for _, raw := range invalidTypes { + if _, errBad := NormalizeAndValidateType(raw); errBad == nil || errBad.Error() != "invalid or missing type" { + t.Fatalf("NormalizeAndValidateType(%q) = %v, want error 'invalid or missing type'", raw, errBad) + } + } + }) +} + +func TestBinaryDataFrameCodec(t *testing.T) { + cases := []struct { + name string + payloadType byte + srcUUID string + dstUUID string + payload []byte + }{ + { + name: "empty payload", + payloadType: PayloadTypeBinary, + srcUUID: "cli-1", + dstUUID: "srv-1", + payload: nil, + }, + { + name: "utf8 text payload", + payloadType: PayloadTypeText, + srcUUID: "550e8400-e29b-41d4-a716-446655440000", + dstUUID: "6ba7b810-9dad-11d1-80b4-00c04fd430c8", + payload: []byte(`{"hello":"世界"}`), + }, + { + name: "arbitrary binary bytes and custom payload type", + payloadType: 0x42, + srcUUID: strings.Repeat("c", MaxUUIDLen), + dstUUID: strings.Repeat("s", MaxUUIDLen), + payload: []byte{0x00, 0x01, 0x7f, 0x80, 0xfe, 0xff, 0x00}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + encoded, errEncode := EncodeDataFrame(tc.payloadType, tc.srcUUID, tc.dstUUID, tc.payload) + if errEncode != nil { + t.Fatalf("EncodeDataFrame() error = %v", errEncode) + } + + view, errCode, errParse := ParseDataFrameHeader(encoded) + if errParse != nil || errCode != "" { + t.Fatalf("ParseDataFrameHeader() = (%+v, %q, %v), want nil error", view, errCode, errParse) + } + if view.Version != ProtocolVersion1 { + t.Fatalf("Version = 0x%02x, want 0x%02x", view.Version, ProtocolVersion1) + } + if view.PayloadType != tc.payloadType { + t.Fatalf("PayloadType = 0x%02x, want 0x%02x", view.PayloadType, tc.payloadType) + } + if view.SrcUUID != tc.srcUUID || view.DstUUID != tc.dstUUID { + t.Fatalf("UUIDs = (%q -> %q), want (%q -> %q)", view.SrcUUID, view.DstUUID, tc.srcUUID, tc.dstUUID) + } + if !bytes.Equal(view.Payload, tc.payload) { + t.Fatalf("Payload = %x, want %x", view.Payload, tc.payload) + } + }) + } + + t.Run("encode rejects invalid uuids", func(t *testing.T) { + if _, errEncode := EncodeDataFrame(PayloadTypeBinary, " cli-1 ", "srv-1", []byte("x")); errEncode == nil { + t.Fatal("EncodeDataFrame with untrimmed srcUUID succeeded, want error") + } + if _, errEncode := EncodeDataFrame(PayloadTypeBinary, "cli-1", "", []byte("x")); errEncode == nil { + t.Fatal("EncodeDataFrame with empty dstUUID succeeded, want error") + } + }) + + t.Run("malformed binary frames", func(t *testing.T) { + malformed := []struct { + name string + raw []byte + wantCode string + }{ + { + name: "shorter than 4 byte header", + raw: []byte{0x01, 0x00, 0x01}, + wantCode: ErrCodeInvalidDataFrame, + }, + { + name: "unsupported protocol version", + raw: []byte{0x02, 0x00, 0x01, 0x01, 'a', 'b'}, + wantCode: ErrCodeUnsupportedVersion, + }, + { + name: "zero src uuid length", + raw: []byte{0x01, 0x00, 0x00, 0x01, 'b'}, + wantCode: ErrCodeInvalidDataFrame, + }, + { + name: "zero dst uuid length", + raw: []byte{0x01, 0x00, 0x01, 0x00, 'a'}, + wantCode: ErrCodeInvalidDataFrame, + }, + { + name: "src uuid length exceeds 128", + raw: append([]byte{0x01, 0x00, 129, 0x01}, bytes.Repeat([]byte{'a'}, 130)...), + wantCode: ErrCodeInvalidDataFrame, + }, + { + name: "truncated uuid bytes", + raw: []byte{0x01, 0x00, 0x05, 0x05, 'a', 'b', 'c'}, + wantCode: ErrCodeInvalidDataFrame, + }, + { + name: "non-printable ascii inside uuid", + raw: []byte{0x01, 0x00, 0x02, 0x01, 'a', ' ', 'b'}, + wantCode: ErrCodeInvalidDataFrame, + }, + { + name: "payload exceeds 64 MiB limit", + raw: append([]byte{0x01, 0x00, 0x01, 0x01, 'a', 'b'}, make([]byte, MaxRawPayloadBytes+1)...), + wantCode: ErrCodeInvalidDataFrame, + }, + } + + for _, tc := range malformed { + t.Run(tc.name, func(t *testing.T) { + _, code, errParse := ParseDataFrameHeader(tc.raw) + if errParse == nil { + t.Fatalf("ParseDataFrameHeader() succeeded, want error code %q", tc.wantCode) + } + if code != tc.wantCode { + t.Fatalf("error code = %q, want %q (err=%v)", code, tc.wantCode, errParse) + } + }) + } + }) +} + +func TestControlFrameJSONCodec(t *testing.T) { + t.Run("empty server_list omits request_id and emits empty array", func(t *testing.T) { + raw, errEncode := EncodeServerListFrame("", nil) + if errEncode != nil { + t.Fatalf("EncodeServerListFrame() error = %v", errEncode) + } + if string(raw) != `{"type":"server_list","servers":[]}` { + t.Fatalf("EncodeServerListFrame() = %s, want %s", string(raw), `{"type":"server_list","servers":[]}`) + } + }) + + t.Run("server_list escapes special characters and preserves request_id", func(t *testing.T) { + servers := []ServerInfo{ + {UUID: "srv-1", Name: `Node "Alpha" \ 节点`, Type: `Type "Alpha" \ 类型`}, + {UUID: "srv-2", Name: "Node Beta", Type: "x"}, + } + raw, errEncode := EncodeServerListFrame("req-42", servers) + if errEncode != nil { + t.Fatalf("EncodeServerListFrame() error = %v", errEncode) + } + if !ojson.ValidBytes(raw) { + t.Fatalf("invalid json emitted: %s", string(raw)) + } + parsed := ojson.ParseBytes(raw) + if got := parsed.Get("type").String(); got != ControlTypeServerList { + t.Fatalf("type = %q, want %q", got, ControlTypeServerList) + } + if got := parsed.Get("request_id").String(); got != "req-42" { + t.Fatalf("request_id = %q, want req-42", got) + } + if got := parsed.Get("servers.#").Int(); got != 2 { + t.Fatalf("servers count = %d, want 2", got) + } + if got := parsed.Get("servers.0.name").String(); got != `Node "Alpha" \ 节点` { + t.Fatalf("servers.0.name = %q, want %q", got, `Node "Alpha" \ 节点`) + } + if got := parsed.Get("servers.0.type").String(); got != `Type "Alpha" \ 类型` { + t.Fatalf("servers.0.type = %q, want %q", got, `Type "Alpha" \ 类型`) + } + if got := parsed.Get("servers.1.type").String(); got != "x" { + t.Fatalf("servers.1.type = %q, want x", got) + } + }) + + t.Run("server_online and server_offline events", func(t *testing.T) { + online, errOnline := EncodeServerEventFrame(ControlTypeServerOnline, ServerInfo{UUID: "s1", Name: "Server One", Type: "cpa-desktop"}) + if errOnline != nil { + t.Fatalf("EncodeServerEventFrame(online) error = %v", errOnline) + } + pOnline := ojson.ParseBytes(online) + if pOnline.Get("type").String() != ControlTypeServerOnline || + pOnline.Get("server.uuid").String() != "s1" || + pOnline.Get("server.name").String() != "Server One" || + pOnline.Get("server.type").String() != "cpa-desktop" { + t.Fatalf("unexpected online frame: %s", string(online)) + } + + offline, errOffline := EncodeServerEventFrame(ControlTypeServerOffline, ServerInfo{UUID: "s1", Name: "Server One", Type: "cpa-desktop"}) + if errOffline != nil { + t.Fatalf("EncodeServerEventFrame(offline) error = %v", errOffline) + } + pOffline := ojson.ParseBytes(offline) + if pOffline.Get("type").String() != ControlTypeServerOffline || + pOffline.Get("server.uuid").String() != "s1" || + pOffline.Get("server.name").String() != "Server One" || + pOffline.Get("server.type").String() != "cpa-desktop" { + t.Fatalf("unexpected offline frame: %s", string(offline)) + } + }) + + t.Run("error frame optional fields", func(t *testing.T) { + minimal, errMin := EncodeErrorFrame(ErrCodeInvalidControlFrame, "bad json", "", "") + if errMin != nil { + t.Fatalf("EncodeErrorFrame(minimal) error = %v", errMin) + } + pMin := ojson.ParseBytes(minimal) + if pMin.Get("target_uuid").Exists() || pMin.Get("request_id").Exists() { + t.Fatalf("expected optional fields omitted, got %s", string(minimal)) + } + + full, errFull := EncodeErrorFrame(ErrCodeTargetNotFound, "peer offline", "srv-9", "req-9") + if errFull != nil { + t.Fatalf("EncodeErrorFrame(full) error = %v", errFull) + } + pFull := ojson.ParseBytes(full) + if pFull.Get("code").String() != ErrCodeTargetNotFound || pFull.Get("target_uuid").String() != "srv-9" || pFull.Get("request_id").String() != "req-9" { + t.Fatalf("unexpected full error frame: %s", string(full)) + } + }) + + t.Run("parse incoming control frames", func(t *testing.T) { + req, code, errParse := ParseControlFrame([]byte(`{"type":"list_servers","request_id":"r-1"}`)) + if errParse != nil || code != "" { + t.Fatalf("ParseControlFrame(valid) = (%+v, %q, %v)", req, code, errParse) + } + if req.Type != ControlTypeListServers || req.RequestID != "r-1" { + t.Fatalf("unexpected ControlRequest: %+v", req) + } + + badInputs := [][]byte{ + nil, + []byte("not-json"), + []byte("[]"), + []byte(`{}`), + []byte(`{"type":"unknown_cmd"}`), + []byte("{\"type\":\"list_servers\",\"extra\":\"\xff\"}"), + []byte("{\"type\":\"list_servers\",\"\xff\":\"ignored\"}"), + []byte("{\"type\":\"list_servers\",\"extra\":{\"name\":\"\xc0\xaf\"}}"), + []byte(`{"type":"list_servers","request_id":"` + strings.Repeat("a", MaxRequestIDLen+1) + `"}`), + []byte("{\"type\":\"list_servers\",\"request_id\":\"bad\\u0000id\"}"), + } + for _, bad := range badInputs { + if _, badCode, errBad := ParseControlFrame(bad); errBad == nil || badCode != ErrCodeInvalidControlFrame { + t.Fatalf("ParseControlFrame(%q) = (%q, %v), want (%q, non-nil)", string(bad), badCode, errBad, ErrCodeInvalidControlFrame) + } + } + }) +} diff --git a/internal/wstunnel/transport.go b/internal/wstunnel/transport.go new file mode 100644 index 00000000000..0c2f4218192 --- /dev/null +++ b/internal/wstunnel/transport.go @@ -0,0 +1,107 @@ +package wstunnel + +import ( + "bufio" + "errors" + "net" + "net/http" + "reflect" + "sync/atomic" + "time" +) + +// deadlineGuardResponseWriter protects even Gorilla's internal protocol-error writes. +type deadlineGuardResponseWriter struct { + http.ResponseWriter + conn *deadlineGuardConn +} + +func (w *deadlineGuardResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + conn, rw, errHijack := http.NewResponseController(w.ResponseWriter).Hijack() + if errHijack != nil { + return nil, nil, errHijack + } + // Gorilla v1.5.3 rejects buffered input before sending HTTP 101. The Hub + // sets ReadBufferSize, so its accepted reader always reads through this guard. + w.conn = &deadlineGuardConn{Conn: conn} + return w.conn, rw, nil +} + +// deadlineGuardConn permits handshake deadlines, but never finite upgraded deadlines. +type deadlineGuardConn struct { + net.Conn + postUpgrade atomic.Bool + frames frameInspector + onProtocolError func() +} + +var errInvalidInboundFrame = errors.New("wstunnel: invalid inbound WebSocket frame") + +func (c *deadlineGuardConn) Read(raw []byte) (int, error) { + if c.frames.failed { + return 0, errInvalidInboundFrame + } + n, errRead := c.Conn.Read(raw) + if n > 0 && c.postUpgrade.Load() && !c.frames.inspect(raw[:n]) { + // Do not expose fatal bytes to Gorilla: its reader could otherwise wait + // a second for the write token before attempting a protocol-error close. + if c.onProtocolError != nil { + c.onProtocolError() + } + return 0, errInvalidInboundFrame + } + return n, errRead +} + +// rawTransportConn follows transport wrappers without invoking their Close methods. +func rawTransportConn(conn net.Conn) net.Conn { + seen := make(map[net.Conn]struct{}) + for conn != nil { + value := reflect.ValueOf(conn) + // Reject malformed wrappers before calling methods or using them as map keys. + if !value.Comparable() { + return nil + } + switch value.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + if value.IsNil() { + return nil + } + } + if _, okSeen := seen[conn]; okSeen { + return nil + } + seen[conn] = struct{}{} + wrapper, okWrapper := conn.(interface{ NetConn() net.Conn }) + if !okWrapper { + return conn + } + conn = wrapper.NetConn() + } + return nil +} + +func (c *deadlineGuardConn) NetConn() net.Conn { + return c.Conn +} + +func (c *deadlineGuardConn) SetDeadline(deadline time.Time) error { + if c.postUpgrade.Load() && !deadline.IsZero() { + return nil + } + return c.Conn.SetDeadline(deadline) +} + +func (c *deadlineGuardConn) SetReadDeadline(deadline time.Time) error { + if c.postUpgrade.Load() && !deadline.IsZero() { + return nil + } + return c.Conn.SetReadDeadline(deadline) +} + +func (c *deadlineGuardConn) SetWriteDeadline(deadline time.Time) error { + if c.postUpgrade.Load() && !deadline.IsZero() { + return nil + } + return c.Conn.SetWriteDeadline(deadline) +} diff --git a/internal/wstunnel/transport_protocol_test.go b/internal/wstunnel/transport_protocol_test.go new file mode 100644 index 00000000000..4e28d10eb40 --- /dev/null +++ b/internal/wstunnel/transport_protocol_test.go @@ -0,0 +1,171 @@ +package wstunnel + +import ( + "bufio" + "bytes" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +func TestPeerControl_ProtocolErrorInterruptsActiveWriteImmediately(t *testing.T) { + for _, tc := range []struct { + name string + raw []byte + }{ + {"invalid opcode", []byte{0x83, 0x80}}, + {"reserved close code", maskedTunnelFrame(0x88, []byte{0x03, 0xed}, 0)}, + {"one-byte close", maskedTunnelFrame(0x88, []byte{0x03}, 0)}, + {"invalid UTF-8 close reason", maskedTunnelFrame(0x88, []byte{0x03, 0xe8, 0xff}, 0)}, + } { + t.Run(tc.name, func(t *testing.T) { + forceClose := make(chan time.Time) + t.Cleanup(func() { close(forceClose) }) + hub := NewHub(Options{PingInterval: time.Hour}) + // Never advance the grace reaper: an active write must be interrupted now. + hub.testForceClose = forceClose + inspected := make(chan struct{}) + resumeRead := make(chan struct{}) + t.Cleanup(func() { close(resumeRead) }) + hub.testBeforeProtocolErrorReturn = func() { + close(inspected) + <-resumeRead + } + unregistered := make(chan struct{}, 1) + hub.testOnPeerUnregistered = func(_, uuid string) { + if uuid == "server" { + unregistered <- struct{}{} + } + } + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := httptest.NewUnstartedServer(hub) + srv.Listener = deadlineTrackingTunnelListener{gatedTunnelListener{srv.Listener}} + srv.Start() + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + observer := dialRole(t, srv.URL, "key", RoleClient, "observer", "Observer") + _ = readTextJSONFrame(t, observer) + stalled := dialRole(t, srv.URL, "key", RoleServer, "server", "Server") + _ = readTextJSONFrame(t, observer) + p := lookupTunnelPeer(t, hub, "key", "server") + guard := p.conn.UnderlyingConn().(*deadlineGuardConn) + transport := guard.Conn.(*deadlineTrackingTunnelConn) + transport.monitoring.Store(true) + gated := transport.Conn.(*gatedTunnelConn) + gated.arm() + if !p.tryEnqueueData([]byte("active WriteMessage holds Gorilla's write token")) { + t.Fatal("could not enqueue active write") + } + waitTunnelSignal(t, gated.blocked, "WriteMessage blocked with Gorilla write token held") + if p.writeMu.TryLock() { + p.writeMu.Unlock() + t.Fatal("transport write is not active") + } + + if n, errWrite := stalled.UnderlyingConn().Write(tc.raw); errWrite != nil || n != len(tc.raw) { + t.Fatalf("write malformed frame: bytes=%d, error=%v", n, errWrite) + } + for _, signal := range []struct { + ch <-chan struct{} + name string + }{ + {inspected, "fatal frame intercepted inside guarded Read"}, + {unregistered, "peer unregistration"}, + {gated.closed, "raw transport close unblocking WriteMessage"}, + {p.done, "raw socket reclamation"}, + {p.writerDone, "blocked writer exit"}, + } { + waitTunnelSignal(t, signal.ch, signal.name) + } + offline := readTextJSONFrame(t, observer) + if offline.Get("type").String() != ControlTypeServerOffline || offline.Get("server.uuid").String() != "server" { + t.Fatalf("unexpected server_offline: %s", offline.Raw) + } + replacement := dialRole(t, srv.URL, "key", RoleServer, "server", "Replacement") + if errWrite := replacement.WriteMessage(websocket.BinaryMessage, []byte{ProtocolVersion1}); errWrite != nil { + t.Fatalf("replacement write: %v", errWrite) + } + if got := readTextJSONFrame(t, replacement); got.Get("code").String() != ErrCodeInvalidDataFrame { + t.Fatalf("replacement is not usable: %s", got.Raw) + } + // Guarded Read has not returned to Gorilla, and neither the write gate + // nor the grace reaper was released. Only raw Close can unblock the writer. + select { + case <-forceClose: + t.Fatal("grace reaper fired before replacement handshake completed") + default: + } + select { + case <-gated.gate: + t.Fatal("blocked write gate was released before replacement handshake completed") + default: + } + if lookupTunnelPeer(t, hub, "key", "server") == p { + t.Fatal("old peer remains registered") + } + if p.queuedBytes.Load() != 0 { + t.Fatal("interrupted active write leaked its byte reservation") + } + assertNoFiniteTunnelDeadlines(t, transport) + }) + } +} + +type bufferedTunnelHijacker struct { + http.ResponseWriter + conn net.Conn + rw *bufio.ReadWriter +} + +func (w bufferedTunnelHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return w.conn, w.rw, nil +} + +func TestDeadlineGuardUpgrade_RejectsBufferedPipelinedFramesBeforeHTTP101(t *testing.T) { + for _, raw := range [][]byte{ + maskedTunnelFrame(0x82, []byte("valid but premature"), 0), + {0x83, 0x80, 0, 0, 0, 0}, + } { + local, remote := net.Pipe() + for _, conn := range []net.Conn{local, remote} { + t.Cleanup(func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close pipelined transport: %v", errClose) + } + }) + } + reader := bufio.NewReader(bytes.NewReader(raw)) + if _, errPeek := reader.Peek(len(raw)); errPeek != nil { + t.Fatal(errPeek) + } + writer := &deadlineGuardResponseWriter{ResponseWriter: bufferedTunnelHijacker{ + ResponseWriter: httptest.NewRecorder(), + conn: local, + rw: bufio.NewReadWriter(reader, bufio.NewWriter(local)), + }} + req := httptest.NewRequest(http.MethodGet, "http://example.test/v1/tunnel", nil) + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "websocket") + req.Header.Set("Sec-WebSocket-Version", "13") + req.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + hub := NewHub(Options{}) + conn, errUpgrade := hub.upgrader.Upgrade(writer, req, nil) + if errUpgrade == nil { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close unexpected upgrade: %v", errClose) + } + t.Fatal("buffered client data bypassed the guarded reader") + } + if !strings.Contains(errUpgrade.Error(), "client sent data before handshake is complete") { + t.Fatalf("unexpected buffered-handshake rejection: %v", errUpgrade) + } + if hub.upgrader.ReadBufferSize == 0 || writer.conn.postUpgrade.Load() { + t.Fatal("accepted post-upgrade data could bypass the guard") + } + } +} diff --git a/internal/wstunnel/transport_test.go b/internal/wstunnel/transport_test.go new file mode 100644 index 00000000000..e394c005a9f --- /dev/null +++ b/internal/wstunnel/transport_test.go @@ -0,0 +1,246 @@ +package wstunnel + +import ( + "crypto/tls" + "errors" + "net" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +func TestRawTransportConn_UnwrapsLayersAndRejectsNilOrCycles(t *testing.T) { + local, remote := net.Pipe() + for _, conn := range []net.Conn{local, remote} { + t.Cleanup(func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close test transport: %v", errClose) + } + }) + } + var typedNil *deadlineGuardConn + selfCycle := &deadlineGuardConn{} + selfCycle.Conn = selfCycle + first := &deadlineGuardConn{} + second := &deadlineGuardConn{Conn: first} + first.Conn = second + tlsConn := tls.Client(&deadlineGuardConn{Conn: local}, &tls.Config{}) + for _, tc := range []struct { + name string + conn net.Conn + want net.Conn + }{ + {"raw transport", local, local}, + {"nested wrappers and TLS", &deadlineGuardConn{Conn: &deadlineGuardConn{Conn: tlsConn}}, local}, + {"nil", nil, nil}, + {"typed nil", typedNil, nil}, + {"nil wrapped connection", &deadlineGuardConn{}, nil}, + {"typed nil wrapped connection", &deadlineGuardConn{Conn: typedNil}, nil}, + {"self cycle", selfCycle, nil}, + {"multi-wrapper cycle", first, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := rawTransportConn(tc.conn); got != tc.want { + t.Fatalf("rawTransportConn() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestDeadlineGuardConn_OnlyHandshakeAllowsFiniteDeadlines(t *testing.T) { + local, remote := net.Pipe() + for _, conn := range []net.Conn{local, remote} { + t.Cleanup(func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close test transport: %v", errClose) + } + }) + } + transport := &deadlineTrackingTunnelConn{Conn: local} + transport.monitoring.Store(true) + guard := &deadlineGuardConn{Conn: transport} + methods := []struct { + name string + set func(time.Time) error + finite *atomic.Int64 + }{ + {"SetDeadline", guard.SetDeadline, &transport.deadlines}, + {"SetReadDeadline", guard.SetReadDeadline, &transport.readDeadlines}, + {"SetWriteDeadline", guard.SetWriteDeadline, &transport.writeDeadlines}, + } + finite := time.Now().Add(time.Hour) + for _, method := range methods { + if errSet := method.set(finite); errSet != nil || method.finite.Load() != 1 { + t.Fatalf("%s did not forward handshake deadline: %v", method.name, errSet) + } + } + guard.postUpgrade.Store(true) + for _, method := range methods { + if errSet := method.set(finite); errSet != nil || method.finite.Load() != 1 { + t.Fatalf("%s forwarded finite upgraded deadline: %v", method.name, errSet) + } + if errSet := method.set(time.Time{}); errSet != nil { + t.Fatalf("%s failed to clear deadline: %v", method.name, errSet) + } + } + if calls := transport.deadlineCalls.Load(); calls != 6 { + t.Fatalf("underlying deadline calls = %d, want 3 handshake + 3 zero deadlines", calls) + } +} + +func TestPeerControl_OversizedMessagesUseWriterCloseWithoutFiniteDeadlines(t *testing.T) { + for _, tc := range []struct { + name string + messageType int + size int + reason string + }{ + {"binary", websocket.BinaryMessage, MaxInboundFrameBytes + 1, "binary frame exceeds maximum allowed size"}, + {"text", websocket.TextMessage, MaxControlFrameBytes + 1, "control frame exceeds 4096 bytes"}, + {"text beyond binary limit", websocket.TextMessage, MaxInboundFrameBytes + 1, "control frame exceeds 4096 bytes"}, + } { + t.Run(tc.name, func(t *testing.T) { + hub := NewHub(Options{PingInterval: time.Hour}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newDeadlineTrackingTunnelServer(t, hub) + client := dialRole(t, srv.URL, "key", RoleClient, "device", "Device") + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "device") + transport := p.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*deadlineTrackingTunnelConn) + transport.monitoring.Store(true) + client.SetCloseHandler(func(int, string) error { return nil }) + written := make(chan struct{}) + go func() { + // A close may interrupt the oversized sender before it finishes writing. + _ = client.WriteMessage(tc.messageType, make([]byte, tc.size)) + close(written) + }() + _, _, errRead := readTunnelTestMessage(client) + var closeErr *websocket.CloseError + if !errors.As(errRead, &closeErr) || closeErr.Code != websocket.CloseMessageTooBig || closeErr.Text != tc.reason { + t.Fatalf("close = %v, want 1009 with reason %q from peer writer", errRead, tc.reason) + } + waitTunnelSignal(t, written, "oversized sender exit") + waitTunnelSignal(t, p.done, "oversized transport close") + waitTunnelSignal(t, p.writerDone, "oversized writer exit") + assertNoFiniteTunnelDeadlines(t, transport) + }) + } +} + +func TestPeerControl_ProtocolErrorReclaimsSaturatedTransport(t *testing.T) { + for _, tc := range []struct { + name string + raw []byte + }{ + {"invalid opcode", []byte{0x83, 0x80, 0, 0, 0, 0}}, + {"reserved close code", []byte{0x88, 0x82, 0, 0, 0, 0, 0x03, 0xed}}, + {"invalid UTF-8 close reason", []byte{0x88, 0x83, 0, 0, 0, 0, 0x03, 0xe8, 0xff}}, + } { + t.Run(tc.name, func(t *testing.T) { + forceClose := make(chan time.Time) + var forceOnce sync.Once + reclaim := func() { forceOnce.Do(func() { close(forceClose) }) } + hub := NewHub(Options{PingInterval: time.Hour}) + hub.testForceClose = forceClose + unregistered := make(chan struct{}, 1) + hub.testOnPeerUnregistered = func(_, uuid string) { + if uuid == "server" { + unregistered <- struct{}{} + } + } + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := httptest.NewUnstartedServer(hub) + srv.Listener = deadlineTrackingTunnelListener{gatedTunnelListener{srv.Listener}} + srv.Start() + t.Cleanup(srv.Close) + t.Cleanup(hub.Close) + t.Cleanup(reclaim) + + observer := dialRole(t, srv.URL, "key", RoleClient, "observer", "Observer") + _ = readTextJSONFrame(t, observer) + stalled := dialRole(t, srv.URL, "key", RoleServer, "server", "Server") + _ = readTextJSONFrame(t, observer) + p := lookupTunnelPeer(t, hub, "key", "server") + transport := p.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*deadlineTrackingTunnelConn) + transport.monitoring.Store(true) + gated := transport.Conn.(*gatedTunnelConn) + // Servers receive no initial frames, so the protocol-error close is the next write. + gated.arm() + if n, errWrite := stalled.UnderlyingConn().Write(tc.raw); errWrite != nil || n != len(tc.raw) { + t.Fatalf("write malformed frame: bytes=%d, error=%v", n, errWrite) + } + waitTunnelSignal(t, gated.blocked, "single-writer protocol-error close write") + waitTunnelSignal(t, unregistered, "protocol-error peer unregistration before socket reclamation") + offline := readTextJSONFrame(t, observer) + if offline.Get("type").String() != ControlTypeServerOffline || offline.Get("server.uuid").String() != "server" { + t.Fatalf("unexpected server_offline: %s", offline.Raw) + } + select { + case <-p.done: + t.Fatal("socket closed before the local grace period elapsed") + default: + } + // The old socket is still blocked, but its UUID must already be reusable. + replacement := dialRole(t, srv.URL, "key", RoleServer, "server", "Replacement") + online := readTextJSONFrame(t, observer) + if online.Get("type").String() != ControlTypeServerOnline || online.Get("server.name").String() != "Replacement" { + t.Fatalf("unexpected replacement server_online: %s", online.Raw) + } + replacementPeer := lookupTunnelPeer(t, hub, "key", "server") + if replacementPeer == p { + t.Fatal("protocol error left the old peer registered") + } + assertNoFiniteTunnelDeadlines(t, transport) + // Advance only the local close grace period, without socket deadlines or sleeps. + reclaim() + waitTunnelSignal(t, gated.closed, "forced underlying socket close") + waitTunnelSignal(t, p.done, "protocol-error socket reclamation") + waitTunnelSignal(t, p.writerDone, "protocol-error writer exit") + assertNoFiniteTunnelDeadlines(t, transport) + if lookupTunnelPeer(t, hub, "key", "server") != replacementPeer { + t.Fatal("old peer cleanup removed the replacement") + } + if errWrite := replacement.WriteMessage(websocket.BinaryMessage, []byte{ProtocolVersion1}); errWrite != nil { + t.Fatalf("replacement write: %v", errWrite) + } + if got := readTextJSONFrame(t, replacement); got.Get("code").String() != ErrCodeInvalidDataFrame { + t.Fatalf("replacement did not remain usable: %s", got.Raw) + } + }) + } +} + +func TestPeerControl_MalformedCloseNeverSetsFiniteDeadlines(t *testing.T) { + for _, tc := range []struct { + name string + payload []byte + }{ + {"reserved close code", []byte{0x03, 0xed}}, + {"invalid UTF-8 close reason", []byte{0x03, 0xe8, 0xff}}, + } { + t.Run(tc.name, func(t *testing.T) { + hub := NewHub(Options{PingInterval: time.Hour}) + hub.UpdateAllowedAPIKeys([]string{"key"}) + srv := newDeadlineTrackingTunnelServer(t, hub) + client := dialRole(t, srv.URL, "key", RoleClient, "device", "Device") + _ = readTextJSONFrame(t, client) + p := lookupTunnelPeer(t, hub, "key", "device") + transport := p.conn.UnderlyingConn().(*deadlineGuardConn).Conn.(*deadlineTrackingTunnelConn) + transport.monitoring.Store(true) + // A zero mask preserves the malformed payload without mutating any slices. + raw := append([]byte{0x88, 0x80 | byte(len(tc.payload)), 0, 0, 0, 0}, tc.payload...) + if n, errWrite := client.UnderlyingConn().Write(raw); errWrite != nil || n != len(raw) { + t.Fatalf("write malformed close: bytes=%d, error=%v", n, errWrite) + } + assertTunnelClose(t, client, websocket.CloseProtocolError) + waitTunnelSignal(t, p.done, "malformed close transport exit") + waitTunnelSignal(t, p.writerDone, "malformed close writer exit") + assertNoFiniteTunnelDeadlines(t, transport) + }) + } +} diff --git a/scripts/pinable/smoke_runtime.py b/scripts/pinable/smoke_runtime.py index 795b854123f..f82f34af64d 100644 --- a/scripts/pinable/smoke_runtime.py +++ b/scripts/pinable/smoke_runtime.py @@ -154,6 +154,19 @@ def configuration(key): and info.get("component_version") == manifest["version"] and info.get("build_time") == manifest["source"]["commit_time"], "host contract metadata mismatch") + code, config_body = request(port, "/v8/management/config", management_key) + runtime.require(code == 200 and isinstance(json.loads(config_body), dict), + "v8 management center config endpoint unavailable") + for unauthorized_key in ("", ephemeral_key): + runtime.require(request(port, "/v8/management/config", unauthorized_key)[0] in (401, 403), + "v8 config management authentication was bypassed") + # A successful management request resets the failed-attempt + # counter between independent negative-authentication groups. + # Otherwise this group plus the existing host-control checks + # legitimately reaches the five-failure IP ban threshold. + runtime.require(request(port, "/v8/management/config", management_key)[0] == 200, + "valid v8 management key rejected after negative auth checks") + checks.append("authenticated v8 management center config endpoint returns JSON") for key in ("", ephemeral_key): runtime.require(request(port, "/v0/management/runtime-info", key)[0] in (401, 403), "management authentication was bypassed") diff --git a/sdk/api/handlers/claude/code_handlers_cooldown_test.go b/sdk/api/handlers/claude/code_handlers_cooldown_test.go index 33c8e6e37f1..c29353364b8 100644 --- a/sdk/api/handlers/claude/code_handlers_cooldown_test.go +++ b/sdk/api/handlers/claude/code_handlers_cooldown_test.go @@ -224,3 +224,101 @@ func TestClaudeCooldownMessagesRoute(t *testing.T) { }) } } + +type cooldownClaudeTestExecutor struct { + preFTKeepAliveClaudeExecutor +} + +func (*cooldownClaudeTestExecutor) Identifier() string { return "claude" } + +func TestClaudeCooldownMessagesRoute_PassthroughUnifiedRateLimitHeaders(t *testing.T) { + gin.SetMode(gin.TestMode) + chunks := make(chan coreexecutor.StreamChunk) + close(chunks) + executor := &cooldownClaudeTestExecutor{preFTKeepAliveClaudeExecutor: preFTKeepAliveClaudeExecutor{chunks: chunks}} + manager := coreauth.NewManager(nil, coreauth.NewSessionAffinitySelector(&coreauth.RoundRobinSelector{}), nil) + manager.RegisterExecutor(executor) + const model = "issue-7417-cooldown-route-model" + const authID = "issue-7417-cooldown-route-auth" + next := time.Now().Add(7823 * time.Second) + auth := &coreauth.Auth{ + ID: authID, + Provider: executor.Identifier(), + Status: coreauth.StatusActive, + Unavailable: true, + NextRetryAfter: next, + Quota: coreauth.QuotaState{ + Exceeded: true, + Reason: "credential_quota", + NextRecoverAt: next, + Signals: map[string]string{ + "Anthropic-Ratelimit-Unified-Status": "rejected", + "Anthropic-Ratelimit-Unified-5h-Status": "rejected", + "Anthropic-Ratelimit-Unified-Reset": strconv.FormatInt(next.Add(-10*time.Second).Unix(), 10), + }, + }, + LastError: &coreauth.Error{Code: "rate_limit_error", Message: "upstream quota exceeded", HTTPStatus: http.StatusTooManyRequests}, + } + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + registry.GetGlobalRegistry().RegisterClient(authID, executor.Identifier(), []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + for _, passthrough := range []bool{false, true} { + for _, streaming := range []bool{false, true} { + name := "passthrough_" + strconv.FormatBool(passthrough) + "_stream_" + strconv.FormatBool(streaming) + t.Run(name, func(t *testing.T) { + handler := NewClaudeCodeAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{PassthroughHeaders: passthrough}, manager)) + router := gin.New() + router.POST("/v1/messages", handler.ClaudeMessages) + + requestBody := `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}],"stream":` + strconv.FormatBool(streaming) + `}` + request := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)) + request.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + + before := time.Now().Unix() + router.ServeHTTP(recorder, request) + after := time.Now().Unix() + + if recorder.Code != http.StatusTooManyRequests { + t.Fatalf("status = %d, want 429; body=%s", recorder.Code, recorder.Body.String()) + } + seconds, errSeconds := strconv.ParseInt(recorder.Header().Get("Retry-After"), 10, 64) + if errSeconds != nil || seconds <= 0 { + t.Fatalf("Retry-After = %q, want positive seconds", recorder.Header().Get("Retry-After")) + } + + if !passthrough { + if got := recorder.Header().Get("Anthropic-Ratelimit-Unified-Status"); got != "" { + t.Fatalf("passthrough=false leaked Anthropic-Ratelimit-Unified-Status = %q", got) + } + return + } + + if got := recorder.Header().Get("Anthropic-Ratelimit-Unified-Status"); got != "rejected" { + t.Fatalf("Anthropic-Ratelimit-Unified-Status = %q, want rejected", got) + } + if got := recorder.Header().Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "five_hour" { + t.Fatalf("Anthropic-Ratelimit-Unified-Representative-Claim = %q, want five_hour", got) + } + if got := recorder.Header().Get("Anthropic-Ratelimit-Unified-Overage-Status"); got != "rejected" { + t.Fatalf("Anthropic-Ratelimit-Unified-Overage-Status = %q, want rejected", got) + } + if got := recorder.Header().Get("Anthropic-Ratelimit-Unified-5h-Status"); got != "rejected" { + t.Fatalf("Anthropic-Ratelimit-Unified-5h-Status = %q, want rejected", got) + } + resetAt, errReset := strconv.ParseInt(recorder.Header().Get("Anthropic-Ratelimit-Unified-Reset"), 10, 64) + if errReset != nil || resetAt < before+seconds || resetAt > after+seconds { + t.Fatalf("Anthropic-Ratelimit-Unified-Reset = %q, want unix epoch in [%d, %d]", recorder.Header().Get("Anthropic-Ratelimit-Unified-Reset"), before+seconds, after+seconds) + } + if got := recorder.Header().Get("Anthropic-Ratelimit-Unified-5h-Reset"); got != strconv.FormatInt(resetAt, 10) { + t.Fatalf("Anthropic-Ratelimit-Unified-5h-Reset = %q, want %d", got, resetAt) + } + }) + } + } +} diff --git a/sdk/api/handlers/claude/code_handlers_pool_cooldown_test.go b/sdk/api/handlers/claude/code_handlers_pool_cooldown_test.go new file mode 100644 index 00000000000..6ee677bcc79 --- /dev/null +++ b/sdk/api/handlers/claude/code_handlers_pool_cooldown_test.go @@ -0,0 +1,174 @@ +package claude + +import ( + "context" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +type issue7521UpstreamError struct { + status int + body string + retryAfter time.Duration + headers http.Header +} + +func (e *issue7521UpstreamError) Error() string { return e.body } +func (e *issue7521UpstreamError) StatusCode() int { return e.status } +func (e *issue7521UpstreamError) RetryAfter() *time.Duration { + d := e.retryAfter + return &d +} +func (e *issue7521UpstreamError) Headers() http.Header { + if e.headers == nil { + return nil + } + return e.headers.Clone() +} + +type issue7521ClaudeExecutor struct { + executeFn func(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) + streamFn func(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) + countFn func(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) +} + +func (e *issue7521ClaudeExecutor) Identifier() string { return "claude" } + +func (e *issue7521ClaudeExecutor) Execute(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) { + coreexecutor.MarkUpstreamAttempt(ctx) + return e.executeFn(ctx, auth, req, opts) +} + +func (e *issue7521ClaudeExecutor) ExecuteStream(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) { + coreexecutor.MarkUpstreamAttempt(ctx) + return e.streamFn(ctx, auth, req, opts) +} + +func (e *issue7521ClaudeExecutor) CountTokens(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) { + coreexecutor.MarkUpstreamAttempt(ctx) + return e.countFn(ctx, auth, req, opts) +} + +func (e *issue7521ClaudeExecutor) Refresh(_ context.Context, auth *coreauth.Auth) (*coreauth.Auth, error) { + return auth, nil +} + +func (e *issue7521ClaudeExecutor) HttpRequest(_ context.Context, _ *coreauth.Auth, _ *http.Request) (*http.Response, error) { + return nil, nil +} + +func TestClaudeLastCredential429AppendsPoolResetTime(t *testing.T) { + gin.SetMode(gin.TestMode) + + const model = "issue-7521-claude-route-model" + shortHint := 95 * time.Minute + longHint := 3 * time.Hour + + makeErr := func(authID string) error { + if strings.HasSuffix(authID, "-a") { + return &issue7521UpstreamError{ + status: http.StatusTooManyRequests, + body: `{"type":"error","error":{"type":"rate_limit_error","message":"First account rate limited."}}`, + retryAfter: shortHint, + headers: http.Header{"Retry-After": {"5700"}}, + } + } + return &issue7521UpstreamError{ + status: http.StatusTooManyRequests, + body: `{"type":"error","error":{"type":"rate_limit_error","message":"This request would exceed your account's monthly spend limit. Please try again later."}}`, + retryAfter: longHint, + headers: http.Header{"Retry-After": {"10800"}, "X-Upstream-Trace": {"trace-b"}}, + } + } + + for _, tc := range []struct { + name string + path string + streaming bool + }{ + {name: "messages_non_stream", path: "/v1/messages", streaming: false}, + {name: "messages_stream", path: "/v1/messages", streaming: true}, + {name: "count_tokens", path: "/v1/messages/count_tokens", streaming: false}, + } { + t.Run(tc.name, func(t *testing.T) { + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(&issue7521ClaudeExecutor{ + executeFn: func(_ context.Context, auth *coreauth.Auth, _ coreexecutor.Request, _ coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, makeErr(auth.ID) + }, + streamFn: func(_ context.Context, auth *coreauth.Auth, _ coreexecutor.Request, _ coreexecutor.Options) (*coreexecutor.StreamResult, error) { + chunks := make(chan coreexecutor.StreamChunk, 1) + chunks <- coreexecutor.StreamChunk{Err: makeErr(auth.ID)} + close(chunks) + return &coreexecutor.StreamResult{Chunks: chunks}, nil + }, + countFn: func(_ context.Context, auth *coreauth.Auth, _ coreexecutor.Request, _ coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, makeErr(auth.ID) + }, + }) + + reg := registry.GetGlobalRegistry() + for _, suffix := range []string{"-a", "-b"} { + authID := "issue-7521-route-" + tc.name + suffix + auth := &coreauth.Auth{ + ID: authID, + Provider: "claude", + Status: coreauth.StatusActive, + Attributes: map[string]string{"api_key": "key" + suffix}, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("register auth: %v", errReg) + } + reg.RegisterClient(authID, "claude", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + } + + handler := NewClaudeCodeAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{PassthroughHeaders: true}, manager)) + router := gin.New() + router.POST("/v1/messages", handler.ClaudeMessages) + router.POST("/v1/messages/count_tokens", handler.ClaudeCountTokens) + + body := `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}],"stream":` + strconv.FormatBool(tc.streaming) + `}` + req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + if rec.Code != http.StatusTooManyRequests { + t.Fatalf("status = %d, want 429; body=%s", rec.Code, rec.Body.String()) + } + seconds, errParse := strconv.ParseInt(rec.Header().Get("Retry-After"), 10, 64) + if errParse != nil || seconds <= 0 { + t.Fatalf("Retry-After = %q, want positive integer seconds", rec.Header().Get("Retry-After")) + } + if seconds > int64((shortHint + 10*time.Second).Seconds()) { + t.Fatalf("Retry-After = %d, want pool deadline near %d rather than last attempt 10800", seconds, int64(shortHint.Seconds())) + } + if gotTrace := rec.Header().Get("X-Upstream-Trace"); gotTrace != "trace-b" { + t.Fatalf("X-Upstream-Trace = %q, want trace-b preserved under passthrough-headers", gotTrace) + } + if gotType := ojson.GetBytesNoCopy(rec.Body.Bytes(), "error.type").String(); gotType != "rate_limit_error" { + t.Fatalf("error.type = %q, want rate_limit_error", gotType) + } + wantDelay := (time.Duration(seconds) * time.Second).String() + wantMessage := "This request would exceed your account's monthly spend limit. Please try again later. (reset after " + wantDelay + ")" + if gotMsg := ojson.GetBytesNoCopy(rec.Body.Bytes(), "error.message").String(); gotMsg != wantMessage { + t.Fatalf("error.message = %q, want %q", gotMsg, wantMessage) + } + }) + } +} diff --git a/sdk/api/handlers/gemini/issue7513_bootstrap_failover_test.go b/sdk/api/handlers/gemini/issue7513_bootstrap_failover_test.go new file mode 100644 index 00000000000..529e9c855c6 --- /dev/null +++ b/sdk/api/handlers/gemini/issue7513_bootstrap_failover_test.go @@ -0,0 +1,178 @@ +package gemini + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestIssue7513_GeminiStreamRotatesFromAntigravityZeroOutputToHealthyVertex(t *testing.T) { + gin.SetMode(gin.TestMode) + + var antigravityCalls atomic.Int32 + antigravityServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + antigravityCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":540000,"candidatesTokenCount":10,"thoughtsTokenCount":400,"totalTokenCount":540410},"modelVersion":"gemini-4-hydrogen"}}`+"\n\n") + })) + defer antigravityServer.Close() + + var vertexCalls atomic.Int32 + vertexServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + vertexCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"recovered from vertex"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":540000,"candidatesTokenCount":4,"totalTokenCount":540004},"modelVersion":"gemini-4-hydrogen"}`+"\n\n") + })) + defer vertexServer.Close() + + cfg := &config.Config{} + manager := coreauth.NewManager(nil, nil, nil) + affinity := coreauth.NewSessionAffinitySelectorWithConfig(coreauth.SessionAffinityConfig{ + Fallback: &coreauth.RoundRobinSelector{}, + TTL: time.Hour, + RebindOn: coreauth.SessionAffinityRebindOnQuota, + }) + defer affinity.Stop() + manager.SetSelector(affinity) + manager.RegisterExecutor(executor.NewAntigravityExecutor(cfg)) + manager.RegisterExecutor(executor.NewGeminiVertexExecutor(cfg)) + + model := "gemini-4-hydrogen-issue7513-failover" + agAuth := &coreauth.Auth{ + ID: "ag-issue7513-primary", + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-ag", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-ag", + }, + Attributes: map[string]string{ + "base_url": antigravityServer.URL, + "priority": "10", + }, + } + vertexAuth := &coreauth.Auth{ + ID: "vertex-issue7513-fallback", + Provider: "vertex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "api_key": "vertex-test-key", + "base_url": vertexServer.URL, + "priority": "1", + }, + } + for _, auth := range []*coreauth.Auth{agAuth, vertexAuth} { + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("Register(%s) error = %v", auth.ID, errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(auth.ID) + }) + } + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + h := NewGeminiAPIHandler(base) + router := gin.New() + router.POST("/v1beta/models/*action", h.GeminiHandler) + + reqBody := `{"contents":[{"role":"user","parts":[{"text":"turn 1"}]},{"role":"model","parts":[{"text":"ok"}]},{"role":"user","parts":[{"text":"turn 2"}]}]}` + req := httptest.NewRequest(http.MethodPost, "/v1beta/models/"+model+":streamGenerateContent?alt=sse", strings.NewReader(reqBody)) + req.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 after failover; body=%s", recorder.Code, recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), "recovered from vertex") { + t.Fatalf("expected failover response from vertex, got: %s", recorder.Body.String()) + } + if antigravityCalls.Load() != 1 || vertexCalls.Load() != 1 { + t.Fatalf("calls = (antigravity=%d, vertex=%d), want (1, 1)", antigravityCalls.Load(), vertexCalls.Load()) + } +} + +func TestIssue7513_GeminiStreamAndNonStreamReturnHTTP502WhenRetriesExhausted(t *testing.T) { + gin.SetMode(gin.TestMode) + + var upstreamCalls atomic.Int32 + antigravityServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":540000,"candidatesTokenCount":10,"thoughtsTokenCount":400,"totalTokenCount":540410},"modelVersion":"gemini-4-hydrogen"}}`+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":540000,"candidatesTokenCount":10,"thoughtsTokenCount":400,"totalTokenCount":540410},"modelVersion":"gemini-4-hydrogen"}}`) + })) + defer antigravityServer.Close() + + cfg := &config.Config{} + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor.NewAntigravityExecutor(cfg)) + + model := "gemini-4-hydrogen-issue7513-exhausted" + agAuth := &coreauth.Auth{ + ID: "ag-issue7513-only", + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-ag", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-ag", + "disable_cooling": true, + }, + Attributes: map[string]string{"base_url": antigravityServer.URL}, + } + if _, errRegister := manager.Register(context.Background(), agAuth); errRegister != nil { + t.Fatalf("Register() error = %v", errRegister) + } + registry.GetGlobalRegistry().RegisterClient(agAuth.ID, agAuth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(agAuth.ID) + }) + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{ + Streaming: sdkconfig.StreamingConfig{ + BootstrapRetries: 1, + }, + }, manager) + h := NewGeminiAPIHandler(base) + router := gin.New() + router.POST("/v1beta/models/*action", h.GeminiHandler) + + streamReq := httptest.NewRequest(http.MethodPost, "/v1beta/models/"+model+":streamGenerateContent?alt=sse", strings.NewReader(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)) + streamReq.Header.Set("Content-Type", "application/json") + streamRec := httptest.NewRecorder() + router.ServeHTTP(streamRec, streamReq) + if streamRec.Code != http.StatusBadGateway { + t.Fatalf("stream status = %d, want 502; body=%s", streamRec.Code, streamRec.Body.String()) + } + if upstreamCalls.Load() < 2 { + t.Fatalf("expected bootstrap retry to retry upstream at least once, got %d calls", upstreamCalls.Load()) + } + + nonStreamReq := httptest.NewRequest(http.MethodPost, "/v1beta/models/"+model+":generateContent", strings.NewReader(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)) + nonStreamReq.Header.Set("Content-Type", "application/json") + nonStreamRec := httptest.NewRecorder() + router.ServeHTTP(nonStreamRec, nonStreamReq) + if nonStreamRec.Code != http.StatusBadGateway { + t.Fatalf("non-stream status = %d, want 502; body=%s", nonStreamRec.Code, nonStreamRec.Body.String()) + } +} diff --git a/sdk/api/handlers/handlers.go b/sdk/api/handlers/handlers.go index 2f1b89a5072..47c9f9969f7 100644 --- a/sdk/api/handlers/handlers.go +++ b/sdk/api/handlers/handlers.go @@ -635,6 +635,14 @@ func (h *BaseAPIHandler) GetContextWithCancel(handler interfaces.APIHandler, c * if requestCtx != nil { parentCtx = httptransport.InheritDecorator(parentCtx, requestCtx) + parentCtx = logging.InheritDeferredCapture(parentCtx, requestCtx) + } + if c != nil && logging.DeferredAPICaptureFromContext(parentCtx) == nil && !logging.DeferredAPIRequestCaptureDisabled(parentCtx) { + if value, exists := c.Get(logging.DeferredAPIResponseContextKey); exists { + if capture, ok := value.(*logging.DeferredAPICapture); ok && capture != nil { + parentCtx = logging.WithDeferredAPICapture(parentCtx, capture) + } + } } if requestCtx != nil && logging.GetRequestID(parentCtx) == "" { if requestID := logging.GetRequestID(requestCtx); requestID != "" { diff --git a/sdk/api/handlers/handlers_interceptors.go b/sdk/api/handlers/handlers_interceptors.go index 16203c447b7..dbb110c2e56 100644 --- a/sdk/api/handlers/handlers_interceptors.go +++ b/sdk/api/handlers/handlers_interceptors.go @@ -674,6 +674,48 @@ func (h *BaseAPIHandler) applyResponseInterceptors(ctx context.Context, requestI // ModelDetailIDContextKey requests selection from the final, plugin-filtered catalog. const ModelDetailIDContextKey = "cliproxy.model_detail_id" +// Metadata keys carrying downstream caller identity to model-directory interceptors. +const ( + modelListAccessProviderMetadataKey = "access_provider" + modelListFrontendAuthMetadataKey = "frontend_auth_metadata" +) + +// modelListInterceptorMetadata assembles the caller identity metadata forwarded to model-list +// response interceptors and lifecycle events, mirroring the metadata built for execution paths. +func modelListInterceptorMetadata(c *gin.Context) map[string]any { + if c == nil { + return nil + } + var meta map[string]any + setMeta := func(key string, value any) { + if meta == nil { + meta = make(map[string]any) + } + meta[key] = value + } + if callerScope := requestCallerScope(c); callerScope != "" { + setMeta(coreexecutor.CallerScopeMetadataKey, callerScope) + } + if provider, ok := c.Get("accessProvider"); ok { + if providerName, isString := provider.(string); isString && strings.TrimSpace(providerName) != "" { + setMeta(modelListAccessProviderMetadataKey, strings.TrimSpace(providerName)) + } + } + if rawMetadata, ok := c.Get("accessMetadata"); ok { + switch authMetadata := rawMetadata.(type) { + case map[string]string: + if len(authMetadata) > 0 { + setMeta(modelListFrontendAuthMetadataKey, maps.Clone(authMetadata)) + } + case map[string]any: + if len(authMetadata) > 0 { + setMeta(modelListFrontendAuthMetadataKey, maps.Clone(authMetadata)) + } + } + } + return meta +} + // WriteModelListResponse serializes the model-list payload, applies plugin response interceptors // if a plugin host is configured, and writes the resulting headers and body to the Gin context. func (h *BaseAPIHandler) WriteModelListResponse(c *gin.Context, sourceFormat string, payload any) { @@ -708,7 +750,8 @@ func (h *BaseAPIHandler) WriteModelListResponse(c *gin.Context, sourceFormat str ctx = reqCtx } } - lifecycle = h.newRequestLifecycleTracker(ctx, sourceFormat, "", "", false, nil, "") + metadata := modelListInterceptorMetadata(c) + lifecycle = h.newRequestLifecycleTracker(ctx, sourceFormat, "", "", false, metadata, "") resp := interceptResponse(ctx, host, pluginapi.ResponseInterceptRequest{ RequestID: lifecycle.requestID(), SourceFormat: sourceFormat, @@ -721,7 +764,7 @@ func (h *BaseAPIHandler) WriteModelListResponse(c *gin.Context, sourceFormat str RequestBody: nil, Body: cloneBytes(body), StatusCode: http.StatusOK, - Metadata: nil, + Metadata: metadata, }, "") if len(resp.Body) > 0 { body = cloneBytes(resp.Body) diff --git a/sdk/api/handlers/handlers_interceptors_issue7499_test.go b/sdk/api/handlers/handlers_interceptors_issue7499_test.go new file mode 100644 index 00000000000..a618a155559 --- /dev/null +++ b/sdk/api/handlers/handlers_interceptors_issue7499_test.go @@ -0,0 +1,162 @@ +package handlers + +import ( + "context" + "testing" + + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +// issue7499InterceptorHost is a minimal PluginInterceptorHost used to prove +// embedder-installed hosts are invoked through the real dispatch chain. +type issue7499InterceptorHost struct { + beforeAuthCalls int + afterAuthCalls int + responseCalls int + streamCalls int +} + +func (h *issue7499InterceptorHost) InterceptRequestBeforeAuth(context.Context, pluginapi.RequestInterceptRequest) pluginapi.RequestInterceptResponse { + h.beforeAuthCalls++ + return pluginapi.RequestInterceptResponse{} +} + +func (h *issue7499InterceptorHost) InterceptRequestAfterAuth(context.Context, pluginapi.RequestInterceptRequest) pluginapi.RequestInterceptResponse { + h.afterAuthCalls++ + return pluginapi.RequestInterceptResponse{} +} + +func (h *issue7499InterceptorHost) InterceptResponse(context.Context, pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + h.responseCalls++ + return pluginapi.ResponseInterceptResponse{} +} + +func (h *issue7499InterceptorHost) InterceptStreamChunk(context.Context, pluginapi.StreamChunkInterceptRequest) pluginapi.StreamChunkInterceptResponse { + h.streamCalls++ + return pluginapi.StreamChunkInterceptResponse{} +} + +// issue7499DirectExecutorHost routes the request to a plugin executor so the +// test can drive the real ExecuteWithAuthManager chain end to end and prove +// the wired interceptor host is invoked during dispatch. +type issue7499DirectExecutorHost struct { + issue7499InterceptorHost + handlerRouterOnlyTestHost + lastPluginID string + lastRequest coreexecutor.Request +} + +func (h *issue7499DirectExecutorHost) HasModelRouters() bool { return h.hasRouters } + +func (h *issue7499DirectExecutorHost) ExecutePluginExecutor(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) { + h.lastPluginID = pluginID + h.lastRequest = req + return coreexecutor.Response{Payload: []byte("direct-ok")}, nil +} + +func (h *issue7499DirectExecutorHost) CountPluginExecutor(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{Payload: []byte(`{}`)}, nil +} + +func (h *issue7499DirectExecutorHost) ExecutePluginExecutorStream(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) { + return nil, nil +} + +func (h *issue7499DirectExecutorHost) PluginExecutorRequestToFormat(pluginID string, req coreexecutor.Request, opts coreexecutor.Options) sdktranslator.Format { + return sdktranslator.FormatOpenAI +} + +// issue7499SkipHost implements the pluginInterceptorSkipHost surface so the +// test can assert skipPluginID survives dispatch. +type issue7499SkipHost struct { + issue7499DirectExecutorHost + beforeSkips []string + afterSkips []string + respSkips []string + streamSkips []string +} + +func (h *issue7499SkipHost) InterceptRequestBeforeAuthExcept(_ context.Context, _ pluginapi.RequestInterceptRequest, skipPluginID string) pluginapi.RequestInterceptResponse { + h.beforeSkips = append(h.beforeSkips, skipPluginID) + return pluginapi.RequestInterceptResponse{} +} + +func (h *issue7499SkipHost) InterceptRequestAfterAuthExcept(_ context.Context, _ pluginapi.RequestInterceptRequest, skipPluginID string) pluginapi.RequestInterceptResponse { + h.afterSkips = append(h.afterSkips, skipPluginID) + return pluginapi.RequestInterceptResponse{} +} + +func (h *issue7499SkipHost) InterceptResponseExcept(_ context.Context, _ pluginapi.ResponseInterceptRequest, skipPluginID string) pluginapi.ResponseInterceptResponse { + h.respSkips = append(h.respSkips, skipPluginID) + return pluginapi.ResponseInterceptResponse{} +} + +func (h *issue7499SkipHost) InterceptStreamChunkExcept(_ context.Context, _ pluginapi.StreamChunkInterceptRequest, skipPluginID string) pluginapi.StreamChunkInterceptResponse { + h.streamSkips = append(h.streamSkips, skipPluginID) + return pluginapi.StreamChunkInterceptResponse{} +} + +var _ pluginInterceptorSkipHost = (*issue7499SkipHost)(nil) + +// TestIssue7499CustomInterceptorHostInvokedThroughExecuteChain drives the +// real ExecuteWithAuthManager dispatch path so a miswired interceptor host +// cannot pass by only existing as a field. +func TestIssue7499CustomInterceptorHostInvokedThroughExecuteChain(t *testing.T) { + originalModel := "issue7499-original-model" + targetPluginID := "websearch-plugin" + host := &issue7499DirectExecutorHost{} + host.hasRouters = true + host.route = func(context.Context, pluginapi.ModelRouteRequest) (pluginapi.ModelRouteResponse, bool) { + return pluginapi.ModelRouteResponse{Handled: true, TargetKind: pluginapi.ModelRouteTargetExecutor, Target: targetPluginID}, true + } + handler := NewBaseAPIHandlers(nil, nil) + handler.SetModelRouterHost(host) + handler.SetPluginHost(host) + + body, _, errMsg := handler.ExecuteWithAuthManager(context.Background(), "openai", originalModel, + []byte(`{"model":"issue7499-original-model"}`), "") + if errMsg != nil { + t.Fatalf("ExecuteWithAuthManager() error = %+v", errMsg) + } + if string(body) != "direct-ok" { + t.Fatalf("body = %q, want direct-ok", body) + } + if host.beforeAuthCalls != 1 { + t.Fatalf("before-auth calls through execute chain = %d, want 1", host.beforeAuthCalls) + } + if host.lastPluginID != targetPluginID { + t.Fatalf("plugin id = %q, want %q", host.lastPluginID, targetPluginID) + } +} + +// TestIssue7499CustomInterceptorHostSkipThroughExecuteChain verifies a +// skip-aware embedder host receives the plugin-skip identifier through the +// real dispatch chain, not a dropped or rewritten value. +func TestIssue7499CustomInterceptorHostSkipThroughExecuteChain(t *testing.T) { + originalModel := "issue7499-skip-model" + targetPluginID := "websearch-plugin" + host := &issue7499SkipHost{} + host.hasRouters = true + // Route to a plugin executor while skipping interceptor "plugin-a" so the + // nested execution cannot re-enter its own interceptor. + host.route = func(context.Context, pluginapi.ModelRouteRequest) (pluginapi.ModelRouteResponse, bool) { + return pluginapi.ModelRouteResponse{Handled: true, TargetKind: pluginapi.ModelRouteTargetExecutor, Target: targetPluginID}, true + } + handler := NewBaseAPIHandlers(nil, nil) + handler.SetModelRouterHost(host) + handler.SetPluginHost(host) + + // Drive the interceptor dispatch directly with an explicit skip id; the + // public execute path derives it from nested-execution metadata. + _, _, errMsg := handler.applyRequestInterceptorsBeforeAuth( + context.Background(), "openai", originalModel, "req-skip", + coreexecutor.Request{Model: originalModel}, coreexecutor.Options{}, "plugin-a") + if errMsg != nil { + t.Fatalf("applyRequestInterceptorsBeforeAuth error = %+v", errMsg) + } + if len(host.beforeSkips) != 1 || host.beforeSkips[0] != "plugin-a" { + t.Fatalf("before-auth skip calls = %v, want [plugin-a]", host.beforeSkips) + } +} diff --git a/sdk/api/handlers/handlers_interceptors_test.go b/sdk/api/handlers/handlers_interceptors_test.go index 2eea02364a4..01ffe1bd718 100644 --- a/sdk/api/handlers/handlers_interceptors_test.go +++ b/sdk/api/handlers/handlers_interceptors_test.go @@ -18,6 +18,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + coresession "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" ) @@ -1695,6 +1696,87 @@ func TestWriteModelListResponse_ExposesResponseToPluginInterceptors(t *testing.T } } +func TestWriteModelListResponse_ForwardsCallerIdentityToInterceptors(t *testing.T) { + handler := &BaseAPIHandler{} + var capturedReq pluginapi.ResponseInterceptRequest + var completion pluginapi.RequestCompletion + + handler.SetPluginHost(&handlerInterceptorTestHost{ + interceptResponse: func(_ context.Context, req pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + capturedReq = req + return pluginapi.ResponseInterceptResponse{} + }, + completeRequest: func(_ context.Context, comp pluginapi.RequestCompletion) { + completion = comp + }, + }) + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?key=query-credential", nil) + ctx.Set("userApiKey", "plugin-principal-123") + ctx.Set("accessProvider", "plugin-frontend-auth") + ctx.Set("accessMetadata", map[string]string{"source": "query-key", "team": "alpha"}) + + payload := gin.H{"models": []map[string]any{{"name": "models/gemini-3-pro"}}} + handler.WriteModelListResponse(ctx, "gemini", payload) + + if rec.Code != http.StatusOK { + t.Fatalf("code = %d, want %d", rec.Code, http.StatusOK) + } + + wantScope := coresession.CallerScope("plugin-principal-123") + if got := capturedReq.Metadata[pluginapi.CallerScopeMetadataKey]; got != wantScope { + t.Fatalf("Metadata[%q] = %v, want %q", pluginapi.CallerScopeMetadataKey, got, wantScope) + } + if got := capturedReq.Metadata["access_provider"]; got != "plugin-frontend-auth" { + t.Fatalf("Metadata[access_provider] = %v, want plugin-frontend-auth", got) + } + rawAuthMeta, ok := capturedReq.Metadata["frontend_auth_metadata"].(map[string]string) + if !ok { + t.Fatalf("Metadata[frontend_auth_metadata] type = %T, want map[string]string", capturedReq.Metadata["frontend_auth_metadata"]) + } + if rawAuthMeta["source"] != "query-key" || rawAuthMeta["team"] != "alpha" { + t.Fatalf("frontend_auth_metadata = %#v, want source=query-key team=alpha", rawAuthMeta) + } + if got := completion.Metadata[pluginapi.CallerScopeMetadataKey]; got != wantScope { + t.Fatalf("completion Metadata[%q] = %v, want %q", pluginapi.CallerScopeMetadataKey, got, wantScope) + } + + // The forwarded auth metadata must be a clone: mutating the interceptor-visible + // map must not corrupt the gin context copy shared with other consumers. + rawAuthMeta["source"] = "mutated-by-plugin" + ctxMeta, _ := ctx.Get("accessMetadata") + if got := ctxMeta.(map[string]string)["source"]; got != "query-key" { + t.Fatalf("accessMetadata[source] in context = %q, want query-key (interceptor metadata must be isolated)", got) + } +} + +func TestWriteModelListResponse_MetadataNilWithoutAuthContext(t *testing.T) { + handler := &BaseAPIHandler{} + var capturedReq pluginapi.ResponseInterceptRequest + + handler.SetPluginHost(&handlerInterceptorTestHost{ + interceptResponse: func(_ context.Context, req pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + capturedReq = req + return pluginapi.ResponseInterceptResponse{} + }, + }) + + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + + handler.WriteModelListResponse(ctx, "openai", gin.H{"object": "list", "data": []map[string]any{}}) + + if rec.Code != http.StatusOK { + t.Fatalf("code = %d, want %d", rec.Code, http.StatusOK) + } + if capturedReq.Metadata != nil { + t.Fatalf("Metadata = %#v, want nil for unauthenticated context", capturedReq.Metadata) + } +} + func TestRequestAfterAuthCapture_ReadOnlyInterceptorDoesNotReallocatePayload_Issue6101(t *testing.T) { capture := &requestAfterAuthCapture{} payload := []byte(`{"messages":[{"role":"user","content":"hello"}]}`) diff --git a/sdk/api/handlers/openai/openai_responses_handlers.go b/sdk/api/handlers/openai/openai_responses_handlers.go index 6eb68e89164..0dd4aea02a2 100644 --- a/sdk/api/handlers/openai/openai_responses_handlers.go +++ b/sdk/api/handlers/openai/openai_responses_handlers.go @@ -25,6 +25,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/httpwire" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" @@ -935,7 +936,8 @@ func (h *OpenAIResponsesAPIHandler) prepareCodexRequestPayload(c *gin.Context, p doc := ojson.NewDoc(payload) toolsChanged := h.prepareCodexMultiAgentV2ToolsDoc(c, doc) orphanChanged := h.prepareCodexOrphanDelegationDoc(c, doc) - if len(payload) == 0 || (!toolsChanged && !orphanChanged) { + toolOutputChanged := translatorcommon.SanitizeOrphanResponsesToolOutputsDoc(doc) + if len(payload) == 0 || (!toolsChanged && !orphanChanged && !toolOutputChanged) { return payload } return doc.Bytes() @@ -986,6 +988,7 @@ func (h *OpenAIResponsesAPIHandler) Compact(c *gin.Context) { doc := ojson.NewDoc(rawJSON) orphanChanged := h.prepareCodexOrphanDelegationDoc(c, doc) + toolOutputChanged := translatorcommon.SanitizeOrphanResponsesToolOutputsDoc(doc) streamResult := doc.Get("stream") if streamResult.Type == ojson.True { @@ -1002,7 +1005,7 @@ func (h *OpenAIResponsesAPIHandler) Compact(c *gin.Context) { _ = doc.Delete("stream") streamDeleted = true } - if orphanChanged || streamDeleted { + if orphanChanged || toolOutputChanged || streamDeleted { rawJSON = doc.Bytes() } diff --git a/sdk/api/handlers/openai/openai_responses_interrupt_test.go b/sdk/api/handlers/openai/openai_responses_interrupt_test.go index 3d4d0b787e2..c90dcf5ecc3 100644 --- a/sdk/api/handlers/openai/openai_responses_interrupt_test.go +++ b/sdk/api/handlers/openai/openai_responses_interrupt_test.go @@ -270,9 +270,10 @@ func (e *homeInterruptExecutor) InterruptExecutionSession(ctx context.Context, s } type blockingHTTPInterruptExecutor struct { - calls atomic.Int32 - canceled atomic.Bool - cancelObserved chan struct{} + calls atomic.Int32 + canceled atomic.Bool + canceledCh chan struct{} + cancelOnce sync.Once } func (*blockingHTTPInterruptExecutor) Identifier() string { return "codex" } @@ -284,6 +285,16 @@ func (*blockingHTTPInterruptExecutor) Execute(context.Context, *coreauth.Auth, c func (e *blockingHTTPInterruptExecutor) ExecuteStream(ctx context.Context, _ *coreauth.Auth, _ coreexecutor.Request, _ coreexecutor.Options) (*coreexecutor.StreamResult, error) { call := e.calls.Add(1) chunks := make(chan coreexecutor.StreamChunk, 2) + if call == 1 { + context.AfterFunc(ctx, func() { + e.canceled.Store(true) + e.cancelOnce.Do(func() { + if e.canceledCh != nil { + close(e.canceledCh) + } + }) + }) + } go func() { defer close(chunks) if call > 1 { @@ -294,7 +305,11 @@ func (e *blockingHTTPInterruptExecutor) ExecuteStream(ctx context.Context, _ *co chunks <- coreexecutor.StreamChunk{Payload: []byte(`{"type":"response.created","response":{"id":"r-http"}}`)} <-ctx.Done() e.canceled.Store(true) - close(e.cancelObserved) + e.cancelOnce.Do(func() { + if e.canceledCh != nil { + close(e.canceledCh) + } + }) }() return &coreexecutor.StreamResult{Chunks: chunks}, nil } @@ -315,11 +330,45 @@ func (*blockingHTTPInterruptExecutor) InterruptExecutionSession(context.Context, return coreexecutor.ErrNoActiveUpstreamWebsocket } +type cancelOrderTimelineAppender struct { + onAppend func(eventType string) +} + +func (a cancelOrderTimelineAppender) Append(eventType string, _ []byte, _ time.Time) { + if a.onAppend != nil { + a.onAppend(eventType) + } +} + +func TestCompleteResponsesWebsocketLocalInterruptCancelsBeforeWritingIncomplete(t *testing.T) { + canceled := false + cancelCalledBeforeWrite := false + timeline := cancelOrderTimelineAppender{ + onAppend: func(eventType string) { + if eventType == "response" { + cancelCalledBeforeWrite = canceled + } + }, + } + _, _, _, _, _ = completeResponsesWebsocketLocalInterrupt( + &responsesWebsocketWriter{}, + timeline, + func(...any) { canceled = true }, + []byte(`{"type":"response.interrupt","response_id":"r-http"}`), + nil, + nil, + nil, + ) + if !cancelCalledBeforeWrite { + t.Fatal("expected completeResponsesWebsocketLocalInterrupt to cancel upstream HTTP context before writing response.incomplete downstream") + } +} + // TestResponsesInterruptStopsHTTPUpstream verifies that an in-flight interrupt // cancels an HTTP upstream turn and lets the same socket continue. func TestResponsesInterruptStopsHTTPUpstream(t *testing.T) { gin.SetMode(gin.TestMode) - executor := &blockingHTTPInterruptExecutor{cancelObserved: make(chan struct{})} + executor := &blockingHTTPInterruptExecutor{canceledCh: make(chan struct{})} manager := coreauth.NewManager(nil, nil, nil) manager.SetConfig(&config.Config{}) manager.RegisterExecutor(executor) @@ -374,13 +423,10 @@ func TestResponsesInterruptStopsHTTPUpstream(t *testing.T) { if got := ojson.GetBytesNoCopy(interrupted, "response.incomplete_details.reason").String(); got != "interrupted" { t.Fatalf("interrupt reason = %q, payload %s", got, interrupted) } - // The incomplete frame is written before cancellation, and the executor - // observes context cancellation on another goroutine. Wait for that actual - // observation instead of assuming it happened before the client read. select { - case <-executor.cancelObserved: - case <-time.After(5 * time.Second): - t.Fatal("http upstream cancellation was not observed") + case <-executor.canceledCh: + case <-time.After(time.Second): + t.Fatal("http upstream was not canceled") } if !executor.canceled.Load() { t.Fatal("http upstream was not canceled") diff --git a/sdk/api/handlers/openai/openai_responses_multi_agent_test.go b/sdk/api/handlers/openai/openai_responses_multi_agent_test.go index d1de0e41ddc..fbdeb5a14b1 100644 --- a/sdk/api/handlers/openai/openai_responses_multi_agent_test.go +++ b/sdk/api/handlers/openai/openai_responses_multi_agent_test.go @@ -330,3 +330,105 @@ func TestResponsesOrphanCodexDelegationCompatibility(t *testing.T) { t.Fatalf("input.0.type = %q, want function_call_output without header; captured=%s", itemType, capturedNoHeader) } } + +func TestResponsesSanitizesOrphanToolOutputsThroughHTTPAndCompact(t *testing.T) { + gin.SetMode(gin.TestMode) + + const modelID = "test-responses-orphan-tool-output-model" + authID := "test-responses-orphan-tool-output-auth" + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + + coreManager := coreauth.NewManager(nil, nil, nil) + executor := &responsesMultiAgentCaptureExecutor{} + coreManager.RegisterExecutor(executor) + if _, errRegister := coreManager.Register(context.Background(), &coreauth.Auth{ + ID: authID, + Provider: "codex", + Status: coreauth.StatusActive, + }); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + baseHandler := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, coreManager) + responsesHandler := NewOpenAIResponsesAPIHandler(baseHandler) + + router := gin.New() + router.POST("/v1/responses", responsesHandler.Responses) + router.POST("/v1/responses/compact", responsesHandler.Compact) + + payload := fmt.Sprintf(`{ + "model": %q, + "stream": false, + "input": [ + {"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]}, + {"type":"function_call_output","id":"fco_1","name":"codex_apps_open_page","namespace":"agent","output":"{\"page_id\":null}"}, + {"type":"custom_tool_call_output","id":"fco_2","name":"custom_ctx","output":[{"type":"input_text","text":"part one"},{"type":"input_text","text":"part two"},{"type":"input_image","image_url":"https://example.com/page.png"}]}, + {"type":"function_call","call_id":"call_ok","name":"shell","arguments":"{}"}, + {"type":"function_call_output","call_id":"call_ok","output":"ok"}, + {"type":"function_call_output","call_id":" ","output":"blank id"}, + {"type":"function_call_output","id":"fco_3","name":"create_thread","namespace":"codex_app","output":"task"}, + {"type":"function_call","call_id":"call_pair","name":"shell","arguments":"{}"}, + {"type":"function_call_output","output":"paired without call_id"} + ] + }`, modelID) + + for idx, path := range []string{"/v1/responses", "/v1/responses/compact"} { + req := httptest.NewRequest(http.MethodPost, path, bytes.NewBufferString(payload)) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("%s status = %d, want 200; body=%s", path, rec.Code, rec.Body.String()) + } + payloads := executor.Payloads() + if len(payloads) != idx+1 { + t.Fatalf("%s captured payload count = %d, want %d", path, len(payloads), idx+1) + } + input := ojson.GetBytesNoCopy(payloads[idx], "input").Array() + if len(input) != 9 { + t.Fatalf("%s input len = %d, want 9", path, len(input)) + } + if got := input[1].Get("type").String(); got != "message" { + t.Fatalf("%s input[1].type = %q, want message", path, got) + } + want1 := "Tool output from codex_apps_open_page:\n{\"page_id\":null}" + if got := input[1].Get("content.0.text").String(); got != want1 { + t.Fatalf("%s input[1].content.0.text = %q, want %q", path, got, want1) + } + if got := input[2].Get("type").String(); got != "message" { + t.Fatalf("%s input[2].type = %q, want message", path, got) + } + want2 := "Tool output from custom_ctx:\npart one\npart two" + if got := input[2].Get("content.0.text").String(); got != want2 { + t.Fatalf("%s input[2].content.0.text = %q, want %q", path, got, want2) + } + if got := input[2].Get("content.1.type").String(); got != "input_image" { + t.Fatalf("%s input[2].content.1.type = %q, want input_image", path, got) + } + if got := input[2].Get("content.1.image_url").String(); got != "https://example.com/page.png" { + t.Fatalf("%s input[2].content.1.image_url = %q, want https://example.com/page.png", path, got) + } + if got := input[4].Get("type").String(); got != "function_call_output" { + t.Fatalf("%s input[4].type = %q, want function_call_output", path, got) + } + if got := input[5].Get("type").String(); got != "message" { + t.Fatalf("%s input[5].type = %q, want message", path, got) + } + want5 := "Tool output from tool:\nblank id" + if got := input[5].Get("content.0.text").String(); got != want5 { + t.Fatalf("%s input[5].content.0.text = %q, want %q", path, got, want5) + } + if got := input[6].Get("type").String(); got != "function_call_output" { + t.Fatalf("%s input[6].type = %q, want function_call_output", path, got) + } + if got := input[8].Get("type").String(); got != "function_call_output" { + t.Fatalf("%s input[8].type = %q, want function_call_output", path, got) + } + if got := input[8].Get("call_id").String(); got != "call_pair" { + t.Fatalf("%s input[8].call_id = %q, want call_pair", path, got) + } + } +} diff --git a/sdk/api/handlers/openai/openai_responses_steering_integration_test.go b/sdk/api/handlers/openai/openai_responses_steering_integration_test.go index 359e6af24e7..e144f52ea9e 100644 --- a/sdk/api/handlers/openai/openai_responses_steering_integration_test.go +++ b/sdk/api/handlers/openai/openai_responses_steering_integration_test.go @@ -3,6 +3,8 @@ package openai import ( "bytes" "context" + "fmt" + "io" "net/http" "net/http/httptest" "strings" @@ -197,3 +199,300 @@ func TestResponsesSteeringFullDuplexIntegration(t *testing.T) { }) } } + +func TestResponsesWebsocketIsCompatLocalCompactionIntegration_Issue7406(t *testing.T) { + gin.SetMode(gin.TestMode) + const marker = "WS-HANDLER-COMPACT-7406" + for _, steering := range []bool{false, true} { + t.Run(fmt.Sprintf("steering=%t", steering), func(t *testing.T) { + wsReceived := make(chan []byte, 8) + httpReceived := make(chan []byte, 4) + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if websocket.IsWebSocketUpgrade(r) { + conn, errUp := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUp != nil { + t.Errorf("upgrade ws: %v", errUp) + return + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close websocket: %v", errClose) + } + }() + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + + for idx := 1; ; idx++ { + _, frame, errRead := conn.ReadMessage() + if errRead != nil { + return + } + wsReceived <- frame + respID := fmt.Sprintf("resp_ws_%d", idx) + _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.created","response":{"id":%q,"output":[]}}`, respID))) + _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.completed","response":{"id":%q,"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ws-ok-%d"}]}],"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}`, respID, idx))) + } + } + + body, _ := io.ReadAll(r.Body) + httpReceived <- body + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_sum\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Compacted summary keeping "+marker+".\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_http_sum\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":10,\"output_tokens\":4,\"total_tokens\":14}}}\n\n", + ) + })) + defer upstream.Close() + + modelID := fmt.Sprintf("compat-ws-model-%t", steering) + cfg := &config.Config{ + CodexKey: []config.CodexKey{{ + APIKey: "test-compat-key", + BaseURL: upstream.URL, + Models: []config.CodexModel{{Name: modelID, IsCompat: true}}, + }}, + } + cfg.Codex.ResponseSteering = steering + cfg.CodexResponseSteering = steering + + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(runtimeexecutor.NewCodexAutoExecutor(cfg)) + authID := fmt.Sprintf("compat-ws-auth-%t", steering) + if _, errReg := manager.Register(context.Background(), &coreauth.Auth{ + ID: authID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{"api_key": "test-compat-key", "base_url": upstream.URL, "websockets": "true"}, + }); errReg != nil { + t.Fatal(errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: modelID, IsCompat: true}}) + defer registry.GetGlobalRegistry().UnregisterClient(authID) + + h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&cfg.SDKConfig, manager)) + router := gin.New() + router.GET("/v1/responses", h.ResponsesWebsocket) + downstream := httptest.NewServer(router) + defer downstream.Close() + + conn, _, errDial := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(downstream.URL, "http")+"/v1/responses", nil) + if errDial != nil { + t.Fatal(errDial) + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close websocket: %v", errClose) + } + }() + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + + readUntil := func(wantType string) ojson.Result { + t.Helper() + for { + _, b, errRead := conn.ReadMessage() + if errRead != nil { + t.Fatalf("downstream read waiting for %s: %v", wantType, errRead) + } + parsed := ojson.ParseBytes(b) + gotType := parsed.Get("type").String() + if gotType == wantType { + return parsed + } + if gotType == "error" && wantType != "error" { + t.Fatalf("unexpected error while waiting for %s: %s", wantType, b) + } + } + } + + // Turn 1: First turn is local compaction_trigger; socket must stay open even when steering=true. + if errWrite := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"PRE_COMPACT_RAW_TEXT"}]},{"type":"compaction_trigger"}]}`, modelID))); errWrite != nil { + t.Fatal(errWrite) + } + compactedEv := readUntil("response.completed") + synthID := compactedEv.Get("response.id").String() + if !strings.HasPrefix(synthID, "resp_ag_compact_") { + t.Fatalf("expected synthetic compaction response ID, got %q (%s)", synthID, compactedEv.Raw) + } + <-httpReceived + + // Turn 2a: Bogus synthetic previous_response_id is rejected locally without hitting upstream. + if errWrite := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"previous_response_id":"resp_ag_compact_wrong","input":[{"type":"message","role":"user","content":"next"}]}`, modelID))); errWrite != nil { + t.Fatal(errWrite) + } + bogusErr := readUntil("error") + if bogusErr.Get("error.code").String() != "previous_response_not_found" { + t.Fatalf("expected previous_response_not_found for wrong synthetic ID, got %s", bogusErr.Raw) + } + + // Turn 2b: Valid synthetic previous_response_id starts a fresh root WS turn with expanded summary and NO pre-compaction raw text or synthetic ID. + if errWrite := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","previous_response_id":%q,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Post-compaction question"}]}]}`, synthID))); errWrite != nil { + t.Fatal(errWrite) + } + turn2Done := readUntil("response.completed") + if turn2Done.Get("response.id").String() != "resp_ws_1" { + t.Fatalf("turn 2 response.id = %q, want resp_ws_1", turn2Done.Get("response.id").String()) + } + wsRoot := <-wsReceived + if ojson.GetBytes(wsRoot, "previous_response_id").Exists() { + t.Fatalf("synthetic previous_response_id leaked to upstream WS: %s", wsRoot) + } + if bytes.Contains(wsRoot, []byte("PRE_COMPACT_RAW_TEXT")) { + t.Fatalf("pre-compaction history leaked alongside summary capsule: %s", wsRoot) + } + if bytes.Contains(wsRoot, []byte("cpa-ag-compact-v1:")) || !bytes.Contains(wsRoot, []byte(marker)) { + t.Fatalf("expected expanded summary marker without raw capsule: %s", wsRoot) + } + + // Turn 3: Normal incremental continuation on upstream WS works seamlessly. + if errWrite := conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.create","previous_response_id":"resp_ws_1","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Incremental follow-up"}]}]}`)); errWrite != nil { + t.Fatal(errWrite) + } + turn3Done := readUntil("response.completed") + if turn3Done.Get("response.id").String() != "resp_ws_2" { + t.Fatalf("turn 3 response.id = %q, want resp_ws_2", turn3Done.Get("response.id").String()) + } + wsCont := <-wsReceived + if gotPrev := ojson.GetBytes(wsCont, "previous_response_id").String(); gotPrev != "resp_ws_1" { + t.Fatalf("turn 3 WS previous_response_id = %q, want resp_ws_1; frame=%s", gotPrev, wsCont) + } + }) + } +} + +func TestResponsesWebsocketExistingWSCompactionRejectsStaleParent_Issue7406(t *testing.T) { + gin.SetMode(gin.TestMode) + wsReceived := make(chan []byte, 8) + var wsConnCount atomic.Int32 + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if websocket.IsWebSocketUpgrade(r) { + connNum := wsConnCount.Add(1) + conn, errUp := (&websocket.Upgrader{}).Upgrade(w, r, nil) + if errUp != nil { + return + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close websocket: %v", errClose) + } + }() + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + + for turn := 1; ; turn++ { + _, frame, errRead := conn.ReadMessage() + if errRead != nil { + return + } + wsReceived <- frame + respID := fmt.Sprintf("resp_ws_c%d_t%d", connNum, turn) + _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.created","response":{"id":%q,"output":[]}}`, respID))) + _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.completed","response":{"id":%q,"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":4,"output_tokens":2,"total_tokens":6}}}`, respID))) + } + } + + _, _ = io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, + "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"id\":\"msg_sum\",\"type\":\"message\",\"status\":\"completed\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Summary after turn 1.\"}]}}\n\n"+ + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_http_sum\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":8,\"output_tokens\":4,\"total_tokens\":12}}}\n\n", + ) + })) + defer upstream.Close() + + const modelID = "compat-ws-stale-parent-model" + cfg := &config.Config{ + CodexKey: []config.CodexKey{{ + APIKey: "test-compat-key", + BaseURL: upstream.URL, + Models: []config.CodexModel{{Name: modelID, IsCompat: true}}, + }}, + } + manager := coreauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(runtimeexecutor.NewCodexAutoExecutor(cfg)) + const authID = "compat-ws-stale-parent-auth" + if _, errReg := manager.Register(context.Background(), &coreauth.Auth{ + ID: authID, + Provider: "codex", + Status: coreauth.StatusActive, + Attributes: map[string]string{"api_key": "test-compat-key", "base_url": upstream.URL, "websockets": "true"}, + }); errReg != nil { + t.Fatal(errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "codex", []*registry.ModelInfo{{ID: modelID, IsCompat: true}}) + defer registry.GetGlobalRegistry().UnregisterClient(authID) + + h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&cfg.SDKConfig, manager)) + router := gin.New() + router.GET("/v1/responses", h.ResponsesWebsocket) + downstream := httptest.NewServer(router) + defer downstream.Close() + + conn, _, errDial := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(downstream.URL, "http")+"/v1/responses", nil) + if errDial != nil { + t.Fatal(errDial) + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Errorf("close websocket: %v", errClose) + } + }() + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + + readUntil := func(wantType string) ojson.Result { + t.Helper() + for { + _, b, errRead := conn.ReadMessage() + if errRead != nil { + t.Fatalf("downstream read waiting for %s: %v", wantType, errRead) + } + parsed := ojson.ParseBytes(b) + gotType := parsed.Get("type").String() + if gotType == wantType { + return parsed + } + if gotType == "error" && wantType != "error" { + t.Fatalf("unexpected error while waiting for %s: %s", wantType, b) + } + } + } + + // Turn 1: Real upstream WS response -> resp_ws_c1_t1. + _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"input":[{"type":"message","role":"user","content":"turn 1"}]}`, modelID))) + turn1Done := readUntil("response.completed") + oldWSRespID := turn1Done.Get("response.id").String() + if oldWSRespID != "resp_ws_c1_t1" { + t.Fatalf("turn 1 response.id = %q, want resp_ws_c1_t1", oldWSRespID) + } + <-wsReceived + + // Turn 2: Full local compaction_trigger invalidates c1 and establishes compaction boundary. + _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"input":[{"type":"message","role":"user","content":"turn 1"},{"type":"compaction_trigger"}]}`, modelID))) + compactDone := readUntil("response.completed") + synthID := compactDone.Get("response.id").String() + if !strings.HasPrefix(synthID, "resp_ag_compact_") { + t.Fatalf("turn 2 response.id = %q, want resp_ag_compact_*", synthID) + } + + // Turn 3a: Stale pre-compaction WS response ID (resp_ws_c1_t1) MUST be rejected with 409 previous_response_not_found, NOT silently grafted onto synthID. + _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","model":%q,"previous_response_id":%q,"input":[{"type":"message","role":"user","content":"wrong branch"}]}`, modelID, oldWSRespID))) + staleErr := readUntil("error") + if staleErr.Get("status").Int() != http.StatusConflict || staleErr.Get("error.code").String() != "previous_response_not_found" { + t.Fatalf("expected 409 previous_response_not_found for pre-compaction WS ID %q, got %s", oldWSRespID, staleErr.Raw) + } + + // Turn 3b: Valid continuation referencing synthID dials fresh WS c2 with expanded summary and no previous_response_id. + _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"type":"response.create","previous_response_id":%q,"input":[{"type":"message","role":"user","content":"clean post-compact turn"}]}`, synthID))) + turn3Done := readUntil("response.completed") + if turn3Done.Get("response.id").String() != "resp_ws_c2_t1" { + t.Fatalf("turn 3b response.id = %q, want resp_ws_c2_t1", turn3Done.Get("response.id").String()) + } + wsTurn3 := <-wsReceived + if ojson.GetBytes(wsTurn3, "previous_response_id").Exists() { + t.Fatalf("unexpected previous_response_id on fresh WS root: %s", wsTurn3) + } + if !bytes.Contains(wsTurn3, []byte("Summary after turn 1.")) { + t.Fatalf("expected expanded summary in Turn 3b WS root: %s", wsTurn3) + } +} diff --git a/sdk/api/handlers/openai/openai_responses_websocket.go b/sdk/api/handlers/openai/openai_responses_websocket.go index 41e6a373af1..125f2045e86 100644 --- a/sdk/api/handlers/openai/openai_responses_websocket.go +++ b/sdk/api/handlers/openai/openai_responses_websocket.go @@ -133,8 +133,8 @@ func newResponsesWebsocketWriter(conn *websocket.Conn) *responsesWebsocketWriter } // closeForUpstreamError sends a best-effort close frame without waiting behind -// an active downstream data writer. If a data write already owns writeMu, the -// connection is closed immediately so the blocked writer and session can exit. +// an active downstream writer. If a data or Ping write already owns writeMu, +// the connection is closed immediately so the blocked writer and session can exit. func (w *responsesWebsocketWriter) closeForUpstreamError(err error) (bool, error) { if w == nil || w.conn == nil { return false, nil @@ -173,7 +173,15 @@ func (w *responsesWebsocketWriter) writePing() error { if w == nil || w.conn == nil { return errors.New("responses websocket: writer is nil") } - w.writeMu.Lock() + if w.closing.Load() { + return websocket.ErrCloseSent + } + if !w.writeMu.TryLock() { + if w.closing.Load() { + return websocket.ErrCloseSent + } + return nil + } defer w.writeMu.Unlock() if w.closing.Load() { return websocket.ErrCloseSent @@ -181,6 +189,56 @@ func (w *responsesWebsocketWriter) writePing() error { return w.conn.WriteControl(websocket.PingMessage, nil, time.Time{}) } +func (w *responsesWebsocketWriter) keepAlive(ctx context.Context, cancel context.CancelCauseFunc, intervals <-chan time.Duration) { + if errPing := runResponsesWebsocketKeepAlive(ctx, intervals, w.writePing); errPing != nil { + cancel(errPing) + _, _ = w.closeWithoutError() + } +} + +func runResponsesWebsocketKeepAlive(ctx context.Context, intervals <-chan time.Duration, ping func() error) error { + var ticker *time.Ticker + var ticks <-chan time.Time + defer func() { + if ticker != nil { + ticker.Stop() + } + }() + for { + select { + case <-ctx.Done(): + return nil + case interval := <-intervals: + if interval <= 0 { + if ticker != nil { + ticker.Stop() + } + ticks = nil + continue + } + if ticker == nil { + ticker = time.NewTicker(interval) + } else { + ticker.Reset(interval) + } + ticks = ticker.C + case <-ticks: + if errPing := ping(); errPing != nil { + return errPing + } + } + } +} + +func queueResponsesWebsocketKeepAliveInterval(intervals chan time.Duration, interval time.Duration) { + // A single producer replaces a pending interval without waiting for a Ping write. + select { + case <-intervals: + default: + } + intervals <- interval +} + func (w *responsesWebsocketWriter) closeWithPayload(payload []byte) (bool, error) { if w == nil || w.conn == nil { return false, nil @@ -374,6 +432,25 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { defer cancelSocket(nil) c.Request = c.Request.WithContext(socketCtx) upgradeRequest := c.Request.Clone(socketCtx) + // Start Ping at upgrade, before opening an upstream stream can block. + var keepAliveIntervals chan time.Duration + var keepAliveInterval time.Duration + updateKeepAlive := func() { + if h == nil { + return + } + interval := handlers.StreamingKeepAliveInterval(h.CurrentConfig()) + if interval == keepAliveInterval { + return + } + keepAliveInterval = interval + if keepAliveIntervals == nil { + keepAliveIntervals = make(chan time.Duration, 1) + go writer.keepAlive(socketCtx, cancelSocket, keepAliveIntervals) + } + queueResponsesWebsocketKeepAliveInterval(keepAliveIntervals, interval) + } + updateKeepAlive() // The reader owns the client socket so an in-flight interrupt is not stuck // behind the response currently being forwarded. requestLogEnabled := false @@ -472,6 +549,7 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { lastResponseOutput := []byte("[]") var observedCompaction responsesWebsocketObservedCompactionState lastResponseID := "" + localCompactionBoundary := false // Remains pending until a generating request commits successfully. pendingPrewarmID := "" var lastResponsePendingToolCallIDs []string @@ -568,6 +646,7 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { if msgType != websocket.TextMessage && msgType != websocket.BinaryMessage { continue } + updateKeepAlive() // log.Infof( // "responses websocket: downstream_in id=%s type=%d event=%s payload=%s", // passthroughSessionID, @@ -776,6 +855,8 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { requestJSON, errMsg = normalizeResponsesWebsocketPassthroughRequest(payload, requestModelName) } else if len(lastRequest) == 0 && previousResponseID != "" { errMsg = responsesWebsocketPreviousResponseNotFoundError() + } else if previousResponseID != "" && (localCompactionBoundary || strings.HasPrefix(previousResponseID, "resp_ag_compact_")) && previousResponseID != strings.TrimSpace(lastResponseID) { + errMsg = responsesWebsocketPreviousResponseNotFoundError() } else { requestJSON, updatedLastRequest, errMsg = normalizeResponsesWebsocketRequestWithIncrementalState( payload, @@ -828,6 +909,7 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { lastResponseOutput = []byte("[]") observedCompaction.clear() lastResponseID = "" + localCompactionBoundary = false lastResponsePendingToolCallIDs = nil prewarmID, errWrite := writeResponsesWebsocketSyntheticPrewarm(c, writer, requestJSON, wsTimelineLog, passthroughSessionID) if errWrite != nil { @@ -860,6 +942,7 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { turnStartEpoch := inputEpoch.Load() cliCtx, cliCancel := h.GetContextWithCancel(h, c, executionParent) cliCtx = cliproxyexecutor.WithDownstreamWebsocket(cliCtx) + cliCtx = cliproxyexecutor.WithLocalWebsocketTurnTracker(cliCtx) cliCtx = cliproxyexecutor.WithWebsocketInputEpoch(cliCtx, &inputEpoch, msgEpoch) if duplexInput != nil { cliCtx = cliproxyexecutor.WithWebsocketInput(cliCtx, duplexInput) @@ -889,6 +972,7 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { cliCtx = handlers.WithSelectedAuthIDCallback(cliCtx, func(authID string) { preserveNativeOutput.Store(false) codexDuplexStream.Store(false) + cliproxyexecutor.ResetLocalWebsocketTurn(cliCtx) authID = strings.TrimSpace(authID) if authID == "" || h == nil || h.AuthManager == nil { return @@ -964,12 +1048,14 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { passthroughSessionID, responsesWebsocketForwardOptions{ preserveCompletionOutput: preserveNativeOutput.Load, - duplexStream: codexDuplexStream.Load, - toolCacheTurn: toolCacheTurn, - suppressError: replayPinnedAuthFailure, - localInterrupt: localInterrupt, + duplexStream: func() bool { + return codexDuplexStream.Load() && !cliproxyexecutor.LocalWebsocketTurnExecuted(cliCtx) + }, + toolCacheTurn: toolCacheTurn, + suppressError: replayPinnedAuthFailure, + localInterrupt: localInterrupt, websocketOwned: func() bool { - return attemptedUpstreamMode == responsesWebsocketUpstreamModeWS + return attemptedUpstreamMode == responsesWebsocketUpstreamModeWS && !cliproxyexecutor.LocalWebsocketTurnExecuted(cliCtx) }, }, ) @@ -1020,6 +1106,15 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { toolCacheTurn.commit() pendingPrewarmID = "" + localTurnExecuted := cliproxyexecutor.LocalWebsocketTurnExecuted(cliCtx) + if localTurnExecuted { + attemptedUpstreamMode = responsesWebsocketUpstreamModeHTTP + if lastAttemptedAuthID != "" { + rememberPinnedAuth(lastAttemptedAuthID, modelName) + } + nextLastRequest = responsesWebsocketLocalCompactionBoundaryRequest(requestJSON) + } + localCompactionBoundary = localTurnExecuted upstreamMode = attemptedUpstreamMode if upstreamMode == responsesWebsocketUpstreamModeWS { upstreamWebsocketAuthID = lastAttemptedAuthID @@ -1093,6 +1188,17 @@ func (s *responsesWebsocketObservedCompactionState) clear() { *s = responsesWebsocketObservedCompactionState{} } +func responsesWebsocketLocalCompactionBoundaryRequest(requestJSON []byte) []byte { + if len(requestJSON) == 0 { + return []byte(`{"input":[]}`) + } + doc := ojson.NewDoc(requestJSON) + _ = doc.Delete("type") + _ = doc.Delete("previous_response_id") + _ = doc.SetRawBytes("input", []byte("[]")) + return doc.Bytes() +} + func responsesWebsocketHTTPReplayRequiredError() error { return cliproxyexecutor.NewUpstreamWebsocketReplayRequiredError() } diff --git a/sdk/api/handlers/openai/openai_responses_websocket_forward.go b/sdk/api/handlers/openai/openai_responses_websocket_forward.go index 147273f7835..a4749900b98 100644 --- a/sdk/api/handlers/openai/openai_responses_websocket_forward.go +++ b/sdk/api/handlers/openai/openai_responses_websocket_forward.go @@ -28,7 +28,6 @@ type responsesWebsocketForwardOptions struct { duplexStream func() bool toolCacheTurn *responsesWebsocketToolCacheTurn suppressError func(*interfaces.ErrorMessage) bool - keepAliveInterval *time.Duration localInterrupt *responsesLocalInterrupt // websocketOwned reports whether this turn runs on an upstream // websocket. While true, no interrupt may claim the local HTTP path. @@ -66,20 +65,6 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesWebsocket( downstreamSessionKey = websocketDownstreamSessionKey(c.Request) } - var keepAliveTicker *time.Ticker - var keepAliveC <-chan time.Time - keepAliveInterval := time.Duration(0) - if h != nil { - keepAliveInterval = handlers.StreamingKeepAliveInterval(h.CurrentConfig()) - } - if opts.keepAliveInterval != nil { - keepAliveInterval = *opts.keepAliveInterval - } - if keepAliveInterval > 0 { - keepAliveTicker = time.NewTicker(keepAliveInterval) - defer keepAliveTicker.Stop() - keepAliveC = keepAliveTicker.C - } if opts.localInterrupt != nil { websocketOwned := opts.websocketOwned != nil && opts.websocketOwned() opts.localInterrupt.begin(websocketOwned) @@ -158,13 +143,9 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesWebsocket( } return completeResponsesWebsocketLocalInterrupt(writer, wsTimelineLog, cancel, interruptPayload, outputItemsByIndex, outputItemsFallback, pendingToolCallIDs) case <-c.Request.Context().Done(): - cancel(c.Request.Context().Err()) - return completedOutput, completedResponseID, sortedStringSet(pendingToolCallIDs), nil, c.Request.Context().Err() - case <-keepAliveC: - if errPing := writer.writePing(); errPing != nil { - cancel(errPing) - return completedOutput, completedResponseID, sortedStringSet(pendingToolCallIDs), nil, errPing - } + cause := context.Cause(c.Request.Context()) + cancel(cause) + return completedOutput, completedResponseID, sortedStringSet(pendingToolCallIDs), nil, cause case errMsg, ok := <-errs: if !ok { errs = nil @@ -215,9 +196,6 @@ func (h *OpenAIResponsesAPIHandler) forwardResponsesWebsocket( cancel(nil) return completedOutput, completedResponseID, sortedStringSet(pendingToolCallIDs), nil, nil } - if keepAliveTicker != nil && keepAliveInterval > 0 { - keepAliveTicker.Reset(keepAliveInterval) - } // A queued local interrupt belongs to an in-flight HTTP turn: // consume it before forwarding more upstream payload. Once the @@ -375,11 +353,10 @@ func completeResponsesWebsocketLocalInterrupt( cancel(errSet) return output, responseID, sortedStringSet(pendingToolCallIDs), nil, errSet } + cancel(context.Canceled) if errWrite := writeResponsesWebsocketPayload(writer, wsTimelineLog, incompleteDoc.Bytes(), time.Now()); errWrite != nil { - cancel(errWrite) return output, responseID, sortedStringSet(pendingToolCallIDs), nil, errWrite } - cancel(context.Canceled) return output, responseID, sortedStringSet(pendingToolCallIDs), nil, nil } diff --git a/sdk/api/handlers/openai/openai_responses_websocket_test.go b/sdk/api/handlers/openai/openai_responses_websocket_test.go index c2f60c9a085..4a3b8de3fed 100644 --- a/sdk/api/handlers/openai/openai_responses_websocket_test.go +++ b/sdk/api/handlers/openai/openai_responses_websocket_test.go @@ -1,6 +1,7 @@ package openai import ( + "bufio" "bytes" "context" "encoding/json" @@ -8,6 +9,7 @@ import ( "fmt" "io" "maps" + "net" "net/http" "net/http/httptest" "runtime" @@ -16,6 +18,7 @@ import ( "sync" "sync/atomic" "testing" + "testing/synctest" "time" "unicode/utf8" @@ -7502,195 +7505,111 @@ func TestNormalizeSubsequentRequestAssistantInputTriggersTranscriptReplacement(t } } -func TestForwardResponsesWebsocketEmitsPeriodicPingControlFrames(t *testing.T) { - gin.SetMode(gin.TestMode) - - serverErrCh := make(chan error, 1) - data := make(chan []byte) - errCh := make(chan *interfaces.ErrorMessage) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - conn, err := responsesWebsocketUpgrader.Upgrade(w, r, nil) - if err != nil { - serverErrCh <- err - return - } - defer func() { _ = conn.Close() }() +type websocketKeepAliveBootstrapExecutor struct { + websocketCaptureExecutor + started chan struct{} + release chan struct{} +} - ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) - ctx.Request = r +func (e *websocketKeepAliveBootstrapExecutor) ExecuteStream(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) { + close(e.started) + select { + case <-e.release: + return e.websocketCaptureExecutor.ExecuteStream(ctx, auth, req, opts) + case <-ctx.Done(): + return nil, ctx.Err() + } +} - cfg := &sdkconfig.SDKConfig{ - Streaming: sdkconfig.StreamingConfig{ - KeepAliveSeconds: 1, - }, - } - h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(cfg, nil)) +func TestResponsesWebsocketPingsBeforeUpstreamStreamIsReady(t *testing.T) { + gin.SetMode(gin.TestMode) + executor := &websocketKeepAliveBootstrapExecutor{ + started: make(chan struct{}), + release: make(chan struct{}), + } + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(executor) + auth := &coreauth.Auth{ID: "auth-ws-keepalive", Provider: executor.Identifier(), Status: coreauth.StatusActive} + if _, err := manager.Register(context.Background(), auth); err != nil { + t.Fatalf("register auth: %v", err) + } + const model = "ws-keepalive-test-model" + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) - _, _, _, errMsg, errForward := h.forwardResponsesWebsocket( - ctx, - newResponsesWebsocketWriter(conn), - func(...interface{}) {}, - data, - errCh, - newInMemoryWebsocketTimelineLog(), - "session-keepalive-test", - ) - if errMsg != nil { - serverErrCh <- fmt.Errorf("unexpected error message: %v", errMsg.Error) - return - } - if errForward != nil { - serverErrCh <- fmt.Errorf("unexpected forward error: %v", errForward) - return - } - serverErrCh <- nil - })) + cfg := &sdkconfig.SDKConfig{Streaming: sdkconfig.StreamingConfig{KeepAliveSeconds: 1}} + h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(cfg, manager)) + router := gin.New() + router.GET("/v1/responses", h.ResponsesWebsocket) + server := httptest.NewServer(router) defer server.Close() - wsURL := "ws" + strings.TrimPrefix(server.URL, "http") - clientConn, _, err := websocket.DefaultDialer.Dial(wsURL, nil) + wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/v1/responses" + conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil) if err != nil { t.Fatalf("dial websocket: %v", err) } - defer func() { _ = clientConn.Close() }() + defer func() { _ = conn.Close() }() - pingReceived := make(chan struct{}, 1) - clientConn.SetPingHandler(func(appData string) error { + pings := make(chan bool, 1) + pong := conn.PingHandler() + conn.SetPingHandler(func(payload string) error { + started := false select { - case pingReceived <- struct{}{}: + case <-executor.started: + started = true default: } - return clientConn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(time.Second)) + select { + case pings <- started: + default: + } + return pong(payload) }) - clientDone := make(chan struct{}) + completed := make(chan error, 1) go func() { - defer close(clientDone) - for { - _, _, errRead := clientConn.ReadMessage() - if errRead != nil { - return - } + _, payload, errRead := conn.ReadMessage() + if errRead == nil && ojson.GetBytesNoCopy(payload, "type").String() != wsEventTypeCompleted { + errRead = fmt.Errorf("expected response.completed, got %s", payload) } + completed <- errRead }() select { - case <-pingReceived: - // Received expected Ping control frame while upstream is waiting. - case <-time.After(1500 * time.Millisecond): - t.Fatal("expected websocket Ping control frame during upstream wait, got none") - } - - // Unblock forwardResponsesWebsocket with terminal completion. - data <- []byte(`{"type":"response.done","response":{"id":"resp-ping-1","output":[]}}`) - close(data) - close(errCh) - - select { - case serverErr := <-serverErrCh: - if serverErr != nil { - t.Fatalf("server error: %v", serverErr) - } - case <-time.After(2 * time.Second): - t.Fatal("server timed out completing forwardResponsesWebsocket") + case <-pings: + case errRead := <-completed: + t.Fatalf("websocket ended before the first turn: %v", errRead) + case <-time.After(5 * time.Second): + t.Fatal("expected Ping after upgrade, before sending a turn") } - - <-clientDone -} - -func TestForwardResponsesWebsocketPingKeepAliveOptionsOverride(t *testing.T) { - gin.SetMode(gin.TestMode) - - serverErrCh := make(chan error, 1) - data := make(chan []byte) - errCh := make(chan *interfaces.ErrorMessage) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - conn, err := responsesWebsocketUpgrader.Upgrade(w, r, nil) - if err != nil { - serverErrCh <- err - return - } - defer func() { _ = conn.Close() }() - - ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) - ctx.Request = r - - interval := 20 * time.Millisecond - h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, nil)) - - _, _, _, errMsg, errForward := h.forwardResponsesWebsocket( - ctx, - newResponsesWebsocketWriter(conn), - func(...interface{}) {}, - data, - errCh, - newInMemoryWebsocketTimelineLog(), - "session-keepalive-override", - responsesWebsocketForwardOptions{ - keepAliveInterval: &interval, - }, - ) - if errMsg != nil { - serverErrCh <- fmt.Errorf("unexpected error message: %v", errMsg.Error) - return - } - if errForward != nil { - serverErrCh <- fmt.Errorf("unexpected forward error: %v", errForward) - return - } - serverErrCh <- nil - })) - defer server.Close() - - wsURL := "ws" + strings.TrimPrefix(server.URL, "http") - clientConn, _, err := websocket.DefaultDialer.Dial(wsURL, nil) - if err != nil { - t.Fatalf("dial websocket: %v", err) + if errWrite := conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"response.create","model":"ws-keepalive-test-model","input":[]}`)); errWrite != nil { + t.Fatalf("write websocket request: %v", errWrite) } - defer func() { _ = clientConn.Close() }() - - pingReceived := make(chan struct{}, 1) - clientConn.SetPingHandler(func(appData string) error { + deadline := time.After(5 * time.Second) +waitForBootstrapPing: + for { select { - case pingReceived <- struct{}{}: - default: - } - return clientConn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(time.Second)) - }) - - clientDone := make(chan struct{}) - go func() { - defer close(clientDone) - for { - _, _, errRead := clientConn.ReadMessage() - if errRead != nil { - return + case started := <-pings: + if started { + break waitForBootstrapPing } + case errRead := <-completed: + t.Fatalf("websocket ended before the upstream stream was released: %v", errRead) + case <-deadline: + t.Fatal("expected Ping while the upstream stream is blocked") } - }() - - select { - case <-pingReceived: - case <-time.After(500 * time.Millisecond): - t.Fatal("expected websocket Ping control frame via option override, got none") } - data <- []byte(`{"type":"response.done","response":{"id":"resp-override","output":[]}}`) - close(data) - close(errCh) - + close(executor.release) select { - case serverErr := <-serverErrCh: - if serverErr != nil { - t.Fatalf("server error: %v", serverErr) + case errRead := <-completed: + if errRead != nil { + t.Fatalf("read completed response: %v", errRead) } - case <-time.After(2 * time.Second): - t.Fatal("server timed out completing forwardResponsesWebsocket") + case <-time.After(5 * time.Second): + t.Fatal("expected response.completed after releasing the upstream stream") } - - <-clientDone } func TestResponsesWebsocketWriterWritePing(t *testing.T) { @@ -7709,6 +7628,23 @@ func TestResponsesWebsocketWriterWritePing(t *testing.T) { defer func() { _ = conn.Close() }() writer := newResponsesWebsocketWriter(conn) + // A background Ping must skip rather than block behind an active data write. + writer.writeMu.Lock() + pingDone := make(chan error, 1) + go func() { pingDone <- writer.writePing() }() + select { + case errPing := <-pingDone: + writer.writeMu.Unlock() + if errPing != nil { + t.Errorf("writePing() while data write active = %v, want nil", errPing) + } + case <-time.After(time.Second): + writer.writeMu.Unlock() + <-pingDone + t.Error("Ping waited for the data write mutex") + return + } + if errPing := writer.writePing(); errPing != nil { t.Errorf("writePing() error = %v, want nil", errPing) } @@ -7751,81 +7687,275 @@ func TestResponsesWebsocketWriterWritePing(t *testing.T) { } } -func TestForwardResponsesWebsocketPingWriteFailureAbortsSession(t *testing.T) { - gin.SetMode(gin.TestMode) +type blockingWebsocketWriteConn struct { + net.Conn + blockWrites atomic.Bool + writeBlock chan struct{} + closed chan struct{} + closeOnce sync.Once +} - serverErrCh := make(chan error, 1) - cancelledCh := make(chan error, 1) - data := make(chan []byte) - errCh := make(chan *interfaces.ErrorMessage) +func newBlockingWebsocketWriteConn(conn net.Conn) *blockingWebsocketWriteConn { + return &blockingWebsocketWriteConn{ + Conn: conn, + writeBlock: make(chan struct{}, 1), + closed: make(chan struct{}), + } +} - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - conn, err := responsesWebsocketUpgrader.Upgrade(w, r, nil) - if err != nil { - serverErrCh <- err - return +func (c *blockingWebsocketWriteConn) Write(b []byte) (int, error) { + if c.blockWrites.Load() { + select { + case c.writeBlock <- struct{}{}: + default: } - defer func() { _ = conn.Close() }() + <-c.closed + return 0, net.ErrClosed + } + return c.Conn.Write(b) +} - ctx, _ := gin.CreateTestContext(httptest.NewRecorder()) - ctx.Request = r +func (c *blockingWebsocketWriteConn) Close() error { + c.closeOnce.Do(func() { + close(c.closed) + }) + return c.Conn.Close() +} - interval := 10 * time.Millisecond - h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, nil)) +type hijackableWebsocketResponseWriter struct { + header http.Header + conn net.Conn +} - _, _, _, errMsg, errForward := h.forwardResponsesWebsocket( - ctx, - newResponsesWebsocketWriter(conn), - func(errs ...interface{}) { - if len(errs) > 0 { - if errVal, ok := errs[0].(error); ok { - cancelledCh <- errVal - return - } +func newHijackableWebsocketResponseWriter(conn net.Conn) *hijackableWebsocketResponseWriter { + return &hijackableWebsocketResponseWriter{ + header: make(http.Header), + conn: conn, + } +} + +func (w *hijackableWebsocketResponseWriter) Header() http.Header { return w.header } +func (w *hijackableWebsocketResponseWriter) Write(b []byte) (int, error) { return w.conn.Write(b) } +func (w *hijackableWebsocketResponseWriter) WriteHeader(int) {} +func (w *hijackableWebsocketResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return w.conn, bufio.NewReadWriter(bufio.NewReader(w.conn), bufio.NewWriter(w.conn)), nil +} + +func TestResponsesWebsocketWriterCloseInterruptsBlockedPing(t *testing.T) { + cases := []struct { + name string + close func(*responsesWebsocketWriter) error + }{ + { + name: "closeForUpstreamError", + close: func(w *responsesWebsocketWriter) error { + matched, errClose := w.closeForUpstreamError(&websocket.CloseError{ + Code: websocket.CloseMessageTooBig, + Text: "message too big", + }) + if !matched && errClose == nil { + return errors.New("message-too-big error did not match") } - cancelledCh <- nil + return errClose }, - data, - errCh, - newInMemoryWebsocketTimelineLog(), - "session-ping-fail", - responsesWebsocketForwardOptions{ - keepAliveInterval: &interval, + }, + { + name: "closeWithPayload", + close: func(w *responsesWebsocketWriter) error { + _, errClose := w.closeWithPayload([]byte(`{"type":"error","status":400}`)) + return errClose }, - ) - if errMsg != nil { - serverErrCh <- fmt.Errorf("unexpected error message: %v", errMsg.Error) + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + clientRaw, serverRaw := net.Pipe() + defer func() { _ = clientRaw.Close() }() + blockingServer := newBlockingWebsocketWriteConn(serverRaw) + defer func() { _ = blockingServer.Close() }() + + serverConnCh := make(chan *websocket.Conn, 1) + serverErrCh := make(chan error, 1) + go func() { + req, errReq := http.NewRequest(http.MethodGet, "http://example.com/v1/responses", nil) + if errReq != nil { + serverErrCh <- errReq + return + } + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "websocket") + req.Header.Set("Sec-WebSocket-Version", "13") + req.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + rw := newHijackableWebsocketResponseWriter(blockingServer) + conn, errUpgrade := responsesWebsocketUpgrader.Upgrade(rw, req, nil) + if errUpgrade != nil { + serverErrCh <- errUpgrade + return + } + serverConnCh <- conn + }() + + // Drain the HTTP 101 Switching Protocols response on the client side of the pipe. + buf := make([]byte, 512) + if _, errRead := clientRaw.Read(buf); errRead != nil { + t.Fatalf("read upgrade response: %v", errRead) + } + + var serverConn *websocket.Conn + select { + case serverConn = <-serverConnCh: + case errUpgrade := <-serverErrCh: + t.Fatalf("upgrade websocket: %v", errUpgrade) + case <-time.After(time.Second): + t.Fatal("timed out waiting for websocket upgrade") + } + + writer := newResponsesWebsocketWriter(serverConn) + blockingServer.blockWrites.Store(true) + + pingDone := make(chan error, 1) + go func() { + pingDone <- writer.writePing() + }() + + select { + case <-blockingServer.writeBlock: + case <-time.After(time.Second): + t.Fatal("timed out waiting for writePing to enter blocked network write") + } + + closeDone := make(chan error, 1) + go func() { + closeDone <- tc.close(writer) + }() + + select { + case errClose := <-closeDone: + if errClose != nil { + t.Fatalf("close returned error: %v", errClose) + } + case <-time.After(time.Second): + t.Fatal("terminal close blocked behind stuck Ping write") + } + + select { + case errPing := <-pingDone: + if !errors.Is(errPing, net.ErrClosed) { + t.Fatalf("writePing error = %v, want net.ErrClosed", errPing) + } + case <-time.After(time.Second): + t.Fatal("writePing did not exit after connection close") + } + }) + } +} + +func TestResponsesWebsocketKeepAliveUpdatesInterval(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + intervals := make(chan time.Duration, 1) + queueResponsesWebsocketKeepAliveInterval(intervals, time.Second) + queueResponsesWebsocketKeepAliveInterval(intervals, 20*time.Millisecond) + + pings := 0 + done := make(chan error, 1) + go func() { + done <- runResponsesWebsocketKeepAlive(ctx, intervals, func() error { + pings++ + return nil + }) + }() + + synctest.Wait() + time.Sleep(20 * time.Millisecond) + synctest.Wait() + if pings != 1 { + t.Fatalf("pings after replacing pending interval = %d, want 1", pings) + } + + queueResponsesWebsocketKeepAliveInterval(intervals, 10*time.Millisecond) + synctest.Wait() + time.Sleep(10 * time.Millisecond) + synctest.Wait() + if pings != 2 { + t.Fatalf("pings after shortening interval = %d, want 2", pings) + } + + queueResponsesWebsocketKeepAliveInterval(intervals, 0) + synctest.Wait() + time.Sleep(time.Second) + synctest.Wait() + if pings != 2 { + t.Fatalf("pings after disabling keepalive = %d, want 2", pings) + } + + queueResponsesWebsocketKeepAliveInterval(intervals, 10*time.Millisecond) + synctest.Wait() + time.Sleep(10 * time.Millisecond) + synctest.Wait() + if pings != 3 { + t.Fatalf("pings after re-enabling keepalive = %d, want 3", pings) + } + + cancel() + if err := <-done; err != nil { + t.Fatalf("keepalive did not shut down cleanly: %v", err) + } + }) +} + +func TestForwardResponsesWebsocketPreservesPingFailureCause(t *testing.T) { + requestCtx, cancelSocket := context.WithCancelCause(context.Background()) + cancelSocket(net.ErrClosed) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil).WithContext(requestCtx) + + var canceledWith error + _, _, _, _, err := (*OpenAIResponsesAPIHandler)(nil).forwardResponsesWebsocket( + c, nil, func(args ...interface{}) { + canceledWith, _ = args[0].(error) + }, nil, nil, nil, "ping-write-failure", + ) + if !errors.Is(err, net.ErrClosed) || !errors.Is(canceledWith, net.ErrClosed) { + t.Fatalf("forward error = %v, cancellation cause = %v, want closed connection", err, canceledWith) + } +} + +func TestResponsesWebsocketKeepAliveCancelsOnPingFailure(t *testing.T) { + serverErr := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := responsesWebsocketUpgrader.Upgrade(w, r, nil) + if err != nil { + serverErr <- err return } - serverErrCh <- errForward + _ = conn.Close() + + ctx, cancel := context.WithCancelCause(r.Context()) + defer cancel(nil) + intervals := make(chan time.Duration, 1) + intervals <- 10 * time.Millisecond + newResponsesWebsocketWriter(conn).keepAlive(ctx, cancel, intervals) + serverErr <- context.Cause(ctx) })) defer server.Close() wsURL := "ws" + strings.TrimPrefix(server.URL, "http") - clientConn, _, err := websocket.DefaultDialer.Dial(wsURL, nil) + conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil) if err != nil { t.Fatalf("dial websocket: %v", err) } - - // Close client connection immediately so the next server Ping write fails. - _ = clientConn.Close() + defer func() { _ = conn.Close() }() select { - case serverErr := <-serverErrCh: - if serverErr == nil { - t.Fatal("expected error on server ping write failure, got nil") + case errKeepAlive := <-serverErr: + if !errors.Is(errKeepAlive, net.ErrClosed) { + t.Fatalf("keepalive cancellation cause = %v, want closed connection", errKeepAlive) } case <-time.After(2 * time.Second): - t.Fatal("server timed out awaiting ping write abort") - } - - select { - case cancelErr := <-cancelledCh: - if cancelErr == nil { - t.Fatal("expected cancel callback to be invoked with ping error, got nil") - } - case <-time.After(time.Second): - t.Fatal("timed out awaiting cancel callback on ping write failure") + t.Fatal("timed out awaiting cancellation after Ping failed") } } diff --git a/sdk/auth/interfaces.go b/sdk/auth/interfaces.go index 4388de8019f..646c9d57bac 100644 --- a/sdk/auth/interfaces.go +++ b/sdk/auth/interfaces.go @@ -19,6 +19,7 @@ type LoginOptions struct { CallbackPort int Metadata map[string]string Prompt func(prompt string) (string, error) + ProxyURL string } // Authenticator manages login and optional refresh flows for a provider. diff --git a/sdk/auth/manager.go b/sdk/auth/manager.go index 4cbefd98e85..62e9f57cc49 100644 --- a/sdk/auth/manager.go +++ b/sdk/auth/manager.go @@ -12,6 +12,7 @@ import ( xaiauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/proxyutil" ) // Manager aggregates authenticators and coordinates persistence via a token store. @@ -56,6 +57,17 @@ func (m *Manager) Login(ctx context.Context, provider string, cfg *config.Config return nil, "", fmt.Errorf("cliproxy auth: authenticator %s not registered", provider) } + loginProxyURL := "" + if opts != nil { + loginProxyURL = strings.TrimSpace(opts.ProxyURL) + } + if loginProxyURL != "" { + if !proxyutil.ValidRequestProxy(loginProxyURL) { + return nil, "", fmt.Errorf("cliproxy auth: invalid login proxy URL %q", proxyutil.Redact(loginProxyURL)) + } + cfg = configWithLoginProxy(cfg, loginProxyURL) + } + record, err := auth.Login(ctx, cfg, opts) if err != nil { return nil, "", err @@ -127,6 +139,7 @@ func (m *Manager) Login(ctx context.Context, provider string, cfg *config.Config if adoptXAICredential { adoptLegacyXAIFileName(record, legacyXAICredential) } + applyLoginProxyToRecord(record, loginProxyURL) savedPath, err := m.store.Save(coreauth.WithAuthCreationIntent(ctx), record) if err != nil { @@ -159,6 +172,33 @@ func (m *Manager) Login(ctx context.Context, provider string, cfg *config.Config return record, savedPath, nil } +func configWithLoginProxy(cfg *config.Config, proxyURL string) *config.Config { + if cfg == nil { + return &config.Config{SDKConfig: config.SDKConfig{ProxyURL: proxyURL}} + } + cloned := cfg.CloneForRuntime() + if cloned == nil { + copied := *cfg + cloned = &copied + } + cloned.ProxyURL = proxyURL + return cloned +} + +func applyLoginProxyToRecord(record *coreauth.Auth, proxyURL string) { + if record == nil || proxyURL == "" { + return + } + record.ProxyURL = proxyURL + if record.Metadata == nil { + record.Metadata = make(map[string]any) + } + record.Metadata["proxy_url"] = proxyURL + if setter, ok := record.Storage.(interface{ SetMetadata(map[string]any) }); ok { + setter.SetMetadata(record.Metadata) + } +} + func metadataStringValue(metadata map[string]any, key string) string { value, _ := metadata[key].(string) return strings.TrimSpace(value) diff --git a/sdk/auth/manager_login_proxy_test.go b/sdk/auth/manager_login_proxy_test.go new file mode 100644 index 00000000000..6c031f9981b --- /dev/null +++ b/sdk/auth/manager_login_proxy_test.go @@ -0,0 +1,127 @@ +package auth + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +type proxyCapturingAuthenticator struct { + provider string + record *coreauth.Auth + seenCfg *config.Config +} + +func (a *proxyCapturingAuthenticator) Provider() string { + return a.provider +} + +func (a *proxyCapturingAuthenticator) Login(_ context.Context, cfg *config.Config, _ *LoginOptions) (*coreauth.Auth, error) { + a.seenCfg = cfg + return a.record, nil +} + +func (a *proxyCapturingAuthenticator) RefreshLead() *time.Duration { + return nil +} + +func TestManagerLoginWithProxyOverridesFlowAndPersists(t *testing.T) { + authDir := t.TempDir() + fileName := "demo-proxy.json" + proxyURL := "socks5://user:pass@127.0.0.1:1080" + + authenticator := &proxyCapturingAuthenticator{ + provider: "demo", + record: &coreauth.Auth{ + ID: fileName, + FileName: fileName, + Provider: "demo", + Metadata: map[string]any{"type": "demo", "email": "user@example.com"}, + }, + } + store := NewFileTokenStore() + store.SetBaseDir(authDir) + mgr := NewManager(store, authenticator) + cfg := &config.Config{AuthDir: authDir, SDKConfig: config.SDKConfig{ProxyURL: "http://global.example:8080"}} + + record, _, err := mgr.Login(context.Background(), "demo", cfg, &LoginOptions{ProxyURL: proxyURL}) + if err != nil { + t.Fatalf("Login error: %v", err) + } + if authenticator.seenCfg == nil || authenticator.seenCfg.ProxyURL != proxyURL { + t.Fatalf("authenticator cfg proxy = %v, want %q", authenticator.seenCfg, proxyURL) + } + if cfg.ProxyURL != "http://global.example:8080" { + t.Fatalf("caller cfg mutated: %q", cfg.ProxyURL) + } + if record.ProxyURL != proxyURL { + t.Fatalf("record.ProxyURL = %q, want %q", record.ProxyURL, proxyURL) + } + + raw, errRead := os.ReadFile(filepath.Join(authDir, fileName)) + if errRead != nil { + t.Fatalf("read saved auth: %v", errRead) + } + var saved map[string]any + if errUnmarshal := json.Unmarshal(raw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal saved auth: %v", errUnmarshal) + } + if saved["proxy_url"] != proxyURL { + t.Fatalf("saved proxy_url = %v, want %q", saved["proxy_url"], proxyURL) + } +} + +func TestManagerLoginWithoutProxyLeavesRecordUntouched(t *testing.T) { + authDir := t.TempDir() + fileName := "demo-noproxy.json" + authenticator := &proxyCapturingAuthenticator{ + provider: "demo", + record: &coreauth.Auth{ + ID: fileName, + FileName: fileName, + Provider: "demo", + Metadata: map[string]any{"type": "demo"}, + }, + } + store := NewFileTokenStore() + store.SetBaseDir(authDir) + mgr := NewManager(store, authenticator) + cfg := &config.Config{AuthDir: authDir} + + if _, _, err := mgr.Login(context.Background(), "demo", cfg, &LoginOptions{}); err != nil { + t.Fatalf("Login error: %v", err) + } + if authenticator.seenCfg != cfg { + t.Fatalf("authenticator received a different cfg without a login proxy") + } + raw, errRead := os.ReadFile(filepath.Join(authDir, fileName)) + if errRead != nil { + t.Fatalf("read saved auth: %v", errRead) + } + var saved map[string]any + if errUnmarshal := json.Unmarshal(raw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal saved auth: %v", errUnmarshal) + } + if _, ok := saved["proxy_url"]; ok { + t.Fatalf("saved auth unexpectedly contains proxy_url: %v", saved["proxy_url"]) + } +} + +func TestManagerLoginRejectsInvalidProxy(t *testing.T) { + authenticator := &proxyCapturingAuthenticator{provider: "demo", record: &coreauth.Auth{ID: "x.json", Provider: "demo"}} + mgr := NewManager(NewFileTokenStore(), authenticator) + for _, bad := range []string{"ftp://127.0.0.1:21", "direct", "not a url", "http://127.0.0.1:99999"} { + if _, _, err := mgr.Login(context.Background(), "demo", &config.Config{AuthDir: t.TempDir()}, &LoginOptions{ProxyURL: bad}); err == nil { + t.Fatalf("proxy %q: expected error", bad) + } + } + if authenticator.seenCfg != nil { + t.Fatalf("authenticator ran despite invalid proxy") + } +} diff --git a/sdk/cliproxy/auth/conductor.go b/sdk/cliproxy/auth/conductor.go index 3f485fcf10d..7fed87d7abc 100644 --- a/sdk/cliproxy/auth/conductor.go +++ b/sdk/cliproxy/auth/conductor.go @@ -91,6 +91,10 @@ type Result struct { SkipQuotaObservation bool // AccessToken captures the active access token under which the request was executed. AccessToken string + // RefreshToken captures the refresh credential associated with the request, + // used to distinguish a same-account OAuth token rotation from a genuine + // credential replacement when evaluating result staleness. + RefreshToken string // CredentialVersion captures the credential version under which the request was executed. CredentialVersion uint64 // RegistrationEpoch captures the registration epoch under which the request was executed. @@ -172,6 +176,7 @@ type resultPolicyHolder struct { // Manager orchestrates auth lifecycle, selection, execution, and persistence. type Manager struct { + inFlightTracker *inFlightTracker store Store cooldownStore CooldownStateStore pendingCooldownStateStore CooldownStateStore @@ -258,6 +263,7 @@ func NewManager(store Store, selector Selector, hook Hook) *Manager { hook = NoopHook{} } manager := &Manager{ + inFlightTracker: newInFlightTracker(), store: store, authLoadGate: semaphore.NewWeighted(math.MaxInt64), executors: make(map[string]ProviderExecutor), diff --git a/sdk/cliproxy/auth/conductor_claude_thread.go b/sdk/cliproxy/auth/conductor_claude_thread.go new file mode 100644 index 00000000000..1ba7f11557c --- /dev/null +++ b/sdk/cliproxy/auth/conductor_claude_thread.go @@ -0,0 +1,56 @@ +package auth + +import ( + "context" + "net/http" + + "github.com/MoeForge/moego/ojson" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + cliproxysession "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" + log "github.com/sirupsen/logrus" +) + +// withClaudeThreadAuth pins continuations before ordinary selection, including +// default round-robin. It never bypasses the selector's availability checks. +func withClaudeThreadAuth(ctx context.Context, providers []string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Options, error) { + if opts.SourceFormat != sdktranslator.FormatClaude { + return opts, nil + } + hasClaude := false + for _, provider := range providers { + if provider == "claude" { + hasClaude = true + break + } + } + if !hasClaude { + return opts, nil + } + previousID := ojson.GetBytesNoCopy(req.Payload, "thread.previous_message_id").String() + if previousID == "" { + return opts, nil + } + callerScope := cliproxysession.ClaudeThreadCallerScope(coreusage.APIKeyFromContext(ctx), opts.Metadata, req.Metadata) + owner, found, errOwner := cliproxysession.ClaudeThreadAuth(ctx, callerScope, previousID) + if errOwner != nil { + if ctx != nil && ctx.Err() != nil { + return opts, ctx.Err() + } + log.WithError(errOwner).Warn("Claude Thread credential binding lookup failed") + return opts, &Error{Code: "thread_auth_unavailable", Message: "Claude Thread credential binding is temporarily unavailable", Retryable: true, HTTPStatus: http.StatusServiceUnavailable} + } + if !found { + return opts, nil + } + if pinned := pinnedAuthIDFromMetadata(opts.Metadata); pinned != "" && pinned != owner { + return opts, &Error{Code: "thread_auth_conflict", Message: "the pinned credential does not own this Claude Thread; replay with thread create", HTTPStatus: http.StatusConflict} + } + opts.Metadata = cloneRequestMetadata(opts.Metadata) + if opts.Metadata == nil { + opts.Metadata = make(map[string]any) + } + opts.Metadata[cliproxyexecutor.PinnedAuthMetadataKey] = owner + return opts, nil +} diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index ce4d85c56a2..f3b5dcb2200 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "maps" "net" "net/http" "regexp" @@ -16,6 +17,7 @@ import ( "time" "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" internallogging "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" @@ -290,10 +292,17 @@ func (m *Manager) clearDisabledCooldownStates(cfg *internalconfig.Config) bool { if auth == nil { continue } - if !quotaCooldownDisabledForAuthWithConfig(auth, cfg) && !auth.Disabled && auth.Status != StatusDisabled { + isDisabled := auth.Disabled || auth.Status == StatusDisabled + if !isDisabled && !quotaCooldownDisabledForAuthWithConfig(auth, cfg) { continue } - if clearCooldownStateForAuth(auth, now) { + var cleared bool + if isDisabled { + cleared = clearCooldownStateForAuth(auth, now) + } else { + cleared = clearDisabledCooldownStateForAuth(auth, now) + } + if cleared { snapshots = append(snapshots, auth.Clone()) } } @@ -352,6 +361,13 @@ func (m *Manager) RestoreCooldownStates(ctx context.Context) error { } } } + for authID := range snapshotsByID { + if auth := m.auths[authID]; auth != nil && m.cooldownDisabledForAuth(auth) { + if clearDisabledCooldownStateForAuth(auth, now) { + snapshotsByID[authID] = auth.Clone() + } + } + } m.mu.Unlock() if m.scheduler != nil { @@ -369,7 +385,7 @@ func (m *Manager) restoreCooldownRecordLocked(record CooldownStateRecord, now ti return false } auth := m.auths[authID] - if auth == nil || auth.Disabled || auth.Status == StatusDisabled || m.cooldownDisabledForAuth(auth) || hasUnauthorizedAuthFailure(auth) { + if auth == nil || auth.Disabled || auth.Status == StatusDisabled || (m.cooldownDisabledForAuth(auth) && !isForceCooldownRecordAt(record, now)) || hasUnauthorizedAuthFailure(auth) { return false } updatedAt := record.UpdatedAt @@ -382,19 +398,104 @@ func (m *Manager) restoreCooldownRecordLocked(record CooldownStateRecord, now ti if quota.Exceeded && quota.NextRecoverAt.IsZero() { quota.NextRecoverAt = record.NextRetryAfter } + quota.cooldownEvaluated = quota.Exceeded + if executorKeyFromAuth(auth) == "claude" || strings.EqualFold(strings.TrimSpace(record.Provider), "claude") { + quota.cooldownSignals = sanitizePersistedClaudeCooldownSignals(record.CooldownSignals) + } + seedInitialForceCooldownDeadlines(auth) + outerForceUntil := recordOuterForceUntil(record) + indepForceUntil := recordIndependentForceUntil(record) if model == "" { + prevNextRetry := auth.NextRetryAfter + prevQuota := auth.Quota.Clone() + prevUpdatedAt := auth.UpdatedAt + prevLastErr := cloneError(auth.LastError) + prevStatusMsg := auth.StatusMessage + hadLiveAuthBlock := auth.Unavailable && (prevNextRetry.After(now) || (prevQuota.Exceeded && prevQuota.NextRecoverAt.After(now))) + liveNewer := hadLiveAuthBlock && prevUpdatedAt.After(updatedAt) + auth.Unavailable = true auth.Status = StatusError - auth.NextRetryAfter = record.NextRetryAfter - applyCooldownFields(&auth.Quota, quota) + if prevNextRetry.After(now) && prevNextRetry.After(record.NextRetryAfter) { + auth.NextRetryAfter = prevNextRetry + } else { + auth.NextRetryAfter = record.NextRetryAfter + } + mergedQuota := quota + prevCredQuota := prevQuota.Exceeded && strings.TrimSpace(prevQuota.Reason) == "credential_quota" && prevQuota.NextRecoverAt.After(now) + recCredQuota := quota.Exceeded && strings.TrimSpace(quota.Reason) == "credential_quota" && quota.NextRecoverAt.After(now) + if prevCredQuota || recCredQuota { + mergedQuota.Exceeded = true + mergedQuota.Reason = "credential_quota" + var credRecover time.Time + if prevCredQuota { + credRecover = prevQuota.NextRecoverAt + } + if recCredQuota && quota.NextRecoverAt.After(credRecover) { + credRecover = quota.NextRecoverAt + } + mergedQuota.NextRecoverAt = credRecover + if prevQuota.BackoffLevel > mergedQuota.BackoffLevel { + mergedQuota.BackoffLevel = prevQuota.BackoffLevel + } + if prevCredQuota && (!recCredQuota || prevQuota.NextRecoverAt.After(quota.NextRecoverAt) || len(mergedQuota.cooldownSignals) == 0) { + mergedQuota.cooldownSignals = prevQuota.cooldownSignals + } + } else if prevQuota.Exceeded && prevQuota.NextRecoverAt.After(now) { + mergedQuota.Exceeded = true + if prevQuota.NextRecoverAt.After(mergedQuota.NextRecoverAt) { + mergedQuota.NextRecoverAt = prevQuota.NextRecoverAt + } + if prevQuota.BackoffLevel > mergedQuota.BackoffLevel { + mergedQuota.BackoffLevel = prevQuota.BackoffLevel + } + if liveNewer && prevQuota.Reason != "" { + mergedQuota.Reason = prevQuota.Reason + } else if mergedQuota.Reason == "" { + mergedQuota.Reason = prevQuota.Reason + } + if prevQuota.NextRecoverAt.After(quota.NextRecoverAt) || len(mergedQuota.cooldownSignals) == 0 { + mergedQuota.cooldownSignals = prevQuota.cooldownSignals + } + } + applyCooldownFields(&auth.Quota, mergedQuota) + auth.Quota = mergeQuotaObservation(auth.Quota, prevQuota) auth.Quota = mergeQuotaObservation(auth.Quota, quota) + if credForce := recordCredQuotaForceUntil(record); credForce.After(now) && credForce.After(auth.credQuotaForceUntil) { + auth.credQuotaForceUntil = credForce + } + authForce := recordAuthLevelForceUntil(record) + if isLegacyAggregatedAuthRecord(record, auth.ModelStates, now) { + authForce = time.Time{} + } + if authForce.After(now) && authForce.After(auth.forceCooldownUntil) { + auth.forceCooldownUntil = authForce + } + if record.CredentialRetryAfter.After(now) && record.CredentialRetryAfter.After(auth.credentialRetryAfter) { + auth.credentialRetryAfter = record.CredentialRetryAfter + } + auth.forceCooldownSeeded = true auth.Generation++ - auth.UpdatedAt = updatedAt - if reason != "" { - auth.StatusMessage = reason + if liveNewer { + auth.UpdatedAt = prevUpdatedAt + if prevStatusMsg != "" { + auth.StatusMessage = prevStatusMsg + } else if reason != "" { + auth.StatusMessage = reason + } + if prevLastErr != nil { + auth.LastError = prevLastErr + } else { + auth.LastError = cloneError(record.LastError) + } + } else { + auth.UpdatedAt = updatedAt + if reason != "" { + auth.StatusMessage = reason + } + auth.LastError = cloneError(record.LastError) } - auth.LastError = cloneError(record.LastError) return true } @@ -406,6 +507,7 @@ func (m *Manager) restoreCooldownRecordLocked(record CooldownStateRecord, now ti // state (reason "quota" whose own error is the explicit daily/weekly // exhaustion message) is credential-derived and must not be captured; // genuine model-scoped 429s carry different messages and stay eligible. + seedModelForceCooldownDeadline(state) liveShadow := state.credentialQuotaShadow.cloneShallow() if liveShadow == nil && !state.credentialQuotaPropagated && state.Quota.Reason != "credential_quota" && isModelStateActiveCooldown(state, now) && !isDevinQuotaExhaustionMessage(devinStateErrorText(state)) { @@ -413,21 +515,29 @@ func (m *Manager) restoreCooldownRecordLocked(record CooldownStateRecord, now ti } wasLiveWrapped := state.credentialQuotaPropagated || state.Quota.Reason == "credential_quota" || (auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now)) + isWrappedRecord := record.IndependentState != nil || record.CredentialQuotaPropagated || strings.TrimSpace(quota.Reason) == "credential_quota" + var recordModelForceUntil time.Time + if !isWrappedRecord && outerForceUntil.After(now) { + recordModelForceUntil = outerForceUntil + } else if isWrappedRecord && outerForceUntil.After(now) && outerForceUntil.After(auth.credQuotaForceUntil) { + auth.credQuotaForceUntil = outerForceUntil + } mergeModelState(state, &ModelState{ - Unavailable: true, - Status: StatusError, - StatusMessage: reason, - NextRetryAfter: record.NextRetryAfter, - Quota: quota, - LastError: cloneError(record.LastError), - UpdatedAt: updatedAt, + Unavailable: true, + Status: StatusError, + StatusMessage: reason, + NextRetryAfter: record.NextRetryAfter, + Quota: quota, + LastError: cloneError(record.LastError), + UpdatedAt: updatedAt, + forceCooldownUntil: recordModelForceUntil, + forceCooldownSeeded: true, }) // The persisted independent layer joins the merge newest-wins; a newer // live independent layer (shadow or freshly captured unwrapped state, // e.g. an own failure recorded during a delayed store load) is never // clobbered by the older record. A wrapped record is any record whose // outer reason is the propagated credential quota. - isWrappedRecord := record.IndependentState != nil || record.CredentialQuotaPropagated || strings.TrimSpace(quota.Reason) == "credential_quota" if !isWrappedRecord && wasLiveWrapped { // An unwrapped independent record landing beneath a live wrap becomes // the model's independent layer (unless it is itself a legacy @@ -435,48 +545,452 @@ func (m *Manager) restoreCooldownRecordLocked(record CooldownStateRecord, now ti // presenting the propagated credential quota. if !isDevinQuotaExhaustionMessage(devinRecordErrorText(record)) { recordShadow := &ModelState{ - Unavailable: true, - Status: StatusError, - StatusMessage: reason, - NextRetryAfter: record.NextRetryAfter, - Quota: quota, - LastError: cloneError(record.LastError), - UpdatedAt: updatedAt, - } - preferred := state.credentialQuotaShadow - if preferred == nil || (liveShadow != nil && !liveShadow.UpdatedAt.After(updatedAt)) { - preferred = recordShadow - } else if liveShadow != nil && liveShadow.UpdatedAt.After(updatedAt) { - preferred = liveShadow + Unavailable: true, + Status: StatusError, + StatusMessage: reason, + NextRetryAfter: record.NextRetryAfter, + Quota: quota, + LastError: cloneError(record.LastError), + UpdatedAt: updatedAt, + forceCooldownUntil: recordModelForceUntil, + forceCooldownSeeded: true, } + preferred := state.credentialQuotaShadow.cloneShallow() + if liveShadow != nil { + preferred = mergeModelState(preferred, liveShadow.cloneShallow()) + } + preferred = mergeModelState(preferred, recordShadow) state.credentialQuotaShadow = preferred } state.credentialQuotaPropagated = true applyCooldownFields(&state.Quota, QuotaState{ - Exceeded: true, - Reason: "credential_quota", - NextRecoverAt: auth.Quota.NextRecoverAt, - BackoffLevel: auth.Quota.BackoffLevel, + Exceeded: true, + Reason: "credential_quota", + NextRecoverAt: auth.Quota.NextRecoverAt, + BackoffLevel: auth.Quota.BackoffLevel, + cooldownSignals: auth.Quota.cooldownSignals, }) if state.NextRetryAfter.Before(auth.Quota.NextRecoverAt) { state.NextRetryAfter = auth.Quota.NextRecoverAt } + if state.credentialQuotaShadow != nil && state.credentialQuotaShadow.NextRetryAfter.After(state.NextRetryAfter) { + state.NextRetryAfter = state.credentialQuotaShadow.NextRetryAfter + } state.Unavailable = true state.Status = StatusError } else if isWrappedRecord { state.credentialQuotaPropagated = true - if record.IndependentState != nil && (liveShadow == nil || !liveShadow.UpdatedAt.After(record.IndependentState.UpdatedAt)) { - state.credentialQuotaShadow = record.IndependentState.cloneShallow() - } else if liveShadow != nil { - state.credentialQuotaShadow = liveShadow + var restoredShadow *ModelState + if record.IndependentState != nil { + restoredShadow = record.IndependentState.cloneShallow() + restoredShadow.Quota.cooldownEvaluated = restoredShadow.Quota.Exceeded + if indepForceUntil.After(restoredShadow.forceCooldownUntil) { + restoredShadow.forceCooldownUntil = indepForceUntil + } + restoredShadow.forceCooldownSeeded = true + if executorKeyFromAuth(auth) == "claude" || strings.EqualFold(strings.TrimSpace(record.Provider), "claude") { + restoredShadow.Quota.cooldownSignals = sanitizePersistedClaudeCooldownSignals(record.IndependentCooldownSignals) + } + } + state.credentialQuotaShadow = mergeModelState(liveShadow, restoredShadow) + if state.credentialQuotaShadow != nil && state.credentialQuotaShadow.NextRetryAfter.After(state.NextRetryAfter) { + state.NextRetryAfter = state.credentialQuotaShadow.NextRetryAfter } } + auth.forceCooldownSeeded = true auth.Generation++ - auth.UpdatedAt = updatedAt + if updatedAt.After(auth.UpdatedAt) { + auth.UpdatedAt = updatedAt + } updateAggregatedAvailability(auth, now) return true } +func isForceCooldownError(err *Error) bool { + return err != nil && err.Code == ErrorCodeForceCooldown +} + +func recordOuterForceUntil(record CooldownStateRecord) time.Time { + if record.ForceCooldownEvaluated { + return record.ForceCooldownUntil + } + if isForceCooldownError(record.LastError) { + return record.NextRetryAfter + } + return time.Time{} +} + +func recordCredQuotaForceUntil(record CooldownStateRecord) time.Time { + if record.ForceCooldownEvaluated { + return record.CredQuotaForceCooldownUntil + } + if strings.TrimSpace(record.Quota.Reason) == "credential_quota" && isForceCooldownError(record.LastError) { + if !record.Quota.NextRecoverAt.IsZero() { + return record.Quota.NextRecoverAt + } + return record.NextRetryAfter + } + return time.Time{} +} + +func recordAuthLevelForceUntil(record CooldownStateRecord) time.Time { + if record.ForceCooldownEvaluated { + return record.ForceCooldownUntil + } + if strings.TrimSpace(record.Quota.Reason) != "credential_quota" && isForceCooldownError(record.LastError) { + return record.NextRetryAfter + } + return time.Time{} +} + +// isLegacyAggregatedAuthRecord reports whether a pre-ForceCooldownEvaluated +// Model=="" record is merely the updateAggregatedAvailability copy of +// auth.ModelStates rather than an independent model-less cooldown. +func isLegacyAggregatedAuthRecord(record CooldownStateRecord, states map[string]*ModelState, now time.Time) bool { + if record.ForceCooldownEvaluated || len(states) == 0 || strings.TrimSpace(record.Quota.Reason) == "credential_quota" { + return false + } + var earliestRetry time.Time + matchedOrigin := false + hasState := false + for _, st := range states { + if st == nil { + continue + } + hasState = true + if st.Status == StatusDisabled { + continue + } + if !st.Unavailable || st.NextRetryAfter.IsZero() || !st.NextRetryAfter.After(now) { + return false + } + if earliestRetry.IsZero() || st.NextRetryAfter.Before(earliestRetry) { + earliestRetry = st.NextRetryAfter + } + if st.UpdatedAt.Equal(record.UpdatedAt) && cooldownErrorEqual(st.LastError, record.LastError) { + matchedOrigin = true + } + } + return hasState && matchedOrigin && !earliestRetry.IsZero() && record.NextRetryAfter.Equal(earliestRetry) +} + +func recordIndependentForceUntil(record CooldownStateRecord) time.Time { + if record.IndependentState == nil { + return time.Time{} + } + if record.ForceCooldownEvaluated { + return record.IndependentForceCooldownUntil + } + if isForceCooldownError(record.IndependentState.LastError) { + return record.IndependentState.NextRetryAfter + } + return time.Time{} +} + +func isForceCooldownRecordAt(record CooldownStateRecord, now time.Time) bool { + if strings.TrimSpace(record.Model) == "" { + return recordAuthLevelForceUntil(record).After(now) || recordCredQuotaForceUntil(record).After(now) + } + return recordOuterForceUntil(record).After(now) || recordIndependentForceUntil(record).After(now) +} + +// Pure read-only force deadline accessors safe under RLock. +func effectiveCredQuotaForceUntil(auth *Auth) time.Time { + if auth == nil { + return time.Time{} + } + if auth.forceCooldownSeeded { + return auth.credQuotaForceUntil + } + if isForceCooldownError(auth.LastError) && auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" { + return auth.Quota.NextRecoverAt + } + return time.Time{} +} + +func effectiveAuthForceUntil(auth *Auth) time.Time { + if auth == nil { + return time.Time{} + } + if auth.forceCooldownSeeded { + return auth.forceCooldownUntil + } + if len(auth.ModelStates) == 0 && isForceCooldownError(auth.LastError) { + return auth.NextRetryAfter + } + return time.Time{} +} + +func effectiveModelForceUntil(state *ModelState) time.Time { + if state == nil { + return time.Time{} + } + if state.forceCooldownSeeded { + return state.forceCooldownUntil + } + isWrapped := state.credentialQuotaPropagated || state.Quota.Reason == "credential_quota" + if !isWrapped && isForceCooldownError(state.LastError) { + return state.NextRetryAfter + } + return time.Time{} +} + +func seedModelForceCooldownDeadline(state *ModelState) { + if state == nil { + return + } + if state.credentialQuotaShadow != nil { + seedModelForceCooldownDeadline(state.credentialQuotaShadow) + } + if state.forceCooldownSeeded { + return + } + state.forceCooldownSeeded = true + isWrapped := state.credentialQuotaPropagated || state.Quota.Reason == "credential_quota" + if !isWrapped && isForceCooldownError(state.LastError) && !state.NextRetryAfter.IsZero() { + state.forceCooldownUntil = state.NextRetryAfter + } +} + +// seedInitialForceCooldownDeadlines initializes explicit force-cooldown provenance +// once from pre-populated Auth/ModelState struct literals before runtime updates. +func seedInitialForceCooldownDeadlines(auth *Auth) { + if auth == nil { + return + } + for _, state := range auth.ModelStates { + seedModelForceCooldownDeadline(state) + } + if auth.forceCooldownSeeded { + return + } + auth.forceCooldownSeeded = true + if !isForceCooldownError(auth.LastError) { + return + } + if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && !auth.Quota.NextRecoverAt.IsZero() { + auth.credQuotaForceUntil = auth.Quota.NextRecoverAt + } else if len(auth.ModelStates) == 0 && !auth.NextRetryAfter.IsZero() { + auth.forceCooldownUntil = auth.NextRetryAfter + } +} + +func clampStateToForceDeadline(state *ModelState, now time.Time) (kept bool, mutated bool) { + if state == nil { + return false, false + } + seedModelForceCooldownDeadline(state) + if !state.forceCooldownUntil.After(now) || !state.NextRetryAfter.After(now) { + return false, false + } + if state.NextRetryAfter.After(state.forceCooldownUntil) { + state.NextRetryAfter = state.forceCooldownUntil + mutated = true + } + if state.Quota.Exceeded && state.Quota.NextRecoverAt.After(state.forceCooldownUntil) { + state.Quota.NextRecoverAt = state.forceCooldownUntil + mutated = true + } + return true, mutated +} + +// clearDisabledCooldownStateForAuth clears ordinary cooldown/quota state for an auth +// under disable-cooling while preserving active ErrorCodeForceCooldown deadlines. +func clearDisabledCooldownStateForAuth(auth *Auth, now time.Time) bool { + if auth == nil || hasUnauthorizedAuthFailure(auth) { + return false + } + seedInitialForceCooldownDeadlines(auth) + + keepCredQuotaForce := auth.Quota.Exceeded && + auth.Quota.Reason == "credential_quota" && + auth.credQuotaForceUntil.After(now) && + auth.Quota.NextRecoverAt.After(now) + keepAuthLevelForce := auth.Unavailable && + auth.forceCooldownUntil.After(now) && + auth.NextRetryAfter.After(now) + combinedAuthForceUntil := time.Time{} + if keepCredQuotaForce { + combinedAuthForceUntil = auth.credQuotaForceUntil + } + if keepAuthLevelForce && auth.forceCooldownUntil.After(combinedAuthForceUntil) { + combinedAuthForceUntil = auth.forceCooldownUntil + } + + if len(auth.ModelStates) == 0 { + if keepCredQuotaForce || keepAuthLevelForce { + changed := false + if !keepCredQuotaForce && !auth.credQuotaForceUntil.IsZero() { + auth.credQuotaForceUntil = time.Time{} + changed = true + } + if !keepAuthLevelForce && !auth.forceCooldownUntil.IsZero() { + auth.forceCooldownUntil = time.Time{} + changed = true + } + if !auth.credentialRetryAfter.IsZero() { + auth.credentialRetryAfter = time.Time{} + changed = true + } + if keepCredQuotaForce { + if !auth.Quota.NextRecoverAt.Equal(auth.credQuotaForceUntil) { + auth.Quota.NextRecoverAt = auth.credQuotaForceUntil + changed = true + } + } else if auth.Quota.Reason == "credential_quota" { + applyCooldownFields(&auth.Quota, QuotaState{}) + changed = true + } else if auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(combinedAuthForceUntil) { + auth.Quota.NextRecoverAt = combinedAuthForceUntil + changed = true + } + if !auth.NextRetryAfter.Equal(combinedAuthForceUntil) { + auth.NextRetryAfter = combinedAuthForceUntil + changed = true + } + if changed { + auth.Generation++ + auth.UpdatedAt = now + } + return changed + } + return clearCooldownStateForAuth(auth, now) + } + + savedAuthNextRetry := combinedAuthForceUntil + savedAuthQuota := cooldownFieldsOf(auth.Quota) + if !keepCredQuotaForce { + if savedAuthQuota.Reason == "credential_quota" { + savedAuthQuota = QuotaState{} + } else if keepAuthLevelForce && savedAuthQuota.Exceeded && savedAuthQuota.NextRecoverAt.After(auth.forceCooldownUntil) { + savedAuthQuota.NextRecoverAt = auth.forceCooldownUntil + } + } + + changed := false + if keepCredQuotaForce { + if !auth.Quota.NextRecoverAt.Equal(auth.credQuotaForceUntil) { + auth.Quota.NextRecoverAt = auth.credQuotaForceUntil + changed = true + } + if !auth.NextRetryAfter.Equal(combinedAuthForceUntil) { + auth.NextRetryAfter = combinedAuthForceUntil + changed = true + } + } + + for _, state := range auth.ModelStates { + if state == nil { + continue + } + isWrapped := state.credentialQuotaPropagated || state.Quota.Reason == "credential_quota" + if isWrapped { + if keepCredQuotaForce { + var shadowDeadline time.Time + if state.credentialQuotaShadow != nil { + keptShadow, mutatedShadow := clampStateToForceDeadline(state.credentialQuotaShadow, now) + if !keptShadow { + state.credentialQuotaShadow = nil + state.UpdatedAt = now + changed = true + } else { + shadowDeadline = state.credentialQuotaShadow.NextRetryAfter + if mutatedShadow { + state.UpdatedAt = now + changed = true + } + } + } + effectiveOuter := auth.credQuotaForceUntil + if shadowDeadline.After(effectiveOuter) { + effectiveOuter = shadowDeadline + } + if state.Quota.NextRecoverAt.After(auth.credQuotaForceUntil) { + state.Quota.NextRecoverAt = auth.credQuotaForceUntil + state.UpdatedAt = now + changed = true + } + if state.NextRetryAfter.After(effectiveOuter) { + state.NextRetryAfter = effectiveOuter + state.UpdatedAt = now + changed = true + } + continue + } + if shadow := state.credentialQuotaShadow; shadow != nil { + if keptShadow, _ := clampStateToForceDeadline(shadow, now); keptShadow { + preservedSeq := shadow.cooldownRecordedSeq + *state = *shadow.cloneShallow() + state.cooldownRecordedSeq = preservedSeq + state.credentialQuotaPropagated = false + state.credentialQuotaShadow = nil + state.UpdatedAt = now + changed = true + continue + } + } + } else if keptModel, mutatedModel := clampStateToForceDeadline(state, now); keptModel { + if mutatedModel { + state.UpdatedAt = now + changed = true + } + continue + } + if state.Unavailable || !state.NextRetryAfter.IsZero() || state.Quota.Exceeded || !state.Quota.NextRecoverAt.IsZero() || state.credentialQuotaShadow != nil || state.credentialQuotaPropagated || !state.forceCooldownUntil.IsZero() { + state.Unavailable = false + state.NextRetryAfter = time.Time{} + applyCooldownFields(&state.Quota, QuotaState{}) + state.cooldownRecordedSeq = 0 + state.forceCooldownUntil = time.Time{} + state.credentialQuotaShadow = nil + state.credentialQuotaPropagated = false + state.UpdatedAt = now + changed = true + } + } + + if !keepCredQuotaForce { + auth.credQuotaForceUntil = time.Time{} + } + if !keepAuthLevelForce { + auth.forceCooldownUntil = time.Time{} + } + if !auth.credentialRetryAfter.IsZero() { + auth.credentialRetryAfter = time.Time{} + changed = true + } + + prevUnavailable := auth.Unavailable + prevNextRetry := auth.NextRetryAfter + prevQuota := cooldownFieldsOf(auth.Quota) + if !keepCredQuotaForce { + auth.Unavailable = false + auth.NextRetryAfter = time.Time{} + applyCooldownFields(&auth.Quota, QuotaState{}) + if !keepAuthLevelForce { + auth.cooldownRecordedSeq = 0 + } + updateAggregatedAvailability(auth, now) + } + if keepAuthLevelForce { + auth.Unavailable = true + if savedAuthNextRetry.After(auth.NextRetryAfter) { + auth.NextRetryAfter = savedAuthNextRetry + } + if !keepCredQuotaForce && savedAuthQuota.Exceeded && savedAuthQuota.NextRecoverAt.After(now) && !auth.Quota.NextRecoverAt.After(savedAuthQuota.NextRecoverAt) { + applyCooldownFields(&auth.Quota, savedAuthQuota) + } + } + if auth.Unavailable != prevUnavailable || !auth.NextRetryAfter.Equal(prevNextRetry) || !cooldownQuotaEqual(cooldownFieldsOf(auth.Quota), prevQuota) { + changed = true + } + if changed { + auth.Generation++ + auth.UpdatedAt = now + } + return changed +} + func clearCooldownStateForAuth(auth *Auth, now time.Time) bool { if auth == nil { return false @@ -485,6 +999,10 @@ func clearCooldownStateForAuth(auth *Auth, now time.Time) bool { return false } changed := false + auth.forceCooldownUntil = time.Time{} + auth.credQuotaForceUntil = time.Time{} + auth.credentialRetryAfter = time.Time{} + auth.cooldownRecordedSeq = 0 if auth.Unavailable || !auth.NextRetryAfter.IsZero() || auth.Quota.Exceeded || !auth.Quota.NextRecoverAt.IsZero() { auth.Unavailable = false auth.NextRetryAfter = time.Time{} @@ -496,6 +1014,8 @@ func clearCooldownStateForAuth(auth *Auth, now time.Time) bool { if state == nil { continue } + state.forceCooldownUntil = time.Time{} + state.cooldownRecordedSeq = 0 if state.Unavailable || !state.NextRetryAfter.IsZero() || state.Quota.Exceeded || !state.Quota.NextRecoverAt.IsZero() || state.credentialQuotaShadow != nil || state.credentialQuotaPropagated { state.Unavailable = false state.NextRetryAfter = time.Time{} @@ -708,15 +1228,16 @@ func (m *Manager) cooldownStateRecordsSnapshot() []CooldownStateRecord { } func (m *Manager) cooldownStateRecordsForAuthLocked(auth *Auth, now time.Time) []CooldownStateRecord { - if auth == nil || auth.ID == "" || auth.Disabled || auth.Status == StatusDisabled || m.cooldownDisabledForAuth(auth) { + if auth == nil || auth.ID == "" || auth.Disabled || auth.Status == StatusDisabled { return nil } + coolingDisabled := m.cooldownDisabledForAuth(auth) records := make([]CooldownStateRecord, 0, 1+len(auth.ModelStates)) - if record, ok := authCooldownStateRecord(auth, now); ok { + if record, ok := authCooldownStateRecord(auth, now); ok && (!coolingDisabled || isForceCooldownRecordAt(record, now)) { records = append(records, record) } for model, state := range auth.ModelStates { - if record, ok := modelCooldownStateRecord(auth, model, state, now); ok { + if record, ok := modelCooldownStateRecord(auth, model, state, now); ok && (!coolingDisabled || isForceCooldownRecordAt(record, now)) { records = append(records, record) } } @@ -756,6 +1277,16 @@ func cooldownStateRecordEqual(a, b CooldownStateRecord) bool { if !cooldownErrorEqual(a.LastError, b.LastError) { return false } + if a.ForceCooldownEvaluated != b.ForceCooldownEvaluated || + !a.ForceCooldownUntil.Equal(b.ForceCooldownUntil) || + !a.CredQuotaForceCooldownUntil.Equal(b.CredQuotaForceCooldownUntil) || + !a.IndependentForceCooldownUntil.Equal(b.IndependentForceCooldownUntil) || + !a.CredentialRetryAfter.Equal(b.CredentialRetryAfter) { + return false + } + if !maps.Equal(a.CooldownSignals, b.CooldownSignals) || !maps.Equal(a.IndependentCooldownSignals, b.IndependentCooldownSignals) { + return false + } return cooldownIndependentStateEqual(a.IndependentState, b.IndependentState) } @@ -786,23 +1317,47 @@ func cooldownErrorEqual(a, b *Error) bool { return a.Code == b.Code && a.Message == b.Message && a.Retryable == b.Retryable && - a.HTTPStatus == b.HTTPStatus + a.HTTPStatus == b.HTTPStatus && + maps.Equal(a.Metadata, b.Metadata) } func authCooldownStateRecord(auth *Auth, now time.Time) (CooldownStateRecord, bool) { if auth == nil || !auth.Unavailable || auth.NextRetryAfter.IsZero() || !auth.NextRetryAfter.After(now) { return CooldownStateRecord{}, false } + var cooldownSignals map[string]string + if auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(now) && !auth.NextRetryAfter.After(auth.Quota.NextRecoverAt) { + cooldownSignals = sanitizePersistedClaudeCooldownSignals(auth.Quota.cooldownSignals) + } + var authForceUntil time.Time + if u := effectiveAuthForceUntil(auth); u.After(now) { + authForceUntil = u + } + var credQuotaForceUntil time.Time + if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { + if u := effectiveCredQuotaForceUntil(auth); u.After(now) { + credQuotaForceUntil = u + } + } + var credentialRetryAfter time.Time + if !auth.credentialRetryAfter.IsZero() && auth.credentialRetryAfter.After(now) { + credentialRetryAfter = auth.credentialRetryAfter + } return CooldownStateRecord{ - Provider: strings.TrimSpace(auth.Provider), - AuthID: auth.ID, - AuthFile: cooldownAuthFile(auth), - Status: "cooling", - NextRetryAfter: auth.NextRetryAfter, - Reason: cooldownReason(auth.StatusMessage, auth.Quota, auth.LastError), - Quota: cooldownFieldsOf(auth.Quota), - LastError: cloneError(auth.LastError), - UpdatedAt: auth.UpdatedAt, + Provider: strings.TrimSpace(auth.Provider), + AuthID: auth.ID, + AuthFile: cooldownAuthFile(auth), + Status: "cooling", + NextRetryAfter: auth.NextRetryAfter, + Reason: cooldownReason(auth.StatusMessage, auth.Quota, auth.LastError), + Quota: cooldownFieldsOf(auth.Quota), + LastError: cloneError(auth.LastError), + UpdatedAt: auth.UpdatedAt, + CooldownSignals: cooldownSignals, + ForceCooldownUntil: authForceUntil, + CredQuotaForceCooldownUntil: credQuotaForceUntil, + ForceCooldownEvaluated: true, + CredentialRetryAfter: credentialRetryAfter, }, true } @@ -811,20 +1366,45 @@ func modelCooldownStateRecord(auth *Auth, model string, state *ModelState, now t if auth == nil || state == nil || model == "" || !state.Unavailable || state.NextRetryAfter.IsZero() || !state.NextRetryAfter.After(now) { return CooldownStateRecord{}, false } + var cooldownSignals map[string]string + liveCredentialWrap := auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) + expiredCredentialWrap := (state.credentialQuotaPropagated || state.Quota.Reason == "credential_quota") && !liveCredentialWrap + if !expiredCredentialWrap && state.Quota.Exceeded && state.Quota.NextRecoverAt.After(now) && + (state.Quota.Reason == "credential_quota" || !state.NextRetryAfter.After(state.Quota.NextRecoverAt)) { + cooldownSignals = sanitizePersistedClaudeCooldownSignals(state.Quota.cooldownSignals) + } + var outerForceUntil time.Time + if liveCredentialWrap { + if u := effectiveCredQuotaForceUntil(auth); u.After(now) { + outerForceUntil = u + } + } else if u := effectiveModelForceUntil(state); u.After(now) { + outerForceUntil = u + } record := CooldownStateRecord{ - Provider: strings.TrimSpace(auth.Provider), - AuthID: auth.ID, - AuthFile: cooldownAuthFile(auth), - Model: model, - Status: "cooling", - NextRetryAfter: state.NextRetryAfter, - Reason: cooldownReason(state.StatusMessage, state.Quota, state.LastError), - Quota: cooldownFieldsOf(state.Quota), - LastError: cloneError(state.LastError), - UpdatedAt: state.UpdatedAt, + Provider: strings.TrimSpace(auth.Provider), + AuthID: auth.ID, + AuthFile: cooldownAuthFile(auth), + Model: model, + Status: "cooling", + NextRetryAfter: state.NextRetryAfter, + Reason: cooldownReason(state.StatusMessage, state.Quota, state.LastError), + Quota: cooldownFieldsOf(state.Quota), + LastError: cloneError(state.LastError), + UpdatedAt: state.UpdatedAt, + CooldownSignals: cooldownSignals, + ForceCooldownUntil: outerForceUntil, + ForceCooldownEvaluated: true, } if state.credentialQuotaShadow != nil { record.IndependentState = state.credentialQuotaShadow.cloneShallow() + if u := effectiveModelForceUntil(state.credentialQuotaShadow); u.After(now) { + record.IndependentForceCooldownUntil = u + } + if state.credentialQuotaShadow.Quota.Exceeded && state.credentialQuotaShadow.Quota.NextRecoverAt.After(now) && + !state.credentialQuotaShadow.NextRetryAfter.After(state.credentialQuotaShadow.Quota.NextRecoverAt) { + record.IndependentCooldownSignals = sanitizePersistedClaudeCooldownSignals(state.credentialQuotaShadow.Quota.cooldownSignals) + } } record.CredentialQuotaPropagated = state.credentialQuotaPropagated return record, true @@ -851,6 +1431,12 @@ func cooldownReason(statusMessage string, quota QuotaState, lastErr *Error) stri // nextExecutionSeq stamps a new upstream dispatch with the next monotonic // execution sequence. The stamp travels on the execution's Result so that // MarkResult can order the execution against cooldowns recorded meanwhile. +// NextExecutionSeq allocates the next monotonic execution sequence number for +// ordering concurrent MarkResult updates against newly recorded cooldowns. +func (m *Manager) NextExecutionSeq() uint64 { + return m.nextExecutionSeq() +} + func (m *Manager) nextExecutionSeq() uint64 { if m == nil { return 0 @@ -881,6 +1467,23 @@ func isStaleExecutionResult(result Result, current *Auth) bool { if result.AccessToken != "" && authMatchesTokenPartition(current, result.AccessToken) { return false } + if isTOSViolationResultError(result.Error) { + // A service-scoped TOS suspension applies to the account, so a plain OAuth + // access-token refresh (same credential, refresh token retained) must not + // discard the terminal signal. A genuine credential replacement under the + // same auth ID is a different account: an old request's TOS result must + // not disable the fresh credential. The access token alone cannot tell + // these apart, so exempt only when the refresh credential proves the same + // account (identical refresh token) or the result carries no account hint + // (internal/token-less paths where replacement cannot be detected). + if result.AccessToken == "" { + return false + } + refreshNow := authRefreshToken(current) + if refreshNow != "" && result.RefreshToken != "" && refreshNow == result.RefreshToken { + return false + } + } staleVersion := result.CredentialVersion < current.CredentialVersion && (result.CredentialVersion > 0 || current.CredentialVersion > 1) return staleVersion } @@ -938,12 +1541,18 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } now = time.Now() responseHeaders := internallogging.GetResponseHeaders(ctx) - modelState := existingModelState(auth, modelKey) var cooldownRecordsBefore []CooldownStateRecord trackCooldownState := m.cooldownStore != nil if trackCooldownState { cooldownRecordsBefore = m.cooldownStateRecordsForAuthLocked(auth, now) } + if m != nil { + _ = m.migrateAuthAliasModelStatesLocked(auth, nil, now, false) + if modelKey != "" { + modelKey = m.resolveMarkResultModelKeyLocked(auth, modelKey, result.RouteModel) + } + } + modelState := existingModelState(auth, modelKey) auth.recordRecentRequest(now, result.Success) if result.Success { auth.Success++ @@ -967,9 +1576,12 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } retainAuthCooldown := modelKey == "" && !wasTerminalUnauthorized && result.ExecutionSeq > 0 && isAuthActiveCooldown(auth, now) && auth.cooldownRecordedSeq > 0 && result.ExecutionSeq <= auth.cooldownRecordedSeq + retainCredentialRetry := !wasTerminalUnauthorized && result.ExecutionSeq > 0 && + !auth.credentialRetryAfter.IsZero() && auth.credentialRetryAfter.After(now) && + auth.cooldownRecordedSeq > 0 && result.ExecutionSeq <= auth.cooldownRecordedSeq if result.Success { - if result.CompletedResponse && !result.SkipQuotaObservation && !wasTerminalUnauthorized && !(auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now)) && !retainModelCooldown && !retainAuthCooldown { + if result.CompletedResponse && !result.SkipQuotaObservation && !wasTerminalUnauthorized && !(auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now)) && !retainModelCooldown && !retainAuthCooldown && !retainCredentialRetry { auth.InferenceVerified = true auth.LastInferenceVerifiedAt = now } @@ -981,24 +1593,29 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } } else if auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { // Retain active credential-scoped cooldown - } else if retainModelCooldown || retainAuthCooldown { + } else if retainModelCooldown || retainAuthCooldown || retainCredentialRetry { // Retain a cooldown recorded after this execution was dispatched. } else if modelKey != "" { state := ensureModelState(auth, modelKey) modelState = state resetModelState(state, now) + auth.credentialRetryAfter = time.Time{} updateAggregatedAvailability(auth, now) - if !hasModelError(auth, now) { + if !auth.Disabled && !hasModelError(auth, now) && !effectiveAuthForceUntil(auth).After(now) { auth.LastError = nil auth.StatusMessage = "" auth.Status = StatusActive } - } else { + } else if !auth.Disabled { clearAuthStateOnSuccess(auth, now) } } else { if modelKey != "" { - if !shouldSkipCredentialCooldown(result.Error) { + if auth.Disabled || auth.Status == StatusDisabled { + // A disabled credential (operator action or terminal TOS) is + // terminal until explicitly re-enabled; a late failure must not + // overwrite its disabled state or arm a new cooldown. + } else if !shouldSkipCredentialCooldown(result.Error) { disableCooling := m.cooldownDisabledForAuth(auth) if result.Error != nil && result.Error.Code == ErrorCodeForceCooldown { disableCooling = false @@ -1040,10 +1657,18 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { *state = *fresh } } + seedInitialForceCooldownDeadlines(auth) + seedModelForceCooldownDeadline(state) state.Unavailable = true state.Status = StatusError state.UpdatedAt = now prevModelRetryAfter := state.NextRetryAfter + prevModelForceUntil := state.forceCooldownUntil + prevModelQuota := cooldownFieldsOf(state.Quota) + prevModelQuotaSignals := maps.Clone(state.Quota.cooldownSignals) + var ownModelForceDeadline time.Time + isForceResult := isForceCooldownError(result.Error) + appliedCredQuotaWrap := false if result.Error != nil { state.LastError = cloneError(result.Error) state.StatusMessage = result.Error.Message @@ -1082,7 +1707,7 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } else { state.NextRetryAfter = now.Add(30 * time.Minute) } - } else if isTransientRateLimitResultError(result.Error) && statusCode == http.StatusTooManyRequests { + } else if !result.CredentialScope && isTransientRateLimitResultError(result.Error) && statusCode == http.StatusTooManyRequests { // Transient per-turn capacity rejection (issue 7017): cool // only the reporting model until the provider retry hint. // The credential quota is not exhausted, so no quota state @@ -1090,6 +1715,9 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { // a still-live genuine quota deadline is left untouched and // keeps blocking through the generic retry branches below. next := transientRateLimitRetryAfter(now, result.RetryAfter, disableCooling) + if isForceResult { + ownModelForceDeadline = next + } if !next.IsZero() && state.Quota.Exceeded && state.Quota.NextRecoverAt.After(next) { next = state.Quota.NextRecoverAt } @@ -1098,6 +1726,14 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } state.NextRetryAfter = next state.Unavailable = !next.IsZero() + } else if isTOSViolationResultError(result.Error) { + // Terminal TOS suspension: keep the model state blocked + // without a retry deadline; the auth-level terminal state + // is finalized below. + state.NextRetryAfter = time.Time{} + state.Unavailable = true + state.Status = StatusDisabled + state.StatusMessage = "tos_violation" } else { switch statusCode { case 401, 402, 403: @@ -1117,8 +1753,12 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { state.NextRetryAfter = next } case 429: + prevStateQuotaActive := state.Quota.Exceeded && state.Quota.NextRecoverAt.After(now) + prevStateRecoverAt := state.Quota.NextRecoverAt + prevStateCooldownSignals := maps.Clone(state.Quota.cooldownSignals) var next time.Time var credentialNext time.Time + keptPriorStateQuota := false backoffLevel := state.Quota.BackoffLevel if result.CredentialScope { backoffLevel = 0 @@ -1127,6 +1767,8 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } } if !disableCooling { + reusedOpenWindow := false + var baseBackoffBefore int if result.RetryAfter != nil { cooldown := *result.RetryAfter if cooldown < minQuotaCooldownFloor { @@ -1143,19 +1785,52 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { quotaForFailure.BackoffLevel = 0 } } + reusedOpenWindow = quotaForFailure.NextRecoverAt.After(now) + baseBackoffBefore = quotaForFailure.BackoffLevel next, backoffLevel = quotaCooldownAfterFailure(quotaForFailure, now) } credentialNext = next - if state.Quota.Exceeded && state.Quota.NextRecoverAt.After(next) { - next = state.Quota.NextRecoverAt + if isForceResult { + if result.RetryAfter != nil || !reusedOpenWindow { + ownModelForceDeadline = credentialNext + } else if result.CredentialScope { + if auth.credQuotaForceUntil.After(now) { + ownModelForceDeadline = auth.credQuotaForceUntil + } else { + ownModelForceDeadline, _ = quotaCooldownAfterFailure(QuotaState{BackoffLevel: baseBackoffBefore}, now) + } + } else if prevModelForceUntil.After(now) { + ownModelForceDeadline = prevModelForceUntil + } else { + ownModelForceDeadline, _ = quotaCooldownAfterFailure(QuotaState{BackoffLevel: baseBackoffBefore}, now) + } + } + if prevStateQuotaActive && (prevStateRecoverAt.After(next) || (!result.CredentialScope && result.RetryAfter == nil)) { + next = prevStateRecoverAt + keptPriorStateQuota = true + } else if result.CredentialScope && result.RetryAfter == nil && auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { + // quotaCooldownAfterFailure reused the open credential_quota window. + keptPriorStateQuota = prevStateQuotaActive && prevStateRecoverAt.Equal(next) + } + } + var cooldownSignals map[string]string + if !disableCooling { + if keptPriorStateQuota { + cooldownSignals = prevStateCooldownSignals + } else { + cooldownSignals = rejectedClaudeSignalsForCooldown(result.Provider, responseHeaders) + if len(cooldownSignals) == 0 && prevStateQuotaActive && prevStateRecoverAt.Equal(next) { + cooldownSignals = prevStateCooldownSignals + } } } state.NextRetryAfter = next applyCooldownFields(&state.Quota, QuotaState{ - Exceeded: true, - Reason: "quota", - NextRecoverAt: next, - BackoffLevel: backoffLevel, + Exceeded: true, + Reason: "quota", + NextRecoverAt: next, + BackoffLevel: backoffLevel, + cooldownSignals: cooldownSignals, }) // Non-credential own failures re-derive their independent layer // below, so a stale shadow is dropped. A credential-scoped @@ -1163,7 +1838,7 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { // refreshes the propagated outer layer. if !result.CredentialScope { state.credentialQuotaShadow = nil - } else if !state.credentialQuotaPropagated && savedOuterState.Quota.Reason != "credential_quota" { + } else if !disableCooling && !state.credentialQuotaPropagated && savedOuterState.Quota.Reason != "credential_quota" { // First wrap of the reporting model: preserve any live prior // own block (including an ordinary model-scoped 429, which // quota restoration does not supersede). An outer @@ -1181,68 +1856,44 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } } if result.CredentialScope && !disableCooling { - for _, otherState := range auth.ModelStates { - if otherState != nil && otherState != state { - // Normalize a naturally expired wrap first (issue #6690) so a - // stale marker cannot suppress snapshotting a fresh block. - if (otherState.credentialQuotaPropagated || otherState.Quota.Reason == "credential_quota") && - !(auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now)) { - if shadow := otherState.credentialQuotaShadow; shadow != nil && isModelStateActiveCooldown(shadow, now) { - preservedSeq := shadow.cooldownRecordedSeq - *otherState = *shadow.cloneShallow() - otherState.cooldownRecordedSeq = preservedSeq - } else { - resetModelState(otherState, now) - } - } - // On first wrap, preserve the sibling's independent layer - // beneath the propagated credential quota (issue #6690): - // a live own block is snapshotted; healthy/propagated-only - // states get none. The marker keeps repeated propagation - // from mistaking its own earlier layer for independence. - alreadyPropagated := otherState.credentialQuotaPropagated || - otherState.Quota.Reason == "credential_quota" - if !alreadyPropagated { - if isModelStateActiveCooldown(otherState, now) && !isDevinQuotaExhaustionMessage(devinStateErrorText(otherState)) { - otherState.credentialQuotaShadow = otherState.cloneShallow() - } else { - otherState.credentialQuotaShadow = nil - } - } - otherState.credentialQuotaPropagated = true - otherState.Unavailable = true - otherState.Status = StatusError - otherQuotaNext := credentialNext - if otherState.Quota.Exceeded && otherState.Quota.NextRecoverAt.After(otherQuotaNext) { - otherQuotaNext = otherState.Quota.NextRecoverAt - } - otherRetryAfter := otherQuotaNext - // Propagation only extends a sibling's still-live - // per-model deadline; it never shortens one. - if !otherState.NextRetryAfter.IsZero() && otherState.NextRetryAfter.After(otherRetryAfter) { - otherRetryAfter = otherState.NextRetryAfter - } - otherState.NextRetryAfter = otherRetryAfter - applyCooldownFields(&otherState.Quota, QuotaState{ - Exceeded: true, - Reason: "credential_quota", - NextRecoverAt: otherQuotaNext, - BackoffLevel: backoffLevel, - }) + appliedCredQuotaWrap = true + prevAuthCredActive := auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) + prevAuthCredRecoverAt := auth.Quota.NextRecoverAt + prevAuthCredSignals := maps.Clone(auth.Quota.cooldownSignals) + var credCooldownSignals map[string]string + if prevAuthCredActive && (prevAuthCredRecoverAt.After(credentialNext) || result.RetryAfter == nil) { + credCooldownSignals = prevAuthCredSignals + } else { + credCooldownSignals = rejectedClaudeSignalsForCooldown(result.Provider, responseHeaders) + if len(credCooldownSignals) == 0 && prevAuthCredActive && prevAuthCredRecoverAt.Equal(credentialNext) { + credCooldownSignals = prevAuthCredSignals } } + propagateCredentialQuotaToModelStatesLocked(auth, state, credentialNext, backoffLevel, credCooldownSignals, prevAuthCredActive, prevAuthCredRecoverAt, now) if !wasTerminalUnauthorized { auth.Unavailable = true authNext := credentialNext - if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && - auth.Quota.NextRecoverAt.After(authNext) { - authNext = auth.Quota.NextRecoverAt + if prevAuthCredActive && prevAuthCredRecoverAt.After(authNext) { + authNext = prevAuthCredRecoverAt } auth.Quota.Exceeded = true auth.Quota.Reason = "credential_quota" auth.Quota.NextRecoverAt = authNext auth.Quota.BackoffLevel = backoffLevel + auth.Quota.cooldownSignals = maps.Clone(credCooldownSignals) + auth.Quota.cooldownEvaluated = true auth.NextRetryAfter = authNext + if authNext.After(state.Quota.NextRecoverAt) || (prevAuthCredActive && result.RetryAfter == nil) { + state.Quota.NextRecoverAt = authNext + state.Quota.cooldownSignals = maps.Clone(credCooldownSignals) + if state.NextRetryAfter.Before(authNext) { + state.NextRetryAfter = authNext + } + } + if isForceResult && ownModelForceDeadline.After(auth.credQuotaForceUntil) { + auth.credQuotaForceUntil = ownModelForceDeadline + } + auth.forceCooldownSeeded = true // The reporting model is now part of the wrap too: mark it // so a later credential report from another model cannot // snapshot this credential-derived state as independent. @@ -1262,10 +1913,54 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { state.Unavailable = false state.Quota.Exceeded = false } - if result.Error != nil && result.Error.Code == ErrorCodeForceCooldown && state.NextRetryAfter.IsZero() { + if isForceResult && state.NextRetryAfter.IsZero() { state.NextRetryAfter = now.Add(transientErrorCooldown) state.Unavailable = true } + if !appliedCredQuotaWrap { + if result.CredentialScope && auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.credQuotaForceUntil.After(now) && auth.Quota.NextRecoverAt.After(now) { + lastErr := cloneError(state.LastError) + statusMsg := state.StatusMessage + *state = *savedOuterState + state.LastError = lastErr + state.StatusMessage = statusMsg + state.Unavailable = true + state.Status = StatusError + if state.NextRetryAfter.Before(auth.credQuotaForceUntil) { + state.NextRetryAfter = auth.credQuotaForceUntil + } + state.UpdatedAt = now + } else { + if isForceResult { + if ownModelForceDeadline.IsZero() { + ownModelForceDeadline = state.NextRetryAfter + } + if ownModelForceDeadline.After(prevModelForceUntil) { + state.forceCooldownUntil = ownModelForceDeadline + } else { + state.forceCooldownUntil = prevModelForceUntil + } + } else { + state.forceCooldownUntil = prevModelForceUntil + } + state.forceCooldownSeeded = true + if state.forceCooldownUntil.After(now) { + if state.NextRetryAfter.Before(state.forceCooldownUntil) { + state.NextRetryAfter = state.forceCooldownUntil + } + state.Unavailable = true + state.Status = StatusError + if (!state.Quota.Exceeded || state.Quota.NextRecoverAt.IsZero()) && prevModelQuota.Exceeded && prevModelQuota.NextRecoverAt.After(now) { + restored := prevModelQuota + if disableCooling && restored.NextRecoverAt.After(state.forceCooldownUntil) { + restored.NextRecoverAt = state.forceCooldownUntil + } + restored.cooldownSignals = prevModelQuotaSignals + applyCooldownFields(&state.Quota, restored) + } + } + } + } // A later failure only extends a still-live cooldown; it never // shortens one. A deliberate zero write (disableCooling) still // clears the deadline. @@ -1304,10 +1999,11 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } if !(outer.Quota.Exceeded && outer.Quota.Reason == "credential_quota") { applyCooldownFields(&outer.Quota, QuotaState{ - Exceeded: true, - Reason: "credential_quota", - NextRecoverAt: auth.Quota.NextRecoverAt, - BackoffLevel: auth.Quota.BackoffLevel, + Exceeded: true, + Reason: "credential_quota", + NextRecoverAt: auth.Quota.NextRecoverAt, + BackoffLevel: auth.Quota.BackoffLevel, + cooldownSignals: auth.Quota.cooldownSignals, }) } *outerState = *outer @@ -1322,7 +2018,16 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { } } } - auth.Status = StatusError + if isTOSViolationResultError(result.Error) { + auth.StatusMessage = "tos_violation" + auth.Status = StatusDisabled + auth.Disabled = true + auth.Unavailable = true + auth.NextRetryAfter = time.Time{} + persistTOSAppealMetadata(auth, result.Error) + } else { + auth.Status = StatusError + } updateAggregatedAvailability(auth, now) } } else { @@ -1330,9 +2035,95 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { if result.Error != nil && result.Error.Code == ErrorCodeForceCooldown { disableCooling = false } - if !wasTerminalUnauthorized { - applyAuthFailureState(auth, result.Error, result.RetryAfter, now, disableCooling) - auth.cooldownRecordedSeq = m.currentExecutionSeq() + if auth.Disabled || auth.Status == StatusDisabled { + // A disabled credential (operator action or terminal TOS) is + // terminal until explicitly re-enabled; a late auth-level failure + // must not overwrite its disabled state or arm a new cooldown. + } else if !wasTerminalUnauthorized { + prevAuthCredActive := auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) + prevAuthCredRecoverAt := auth.Quota.NextRecoverAt + prevAuthCredSignals := maps.Clone(auth.Quota.cooldownSignals) + isolatedModelAgg := result.CredentialScope && len(auth.ModelStates) > 0 && auth.Quota.Reason != "credential_quota" + var savedModelAggQuota QuotaState + if isolatedModelAgg { + savedModelAggQuota = auth.Quota.Clone() + authOwnRetry := auth.credentialRetryAfter + if activeAuthForce := effectiveAuthForceUntil(auth); activeAuthForce.After(authOwnRetry) { + authOwnRetry = activeAuthForce + } + auth.NextRetryAfter = authOwnRetry + auth.Quota = QuotaState{ + ObservedAt: savedModelAggQuota.ObservedAt, + Signals: maps.Clone(savedModelAggQuota.Signals), + } + } + prevAuthQuotaActive := auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(now) + prevAuthRecoverAt := auth.Quota.NextRecoverAt + prevAuthCooldownSignals := maps.Clone(auth.Quota.cooldownSignals) + keptPriorAuthQuota := false + if !disableCooling && statusCodeFromResult(result.Error) == 429 && prevAuthQuotaActive { + if result.RetryAfter == nil { + keptPriorAuthQuota = true + } else { + cooldown := *result.RetryAfter + if cooldown < minQuotaCooldownFloor { + cooldown = minQuotaCooldownFloor + } + if prevAuthRecoverAt.After(now.Add(cooldown).Round(0)) { + keptPriorAuthQuota = true + } + } + } + ownAuthForceDeadline, ownAuthRetryDeadline := applyAuthFailureState(auth, result.Error, result.RetryAfter, now, disableCooling) + cooldownSeq := m.currentExecutionSeq() + isQuota429 := !disableCooling && + statusCodeFromResult(result.Error) == 429 && + !isTransientRateLimitResultError(result.Error) && + !isCloudflareChallengeResultError(result.Error) && + !isCreditBalanceTooLowResultError(result.Error) && + !isInvalidGrantResultError(result.Error) && + auth.Quota.Exceeded + if isQuota429 { + auth.Quota.cooldownEvaluated = true + if keptPriorAuthQuota { + auth.Quota.cooldownSignals = prevAuthCooldownSignals + } else if rejectedSignals := rejectedClaudeSignalsForCooldown(result.Provider, responseHeaders); len(rejectedSignals) > 0 { + auth.Quota.cooldownSignals = rejectedSignals + } else if prevAuthQuotaActive && auth.Quota.NextRecoverAt.Equal(prevAuthRecoverAt) { + auth.Quota.cooldownSignals = prevAuthCooldownSignals + } else { + auth.Quota.cooldownSignals = nil + } + if result.CredentialScope && !shouldSkipCredentialCooldown(result.Error) { + auth.Quota.Reason = "credential_quota" + if isForceCooldownError(result.Error) && ownAuthForceDeadline.After(auth.credQuotaForceUntil) { + auth.credQuotaForceUntil = ownAuthForceDeadline + auth.forceCooldownSeeded = true + } + credSignals := auth.Quota.cooldownSignals + if prevAuthCredActive && (prevAuthCredRecoverAt.After(auth.Quota.NextRecoverAt) || result.RetryAfter == nil) { + credSignals = prevAuthCredSignals + } + propagateCredentialQuotaToModelStatesLocked(auth, nil, auth.Quota.NextRecoverAt, auth.Quota.BackoffLevel, credSignals, prevAuthCredActive, prevAuthCredRecoverAt, now) + for _, otherState := range auth.ModelStates { + if otherState != nil { + otherState.cooldownRecordedSeq = cooldownSeq + } + } + } + } else { + if result.CredentialScope && !disableCooling && !shouldSkipCredentialCooldown(result.Error) && !ownAuthRetryDeadline.IsZero() && ownAuthRetryDeadline.After(now) { + if ownAuthRetryDeadline.After(auth.credentialRetryAfter) { + auth.credentialRetryAfter = ownAuthRetryDeadline + } + } + if isolatedModelAgg && !isCloudflareChallengeResultError(result.Error) { + savedModelAggQuota.Signals = mergeQuotaObservation(auth.Quota, savedModelAggQuota).Signals + applyCooldownFields(&auth.Quota, savedModelAggQuota) + updateAggregatedAvailability(auth, now) + } + } + auth.cooldownRecordedSeq = cooldownSeq } } } @@ -1349,6 +2140,10 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { auth.Status = StatusError auth.NextRefreshAfter = time.Time{} auth.NextRetryAfter = time.Time{} + } else if auth.Status == StatusDisabled { + // A terminal TOS_VIOLATION already deactivated the credential inside + // applyAuthFailureState; preserve that state instead of overwriting + // it with a generic error status. } else if rejectsToken && authHasRefreshCredential(auth) { if auth.NextRefreshAfter.IsZero() { if !auth.LastRefreshedAt.IsZero() && now.Sub(auth.LastRefreshedAt) < refreshFailureBackoff { @@ -1384,7 +2179,7 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) { var targetModels []string if !credentialScopedResult && modelKey != "" { targetModels = append(targetModels, modelKey) - if routeKey := canonicalModelKey(result.RouteModel); routeKey != "" && routeKey != modelKey { + if routeKey := canonicalModelKey(result.RouteModel); routeKey != "" && !sameCanonicalModelKey(routeKey, modelKey) { targetModels = append(targetModels, routeKey) } } @@ -1444,6 +2239,9 @@ func (m *Manager) recordExecutionResult(ctx context.Context, result Result, auth if result.AccessToken == "" { result.AccessToken = authAccessTokenForRequest(ctx, auth, result.Options.Headers) } + if result.RefreshToken == "" { + result.RefreshToken = authRefreshToken(auth) + } } if !ephemeral { m.MarkResult(ctx, result) @@ -1504,10 +2302,28 @@ func (m *Manager) recordAvailabilityNeutralResult(ctx context.Context, result Re func existingModelState(auth *Auth, model string) *ModelState { model = canonicalModelKey(model) - if auth == nil || model == "" { + if auth == nil || model == "" || len(auth.ModelStates) == 0 { return nil } - return auth.ModelStates[model] + if state, ok := auth.ModelStates[model]; ok && state != nil { + return state + } + lookupKey := canonicalModelLookupKey(model) + if lookupKey == "" { + return nil + } + var matched *ModelState + for stateModel, state := range auth.ModelStates { + if state == nil || canonicalModelLookupKey(stateModel) != lookupKey { + continue + } + if matched == nil { + matched = state + } else { + matched = mergeModelState(matched.Clone(), state) + } + } + return matched } func ensureModelState(auth *Auth, model string) *ModelState { @@ -1522,6 +2338,12 @@ func ensureModelState(auth *Auth, model string) *ModelState { if state, ok := auth.ModelStates[model]; ok && state != nil { return state } + lookupKey := canonicalModelLookupKey(model) + for stateModel, state := range auth.ModelStates { + if canonicalModelLookupKey(stateModel) == lookupKey && state != nil { + return state + } + } state := &ModelState{Status: StatusActive} auth.ModelStates[model] = state return state @@ -1531,9 +2353,18 @@ func normalizeModelStates(auth *Auth) bool { if auth == nil || len(auth.ModelStates) == 0 { return false } + keys := make([]string, 0, len(auth.ModelStates)) + for model := range auth.ModelStates { + keys = append(keys, model) + } + if len(keys) > 1 { + sort.Strings(keys) + } normalized := make(map[string]*ModelState, len(auth.ModelStates)) + keyByLookup := make(map[string]string, len(auth.ModelStates)) changed := false - for model, state := range auth.ModelStates { + for _, model := range keys { + state := auth.ModelStates[model] modelKey := canonicalModelKey(model) if modelKey == "" { modelKey = strings.TrimSpace(model) @@ -1541,11 +2372,27 @@ func normalizeModelStates(auth *Auth) bool { if modelKey != model { changed = true } - if existing, ok := normalized[modelKey]; ok { - normalized[modelKey] = mergeModelState(existing, state) + lookupKey := canonicalModelLookupKey(modelKey) + if lookupKey == "" { + lookupKey = strings.ToLower(modelKey) + } + if existingKey, ok := keyByLookup[lookupKey]; ok { + var existingClone *ModelState + if normalized[existingKey] != nil { + existingClone = normalized[existingKey].Clone() + } + merged := mergeModelState(existingClone, state) + targetKey := existingKey + if modelKey == lookupKey && existingKey != lookupKey { + delete(normalized, existingKey) + targetKey = modelKey + keyByLookup[lookupKey] = targetKey + } + normalized[targetKey] = merged changed = true continue } + keyByLookup[lookupKey] = modelKey normalized[modelKey] = state } if changed { @@ -1575,15 +2422,25 @@ func mergeModelState(target, source *ModelState) *ModelState { NextRetryAfter: target.NextRetryAfter, LastError: cloneError(preferred.LastError), Quota: QuotaState{ - Exceeded: target.Quota.Exceeded || source.Quota.Exceeded, - Reason: preferred.Quota.Reason, - NextRecoverAt: target.Quota.NextRecoverAt, - BackoffLevel: target.Quota.BackoffLevel, + Exceeded: target.Quota.Exceeded || source.Quota.Exceeded, + Reason: preferred.Quota.Reason, + NextRecoverAt: target.Quota.NextRecoverAt, + BackoffLevel: target.Quota.BackoffLevel, + cooldownEvaluated: target.Quota.cooldownEvaluated || source.Quota.cooldownEvaluated, }, UpdatedAt: target.UpdatedAt, } merged.Quota = mergeQuotaObservation(merged.Quota, fallback.Quota) merged.Quota = mergeQuotaObservation(merged.Quota, preferred.Quota) + if source.Quota.NextRecoverAt.After(target.Quota.NextRecoverAt) { + merged.Quota.cooldownSignals = maps.Clone(source.Quota.cooldownSignals) + } else if target.Quota.NextRecoverAt.After(source.Quota.NextRecoverAt) { + merged.Quota.cooldownSignals = maps.Clone(target.Quota.cooldownSignals) + } else if len(preferred.Quota.cooldownSignals) > 0 { + merged.Quota.cooldownSignals = maps.Clone(preferred.Quota.cooldownSignals) + } else if len(fallback.Quota.cooldownSignals) > 0 { + merged.Quota.cooldownSignals = maps.Clone(fallback.Quota.cooldownSignals) + } if source.NextRetryAfter.After(merged.NextRetryAfter) { merged.NextRetryAfter = source.NextRetryAfter } @@ -1604,6 +2461,11 @@ func mergeModelState(target, source *ModelState) *ModelState { if source.cooldownRecordedSeq > merged.cooldownRecordedSeq { merged.cooldownRecordedSeq = source.cooldownRecordedSeq } + merged.forceCooldownUntil = target.forceCooldownUntil + if source.forceCooldownUntil.After(merged.forceCooldownUntil) { + merged.forceCooldownUntil = source.forceCooldownUntil + } + merged.forceCooldownSeeded = target.forceCooldownSeeded || source.forceCooldownSeeded if merged.StatusMessage == "" { merged.StatusMessage = fallback.StatusMessage } @@ -1625,12 +2487,12 @@ func mergeModelState(target, source *ModelState) *ModelState { if merged.Quota.Reason == "credential_quota" || merged.Quota.Reason == "quota" || target.credentialQuotaPropagated || source.credentialQuotaPropagated || target.credentialQuotaShadow != nil || source.credentialQuotaShadow != nil { - shadow := fallback.credentialQuotaShadow - if preferred.credentialQuotaShadow != nil { - shadow = preferred.credentialQuotaShadow - } - if shadow != nil { - merged.credentialQuotaShadow = shadow.cloneShallow() + if target.credentialQuotaShadow != nil && source.credentialQuotaShadow != nil { + merged.credentialQuotaShadow = mergeModelState(target.credentialQuotaShadow.cloneShallow(), source.credentialQuotaShadow.cloneShallow()) + } else if preferred.credentialQuotaShadow != nil { + merged.credentialQuotaShadow = preferred.credentialQuotaShadow.cloneShallow() + } else if fallback.credentialQuotaShadow != nil { + merged.credentialQuotaShadow = fallback.credentialQuotaShadow.cloneShallow() } merged.credentialQuotaPropagated = target.credentialQuotaPropagated || source.credentialQuotaPropagated } @@ -1649,6 +2511,7 @@ func resetModelState(state *ModelState, now time.Time) { state.LastError = nil applyCooldownFields(&state.Quota, QuotaState{}) state.cooldownRecordedSeq = 0 + state.forceCooldownUntil = time.Time{} state.credentialQuotaShadow = nil state.credentialQuotaPropagated = false state.UpdatedAt = now @@ -1688,7 +2551,7 @@ func (m *Manager) registryModelsForAuthAndModel(auth *Auth, authID, modelKey str return nil } - targetCanonical := canonicalModelKey(modelKey) + targetCanonical := canonicalModelLookupKey(modelKey) supportedModels := registry.GetGlobalRegistry().GetModelsForClient(authID) if len(supportedModels) == 0 { return nil @@ -1709,7 +2572,7 @@ func (m *Manager) registryModelsForAuthAndModel(auth *Auth, authID, modelKey str if stateKey == "" { stateKey = canonicalModelKey(regModelID) } - if stateKey == targetCanonical { + if canonicalModelLookupKey(stateKey) == targetCanonical { if _, exists := seen[regModelID]; !exists { seen[regModelID] = struct{}{} out = append(out, regModelID) @@ -1751,9 +2614,33 @@ func updateAggregatedAvailability(auth *Auth, now time.Time) { } if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { auth.Unavailable = true + if activeAuthForce := effectiveAuthForceUntil(auth); activeAuthForce.After(now) && auth.NextRetryAfter.Before(activeAuthForce) { + auth.NextRetryAfter = activeAuthForce + } return } + activeAuthForce := effectiveAuthForceUntil(auth) + if !activeAuthForce.After(now) && !auth.forceCooldownUntil.IsZero() { + auth.forceCooldownUntil = time.Time{} + } + if !auth.credentialRetryAfter.IsZero() && !auth.credentialRetryAfter.After(now) { + auth.credentialRetryAfter = time.Time{} + } if len(auth.ModelStates) == 0 { + if activeAuthForce.After(now) { + auth.Unavailable = true + if auth.NextRetryAfter.Before(activeAuthForce) { + auth.NextRetryAfter = activeAuthForce + } + return + } + if auth.credentialRetryAfter.After(now) { + auth.Unavailable = true + if auth.NextRetryAfter.Before(auth.credentialRetryAfter) { + auth.NextRetryAfter = auth.credentialRetryAfter + } + return + } clearAggregatedAvailability(auth) return } @@ -1798,6 +2685,20 @@ func updateAggregatedAvailability(auth *Auth, now time.Time) { } } if !hasState { + if activeAuthForce.After(now) { + auth.Unavailable = true + if auth.NextRetryAfter.Before(activeAuthForce) { + auth.NextRetryAfter = activeAuthForce + } + return + } + if auth.credentialRetryAfter.After(now) { + auth.Unavailable = true + if auth.NextRetryAfter.Before(auth.credentialRetryAfter) { + auth.NextRetryAfter = auth.credentialRetryAfter + } + return + } clearAggregatedAvailability(auth) return } @@ -1807,6 +2708,18 @@ func updateAggregatedAvailability(auth *Auth, now time.Time) { } else { auth.NextRetryAfter = time.Time{} } + if activeAuthForce.After(now) { + auth.Unavailable = true + if auth.NextRetryAfter.Before(activeAuthForce) { + auth.NextRetryAfter = activeAuthForce + } + } + if auth.credentialRetryAfter.After(now) { + auth.Unavailable = true + if auth.NextRetryAfter.Before(auth.credentialRetryAfter) { + auth.NextRetryAfter = auth.credentialRetryAfter + } + } if quotaExceeded { auth.Quota.Exceeded = true auth.Quota.Reason = "quota" @@ -1818,10 +2731,7 @@ func updateAggregatedAvailability(auth *Auth, now time.Time) { } else if auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(now) { // Retain active auth-level quota cooldown } else { - auth.Quota.Exceeded = false - auth.Quota.Reason = "" - auth.Quota.NextRecoverAt = time.Time{} - auth.Quota.BackoffLevel = 0 + applyCooldownFields(&auth.Quota, QuotaState{}) } } @@ -1854,6 +2764,69 @@ func hasModelError(auth *Auth, now time.Time) bool { return false } +func propagateCredentialQuotaToModelStatesLocked(auth *Auth, exclude *ModelState, credentialNext time.Time, backoffLevel int, credCooldownSignals map[string]string, prevAuthCredActive bool, prevAuthCredRecoverAt time.Time, now time.Time) { + if auth == nil { + return + } + for _, otherState := range auth.ModelStates { + if otherState == nil || otherState == exclude { + continue + } + // Normalize a naturally expired wrap first (issue #6690) so a + // stale marker cannot suppress snapshotting a fresh block. + if (otherState.credentialQuotaPropagated || otherState.Quota.Reason == "credential_quota") && + !prevAuthCredActive { + if shadow := otherState.credentialQuotaShadow; shadow != nil && isModelStateActiveCooldown(shadow, now) { + preservedSeq := shadow.cooldownRecordedSeq + *otherState = *shadow.cloneShallow() + otherState.cooldownRecordedSeq = preservedSeq + } else { + resetModelState(otherState, now) + } + } + // On first wrap, preserve the sibling's independent layer + // beneath the propagated credential quota (issue #6690): + // a live own block is snapshotted; healthy/propagated-only + // states get none. The marker keeps repeated propagation + // from mistaking its own earlier layer for independence. + alreadyPropagated := otherState.credentialQuotaPropagated || + otherState.Quota.Reason == "credential_quota" + if !alreadyPropagated { + if isModelStateActiveCooldown(otherState, now) && !isDevinQuotaExhaustionMessage(devinStateErrorText(otherState)) { + otherState.credentialQuotaShadow = otherState.cloneShallow() + } else { + otherState.credentialQuotaShadow = nil + } + } + otherState.credentialQuotaPropagated = true + otherState.Unavailable = true + otherState.Status = StatusError + otherQuotaNext := credentialNext + otherSignals := credCooldownSignals + if prevAuthCredActive && prevAuthCredRecoverAt.After(otherQuotaNext) { + otherQuotaNext = prevAuthCredRecoverAt + } + if otherState.Quota.Exceeded && otherState.Quota.NextRecoverAt.After(otherQuotaNext) { + otherQuotaNext = otherState.Quota.NextRecoverAt + otherSignals = maps.Clone(otherState.Quota.cooldownSignals) + } + otherRetryAfter := otherQuotaNext + // Propagation only extends a sibling's still-live + // per-model deadline; it never shortens one. + if !otherState.NextRetryAfter.IsZero() && otherState.NextRetryAfter.After(otherRetryAfter) { + otherRetryAfter = otherState.NextRetryAfter + } + otherState.NextRetryAfter = otherRetryAfter + applyCooldownFields(&otherState.Quota, QuotaState{ + Exceeded: true, + Reason: "credential_quota", + NextRecoverAt: otherQuotaNext, + BackoffLevel: backoffLevel, + cooldownSignals: otherSignals, + }) + } +} + func clearAuthStateOnSuccess(auth *Auth, now time.Time) { if auth == nil { return @@ -1862,16 +2835,30 @@ func clearAuthStateOnSuccess(auth *Auth, now time.Time) { auth.Unavailable = true return } + for _, state := range auth.ModelStates { + if state == nil { + continue + } + if state.credentialQuotaPropagated || state.Quota.Reason == "credential_quota" { + if shadow := state.credentialQuotaShadow; shadow != nil && isModelStateActiveCooldown(shadow, now) { + preservedSeq := shadow.cooldownRecordedSeq + *state = *shadow.cloneShallow() + state.cooldownRecordedSeq = preservedSeq + } else { + resetModelState(state, now) + } + } + } auth.Unavailable = false auth.Status = StatusActive auth.StatusMessage = "" - auth.Quota.Exceeded = false - auth.Quota.Reason = "" - auth.Quota.NextRecoverAt = time.Time{} - auth.Quota.BackoffLevel = 0 + applyCooldownFields(&auth.Quota, QuotaState{}) auth.LastError = nil auth.NextRetryAfter = time.Time{} auth.cooldownRecordedSeq = 0 + auth.forceCooldownUntil = time.Time{} + auth.credQuotaForceUntil = time.Time{} + auth.credentialRetryAfter = time.Time{} auth.UpdatedAt = now } @@ -1897,12 +2884,7 @@ func cloneError(err *Error) *Error { if err == nil { return nil } - return &Error{ - Code: err.Code, - Message: err.Message, - Retryable: err.Retryable, - HTTPStatus: err.HTTPStatus, - } + return err.Clone() } func errorString(err error) string { @@ -1945,12 +2927,12 @@ func errorCodeFromError(err error) string { } func isRequestScopedError(err error) bool { - if err == nil { + if err == nil || isCredentialScopedError(err) { return false } // A preserved terminal response belongs to this request unless the executor // explicitly classifies the rejection as safe to retry on another credential. - if isRequestTerminatedError(err) && !isCredentialScopedError(err) { + if isRequestTerminatedError(err) { return true } requestErr, ok := errors.AsType[cliproxyexecutor.RequestScopedError](err) @@ -1961,7 +2943,7 @@ func isRequestScopedError(err error) bool { // upstream streams that ended without a terminal frame. Unlike a received // HTTP refusal, the generation was already submitted upstream. func isStreamTruncatedError(err error) bool { - if err == nil { + if err == nil || isCredentialScopedError(err) { return false } truncatedErr, ok := errors.AsType[cliproxyexecutor.StreamTruncatedError](err) @@ -1979,6 +2961,13 @@ func isStreamTruncatedResultError(err *Error) bool { return err != nil && err.Code == streamTruncatedErrorCode } +// ResultErrorFromError classifies an execution or transport error into an auth.Error +// while preserving lifecycle and transient transport classifications so MarkResult +// does not cool credentials on client cancellations or network drops. +func ResultErrorFromError(err error) *Error { + return resultErrorFromError(err) +} + func resultErrorFromError(err error) *Error { if err == nil { return nil @@ -1996,7 +2985,28 @@ func resultErrorFromError(err error) *Error { if resultErr.HTTPStatus == 0 { resultErr.HTTPStatus = statusCodeFromError(err) } + type tosMetadataProvider interface { + TOSAppealMetadata() map[string]string + } + var tmp tosMetadataProvider + if errors.As(err, &tmp) && tmp != nil { + if meta := tmp.TOSAppealMetadata(); len(meta) > 0 { + resultErr.Metadata = meta + } + } switch { + case isCredentialScopedError(err): + // A credential-scoped failure always stays on the credential quota path; + // normalize conflicting model-only or cooldown-skipping codes so MarkResult + // cannot downgrade whole-credential exhaustion. + switch strings.ToLower(strings.TrimSpace(resultErr.Code)) { + case transientRateLimitErrorCode, + requestScopedErrorCode, + streamTruncatedErrorCode, + connectionLifecycleErrorCode, + transientTransportErrorCode: + resultErr.Code = credentialQuotaErrorCode + } case isStreamTruncatedError(err): // Preserve the local truncation classification alongside the public // 502 status so MarkResult can skip credential cooldown. @@ -2232,7 +3242,7 @@ func isTransientTransportMessage(message string) bool { } func isUnauthorizedError(err error) bool { - if err == nil { + if err == nil || codex.IsRefreshPreSendError(err) { return false } if statusCodeFromError(err) == http.StatusUnauthorized { @@ -2367,7 +3377,7 @@ func isTerminalRefreshGrantMessage(message string) bool { } func isTerminalRefreshError(auth *Auth, err error) bool { - if err == nil { + if err == nil || codex.IsRefreshPreSendError(err) { return false } var partErr interface { @@ -2499,7 +3509,8 @@ func retryAfterFromError(err error) *time.Duration { // An expired trusted wrapper reports a negative remaining time; natural // expiry is not an invalid provider hint, so fall through to the wrapped // error's own hint instead of surfacing the negative value. - if _, isTrusted := rap.(*trustedRetryAfterError); isTrusted { + switch rap.(type) { + case *poolCooldownTerminalError, *trustedRetryAfterError: if inner := errors.Unwrap(err); inner != nil { return retryAfterFromError(inner) } @@ -2549,7 +3560,10 @@ func isCredentialScopedError(err error) bool { IsCredentialScoped() bool } var csp credentialScopedProvider - return errors.As(err, &csp) && csp != nil && csp.IsCredentialScoped() + if errors.As(err, &csp) && csp != nil && csp.IsCredentialScoped() { + return true + } + return strings.EqualFold(errorCodeFromError(err), credentialQuotaErrorCode) } func statusCodeFromResult(err *Error) int { @@ -2603,7 +3617,7 @@ func isInvalidGrantErrorMessage(message string) bool { } func isInvalidGrantError(err error) bool { - if err == nil { + if err == nil || codex.IsRefreshPreSendError(err) { return false } if !isInvalidGrantErrorMessage(err.Error()) { @@ -2708,6 +3722,35 @@ func isCloudflareChallengeResultError(err *Error) bool { return isCloudflareChallengeErrorMessage(err.Message) } +// isTOSViolationResultError reports whether the failure is a terminal Antigravity +// Terms-of-Service suspension (403 PERMISSION_DENIED + ErrorInfo reason= +// TOS_VIOLATION). The executor marks these via the tos_violation error code so +// the credential is deactivated instead of cooled; sibling credentials are not +// hammered during an automated sweep. +func isTOSViolationResultError(err *Error) bool { + if err == nil { + return false + } + return strings.EqualFold(strings.TrimSpace(err.Code), "tos_violation") +} + +// persistTOSAppealMetadata copies the appeal detail carried on a TOS_VIOLATION +// result error onto the credential record so the management API can surface it +// for the operator. It is a no-op for errors without appeal metadata. +func persistTOSAppealMetadata(auth *Auth, err *Error) { + if auth == nil || err == nil || len(err.Metadata) == 0 { + return + } + if auth.Metadata == nil { + auth.Metadata = make(map[string]any) + } + for key, value := range err.Metadata { + if trimmed := strings.TrimSpace(value); trimmed != "" { + auth.Metadata[key] = trimmed + } + } +} + func nextCloudflareCooldown(backoffLevel int, disableCooling bool, now time.Time) (time.Time, int) { var next time.Time if !disableCooling { @@ -3066,13 +4109,23 @@ func isRequestInvalidError(err error) bool { return false } -func applyAuthFailureState(auth *Auth, resultErr *Error, retryAfter *time.Duration, now time.Time, disableCooling bool) { +func applyAuthFailureState(auth *Auth, resultErr *Error, retryAfter *time.Duration, now time.Time, disableCooling bool) (time.Time, time.Time) { if auth == nil { - return + return time.Time{}, time.Time{} } + seedInitialForceCooldownDeadlines(auth) prevAuthRetryAfter := auth.NextRetryAfter + prevAuthForceUntil := auth.forceCooldownUntil + prevAuthQuota := cooldownFieldsOf(auth.Quota) + prevAuthQuotaSignals := maps.Clone(auth.Quota.cooldownSignals) + var prevCredQuotaForceUntil time.Time + if prevAuthQuota.Exceeded && prevAuthQuota.Reason == "credential_quota" && prevAuthQuota.NextRecoverAt.After(now) && auth.credQuotaForceUntil.After(now) { + prevCredQuotaForceUntil = auth.credQuotaForceUntil + } + var ownAuthForceDeadline time.Time + isForceAuth := isForceCooldownError(resultErr) if shouldSkipCredentialCooldown(resultErr) { - return + return time.Time{}, time.Time{} } defer func() { if disableCooling && auth.NextRetryAfter.IsZero() && auth.Quota.NextRecoverAt.IsZero() { @@ -3094,6 +4147,9 @@ func applyAuthFailureState(auth *Auth, resultErr *Error, retryAfter *time.Durati // Without a model key the transient capacity rejection degrades to an // auth-level transient cooldown (issue 7017), never quota exhaustion. next := transientRateLimitRetryAfter(now, retryAfter, disableCooling) + if isForceAuth { + ownAuthForceDeadline = next + } if !next.IsZero() && auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(next) { next = auth.Quota.NextRecoverAt } @@ -3136,11 +4192,27 @@ func applyAuthFailureState(auth *Auth, resultErr *Error, retryAfter *time.Durati auth.NextRetryAfter = now.Add(30 * time.Minute) } case 402, 403: - auth.StatusMessage = "payment_required" - if disableCooling { + if isTOSViolationResultError(resultErr) { + // Terminal credential suspension: deactivate so the credential is + // excluded from selection/rotation, but keep OAuth refresh intact + // (the suspension is service-scoped per issue #7515; the token and + // model catalog keep working) so operator tooling can verify + // account liveness. The appeal detail travels on the result error's + // Metadata and is persisted onto the credential record below. + auth.StatusMessage = "tos_violation" + auth.Status = StatusDisabled + auth.Disabled = true + auth.Unavailable = true auth.NextRetryAfter = time.Time{} + auth.LastError = cloneError(resultErr) + persistTOSAppealMetadata(auth, resultErr) } else { - auth.NextRetryAfter = now.Add(30 * time.Minute) + auth.StatusMessage = "payment_required" + if disableCooling { + auth.NextRetryAfter = time.Time{} + } else { + auth.NextRetryAfter = now.Add(30 * time.Minute) + } } case 404: auth.StatusMessage = "not_found" @@ -3163,8 +4235,22 @@ func applyAuthFailureState(auth *Auth, resultErr *Error, retryAfter *time.Durati cooldown = minQuotaCooldownFloor } next = now.Add(cooldown).Round(0) + if isForceAuth { + ownAuthForceDeadline = next + } } else { + reusedOpenAuthWindow := auth.Quota.NextRecoverAt.After(now) + baseAuthBackoff := auth.Quota.BackoffLevel next, auth.Quota.BackoffLevel = quotaCooldownAfterFailure(auth.Quota, now) + if isForceAuth { + if !reusedOpenAuthWindow { + ownAuthForceDeadline = next + } else if prevAuthForceUntil.After(now) { + ownAuthForceDeadline = prevAuthForceUntil + } else { + ownAuthForceDeadline, _ = quotaCooldownAfterFailure(QuotaState{BackoffLevel: baseAuthBackoff}, now) + } + } } if auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(next) { next = auth.Quota.NextRecoverAt @@ -3184,15 +4270,69 @@ func applyAuthFailureState(auth *Auth, resultErr *Error, retryAfter *time.Durati auth.Unavailable = !auth.NextRetryAfter.IsZero() } } + if isForceAuth && auth.NextRetryAfter.IsZero() { + auth.NextRetryAfter = now.Add(transientErrorCooldown) + auth.Unavailable = true + } + if isForceAuth { + if ownAuthForceDeadline.IsZero() { + ownAuthForceDeadline = auth.NextRetryAfter + } + if ownAuthForceDeadline.After(prevAuthForceUntil) { + auth.forceCooldownUntil = ownAuthForceDeadline + } else { + auth.forceCooldownUntil = prevAuthForceUntil + } + } else { + auth.forceCooldownUntil = prevAuthForceUntil + } + auth.forceCooldownSeeded = true + if prevCredQuotaForceUntil.After(now) { + if prevCredQuotaForceUntil.After(auth.credQuotaForceUntil) { + auth.credQuotaForceUntil = prevCredQuotaForceUntil + } + if !auth.Quota.Exceeded || auth.Quota.Reason != "credential_quota" || auth.Quota.NextRecoverAt.Before(prevCredQuotaForceUntil) { + restored := prevAuthQuota + if disableCooling && restored.NextRecoverAt.After(prevCredQuotaForceUntil) { + restored.NextRecoverAt = prevCredQuotaForceUntil + } else if !disableCooling && auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(restored.NextRecoverAt) { + restored.NextRecoverAt = auth.Quota.NextRecoverAt + } + restored.cooldownSignals = prevAuthQuotaSignals + applyCooldownFields(&auth.Quota, restored) + } + } + activeAuthForce := auth.forceCooldownUntil + if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.credQuotaForceUntil.After(activeAuthForce) { + activeAuthForce = auth.credQuotaForceUntil + } + if activeAuthForce.After(now) { + if auth.NextRetryAfter.Before(activeAuthForce) { + auth.NextRetryAfter = activeAuthForce + } + auth.Unavailable = true + if (!auth.Quota.Exceeded || auth.Quota.NextRecoverAt.IsZero()) && prevAuthQuota.Exceeded && prevAuthQuota.NextRecoverAt.After(now) { + restored := prevAuthQuota + if disableCooling && restored.NextRecoverAt.After(activeAuthForce) { + restored.NextRecoverAt = activeAuthForce + } + restored.cooldownSignals = prevAuthQuotaSignals + applyCooldownFields(&auth.Quota, restored) + } + } + ownAuthRetryDeadline := auth.NextRetryAfter + if isForceAuth && ownAuthForceDeadline.After(ownAuthRetryDeadline) { + ownAuthRetryDeadline = ownAuthForceDeadline + } // A later failure only extends a still-live credential cooldown; a // deliberate zero write (disableCooling) still clears it. if !auth.NextRetryAfter.IsZero() && prevAuthRetryAfter.After(auth.NextRetryAfter) && prevAuthRetryAfter.After(now) { auth.NextRetryAfter = prevAuthRetryAfter } - if resultErr != nil && resultErr.Code == ErrorCodeForceCooldown && auth.NextRetryAfter.IsZero() { - auth.NextRetryAfter = now.Add(transientErrorCooldown) - auth.Unavailable = true + if !isForceAuth { + return time.Time{}, ownAuthRetryDeadline } + return ownAuthForceDeadline, ownAuthRetryDeadline } // quotaCooldownAfterFailure returns the recovery deadline and backoff level for diff --git a/sdk/cliproxy/auth/conductor_execution.go b/sdk/cliproxy/auth/conductor_execution.go index 2a9737fee9d..be4d5e4396e 100644 --- a/sdk/cliproxy/auth/conductor_execution.go +++ b/sdk/cliproxy/auth/conductor_execution.go @@ -25,6 +25,14 @@ import ( log "github.com/sirupsen/logrus" ) +func (m *Manager) newUpstreamAttemptContext(ctx context.Context) context.Context { + ctx = logging.WithFreshResponseHeadersHolder(ctx) + if RequestScopedErrorConfigFromContext(ctx) == nil { + ctx = WithRequestScopedErrorConfig(ctx, m.runtimeConfigSnapshot()) + } + return cliproxyexecutor.WithUpstreamAttemptTracker(ctx) +} + func newUpstreamAttemptContext(ctx context.Context) context.Context { ctx = logging.WithFreshResponseHeadersHolder(ctx) return cliproxyexecutor.WithUpstreamAttemptTracker(ctx) @@ -92,12 +100,39 @@ func unwrapUpstreamExecutionAttempt(err error) error { } func unwrapExecutionBoundaryError(err error) error { - err = unwrapRequestStopError(err) - return unwrapUpstreamExecutionAttempt(err) + for err != nil { + switch wrapped := err.(type) { + case requestStopError: + err = wrapped.error + case schedulerRejectError: + err = wrapped.error + case *roundEndedBySchedulerRejectError: + if wrapped == nil || wrapped.cause == nil { + return err + } + err = wrapped.cause + case *upstreamExecutionAttemptError: + if wrapped == nil || wrapped.cause == nil { + return err + } + err = wrapped.cause + default: + return err + } + } + return nil +} + +func roundPickFailureError(lastErr, upstreamErr, errPick error) error { + preferred := preferredExecutionAttemptError(lastErr, upstreamErr) + if isSchedulerRejectError(errPick) { + return markRoundEndedBySchedulerReject(preferred) + } + return preferred } func preferredExecutionAttemptError(fallback, upstream error) error { - if errors.Is(fallback, context.Canceled) || errors.Is(fallback, context.DeadlineExceeded) { + if errors.Is(fallback, context.Canceled) || errors.Is(fallback, context.DeadlineExceeded) || isSessionAffinityRetryError(fallback) { return fallback } if upstream == nil { @@ -118,6 +153,46 @@ func preferredExecutionAttemptError(fallback, upstream error) error { return markUpstreamExecutionAttempt(upstream) } +func (m *Manager) normalizeSessionAffinityNeverTerminalError(err error, providers []string, model string, opts cliproxyexecutor.Options) error { + if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return err + } + if isRequestTerminatedError(err) || isRequestStopError(err) || isSchedulerRejectError(err) || isRequestInvalidError(err) || isSessionAffinityRetryError(err) { + return err + } + var authErr *Error + if errors.As(err, &authErr) && authErr != nil { + switch authErr.Code { + case "session_auth_unavailable", "auth_not_found", "auth_unavailable", "model_cooldown", "provider_not_found", "executor_not_found": + return err + } + } + var cooldownErr *modelCooldownError + if errors.As(err, &cooldownErr) && cooldownErr != nil { + return err + } + affinity, ok := m.Selector().(*SessionAffinitySelector) + if !ok || affinity == nil || !affinity.rebindOnNever { + return err + } + if _, okBound := affinity.boundAuthForRequest(providers, model, opts); !okBound { + return err + } + rerr := resultErrorFromError(err) + if shouldRebindSessionAffinityOnError(rerr) { + return err + } + if shouldSkipCredentialCooldown(rerr) && !isTransientTransportResultError(rerr) && !isConnectionLifecycleResultError(rerr) { + return err + } + return &Error{ + Code: "session_auth_retry", + Message: "bound session credential is transiently unavailable", + Retryable: true, + HTTPStatus: http.StatusServiceUnavailable, + } +} + // Execute performs a non-streaming execution using the configured selector and executor. // It supports multiple providers for the same model and round-robins the starting provider per model. func isOpenAIImageExecutionOptions(opts cliproxyexecutor.Options) bool { @@ -125,14 +200,21 @@ func isOpenAIImageExecutionOptions(opts cliproxyexecutor.Options) bool { } func (m *Manager) Execute(ctx context.Context, providers []string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + scope := m.beginInFlight("") + defer func() { scope.end() }() ctx = cliproxyexecutor.WithRequestProxyURL(ctx, opts.ProxyURL) req, opts = cliproxysession.Enrich(req, opts) ctx = WithCodexClientRequest(ctx, isOpenAIImageExecutionOptions(opts) || IsCodexClientRequest(ctx, opts.Headers)) ctx = coreusage.CaptureIdentity(ctx) + ctx = contextWithInFlightScope(ctx, scope) normalized := m.normalizeProviders(providers) if len(normalized) == 0 { return cliproxyexecutor.Response{}, &Error{Code: "provider_not_found", Message: "no provider supplied"} } + opts, errThread := withClaudeThreadAuth(ctx, normalized, req, opts) + if errThread != nil { + return cliproxyexecutor.Response{}, errThread + } if m.HomeEnabled() { resp, errHome := m.executeHome(ctx, normalized, req, opts, false) return resp, unwrapExecutionBoundaryError(errHome) @@ -142,6 +224,8 @@ func (m *Manager) Execute(ctx context.Context, providers []string, req cliproxye var lastErr error var preferredUpstreamErr error + var selectionCooldownDeadline time.Time + var terminalRoundRejectedByScheduler bool retryModel := authSelectionModelFromOptions(opts, req.Model) for attempt := 0; ; attempt++ { roundAttempted := make(map[string]struct{}) @@ -153,6 +237,15 @@ func (m *Manager) Execute(ctx context.Context, providers []string, req cliproxye if isRequestTerminatedError(errExec) || isRequestStopError(errExec) { return cliproxyexecutor.Response{}, unwrapExecutionBoundaryError(errExec) } + if isSchedulerRejectError(errExec) { + if lastErr == nil && preferredUpstreamErr == nil { + return cliproxyexecutor.Response{}, unwrapExecutionBoundaryError(errExec) + } + terminalRoundRejectedByScheduler = true + break + } + terminalRoundRejectedByScheduler = hasRoundEndedBySchedulerReject(errExec) + observeSelectionCooldownDeadline(&selectionCooldownDeadline, errExec, time.Now()) if hasUpstreamExecutionAttempt(errExec) { preferredUpstreamErr = errExec } @@ -173,13 +266,15 @@ func (m *Manager) Execute(ctx context.Context, providers []string, req cliproxye } lastErr = preferredExecutionAttemptError(lastErr, preferredUpstreamErr) lastErr = unwrapExecutionBoundaryError(lastErr) - if hasAntigravityProvider(normalized) && shouldAttemptAntigravityCreditsFallback(m, lastErr, normalized) { + lastErr = m.normalizeSessionAffinityNeverTerminalError(lastErr, normalized, retryModel, opts) + if !terminalRoundRejectedByScheduler && hasAntigravityProvider(normalized) && shouldAttemptAntigravityCreditsFallback(m, lastErr, normalized) { if resp, ok, errCredits := m.tryAntigravityCreditsExecute(ctx, req, opts); errCredits != nil { return cliproxyexecutor.Response{}, errCredits } else if ok { return resp, nil } } + lastErr = m.annotatePoolCooldownTerminalError(ctx, normalized, retryModel, opts, lastErr, selectionCooldownDeadline) return cliproxyexecutor.Response{}, lastErr } return cliproxyexecutor.Response{}, &Error{Code: "auth_not_found", Message: "no auth available"} @@ -187,10 +282,13 @@ func (m *Manager) Execute(ctx context.Context, providers []string, req cliproxye // It supports multiple providers for the same model and round-robins the starting provider per model. func (m *Manager) ExecuteCount(ctx context.Context, providers []string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + scope := m.beginInFlight("") + defer func() { scope.end() }() ctx = cliproxyexecutor.WithRequestProxyURL(ctx, opts.ProxyURL) req, opts = cliproxysession.Enrich(req, opts) ctx = WithCodexClientRequest(ctx, IsCodexClientRequest(ctx, opts.Headers)) ctx = coreusage.CaptureIdentity(ctx) + ctx = contextWithInFlightScope(ctx, scope) normalized := m.normalizeProviders(providers) if len(normalized) == 0 { return cliproxyexecutor.Response{}, &Error{Code: "provider_not_found", Message: "no provider supplied"} @@ -204,6 +302,7 @@ func (m *Manager) ExecuteCount(ctx context.Context, providers []string, req clip var lastErr error var preferredUpstreamErr error + var selectionCooldownDeadline time.Time retryModel := authSelectionModelFromOptions(opts, req.Model) for attempt := 0; ; attempt++ { roundAttempted := make(map[string]struct{}) @@ -215,6 +314,13 @@ func (m *Manager) ExecuteCount(ctx context.Context, providers []string, req clip if isRequestTerminatedError(errExec) || isRequestStopError(errExec) { return cliproxyexecutor.Response{}, unwrapExecutionBoundaryError(errExec) } + if isSchedulerRejectError(errExec) { + if lastErr == nil && preferredUpstreamErr == nil { + return cliproxyexecutor.Response{}, unwrapExecutionBoundaryError(errExec) + } + break + } + observeSelectionCooldownDeadline(&selectionCooldownDeadline, errExec, time.Now()) if hasUpstreamExecutionAttempt(errExec) { preferredUpstreamErr = errExec } @@ -234,18 +340,29 @@ func (m *Manager) ExecuteCount(ctx context.Context, providers []string, req clip } } lastErr = preferredExecutionAttemptError(lastErr, preferredUpstreamErr) - return cliproxyexecutor.Response{}, unwrapExecutionBoundaryError(lastErr) + lastErr = unwrapExecutionBoundaryError(lastErr) + lastErr = m.normalizeSessionAffinityNeverTerminalError(lastErr, normalized, retryModel, opts) + lastErr = m.annotatePoolCooldownTerminalError(ctx, normalized, retryModel, opts, lastErr, selectionCooldownDeadline) + return cliproxyexecutor.Response{}, lastErr } return cliproxyexecutor.Response{}, &Error{Code: "auth_not_found", Message: "no auth available"} } // ExecuteStream performs a streaming execution using the configured selector and executor. // It supports multiple providers for the same model and round-robins the starting provider per model. -func (m *Manager) ExecuteStream(ctx context.Context, providers []string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { +func (m *Manager) ExecuteStream(ctx context.Context, providers []string, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (result *cliproxyexecutor.StreamResult, err error) { + scope := m.beginInFlight("") + defer func() { + if scope != nil { + result = wrapInFlightStreamResult(result, scope, ctx) + scope = nil + } + }() ctx = cliproxyexecutor.WithRequestProxyURL(ctx, opts.ProxyURL) req, opts = cliproxysession.Enrich(req, opts) ctx = WithCodexClientRequest(ctx, isOpenAIImageExecutionOptions(opts) || IsCodexClientRequest(ctx, opts.Headers)) ctx = coreusage.CaptureIdentity(ctx) + ctx = contextWithInFlightScope(ctx, scope) if m.HomeEnabled() { if unlockSession := m.lockHomeWebsocketSession(ctx, opts); unlockSession != nil { defer unlockSession() @@ -255,11 +372,17 @@ func (m *Manager) ExecuteStream(ctx context.Context, providers []string, req cli if len(normalized) == 0 { return nil, &Error{Code: "provider_not_found", Message: "no provider supplied"} } + opts, errThread := withClaudeThreadAuth(ctx, normalized, req, opts) + if errThread != nil { + return nil, errThread + } defaultRequestRetry, maxRetryCredentials, maxWait := m.retrySettings() var lastErr error var preferredUpstreamErr error + var selectionCooldownDeadline time.Time + var terminalRoundRejectedByScheduler bool homeRetryLimit := -1 retryModel := authSelectionModelFromOptions(opts, req.Model) attempt := 0 @@ -272,6 +395,9 @@ func (m *Manager) ExecuteStream(ctx context.Context, providers []string, req cli if errStream == nil { return result, nil } + if !m.HomeEnabled() { + observeSelectionCooldownDeadline(&selectionCooldownDeadline, errStream, time.Now()) + } if hasUpstreamExecutionAttempt(errStream) { preferredUpstreamErr = errStream } @@ -292,6 +418,14 @@ func (m *Manager) ExecuteStream(ctx context.Context, providers []string, req cli if isRequestTerminatedError(errStream) || isRequestStopError(errStream) { return nil, unwrapExecutionBoundaryError(errStream) } + if isSchedulerRejectError(errStream) { + if lastErr == nil && preferredUpstreamErr == nil { + return nil, unwrapExecutionBoundaryError(errStream) + } + terminalRoundRejectedByScheduler = true + break + } + terminalRoundRejectedByScheduler = hasRoundEndedBySchedulerReject(errStream) lastErr = errStream wait, shouldRetry := m.shouldRetryAfterErrorWithAttempted(ctx, opts, errStream, attempt, normalized, retryModel, maxWait, homeRetryLimit, defaultRequestRetry, roundAttempted) if !shouldRetry { @@ -314,13 +448,17 @@ func (m *Manager) ExecuteStream(ctx context.Context, providers []string, req cli lastErr = preferredExecutionAttemptError(lastErr, preferredUpstreamErr) } lastErr = unwrapExecutionBoundaryError(lastErr) - if hasAntigravityProvider(normalized) && shouldAttemptAntigravityCreditsFallback(m, lastErr, normalized) { + lastErr = m.normalizeSessionAffinityNeverTerminalError(lastErr, normalized, retryModel, opts) + if !terminalRoundRejectedByScheduler && hasAntigravityProvider(normalized) && shouldAttemptAntigravityCreditsFallback(m, lastErr, normalized) { if result, ok, errCredits := m.tryAntigravityCreditsExecuteStream(ctx, req, opts); errCredits != nil { return nil, errCredits } else if ok { return result, nil } } + if !m.HomeEnabled() { + lastErr = m.annotatePoolCooldownTerminalError(ctx, normalized, retryModel, opts, lastErr, selectionCooldownDeadline) + } var bootstrapErr *streamBootstrapError if errors.As(lastErr, &bootstrapErr) && bootstrapErr != nil { return streamErrorResult(bootstrapErr.Headers(), lastErr), nil @@ -547,9 +685,12 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req pickOpts = withHomeExcludedAuthIDs(pickOpts, tried) } auth, executor, provider, errPick := m.pickNextMixed(ctx, providers, routeModel, pickOpts, tried) + if errPick == nil { + updateInFlightScopeProvider(ctx, provider) + } if errPick != nil { if shouldReturnLastErrorOnPickFailure(homeMode, lastErr, errPick) { - return cliproxyexecutor.Response{}, preferredExecutionAttemptError(lastErr, upstreamErr) + return cliproxyexecutor.Response{}, roundPickFailureError(lastErr, upstreamErr, errPick) } return cliproxyexecutor.Response{}, errPick } @@ -566,7 +707,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req } execCtx = contextWithRequestedModelAlias(execCtx, pickOpts, routeModel) execCtx = coreusage.WithSelectionID(execCtx, selectionIDFromOptions(pickOpts)) - execCtx = newUpstreamAttemptContext(execCtx) + execCtx = m.newUpstreamAttemptContext(execCtx) models, pooled, aliasResult, routing := m.preparedExecutionModelsWithAliasForRequest(execCtx, auth, routeModel, pickOpts.Headers) if len(models) == 0 { @@ -583,7 +724,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req if stateModel == "" { stateModel = canonicalModelKey(routeModel) } - result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} + result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), RefreshToken: authRefreshToken(auth), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} m.MarkResult(execCtx, result) lastErr = errPrepare continue @@ -592,7 +733,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req var authErr error didRefreshOnUnauthorized := false for _, upstreamModel := range models { - execCtx = newUpstreamAttemptContext(execCtx) + execCtx = m.newUpstreamAttemptContext(execCtx) resultModel := m.stateModelForExecution(auth, routeModel, upstreamModel, pooled) execReq := req execReq.Model = upstreamModel @@ -643,7 +784,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req if refreshed, okRefresh := m.tryRefreshAfterUnauthorized(refreshCtx, auth, errExec, didRefreshOnUnauthorized, execOpts.Headers); okRefresh { auth = refreshed didRefreshOnUnauthorized = true - execCtx = newUpstreamAttemptContext(execCtx) + execCtx = m.newUpstreamAttemptContext(execCtx) execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) executionSeq = m.nextExecutionSeq() startRetry := time.Now() @@ -666,7 +807,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req if errCancel := claudeOAuthRequestCancellation(execCtx, auth, errExec); errCancel != nil { return cliproxyexecutor.Response{}, errCancel } - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, CompletedResponse: errExec == nil && !resp.Incomplete && isCompletedExecutionPayload(resp.Payload), Options: execOpts, AccessToken: authAccessTokenForRequest(execCtx, auth, execOpts.Headers), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch, ExecutionSeq: executionSeq} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, CompletedResponse: errExec == nil && !resp.Incomplete && isCompletedExecutionPayload(resp.Payload), Options: execOpts, AccessToken: authAccessTokenForRequest(execCtx, auth, execOpts.Headers), RefreshToken: authRefreshToken(auth), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch, ExecutionSeq: executionSeq} if errExec != nil { result.Error = resultErrorFromError(errExec) if ra := retryAfterFromError(errExec); ra != nil { @@ -675,7 +816,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req if isCredentialScopedError(errExec) { result.CredentialScope = true } - action, okAction := matchRequestScopedErrorAction(auth, errExec, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(auth, errExec, m.requestScopedErrorConfig(execCtx)) applyRequestScopedActionToResult(action, okAction, &result) if isResponsesCompactAvailabilityNeutralError(execOpts, errExec, result.Error) { m.recordAvailabilityNeutralResult(execCtx, result) @@ -709,7 +850,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req return resp, nil } if authErr != nil { - action, okAction := matchRequestScopedErrorAction(auth, authErr, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(auth, authErr, m.requestScopedErrorConfig(execCtx)) if okAction { if isRequestScopedStop(action, okAction) { return cliproxyexecutor.Response{}, wrapRequestStopError(authErr) @@ -765,9 +906,12 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, pickOpts = withHomeExcludedAuthIDs(pickOpts, tried) } auth, executor, provider, errPick := m.pickNextMixed(ctx, providers, routeModel, pickOpts, tried) + if errPick == nil { + updateInFlightScopeProvider(ctx, provider) + } if errPick != nil { if shouldReturnLastErrorOnPickFailure(homeMode, lastErr, errPick) { - return cliproxyexecutor.Response{}, preferredExecutionAttemptError(lastErr, upstreamErr) + return cliproxyexecutor.Response{}, roundPickFailureError(lastErr, upstreamErr, errPick) } return cliproxyexecutor.Response{}, errPick } @@ -784,7 +928,7 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, } execCtx = contextWithRequestedModelAlias(execCtx, pickOpts, routeModel) execCtx = coreusage.WithSelectionID(execCtx, selectionIDFromOptions(pickOpts)) - execCtx = newUpstreamAttemptContext(execCtx) + execCtx = m.newUpstreamAttemptContext(execCtx) models, pooled, aliasResult, routing := m.preparedExecutionModelsWithAliasForRequest(execCtx, auth, routeModel, pickOpts.Headers) if len(models) == 0 { @@ -801,7 +945,7 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, if stateModel == "" { stateModel = canonicalModelKey(routeModel) } - result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, SkipQuotaObservation: true, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} + result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, SkipQuotaObservation: true, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), RefreshToken: authRefreshToken(auth), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} m.MarkResult(execCtx, result) lastErr = errPrepare continue @@ -810,7 +954,7 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, var authErr error didRefreshOnUnauthorized := false for _, upstreamModel := range models { - execCtx = newUpstreamAttemptContext(execCtx) + execCtx = m.newUpstreamAttemptContext(execCtx) resultModel := m.stateModelForExecution(auth, routeModel, upstreamModel, pooled) execReq := req execReq.Model = upstreamModel @@ -861,7 +1005,7 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, if refreshed, okRefresh := m.tryRefreshAfterUnauthorized(refreshCtx, auth, errExec, didRefreshOnUnauthorized, execOpts.Headers); okRefresh { auth = refreshed didRefreshOnUnauthorized = true - execCtx = newUpstreamAttemptContext(execCtx) + execCtx = m.newUpstreamAttemptContext(execCtx) execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) executionSeq = m.nextExecutionSeq() startRetry := time.Now() @@ -884,13 +1028,13 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, if errCancel := claudeOAuthRequestCancellation(execCtx, auth, errExec); errCancel != nil { return cliproxyexecutor.Response{}, errCancel } - result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: execOpts, SkipQuotaObservation: true, AccessToken: authAccessTokenForRequest(execCtx, auth, execOpts.Headers), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch, ExecutionSeq: executionSeq} + result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: execOpts, SkipQuotaObservation: true, AccessToken: authAccessTokenForRequest(execCtx, auth, execOpts.Headers), RefreshToken: authRefreshToken(auth), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch, ExecutionSeq: executionSeq} if errExec != nil { result.Error = resultErrorFromError(errExec) if ra := retryAfterFromError(errExec); ra != nil { result.RetryAfter = ra } - action, okAction := matchRequestScopedErrorAction(auth, errExec, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(auth, errExec, m.requestScopedErrorConfig(execCtx)) applyRequestScopedActionToResult(action, okAction, &result) // Some Anthropic-compatible upstreams and plugin executors do not // implement count_tokens and return a generic endpoint 404 or an @@ -932,7 +1076,7 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, return resp, nil } if authErr != nil { - action, okAction := matchRequestScopedErrorAction(auth, authErr, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(auth, authErr, m.requestScopedErrorConfig(execCtx)) if okAction { if isRequestScopedStop(action, okAction) { return cliproxyexecutor.Response{}, wrapRequestStopError(authErr) @@ -1013,6 +1157,9 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string } } else { auth, executor, provider, errPick = m.pickNextMixed(ctx, providers, routeModel, pickOpts, tried) + if errPick == nil { + updateInFlightScopeProvider(ctx, provider) + } } if errPick != nil { preferredErr := preferredExecutionAttemptError(lastErr, upstreamErr) @@ -1025,7 +1172,7 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string if homeMode { return nil, markHomeRetryRoundExhausted(preferredErr, roundTiming.RetryAfter(), isHomeNextRoundImmediatelyAvailable(errPick)) } - return nil, preferredErr + return nil, roundPickFailureError(lastErr, upstreamErr, errPick) } return nil, errPick } @@ -1112,7 +1259,12 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string } execCtx = contextWithRequestedModelAlias(execCtx, pickOpts, routeModel) execCtx = coreusage.WithSelectionID(execCtx, selectionIDFromOptions(pickOpts)) - execCtx = newUpstreamAttemptContext(execCtx) + if selection != nil { + execCtx = coreusage.WithHomeSelection(execCtx, coreusage.HomeSelection{ + Reused: selection.Retained(), Model: routeModel, CredentialPolicy: credentialPolicyFromContext(ctx), + }) + } + execCtx = m.newUpstreamAttemptContext(execCtx) models, pooled, aliasResult, routing := m.executionModelCandidatesWithAlias(auth, routeModel) // Home owns dispatched credential availability; only local selections need state filtering. if selection == nil { @@ -1161,7 +1313,7 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string if stateModel == "" { stateModel = canonicalModelKey(routeModel) } - result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} + result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), RefreshToken: authRefreshToken(auth), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch} if selection != nil { m.reportHomeResult(execCtx, result, auth) releaseAttempt() @@ -1233,15 +1385,16 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string if hasUpstreamExecutionAttempt(errStream) { upstreamErr = errStream } - action, okAction := matchRequestScopedErrorAction(auth, errStream, m.runtimeConfigSnapshot()) - if isRequestScopedStop(action, okAction) || (!okAction && (isRequestInvalidError(errStream) || cliproxyexecutor.IsUpstreamWebsocketTurnError(errStream))) { + action, okAction := matchRequestScopedErrorAction(auth, errStream, m.requestScopedErrorConfig(execCtx)) + stoppedByRule := isRequestStopError(errStream) || isRequestScopedStop(action, okAction) + if stoppedByRule || (!okAction && (isRequestInvalidError(errStream) || cliproxyexecutor.IsUpstreamWebsocketTurnError(errStream))) { // Only redispatch needs a release acknowledgement. Preserve the final // response even when Home cannot acknowledge the released admission. if selection != nil { releaseAttempt() selection.End("request_stopped") } - if isRequestScopedStop(action, okAction) { + if stoppedByRule { return nil, wrapRequestStopError(errStream) } return nil, errStream @@ -2304,7 +2457,7 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, Metadata: map[string]any{cliproxyexecutor.CanonicalSessionIDMetadataKey: sessionID}, } - execCtx := newUpstreamAttemptContext(ctx) + execCtx := m.newUpstreamAttemptContext(ctx) execCtx = syncMetadataSessionToContext(execCtx, opts.Metadata) executionSeq := m.nextExecutionSeq() accessToken := authAccessTokenForRequest(execCtx, auth, opts.Headers) @@ -2333,6 +2486,7 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, CredentialScope: isCredentialScopedError(errExec), Options: opts, AccessToken: accessToken, + RefreshToken: authRefreshToken(auth), CredentialVersion: credVersion, RegistrationEpoch: regEpoch, ExecutionSeq: executionSeq, @@ -2354,6 +2508,7 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, CompletedResponse: true, Options: opts, AccessToken: accessToken, + RefreshToken: authRefreshToken(auth), CredentialVersion: credVersion, RegistrationEpoch: regEpoch, ExecutionSeq: executionSeq, @@ -2381,6 +2536,7 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, CredentialScope: isCredentialScopedError(errStream), Options: opts, AccessToken: accessToken, + RefreshToken: authRefreshToken(auth), CredentialVersion: credVersion, RegistrationEpoch: regEpoch, ExecutionSeq: executionSeq, @@ -2427,6 +2583,7 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, CredentialScope: isCredentialScopedError(chunkErr), Options: opts, AccessToken: accessToken, + RefreshToken: authRefreshToken(auth), CredentialVersion: credVersion, RegistrationEpoch: regEpoch, ExecutionSeq: executionSeq, @@ -2448,6 +2605,7 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, CompletedResponse: true, Options: opts, AccessToken: accessToken, + RefreshToken: authRefreshToken(auth), CredentialVersion: credVersion, RegistrationEpoch: regEpoch, ExecutionSeq: executionSeq, diff --git a/sdk/cliproxy/auth/conductor_home.go b/sdk/cliproxy/auth/conductor_home.go index d6474210003..5451d411a77 100644 --- a/sdk/cliproxy/auth/conductor_home.go +++ b/sdk/cliproxy/auth/conductor_home.go @@ -281,8 +281,16 @@ func isHomeRequestRetryExceededError(err error) bool { return strings.EqualFold(strings.TrimSpace(authErr.Code), homeRequestRetryExceededErrorCode) } +func isSessionAffinityRetryError(err error) bool { + if err == nil { + return false + } + var authErr *Error + return errors.As(err, &authErr) && authErr != nil && authErr.Code == "session_auth_retry" +} + func shouldReturnLastErrorOnPickFailure(homeMode bool, lastErr error, errPick error) bool { - if lastErr == nil || isRequestStopError(errPick) { + if lastErr == nil || isRequestStopError(errPick) || isSessionAffinityRetryError(errPick) { return false } if !homeMode { @@ -1076,11 +1084,17 @@ func (m *Manager) pickHomeDispatchSelection(ctx context.Context, model string, o } dispatchHeaders := homeDispatchHeaders(ctx, opts.Headers) if opts.Metadata != nil { - if nodeKind, ok := opts.Metadata[cliproxyexecutor.NodeKindMetadataKey].(string); ok && strings.TrimSpace(nodeKind) != "" { + nodeKind, _ := opts.Metadata[cliproxyexecutor.NodeKindMetadataKey].(string) + if isFork, _ := opts.Metadata[cliproxyexecutor.IsForkMetadataKey].(bool); isFork { + nodeKind = "fork" + } + if nodeKind = strings.TrimSpace(nodeKind); nodeKind != "" { + // Keep the caller headers unchanged when adding Home-only lineage metadata. + dispatchHeaders = dispatchHeaders.Clone() if dispatchHeaders == nil { dispatchHeaders = make(http.Header) } - dispatchHeaders.Set("X-Node-Kind", strings.TrimSpace(nodeKind)) + dispatchHeaders.Set("X-Node-Kind", nodeKind) } } credentialPolicy := credentialPolicyFromContext(ctx) @@ -1340,8 +1354,18 @@ func (m *Manager) findAllAntigravityCreditsCandidateAuths(ctx context.Context, r return nil, nil } pinnedAuthID := pinnedAuthIDFromMetadata(opts.Metadata) + selectionModel := authSelectionModelFromOptions(opts, routeModel) var candidates []creditsCandidateEntry m.mu.RLock() + if affinity, ok := m.selector.(*SessionAffinitySelector); ok && affinity != nil && affinity.rebindOnNever { + if boundAuthID, okBound := affinity.boundAuthForRequest([]string{"antigravity"}, selectionModel, opts); okBound { + if pinnedAuthID != "" && pinnedAuthID != boundAuthID { + m.mu.RUnlock() + return nil, nil + } + pinnedAuthID = boundAuthID + } + } for _, auth := range m.auths { if auth == nil || auth.Disabled || auth.Status == StatusDisabled { continue @@ -1414,7 +1438,7 @@ func hasAntigravityProvider(providers []string) bool { } func shouldAttemptAntigravityCreditsFallback(m *Manager, lastErr error, providers []string) bool { - if isRequestTerminatedError(lastErr) || isRequestStopError(lastErr) { + if isRequestTerminatedError(lastErr) || isRequestStopError(lastErr) || isSchedulerRejectError(lastErr) || hasRoundEndedBySchedulerReject(lastErr) { return false } status := statusCodeFromError(lastErr) @@ -1449,6 +1473,7 @@ func shouldAttemptAntigravityCreditsFallback(m *Manager, lastErr error, provider } func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, bool, error) { + updateInFlightScopeProvider(ctx, "antigravity") if m != nil && m.HomeEnabled() { return cliproxyexecutor.Response{}, false, &Error{Code: "home_fallback_unsupported", Message: "Home does not support Antigravity credits fallback", HTTPStatus: http.StatusServiceUnavailable} } @@ -1473,6 +1498,7 @@ func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxy clearSchedulerSelectionID(creditsOpts.Metadata) creditsCtx = contextWithRequestedModelAlias(creditsCtx, creditsOpts, routeModel) creditsCtx = coreusage.WithSelectionID(creditsCtx, "") + creditsCtx = m.newUpstreamAttemptContext(creditsCtx) preparedAuth, errPrepare := m.prepareRequestAuth(creditsCtx, c.executor, c.auth) if errPrepare != nil { continue @@ -1484,13 +1510,14 @@ func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxy continue } for _, upstreamModel := range models { + creditsCtx = m.newUpstreamAttemptContext(creditsCtx) resultModel := m.stateModelForExecution(c.auth, routeModel, upstreamModel, pooled) execReq := req execReq.Model = upstreamModel creditsCtx = syncMetadataSessionToContext(creditsCtx, creditsOpts.Metadata) executionSeq := m.nextExecutionSeq() resp, errExec := c.executor.Execute(creditsCtx, c.auth, execReq, creditsOpts) - result := Result{AuthID: c.auth.ID, Provider: c.provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: creditsOpts, CredentialVersion: c.auth.CredentialVersion, RegistrationEpoch: c.auth.RegistrationEpoch, ExecutionSeq: executionSeq} + result := Result{AuthID: c.auth.ID, Provider: c.provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, Options: creditsOpts, AccessToken: authAccessTokenForRequest(creditsCtx, c.auth, creditsOpts.Headers), RefreshToken: authRefreshToken(c.auth), CredentialVersion: c.auth.CredentialVersion, RegistrationEpoch: c.auth.RegistrationEpoch, ExecutionSeq: executionSeq} if errExec != nil { result.Error = resultErrorFromError(errExec) if ra := retryAfterFromError(errExec); ra != nil { @@ -1515,6 +1542,7 @@ func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxy } func (m *Manager) tryAntigravityCreditsExecuteStream(ctx context.Context, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, bool, error) { + updateInFlightScopeProvider(ctx, "antigravity") if m != nil && m.HomeEnabled() { return nil, false, &Error{Code: "home_fallback_unsupported", Message: "Home does not support Antigravity credits fallback", HTTPStatus: http.StatusServiceUnavailable} } @@ -1539,6 +1567,7 @@ func (m *Manager) tryAntigravityCreditsExecuteStream(ctx context.Context, req cl clearSchedulerSelectionID(creditsOpts.Metadata) creditsCtx = contextWithRequestedModelAlias(creditsCtx, creditsOpts, routeModel) creditsCtx = coreusage.WithSelectionID(creditsCtx, "") + creditsCtx = m.newUpstreamAttemptContext(creditsCtx) preparedAuth, errPrepare := m.prepareRequestAuth(creditsCtx, c.executor, c.auth) if errPrepare != nil { continue diff --git a/sdk/cliproxy/auth/conductor_home_execution.go b/sdk/cliproxy/auth/conductor_home_execution.go index f30d811fd92..11fcf62bd26 100644 --- a/sdk/cliproxy/auth/conductor_home_execution.go +++ b/sdk/cliproxy/auth/conductor_home_execution.go @@ -135,7 +135,10 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c clearSchedulerSelectionID(opts.Metadata) execCtx = contextWithRequestedModelAlias(execCtx, opts, routeModel) execCtx = coreusage.WithSelectionID(execCtx, "") - execCtx = newUpstreamAttemptContext(execCtx) + execCtx = coreusage.WithHomeSelection(execCtx, coreusage.HomeSelection{ + Reused: selection.Retained(), Model: routeModel, CredentialPolicy: credentialPolicyFromContext(ctx), + }) + execCtx = m.newUpstreamAttemptContext(execCtx) if rt := m.roundTripperFor(auth); rt != nil { execCtx = context.WithValue(execCtx, roundTripperContextKey{}, rt) execCtx = context.WithValue(execCtx, "cliproxy.roundtripper", rt) @@ -174,7 +177,7 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c continue } for _, upstreamModel := range models { - execCtx = newUpstreamAttemptContext(execCtx) + execCtx = m.newUpstreamAttemptContext(execCtx) resultModel := m.stateModelForExecution(preparedAuth, routeModel, upstreamModel, pooled) execReq := req execReq.Model = upstreamModel @@ -275,7 +278,7 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c if isCredentialScopedError(errExecute) { result.CredentialScope = true } - action, okAction := matchRequestScopedErrorAction(preparedAuth, errExecute, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(preparedAuth, errExecute, m.requestScopedErrorConfig(execCtx)) applyRequestScopedActionToResult(action, okAction, &result) m.reportHomeResult(execCtx, result, preparedAuth) roundTiming.Observe(errExecute) diff --git a/sdk/cliproxy/auth/conductor_inflight.go b/sdk/cliproxy/auth/conductor_inflight.go new file mode 100644 index 00000000000..45cbd6a949f --- /dev/null +++ b/sdk/cliproxy/auth/conductor_inflight.go @@ -0,0 +1,227 @@ +package auth + +import ( + "context" + "sync" + "time" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +// InFlightSnapshot is an immutable view of standalone in-flight executions. +type InFlightSnapshot struct { + InFlight int64 + OldestStartedAt time.Time + ByProvider map[string]int64 +} + +// inFlightTracker counts in-flight local executions for standalone instances. +// It stays disabled while Home mode is active because the execution registry +// already tracks Home-dispatched executions for that lifetime. +type inFlightTracker struct { + mu sync.Mutex + count int64 + oldestStarted time.Time + byProvider map[string]int64 + inflightScopes map[*inFlightScope]time.Time +} + +func newInFlightTracker() *inFlightTracker { + return &inFlightTracker{ + byProvider: make(map[string]int64), + inflightScopes: make(map[*inFlightScope]time.Time), + } +} + +// inFlightScope represents one tracked execution until its end is called. +type inFlightScope struct { + tracker *inFlightTracker + provider string + done sync.Once +} + +// setProvider updates the provider attribution of an in-flight scope without +// changing the total count or its start time. +func (s *inFlightScope) setProvider(provider string) { + if s == nil || s.tracker == nil { + return + } + t := s.tracker + t.mu.Lock() + defer t.mu.Unlock() + if _, ok := t.inflightScopes[s]; !ok || s.provider == provider { + return + } + if next := t.byProvider[s.provider] - 1; next > 0 { + t.byProvider[s.provider] = next + } else { + delete(t.byProvider, s.provider) + } + s.provider = provider + t.byProvider[provider]++ +} + +// end releases the scope exactly once. +func (s *inFlightScope) end() { + if s == nil || s.tracker == nil { + return + } + s.done.Do(func() { + t := s.tracker + t.mu.Lock() + defer t.mu.Unlock() + startedAt, ok := t.inflightScopes[s] + if !ok { + return + } + delete(t.inflightScopes, s) + t.count-- + if next := t.byProvider[s.provider] - 1; next > 0 { + t.byProvider[s.provider] = next + } else { + delete(t.byProvider, s.provider) + } + if t.count == 0 { + t.oldestStarted = time.Time{} + } else if startedAt.Equal(t.oldestStarted) { + t.recomputeOldestLocked() + } + }) +} + +func (t *inFlightTracker) recomputeOldestLocked() { + var oldest time.Time + for _, startedAt := range t.inflightScopes { + if oldest.IsZero() || startedAt.Before(oldest) { + oldest = startedAt + } + } + t.oldestStarted = oldest +} + +// begin tracks a new execution. The returned scope must be ended exactly once. +func (t *inFlightTracker) begin(provider string) *inFlightScope { + if t == nil { + return nil + } + scope := &inFlightScope{tracker: t, provider: provider} + t.mu.Lock() + defer t.mu.Unlock() + now := time.Now() + t.inflightScopes[scope] = now + t.count++ + t.byProvider[provider]++ + if t.oldestStarted.IsZero() || now.Before(t.oldestStarted) { + t.oldestStarted = now + } + return scope +} + +// snapshot copies the current in-flight state into an immutable view. +func (t *inFlightTracker) snapshot() InFlightSnapshot { + if t == nil { + return InFlightSnapshot{ByProvider: map[string]int64{}} + } + t.mu.Lock() + defer t.mu.Unlock() + byProvider := make(map[string]int64, len(t.byProvider)) + for provider, count := range t.byProvider { + byProvider[provider] = count + } + return InFlightSnapshot{ + InFlight: t.count, + OldestStartedAt: t.oldestStarted, + ByProvider: byProvider, + } +} + +// InFlightSnapshot returns the current standalone in-flight execution counts. +// It reports an empty snapshot while Home mode is enabled, where the execution +// registry is the authoritative in-flight source instead. +func (m *Manager) InFlightSnapshot() InFlightSnapshot { + if m == nil || m.inFlightTracker == nil || m.HomeEnabled() { + return InFlightSnapshot{ByProvider: map[string]int64{}} + } + return m.inFlightTracker.snapshot() +} + +// beginInFlight starts tracking one local execution. The returned scope must be +// ended exactly once; it is nil-safe and ends as a no-op in Home mode. +func (m *Manager) beginInFlight(provider string) *inFlightScope { + if m == nil || m.inFlightTracker == nil || m.HomeEnabled() { + return nil + } + return m.inFlightTracker.begin(provider) +} + +// wrapInFlightStreamResult extends an in-flight scope until the returned +// stream finishes or ctx is canceled, whichever comes first. +func wrapInFlightStreamResult(result *cliproxyexecutor.StreamResult, scope *inFlightScope, ctx context.Context) *cliproxyexecutor.StreamResult { + if result == nil || scope == nil { + if scope != nil { + scope.end() + } + return result + } + out := make(chan cliproxyexecutor.StreamChunk) + go func() { + // Release the in-flight scope as soon as forwarding stops (stream end + // or cancellation). The output channel closes only after the inner + // channel is fully drained so callers keep the original happens-before + // between stream end and upstream result bookkeeping. + defer scope.end() + if result.Chunks == nil { + close(out) + return + } + forward := true + for forward { + select { + case <-ctx.Done(): + forward = false + case chunk, ok := <-result.Chunks: + if !ok { + close(out) + return + } + select { + case <-ctx.Done(): + forward = false + case out <- chunk: + } + } + } + // After cancellation, drain the inner channel on the same goroutine so + // the inner stream wrapper finishes its bookkeeping before out closes. + // The scope is released explicitly here before the drain can block; + // the deferred end above remains as the safety net for other exits. + scope.end() + for range result.Chunks { + } + close(out) + }() + return &cliproxyexecutor.StreamResult{Headers: result.Headers, Chunks: out} +} + +// inFlightScopeContextKey carries the request in-flight scope to inner +// selection code so the provider attribution can be corrected after pick. +type inFlightScopeContextKey struct{} + +// contextWithInFlightScope returns a context carrying the scope, or ctx when +// scope is nil. +func contextWithInFlightScope(ctx context.Context, scope *inFlightScope) context.Context { + if ctx == nil || scope == nil { + return ctx + } + return context.WithValue(ctx, inFlightScopeContextKey{}, scope) +} + +// updateInFlightScopeProvider re-attributes the request scope to the actually +// selected provider after auth selection. It is a no-op without a scope. +func updateInFlightScopeProvider(ctx context.Context, provider string) { + if ctx == nil { + return + } + scope, _ := ctx.Value(inFlightScopeContextKey{}).(*inFlightScope) + scope.setProvider(provider) +} diff --git a/sdk/cliproxy/auth/conductor_inflight_test.go b/sdk/cliproxy/auth/conductor_inflight_test.go new file mode 100644 index 00000000000..2f16f9b78cb --- /dev/null +++ b/sdk/cliproxy/auth/conductor_inflight_test.go @@ -0,0 +1,409 @@ +package auth + +import ( + "context" + "errors" + "net/http" + "sync" + "sync/atomic" + "testing" + "time" + + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +// inFlightBlockingExecutor blocks inside Execute until released so the test can +// observe the manager in-flight snapshot mid-request. +type inFlightBlockingExecutor struct { + id string + release chan struct{} + entered chan struct{} + releaseMu sync.Once +} + +func newInFlightBlockingExecutor(id string) *inFlightBlockingExecutor { + return &inFlightBlockingExecutor{ + id: id, + release: make(chan struct{}), + entered: make(chan struct{}, 4), + } +} + +func (e *inFlightBlockingExecutor) Identifier() string { return e.id } + +func (e *inFlightBlockingExecutor) Execute(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + e.entered <- struct{}{} + <-e.release + return cliproxyexecutor.Response{Payload: []byte(`{"status":"ok"}`)}, nil +} + +func (e *inFlightBlockingExecutor) ExecuteStream(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return nil, errors.New("stream not supported") +} + +func (e *inFlightBlockingExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) { + return auth, nil +} + +func (e *inFlightBlockingExecutor) CountTokens(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, errors.New("not supported") +} + +func (e *inFlightBlockingExecutor) HttpRequest(context.Context, *Auth, *http.Request) (*http.Response, error) { + return nil, errors.New("not supported") +} + +// inFlightStreamExecutor returns a stream whose chunks channel stays open until +// the test closes it, letting the stream lifetime be observed via the snapshot. +type inFlightStreamExecutor struct { + id string + chunks chan cliproxyexecutor.StreamChunk +} + +func (e *inFlightStreamExecutor) Identifier() string { return e.id } + +func (e *inFlightStreamExecutor) Execute(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, errors.New("not supported") +} + +func (e *inFlightStreamExecutor) ExecuteStream(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return &cliproxyexecutor.StreamResult{Chunks: e.chunks}, nil +} + +func (e *inFlightStreamExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) { + return auth, nil +} + +func (e *inFlightStreamExecutor) CountTokens(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, errors.New("not supported") +} + +func (e *inFlightStreamExecutor) HttpRequest(context.Context, *Auth, *http.Request) (*http.Response, error) { + return nil, errors.New("not supported") +} + +func registerInFlightAuth(t *testing.T, m *Manager, authID, provider, model string) { + t.Helper() + auth := &Auth{ID: authID, Provider: provider, Status: StatusActive} + if _, errRegister := m.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("Register auth: %v", errRegister) + } + registry.GetGlobalRegistry().RegisterClient(authID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) +} + +func waitForInFlightCount(t *testing.T, m *Manager, want int) InFlightSnapshot { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + snapshot := m.InFlightSnapshot() + if snapshot.InFlight == int64(want) { + return snapshot + } + if time.Now().After(deadline) { + t.Fatalf("in-flight count = %d, want %d (snapshot: %+v)", snapshot.InFlight, want, snapshot) + } + time.Sleep(5 * time.Millisecond) + } +} + +// TestManager_InFlightSnapshot_NonStreaming verifies that an in-flight +// non-streaming request is visible in the manager snapshot while it executes. +func TestManager_InFlightSnapshot_NonStreaming(t *testing.T) { + executor := newInFlightBlockingExecutor("inflight-provider") + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + model := "inflight-model" + registerInFlightAuth(t, m, "auth-inflight-1", executor.Identifier(), model) + + req := cliproxyexecutor.Request{Model: model, Payload: []byte(`{"input":"hi"}`)} + done := make(chan error, 1) + go func() { + _, errExec := m.Execute(context.Background(), []string{executor.Identifier()}, req, cliproxyexecutor.Options{}) + done <- errExec + }() + + <-executor.entered + snapshot := waitForInFlightCount(t, m, 1) + if snapshot.ByProvider[executor.Identifier()] != 1 { + t.Fatalf("by_provider[%q] = %d, want 1 (snapshot: %+v)", executor.Identifier(), snapshot.ByProvider[executor.Identifier()], snapshot) + } + if snapshot.OldestStartedAt.IsZero() { + t.Fatal("expected oldest_started_at to be set while a request is in flight") + } + + executor.releaseMu.Do(func() { close(executor.release) }) + if errExec := <-done; errExec != nil { + t.Fatalf("Execute() error = %v", errExec) + } + waitForInFlightCount(t, m, 0) +} + +// TestManager_InFlightSnapshot_Streaming verifies that a long-lived streaming +// request remains counted until the chunk channel closes. +func TestManager_InFlightSnapshot_Streaming(t *testing.T) { + chunks := make(chan cliproxyexecutor.StreamChunk) + executor := &inFlightStreamExecutor{id: "inflight-stream-provider", chunks: chunks} + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + model := "inflight-stream-model" + registerInFlightAuth(t, m, "auth-inflight-stream-1", executor.Identifier(), model) + + req := cliproxyexecutor.Request{Model: model, Payload: []byte(`{"input":"hi"}`)} + type streamOutcome struct { + result *cliproxyexecutor.StreamResult + err error + } + outcome := make(chan streamOutcome, 1) + go func() { + result, errStream := m.ExecuteStream(context.Background(), []string{executor.Identifier()}, req, cliproxyexecutor.Options{Stream: true}) + outcome <- streamOutcome{result: result, err: errStream} + }() + // readStreamBootstrap blocks until the first payload chunk arrives. + chunks <- cliproxyexecutor.StreamChunk{Payload: []byte("data: bootstrap\n\n")} + streamRes := <-outcome + result, errStream := streamRes.result, streamRes.err + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + + waitForInFlightCount(t, m, 1) + + chunks <- cliproxyexecutor.StreamChunk{Payload: []byte("data: hello\n\n")} + if chunk, ok := <-result.Chunks; !ok || len(chunk.Payload) == 0 { + t.Fatalf("expected forwarded chunk, got ok=%v payload=%q", ok, chunk.Payload) + } + if snapshot := m.InFlightSnapshot(); snapshot.InFlight != 1 { + t.Fatalf("expected stream to remain in flight, snapshot: %+v", snapshot) + } + + close(chunks) + for range result.Chunks { + } + waitForInFlightCount(t, m, 0) +} + +// TestManager_InFlightSnapshot_DisabledInHomeMode verifies that the standalone +// in-flight tracker stays empty when Home mode is enabled, since the execution +// registry covers that mode. +func TestManager_InFlightSnapshot_DisabledInHomeMode(t *testing.T) { + executor := newInFlightBlockingExecutor("inflight-home-provider") + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + m.SetConfigSnapshot(&internalconfig.Config{Home: internalconfig.HomeConfig{Enabled: true}}) + + snapshot := m.InFlightSnapshot() + if snapshot.InFlight != 0 { + t.Fatalf("expected empty snapshot in home mode, got %+v", snapshot) + } +} + +// inFlightRetryableStatusError is a retryable upstream error for retry tests. +type inFlightRetryableStatusError struct{} + +func (inFlightRetryableStatusError) Error() string { return "upstream unavailable" } +func (inFlightRetryableStatusError) StatusCode() int { return http.StatusServiceUnavailable } + +// inFlightFailThenBlockExecutor fails the first Execute call with a retryable +// error and blocks in subsequent calls until released. +type inFlightFailThenBlockExecutor struct { + id string + calls atomic.Int32 + release chan struct{} + releaseOnce sync.Once +} + +func newInFlightFailThenBlockExecutor(id string) *inFlightFailThenBlockExecutor { + return &inFlightFailThenBlockExecutor{id: id, release: make(chan struct{})} +} + +func (e *inFlightFailThenBlockExecutor) Identifier() string { return e.id } + +func (e *inFlightFailThenBlockExecutor) Execute(ctx context.Context, _ *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + call := e.calls.Add(1) + if call == 1 { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return cliproxyexecutor.Response{}, inFlightRetryableStatusError{} + } + <-e.release + return cliproxyexecutor.Response{Payload: []byte(`{"status":"ok"}`)}, nil +} + +func (e *inFlightFailThenBlockExecutor) ExecuteStream(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return nil, errors.New("stream not supported") +} + +func (e *inFlightFailThenBlockExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) { + return auth, nil +} + +func (e *inFlightFailThenBlockExecutor) CountTokens(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, errors.New("not supported") +} + +func (e *inFlightFailThenBlockExecutor) HttpRequest(context.Context, *Auth, *http.Request) (*http.Response, error) { + return nil, errors.New("not supported") +} + +// TestManager_InFlightSnapshot_CoversRetryWait verifies that a request waiting +// between retry rounds still appears in the snapshot instead of blinking to 0. +func TestManager_InFlightSnapshot_CoversRetryWait(t *testing.T) { + executor := newInFlightFailThenBlockExecutor("inflight-retry-provider") + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + m.SetRetryConfig(1, 20*time.Second, 0) + + model := "inflight-retry-model" + if _, errRegister := m.Register(context.Background(), &Auth{ + ID: "auth-inflight-retry-1", + Provider: executor.Identifier(), + Metadata: map[string]any{"request_retry": 1, "disable_cooling": true}, + }); errRegister != nil { + t.Fatalf("Register auth: %v", errRegister) + } + registry.GetGlobalRegistry().RegisterClient("auth-inflight-retry-1", executor.Identifier(), []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient("auth-inflight-retry-1") + }) + + req := cliproxyexecutor.Request{Model: model, Payload: []byte(`{"input":"hi"}`)} + done := make(chan error, 1) + go func() { + _, errExec := m.Execute(context.Background(), []string{executor.Identifier()}, req, cliproxyexecutor.Options{}) + done <- errExec + }() + + // Wait for the first call to record its retryable failure. The request then + // enters the retry wait window while the second call blocks on release. + deadline := time.Now().Add(5 * time.Second) + for executor.calls.Load() < 1 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if executor.calls.Load() < 1 { + t.Fatalf("expected the first upstream call to happen, calls = %d", executor.calls.Load()) + } + // Allow the retry loop to record the failure and enter its wait or the + // blocking second call; either way the request is still active and must + // remain visible in the snapshot. + deadline = time.Now().Add(2 * time.Second) + for { + snapshot := m.InFlightSnapshot() + if snapshot.InFlight == 1 { + break + } + if time.Now().After(deadline) { + t.Fatalf("in_flight = %d during retry, want 1 (snapshot: %+v)", snapshot.InFlight, snapshot) + } + time.Sleep(5 * time.Millisecond) + } + + executor.releaseOnce.Do(func() { close(executor.release) }) + if errExec := <-done; errExec != nil { + t.Fatalf("Execute() error = %v", errExec) + } + waitForInFlightCount(t, m, 0) +} + +// TestManager_InFlightSnapshot_StreamCancel verifies that canceling the request +// context releases the in-flight scope even while the upstream chunk channel +// stays open and silent after the first chunk was already forwarded. +func TestManager_InFlightSnapshot_StreamCancel(t *testing.T) { + chunks := make(chan cliproxyexecutor.StreamChunk) + executor := &inFlightStreamExecutor{id: "inflight-cancel-provider", chunks: chunks} + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + model := "inflight-cancel-model" + registerInFlightAuth(t, m, "auth-inflight-cancel-1", executor.Identifier(), model) + + ctx, cancel := context.WithCancel(context.Background()) + req := cliproxyexecutor.Request{Model: model, Payload: []byte(`{"input":"hi"}`)} + + type streamOutcome struct { + result *cliproxyexecutor.StreamResult + err error + } + outcome := make(chan streamOutcome, 1) + go func() { + result, errStream := m.ExecuteStream(ctx, []string{executor.Identifier()}, req, cliproxyexecutor.Options{Stream: true}) + outcome <- streamOutcome{result: result, err: errStream} + }() + chunks <- cliproxyexecutor.StreamChunk{Payload: []byte("data: bootstrap\n\n")} + res := <-outcome + if res.err != nil { + t.Fatalf("ExecuteStream() error = %v", res.err) + } + result := res.result + + waitForInFlightCount(t, m, 1) + + // Consume the forwarded bootstrap chunk so the wrapper is blocked waiting + // for the next upstream chunk (receive branch) when cancel happens. + chunks <- cliproxyexecutor.StreamChunk{Payload: []byte("data: second\n\n")} + if chunk, ok := <-result.Chunks; !ok || len(chunk.Payload) == 0 { + t.Fatalf("expected forwarded chunk, got ok=%v payload=%q", ok, chunk.Payload) + } + if snapshot := m.InFlightSnapshot(); snapshot.InFlight != 1 { + t.Fatalf("expected stream to remain in flight, snapshot: %+v", snapshot) + } + + // The upstream keeps its chunk channel open but silent; canceling the + // request context must release the scope without needing another chunk. + cancel() + waitForInFlightCount(t, m, 0) + + // Close the source so the drain path and the output channel can finish + // instead of leaking a background goroutine. + close(chunks) + for range result.Chunks { + } +} + +// TestManager_InFlightSnapshot_StreamCancelBeforeConsume verifies the send +// branch: cancellation while the first chunk is still queued for the caller +// also releases the in-flight scope. +func TestManager_InFlightSnapshot_StreamCancelBeforeConsume(t *testing.T) { + chunks := make(chan cliproxyexecutor.StreamChunk) + executor := &inFlightStreamExecutor{id: "inflight-cancel-early-provider", chunks: chunks} + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + + model := "inflight-cancel-early-model" + registerInFlightAuth(t, m, "auth-inflight-cancel-early-1", executor.Identifier(), model) + + ctx, cancel := context.WithCancel(context.Background()) + req := cliproxyexecutor.Request{Model: model, Payload: []byte(`{"input":"hi"}`)} + + type streamOutcome struct { + result *cliproxyexecutor.StreamResult + err error + } + outcome := make(chan streamOutcome, 1) + go func() { + result, errStream := m.ExecuteStream(ctx, []string{executor.Identifier()}, req, cliproxyexecutor.Options{Stream: true}) + outcome <- streamOutcome{result: result, err: errStream} + }() + chunks <- cliproxyexecutor.StreamChunk{Payload: []byte("data: bootstrap\n\n")} + res := <-outcome + if res.err != nil { + t.Fatalf("ExecuteStream() error = %v", res.err) + } + result := res.result + + waitForInFlightCount(t, m, 1) + + // Cancel without consuming the queued bootstrap chunk; the send branch of + // the wrapper must observe the cancellation and release the scope. + cancel() + waitForInFlightCount(t, m, 0) + + close(chunks) + for range result.Chunks { + } +} diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index fd78b1e667b..4eba974b697 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -112,8 +112,11 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { } auth.UpdatedAt = now cooldownStateChanged := normalizeModelStates(auth) - if m.cooldownDisabledForAuth(auth) || auth.Disabled || auth.Status == StatusDisabled { + seedInitialForceCooldownDeadlines(auth) + if auth.Disabled || auth.Status == StatusDisabled { cooldownStateChanged = clearCooldownStateForAuth(auth, now) || cooldownStateChanged + } else if m.cooldownDisabledForAuth(auth) { + cooldownStateChanged = clearDisabledCooldownStateForAuth(auth, now) || cooldownStateChanged } auth.EnsureIndex() m.mu.Lock() @@ -134,6 +137,7 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { auth.CredentialVersion = 1 } auth.Generation = 1 + aliasTableBeforeSave := m.oauthModelAlias.Load() // Serialize this credential, but release the manager lock during store I/O. // Persist failures stay non-fatal, but must not be silent: a restart would // lose the credential that only exists in memory. @@ -144,6 +148,12 @@ func (m *Manager) Register(ctx context.Context, auth *Auth) (*Auth, error) { m.mu.Unlock() return nil, fmt.Errorf("auth %s changed registration during persistence", auth.ID) } + if m.oauthModelAlias.Load() != aliasTableBeforeSave { + cooldownStateChanged = m.migrateAuthAliasModelStatesLocked(auth, nil, now, false) || cooldownStateChanged + if len(auth.ModelStates) > 0 { + updateAggregatedAvailability(auth, now) + } + } auth.ClearFileSnapshot() authClone := auth.Clone() m.auths[auth.ID] = authClone @@ -418,6 +428,10 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo auth.Quota.ObservedAt = observation.ObservedAt auth.Quota.Signals = observation.Signals auth.cooldownRecordedSeq = existing.cooldownRecordedSeq + auth.forceCooldownUntil = existing.forceCooldownUntil + auth.credQuotaForceUntil = existing.credQuotaForceUntil + auth.credentialRetryAfter = existing.credentialRetryAfter + auth.forceCooldownSeeded = existing.forceCooldownSeeded } if credChanged || mode == updateModeRefresh { applyPreservedRejectedTokens(existing, auth, mode == updateModeRefresh) @@ -445,6 +459,8 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo auth.Unavailable = false auth.NextRetryAfter = time.Time{} auth.cooldownRecordedSeq = 0 + auth.forceCooldownUntil = time.Time{} + auth.credentialRetryAfter = time.Time{} auth.LastError = nil auth.StatusMessage = "" auth.Status = StatusActive @@ -504,6 +520,27 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo auth.Quota.ObservedAt = observation.ObservedAt auth.Quota.Signals = observation.Signals auth.cooldownRecordedSeq = existing.cooldownRecordedSeq + auth.forceCooldownUntil = existing.forceCooldownUntil + auth.credQuotaForceUntil = existing.credQuotaForceUntil + auth.credentialRetryAfter = existing.credentialRetryAfter + auth.forceCooldownSeeded = existing.forceCooldownSeeded + if auth.Status == StatusActive { + auth.Status = existing.Status + } + } else if !credChanged && mode == updateModeReplace && existing.forceCooldownUntil.After(now) && !auth.NextRetryAfter.After(now) { + auth.Unavailable = existing.Unavailable + auth.NextRetryAfter = existing.NextRetryAfter + auth.cooldownRecordedSeq = existing.cooldownRecordedSeq + auth.forceCooldownUntil = existing.forceCooldownUntil + auth.credQuotaForceUntil = existing.credQuotaForceUntil + auth.credentialRetryAfter = existing.credentialRetryAfter + auth.forceCooldownSeeded = existing.forceCooldownSeeded + if auth.LastError == nil && existing.LastError != nil { + auth.LastError = cloneError(existing.LastError) + } + if auth.StatusMessage == "" { + auth.StatusMessage = existing.StatusMessage + } if auth.Status == StatusActive { auth.Status = existing.Status } @@ -527,9 +564,12 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo } } auth.UpdatedAt = now - cooldownStateChanged = normalizeModelStates(auth) || cooldownStateChanged - if m.cooldownDisabledForAuth(auth) || auth.Disabled || auth.Status == StatusDisabled { + cooldownStateChanged = m.migrateAuthAliasModelStatesLocked(auth, nil, now, false) || cooldownStateChanged + seedInitialForceCooldownDeadlines(auth) + if auth.Disabled || auth.Status == StatusDisabled { cooldownStateChanged = clearCooldownStateForAuth(auth, now) || cooldownStateChanged + } else if m.cooldownDisabledForAuth(auth) { + cooldownStateChanged = clearDisabledCooldownStateForAuth(auth, now) || cooldownStateChanged } if existing.Metadata != nil { if persistedHints, hasHints := existing.Metadata["antigravity_capability_hints"]; hasHints { @@ -559,6 +599,10 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo return nil, false, false, fmt.Errorf("auth %s changed registration during persistence", auth.ID) } mergeAuthSaveDelta(auth, existingBeforeSave, existing, false) + if m.migrateAuthAliasModelStatesLocked(auth, nil, now, false) { + cooldownStateChanged = true + updateAggregatedAvailability(auth, now) + } if (auth.RejectedAccessToken == "" && existing.RejectedAccessToken != "") || (auth.RejectedSIWCAccessToken == "" && existing.RejectedSIWCAccessToken != "") { probe := auth.Clone() probe.CodexRefreshPatch = refreshPatchBeforeSave @@ -611,8 +655,17 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo if m.scheduler != nil { schedulerSnapshot = authClone.Clone() } + shouldForgetWeighted := authClone.Disabled || + authClone.Status == StatusDisabled || + (authWeight(existingBeforeSave) > 0 && authWeight(authClone) <= 0) || + executorKeyFromAuth(existingBeforeSave) != executorKeyFromAuth(authClone) + forgetEpoch := authClone.RegistrationEpoch + forgetGen := authClone.Generation m.mu.Unlock() _ = schedulerSnapshot + if shouldForgetWeighted { + m.forgetWeightedAuthUpTo(authClone.ID, forgetEpoch, forgetGen) + } return auth.Clone(), true, cooldownStateChanged, nil } @@ -687,6 +740,7 @@ func (m *Manager) RemoveIf(ctx context.Context, id string, predicate func(*Auth) m.authEpochs[id]++ tombstoneEpoch := m.authEpochs[id] m.mu.Unlock() + m.forgetWeightedAuthUpTo(id, tombstoneEpoch, ^uint64(0)) releaseMutation() if !shouldDeferAPIKeyModelAliasRebuild(ctx) { @@ -722,6 +776,22 @@ func (m *Manager) invalidateSessionAffinity(authID string) { } } +func (m *Manager) forgetWeightedAuthUpTo(authID string, maxEpoch, maxGen uint64) { + if m == nil || authID == "" { + return + } + sel := m.Selector() + if epochForgetter, ok := sel.(interface { + ForgetAuthUpTo(string, uint64, uint64) + }); ok && epochForgetter != nil { + epochForgetter.ForgetAuthUpTo(authID, maxEpoch, maxGen) + return + } + if forgetter, ok := sel.(interface{ ForgetAuth(string) }); ok && forgetter != nil { + forgetter.ForgetAuth(authID) + } +} + // Load resets manager state from the backing store. func (m *Manager) Load(ctx context.Context) error { // Exclude complete Save/publication transactions, including new registrations @@ -745,6 +815,7 @@ func (m *Manager) Load(ctx context.Context) error { return err } m.mu.Lock() + now := time.Now() previousAuths := m.auths m.auths = make(map[string]*Auth, len(items)) if m.authEpochs == nil { @@ -759,6 +830,11 @@ func (m *Manager) Load(ctx context.Context) error { continue } auth.EnsureIndex() + _ = m.migrateAuthAliasModelStatesLocked(auth, nil, now, false) + seedInitialForceCooldownDeadlines(auth) + if len(auth.ModelStates) > 0 { + updateAggregatedAvailability(auth, now) + } m.authEpochs[auth.ID] = max(m.authEpochs[auth.ID], auth.RegistrationEpoch) + 1 auth.RegistrationEpoch = m.authEpochs[auth.ID] auth.Generation = 1 @@ -804,6 +880,9 @@ func (m *Manager) Load(ctx context.Context) error { m.scheduler.RecordRemovalTombstone(rt.id, rt.epoch) } } + for _, rt := range removedTombstones { + m.forgetWeightedAuthUpTo(rt.id, rt.epoch, ^uint64(0)) + } m.structuralEpoch.Add(1) m.syncScheduler() return nil diff --git a/sdk/cliproxy/auth/conductor_models.go b/sdk/cliproxy/auth/conductor_models.go index bebb4374f96..d0d3f49a75b 100644 --- a/sdk/cliproxy/auth/conductor_models.go +++ b/sdk/cliproxy/auth/conductor_models.go @@ -237,38 +237,98 @@ func (m *Manager) clientModelProjectionForAuth(auth *Auth, routeModel string, no } state := existingModelState(auth, targetKey) - isSuspended := auth.Disabled || auth.Status == StatusDisabled - if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { - isSuspended = true + authDisabled := auth.Disabled || auth.Status == StatusDisabled + stateDisabled := state != nil && state.Status == StatusDisabled + terminalUnauthorized := hasUnauthorizedAuthFailure(auth) + openEnded := authDisabled || stateDisabled || terminalUnauthorized + isSuspended := openEnded + + var credQuotaUntil time.Time + credQuotaSuspended := false + if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" { + if auth.Quota.NextRecoverAt.IsZero() { + isSuspended = true + credQuotaSuspended = true + openEnded = true + } else if auth.Quota.NextRecoverAt.After(now) { + isSuspended = true + credQuotaSuspended = true + credQuotaUntil = auth.Quota.NextRecoverAt + } } + isQuotaExceeded := false - var suspendReason string + stateSuspended := false + var stateUntil time.Time if state != nil { - if state.Status == StatusDisabled || state.Unavailable || (!state.NextRetryAfter.IsZero() && state.NextRetryAfter.After(now)) { + if stateDisabled { + stateSuspended = true + } else if blocked, _, retryAfter := availabilityBlock(state.Unavailable, state.Quota.Exceeded, state.NextRetryAfter, state.Quota.NextRecoverAt, now); blocked { isSuspended = true + stateSuspended = true + if retryAfter.IsZero() { + openEnded = true + } else { + stateUntil = retryAfter + } } if state.Quota.Exceeded && (state.Quota.NextRecoverAt.IsZero() || state.Quota.NextRecoverAt.After(now)) { isQuotaExceeded = true } - if isSuspended { - suspendReason = cooldownReason(state.StatusMessage, state.Quota, state.LastError) - } } - if len(auth.ModelStates) == 0 && auth.Unavailable && auth.NextRetryAfter.After(now) { + + var authFallbackUntil time.Time + if len(auth.ModelStates) == 0 { // With no per-model states, scheduling falls back to the credential-wide // cooldown (isAuthBlockedForModel); the projection must agree with it. // When states exist, unmatched models stay schedulable by design, so the // credential-wide fields must not suspend them here either. - isSuspended = true + if blocked, _, retryAfter := availabilityBlock(auth.Unavailable, auth.Quota.Exceeded, auth.NextRetryAfter, auth.Quota.NextRecoverAt, now); blocked { + isSuspended = true + if retryAfter.IsZero() { + openEnded = true + } else { + authFallbackUntil = retryAfter + } + } + } + + var suspendReason string + var suspendUntil time.Time + if isSuspended { + switch { + case authDisabled || stateDisabled: + suspendReason = "disabled" + case terminalUnauthorized: + suspendReason = cooldownReason(auth.StatusMessage, QuotaState{}, auth.LastError) + if suspendReason == "" { + suspendReason = "unauthorized" + } + case stateSuspended: + suspendReason = cooldownReason(state.StatusMessage, state.Quota, state.LastError) + suspendUntil = stateUntil + if credQuotaSuspended && (strings.EqualFold(suspendReason, "quota") || strings.EqualFold(suspendReason, "credential_quota")) && credQuotaUntil.After(suspendUntil) { + suspendUntil = credQuotaUntil + } + default: + suspendUntil = authFallbackUntil + if credQuotaUntil.After(suspendUntil) { + suspendUntil = credQuotaUntil + } + } + if suspendReason == "" { + suspendReason = cooldownReason(auth.StatusMessage, auth.Quota, auth.LastError) + } } - if isSuspended && suspendReason == "" { - suspendReason = cooldownReason(auth.StatusMessage, auth.Quota, auth.LastError) + if openEnded || !isSuspended { + suspendUntil = time.Time{} } return registry.ClientModelProjection{ ModelID: targetModel, Suspended: isSuspended, SuspendReason: suspendReason, + SuspendUntil: suspendUntil, QuotaExceeded: isQuotaExceeded, } } @@ -284,7 +344,7 @@ func (m *Manager) stateModelForExecution(auth *Auth, routeModel, upstreamModel s } stateModel := executionResultModel(routeModel, upstreamModel, pooled) selectionModel := m.selectionModelForAuth(auth, routeModel) - if canonicalModelKey(selectionModel) == canonicalModelKey(upstreamModel) && strings.TrimSpace(selectionModel) != "" { + if sameCanonicalModelKey(selectionModel, upstreamModel) && strings.TrimSpace(selectionModel) != "" { return strings.TrimSpace(upstreamModel) } return stateModel diff --git a/sdk/cliproxy/auth/conductor_models_transient_projection_test.go b/sdk/cliproxy/auth/conductor_models_transient_projection_test.go new file mode 100644 index 00000000000..8976df8d6d3 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_models_transient_projection_test.go @@ -0,0 +1,301 @@ +package auth + +import ( + "context" + "net/http" + "testing" + "time" + + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" +) + +func openAIListedModelSet(models []map[string]any) map[string]bool { + out := make(map[string]bool, len(models)) + for _, m := range models { + if id, _ := m["id"].(string); id != "" { + out[id] = true + } + } + return out +} + +func TestManager_ClientModelProjection_TransientCooldownExpiresWithForkedAlias(t *testing.T) { + previousCooldown := transientErrorCooldownSeconds.Load() + transientErrorCooldownSeconds.Store(0) + t.Cleanup(func() { transientErrorCooldownSeconds.Store(previousCooldown) }) + + m := NewManager(nil, nil, nil) + m.SetOAuthModelAlias(map[string][]internalconfig.OAuthModelAlias{ + "xai": {{ + Name: "grok-4.7", + Alias: "grok-4.7-cp", + Fork: true, + ForceMapping: true, + }}, + }) + + auth := &Auth{ + ID: "xai-transient-7421", + Provider: "xai", + Status: StatusActive, + } + if _, errRegister := m.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + reg := registry.GetGlobalRegistry() + nowUnix := time.Now().Unix() + reg.RegisterClient(auth.ID, "xai", []*registry.ModelInfo{ + {ID: "grok-4.7", OwnedBy: "xai", Created: nowUnix}, + {ID: "grok-4.7-cp", OwnedBy: "xai", Created: nowUnix}, + {ID: "grok-4.6", OwnedBy: "xai", Created: nowUnix}, + }) + t.Cleanup(func() { reg.UnregisterClient(auth.ID) }) + + m.MarkResult(context.Background(), Result{ + AuthID: auth.ID, + Provider: "xai", + Model: "grok-4.7", + Success: false, + Error: &Error{ + HTTPStatus: http.StatusRequestTimeout, + Message: "xai stream error: stream disconnected", + }, + }) + + snap, ok := m.GetByID(auth.ID) + if !ok || snap == nil { + t.Fatal("expected auth snapshot after MarkResult") + } + state := existingModelState(snap, "grok-4.7") + if state == nil || !state.Unavailable || state.NextRetryAfter.IsZero() { + t.Fatalf("expected active transient model cooldown, got %+v", state) + } + + listedDuring := openAIListedModelSet(reg.GetAvailableModels("openai")) + if listedDuring["grok-4.7"] || listedDuring["grok-4.7-cp"] { + t.Fatalf("expected grok-4.7 and grok-4.7-cp to be hidden during live transient cooldown, got %v", listedDuring) + } + if !listedDuring["grok-4.6"] { + t.Fatalf("expected unaffected sibling grok-4.6 to remain listed, got %v", listedDuring) + } + + during := state.NextRetryAfter.Add(-time.Second) + after := state.NextRetryAfter.Add(time.Second) + + for _, modelID := range []string{"grok-4.7", "grok-4.7-cp"} { + selectionModel := m.selectionModelForAuth(snap, modelID) + blockedDuring, _, _ := isAuthBlockedForModel(snap, selectionModel, during) + if !blockedDuring { + t.Fatalf("expected selector to block %s during transient cooldown", modelID) + } + projDuring := m.clientModelProjectionForAuth(snap, modelID, during) + if !projDuring.Suspended { + t.Fatalf("expected %s to be projected suspended during transient cooldown: %+v", modelID, projDuring) + } + if !projDuring.SuspendUntil.Equal(state.NextRetryAfter) { + t.Fatalf("expected %s SuspendUntil=%v, got %v", modelID, state.NextRetryAfter, projDuring.SuspendUntil) + } + + blockedAfter, _, _ := isAuthBlockedForModel(snap, selectionModel, after) + if blockedAfter { + t.Fatalf("expected selector to unblock %s after transient cooldown expired", modelID) + } + projAfter := m.clientModelProjectionForAuth(snap, modelID, after) + if projAfter.Suspended { + t.Fatalf("expected %s projection Suspended=false once NextRetryAfter passed, got %+v", modelID, projAfter) + } + if !projAfter.SuspendUntil.IsZero() { + t.Fatalf("expected %s SuspendUntil to be zero once expired, got %v", modelID, projAfter.SuspendUntil) + } + } + + // Simulate the recorded transient deadline now lying in the past without a + // new MarkResult or credential refresh: /v1/models must list both models. + epoch := reg.ClientRegistrationEpoch(auth.ID) + staleUntil := time.Now().Add(-time.Second) + if !reg.ApplyClientModelProjections(auth.ID, epoch, snap.Generation, []registry.ClientModelProjection{ + {ModelID: "grok-4.7", Suspended: true, SuspendReason: "xai stream error: stream disconnected", SuspendUntil: staleUntil}, + {ModelID: "grok-4.7-cp", Suspended: true, SuspendReason: "xai stream error: stream disconnected", SuspendUntil: staleUntil}, + {ModelID: "grok-4.6"}, + }) { + t.Fatal("projection with past deadline rejected") + } + listedAfter := openAIListedModelSet(reg.GetAvailableModels("openai")) + if !listedAfter["grok-4.7"] || !listedAfter["grok-4.7-cp"] || !listedAfter["grok-4.6"] { + t.Fatalf("expected /v1/models to list grok-4.7 and grok-4.7-cp after deadline passed, got %v", listedAfter) + } +} + +func TestManager_ClientModelProjection_OpenEndedAuthGatesStayUnbounded(t *testing.T) { + now := time.Now() + transientUntil := now.Add(time.Minute) + m := NewManager(nil, nil, nil) + + cases := []struct { + name string + auth *Auth + }{ + { + name: "disabled_auth_with_model_transient_deadline", + auth: &Auth{ + ID: "disabled-with-transient", + Provider: "xai", + Disabled: true, + Status: StatusDisabled, + ModelStates: map[string]*ModelState{ + "grok-4.7": { + Unavailable: true, + Status: StatusError, + StatusMessage: "xai stream error: stream disconnected", + NextRetryAfter: transientUntil, + }, + }, + }, + }, + { + name: "disabled_auth_with_active_model_quota", + auth: &Auth{ + ID: "disabled-with-quota", + Provider: "xai", + Disabled: true, + Status: StatusDisabled, + ModelStates: map[string]*ModelState{ + "grok-4.7": { + Unavailable: true, + Status: StatusError, + NextRetryAfter: transientUntil, + Quota: QuotaState{ + Exceeded: true, + Reason: "quota", + NextRecoverAt: transientUntil, + }, + }, + }, + }, + }, + { + name: "disabled_auth_with_auth_level_deadline", + auth: &Auth{ + ID: "disabled-auth-level", + Provider: "xai", + Disabled: true, + Unavailable: true, + NextRetryAfter: transientUntil, + }, + }, + { + name: "terminal_unauthorized_auth_without_model_state", + auth: &Auth{ + ID: "unauthorized-no-model-state", + Provider: "xai", + Unavailable: true, + Status: StatusError, + LastError: &Error{ + HTTPStatus: http.StatusUnauthorized, + Code: "unauthorized", + Message: "refresh token invalid", + }, + }, + }, + { + name: "terminal_unauthorized_auth_with_model_transient_deadline", + auth: &Auth{ + ID: "unauthorized-with-transient", + Provider: "xai", + Unavailable: true, + Status: StatusError, + LastError: &Error{ + HTTPStatus: http.StatusUnauthorized, + Code: "unauthorized", + Message: "refresh token invalid", + }, + ModelStates: map[string]*ModelState{ + "grok-4.7": { + Unavailable: true, + Status: StatusError, + StatusMessage: "xai stream error: stream disconnected", + NextRetryAfter: transientUntil, + }, + }, + }, + }, + { + name: "disabled_model_state_with_transient_deadline", + auth: &Auth{ + ID: "model-disabled-with-transient", + Provider: "xai", + Status: StatusActive, + ModelStates: map[string]*ModelState{ + "grok-4.7": { + Unavailable: true, + Status: StatusDisabled, + StatusMessage: "model disabled", + NextRetryAfter: transientUntil, + }, + }, + }, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + proj := m.clientModelProjectionForAuth(tc.auth, "grok-4.7", now) + if !proj.Suspended { + t.Fatalf("expected Suspended=true, got %+v", proj) + } + if !proj.SuspendUntil.IsZero() { + t.Fatalf("open-ended gate must not carry finite SuspendUntil, got %v", proj.SuspendUntil) + } + if proj.SuspendReason == "quota" || proj.SuspendReason == "credential_quota" { + t.Fatalf("open-ended disabled/unauthorized gate must not carry quota SuspendReason, got %q", proj.SuspendReason) + } + }) + } +} + +func TestManager_ClientModelProjection_CredentialQuotaIgnoresExpiredModelTransientError(t *testing.T) { + now := time.Now() + recoverAt := now.Add(time.Hour) + m := NewManager(nil, nil, nil) + auth := &Auth{ + ID: "xai-cred-quota-stale-transient", + Provider: "xai", + Status: StatusError, + Quota: QuotaState{ + Exceeded: true, + Reason: "credential_quota", + NextRecoverAt: recoverAt, + }, + ModelStates: map[string]*ModelState{ + "grok-4.7": { + Unavailable: true, + Status: StatusError, + StatusMessage: "xai stream error: stream disconnected", + NextRetryAfter: now.Add(-time.Minute), + LastError: &Error{ + HTTPStatus: http.StatusRequestTimeout, + Message: "xai stream error: stream disconnected", + }, + }, + }, + } + + proj := m.clientModelProjectionForAuth(auth, "grok-4.7", now) + if !proj.Suspended { + t.Fatalf("expected model under live credential_quota to be suspended, got %+v", proj) + } + if proj.SuspendReason != "credential_quota" { + t.Fatalf("expected SuspendReason=%q so sole-credential quota stays listed, got %q", "credential_quota", proj.SuspendReason) + } + if !proj.SuspendUntil.Equal(recoverAt) { + t.Fatalf("expected SuspendUntil=%v, got %v", recoverAt, proj.SuspendUntil) + } + + // Sibling model with no ModelState entry also inherits the credential_quota deadline. + siblingProj := m.clientModelProjectionForAuth(auth, "grok-4.6", now) + if !siblingProj.Suspended || siblingProj.SuspendReason != "credential_quota" || !siblingProj.SuspendUntil.Equal(recoverAt) { + t.Fatalf("unexpected sibling projection under credential_quota: %+v", siblingProj) + } +} diff --git a/sdk/cliproxy/auth/conductor_oauth_alias_nofork_test.go b/sdk/cliproxy/auth/conductor_oauth_alias_nofork_test.go index 5f68d06f591..c404d046372 100644 --- a/sdk/cliproxy/auth/conductor_oauth_alias_nofork_test.go +++ b/sdk/cliproxy/auth/conductor_oauth_alias_nofork_test.go @@ -4296,3 +4296,646 @@ func TestManager_Load_MonotonicEpochAssignment_AndRemovalTombstones(t *testing.T } } } + +type stub429CooldownExecutor struct { + id string + retryAfter time.Duration + + mu sync.Mutex + models []string +} + +func (e *stub429CooldownExecutor) Identifier() string { return e.id } + +func (e *stub429CooldownExecutor) Execute(_ context.Context, _ *Auth, req cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + e.mu.Lock() + e.models = append(e.models, req.Model) + e.mu.Unlock() + ra := e.retryAfter + return cliproxyexecutor.Response{}, withTrustedRetryAfter(&Error{ + Code: "rate_limit_exceeded", + Message: "upstream 429 cooldown", + HTTPStatus: http.StatusTooManyRequests, + }, &ra) +} + +func (e *stub429CooldownExecutor) ExecuteStream(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return nil, &Error{HTTPStatus: http.StatusNotImplemented, Message: "ExecuteStream not implemented"} +} + +func (e *stub429CooldownExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) { + return auth, nil +} + +func (e *stub429CooldownExecutor) CountTokens(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, &Error{HTTPStatus: http.StatusNotImplemented, Message: "CountTokens not implemented"} +} + +func (e *stub429CooldownExecutor) HttpRequest(context.Context, *Auth, *http.Request) (*http.Response, error) { + return nil, &Error{HTTPStatus: http.StatusNotImplemented, Message: "HttpRequest not implemented"} +} + +func (e *stub429CooldownExecutor) Calls() []string { + e.mu.Lock() + defer e.mu.Unlock() + out := make([]string, len(e.models)) + copy(out, e.models) + return out +} + +func TestManager_Issue7360_Shape1_MixedCaseAliasAndLowercaseModelIDShareCooldown(t *testing.T) { + const ( + provider = "deepseek-plugin" + mixedCaseModel = "DeepSeek-V4.1-flash-sg" + lowerCaseModel = "deepseek-v4.1-flash-sg" + aliasModel = "DeepSeek V4.1 flash" + authID = "auth-issue7360-shape1" + ) + + manager := NewManager(nil, nil, nil) + executor := &stub429CooldownExecutor{id: provider, retryAfter: time.Hour} + manager.RegisterExecutor(executor) + manager.SetOAuthModelAlias(map[string][]internalconfig.OAuthModelAlias{ + provider: {{ + Name: mixedCaseModel, + Alias: aliasModel, + Fork: true, + }}, + }) + + auth := &Auth{ + ID: authID, + Provider: provider, + Status: StatusActive, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("register auth: %v", errReg) + } + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, provider, []*registry.ModelInfo{ + {ID: lowerCaseModel}, + }) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + manager.RefreshSchedulerEntry(authID) + + _, errFirst := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: aliasModel}, cliproxyexecutor.Options{}) + if errFirst == nil { + t.Fatal("expected first Execute to fail with 429") + } + if calls := executor.Calls(); len(calls) != 1 || calls[0] != mixedCaseModel { + t.Fatalf("after first Execute, calls = %v, want [%q]", calls, mixedCaseModel) + } + + _, errSecond := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: lowerCaseModel}, cliproxyexecutor.Options{}) + if errSecond == nil { + t.Fatal("expected second Execute to fail due to live cooldown") + } + if calls := executor.Calls(); len(calls) != 1 { + t.Fatalf("expected second Execute to be blocked by live cooldown without calling upstream again, got calls = %v", calls) + } + + manager.mu.RLock() + currentAuth := manager.auths[authID] + manager.mu.RUnlock() + if len(currentAuth.ModelStates) != 1 { + t.Fatalf("expected exactly 1 ModelStates cell, got %d: %#v", len(currentAuth.ModelStates), currentAuth.ModelStates) + } + if !reg.IsModelSuspendedForClient(authID, lowerCaseModel) { + t.Fatalf("expected %q to be suspended in registry for %s", lowerCaseModel, authID) + } +} + +func TestManager_Issue7360_Shape2_CooldownRecordedBeforeAliasMappingMigratesToTarget(t *testing.T) { + const ( + provider = "deepseek-plugin" + lowerCaseModel = "deepseek-v4.1-flash-sg" + aliasModel = "DeepSeek V4.1 flash" + ) + + t.Run("execute-before-alias-mapping", func(t *testing.T) { + const authID = "auth-issue7360-shape2-exec" + manager := NewManager(nil, nil, nil) + executor := &stub429CooldownExecutor{id: provider, retryAfter: time.Hour} + manager.RegisterExecutor(executor) + + auth := &Auth{ + ID: authID, + Provider: provider, + Status: StatusActive, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("register auth: %v", errReg) + } + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, provider, []*registry.ModelInfo{ + {ID: lowerCaseModel}, + {ID: aliasModel}, + }) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + manager.RefreshSchedulerEntry(authID) + + _, errFirst := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: aliasModel}, cliproxyexecutor.Options{}) + if errFirst == nil { + t.Fatal("expected first Execute to fail with 429") + } + if calls := executor.Calls(); len(calls) != 1 || calls[0] != aliasModel { + t.Fatalf("after first Execute, calls = %v, want [%q]", calls, aliasModel) + } + + manager.SetOAuthModelAlias(map[string][]internalconfig.OAuthModelAlias{ + provider: {{ + Name: lowerCaseModel, + Alias: aliasModel, + Fork: true, + }}, + }) + + _, errSecond := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: aliasModel}, cliproxyexecutor.Options{}) + if errSecond == nil { + t.Fatal("expected second Execute to fail due to live cooldown") + } + if calls := executor.Calls(); len(calls) != 1 { + t.Fatalf("expected second Execute to honour cooldown recorded before alias mapping without calling upstream again, got calls = %v", calls) + } + + _, errThird := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: lowerCaseModel}, cliproxyexecutor.Options{}) + if errThird == nil { + t.Fatal("expected third Execute on target model to fail due to live cooldown") + } + if calls := executor.Calls(); len(calls) != 1 { + t.Fatalf("expected third Execute on target model to honour migrated cooldown without calling upstream again, got calls = %v", calls) + } + + manager.mu.RLock() + currentAuth := manager.auths[authID] + manager.mu.RUnlock() + if len(currentAuth.ModelStates) != 1 { + t.Fatalf("expected exactly 1 ModelStates cell after alias migration, got %d: %#v", len(currentAuth.ModelStates), currentAuth.ModelStates) + } + if _, existsStale := currentAuth.ModelStates[aliasModel]; existsStale { + t.Fatalf("expected stale route key %q to be migrated away from ModelStates, got %#v", aliasModel, currentAuth.ModelStates) + } + if state := currentAuth.ModelStates[lowerCaseModel]; state == nil || !state.Unavailable { + t.Fatalf("expected target key %q to hold migrated active cooldown, got %#v", lowerCaseModel, state) + } + }) + + t.Run("preexisting-alias-cooldown-with-only-lowercase-model-registered", func(t *testing.T) { + const authID = "auth-issue7360-shape2-preexisting" + manager := NewManager(nil, nil, nil) + executor := &stub429CooldownExecutor{id: provider, retryAfter: time.Hour} + manager.RegisterExecutor(executor) + + retryUntil := time.Now().Add(time.Hour) + auth := &Auth{ + ID: authID, + Provider: provider, + Status: StatusActive, + ModelStates: map[string]*ModelState{ + aliasModel: { + Unavailable: true, + Status: StatusError, + StatusMessage: "quota", + NextRetryAfter: retryUntil, + Quota: QuotaState{ + Exceeded: true, + Reason: "quota", + NextRecoverAt: retryUntil, + }, + }, + }, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("register auth: %v", errReg) + } + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, provider, []*registry.ModelInfo{ + {ID: lowerCaseModel}, + }) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + manager.RefreshSchedulerEntry(authID) + + manager.SetOAuthModelAlias(map[string][]internalconfig.OAuthModelAlias{ + provider: {{ + Name: lowerCaseModel, + Alias: aliasModel, + Fork: true, + }}, + }) + + _, errSecond := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: aliasModel}, cliproxyexecutor.Options{}) + if errSecond == nil { + t.Fatal("expected Execute via alias to fail due to live cooldown") + } + if calls := executor.Calls(); len(calls) != 0 { + t.Fatalf("expected Execute via alias to honour pre-existing cooldown without calling upstream, got calls = %v", calls) + } + + _, errThird := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: lowerCaseModel}, cliproxyexecutor.Options{}) + if errThird == nil { + t.Fatal("expected Execute on target model to fail due to live cooldown") + } + if calls := executor.Calls(); len(calls) != 0 { + t.Fatalf("expected Execute on target model to honour migrated cooldown without calling upstream, got calls = %v", calls) + } + + manager.mu.RLock() + currentAuth := manager.auths[authID] + manager.mu.RUnlock() + if len(currentAuth.ModelStates) != 1 { + t.Fatalf("expected exactly 1 ModelStates cell after alias migration, got %d: %#v", len(currentAuth.ModelStates), currentAuth.ModelStates) + } + if _, existsStale := currentAuth.ModelStates[aliasModel]; existsStale { + t.Fatalf("expected stale route key %q to be migrated away from ModelStates, got %#v", aliasModel, currentAuth.ModelStates) + } + if state := currentAuth.ModelStates[lowerCaseModel]; state == nil || !state.Unavailable { + t.Fatalf("expected target key %q to hold migrated active cooldown, got %#v", lowerCaseModel, state) + } + if !reg.IsModelSuspendedForClient(authID, lowerCaseModel) { + t.Fatalf("expected %q to be suspended in registry for %s", lowerCaseModel, authID) + } + }) + + t.Run("inflight-alias-request-completes-after-alias-mapping", func(t *testing.T) { + const authID = "auth-issue7360-shape2-inflight" + manager := NewManager(nil, nil, nil) + + startedCh := make(chan struct{}) + releaseCh := make(chan struct{}) + var callsMu sync.Mutex + var calls []string + retryAfter := time.Hour + + manager.RegisterExecutor(&customStreamMockExecutor{ + identifier: provider, + mockCustomErrorExecutor: mockCustomErrorExecutor{ + executeFn: func(_ context.Context, _ *Auth, req cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + callsMu.Lock() + callNum := len(calls) + 1 + calls = append(calls, req.Model) + callsMu.Unlock() + if callNum == 1 { + close(startedCh) + <-releaseCh + } + return cliproxyexecutor.Response{}, withTrustedRetryAfter(&Error{ + Code: "rate_limit_exceeded", + Message: "upstream 429 cooldown", + HTTPStatus: http.StatusTooManyRequests, + }, &retryAfter) + }, + }, + }) + + auth := &Auth{ + ID: authID, + Provider: provider, + Status: StatusActive, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("register auth: %v", errReg) + } + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, provider, []*registry.ModelInfo{ + {ID: lowerCaseModel}, + {ID: aliasModel}, + }) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + manager.RefreshSchedulerEntry(authID) + + doneCh := make(chan error, 1) + go func() { + _, errExec := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: aliasModel}, cliproxyexecutor.Options{}) + doneCh <- errExec + }() + + <-startedCh + manager.SetOAuthModelAlias(map[string][]internalconfig.OAuthModelAlias{ + provider: {{ + Name: lowerCaseModel, + Alias: aliasModel, + Fork: true, + }}, + }) + close(releaseCh) + + if errFirst := <-doneCh; errFirst == nil { + t.Fatal("expected in-flight Execute to fail with 429") + } + + _, errSecond := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: lowerCaseModel}, cliproxyexecutor.Options{}) + if errSecond == nil { + t.Fatal("expected Execute on target model to fail due to live cooldown") + } + _, errThird := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: aliasModel}, cliproxyexecutor.Options{}) + if errThird == nil { + t.Fatal("expected Execute via alias to fail due to live cooldown") + } + + callsMu.Lock() + gotCalls := append([]string(nil), calls...) + callsMu.Unlock() + if len(gotCalls) != 1 { + t.Fatalf("expected only 1 upstream call, got %v", gotCalls) + } + + manager.mu.RLock() + currentAuth := manager.auths[authID] + manager.mu.RUnlock() + if len(currentAuth.ModelStates) != 1 { + t.Fatalf("expected exactly 1 ModelStates cell, got %d: %#v", len(currentAuth.ModelStates), currentAuth.ModelStates) + } + if _, existsStale := currentAuth.ModelStates[aliasModel]; existsStale { + t.Fatalf("expected stale route key %q not to exist in ModelStates, got %#v", aliasModel, currentAuth.ModelStates) + } + if state := currentAuth.ModelStates[lowerCaseModel]; state == nil || !state.Unavailable { + t.Fatalf("expected target key %q to hold active cooldown, got %#v", lowerCaseModel, state) + } + }) + + t.Run("chained-alias-with-only-intermediate-target-registered-preserves-cooldown", func(t *testing.T) { + const ( + authID = "auth-issue7360-chained-intermediate" + routeB = "DeepSeek V4.1 flash" + targetA = "deepseek-v4.1-flash-sg" + targetC = "deepseek-v4.1-flash-global" + ) + manager := NewManager(nil, nil, nil) + executor := &stub429CooldownExecutor{id: provider, retryAfter: time.Hour} + manager.RegisterExecutor(executor) + + aliases := map[string][]internalconfig.OAuthModelAlias{ + provider: { + {Name: targetA, Alias: routeB, Fork: true}, + {Name: targetC, Alias: targetA, Fork: true}, + }, + } + manager.SetOAuthModelAlias(aliases) + + auth := &Auth{ + ID: authID, + Provider: provider, + Status: StatusActive, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("register auth: %v", errReg) + } + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, provider, []*registry.ModelInfo{ + {ID: targetA}, + }) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + manager.RefreshSchedulerEntry(authID) + + _, errFirst := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: routeB}, cliproxyexecutor.Options{}) + if errFirst == nil { + t.Fatal("expected first Execute for routeB to fail with 429") + } + if calls := executor.Calls(); len(calls) != 1 || calls[0] != targetA { + t.Fatalf("after first Execute, calls = %v, want [%q]", calls, targetA) + } + + // Re-applying alias configuration or reconciling must not migrate targetA's cooldown to targetC + manager.SetOAuthModelAlias(aliases) + manager.ReconcileRegistryModelStates(context.Background(), authID) + + _, errSecond := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: routeB}, cliproxyexecutor.Options{}) + if errSecond == nil { + t.Fatal("expected second Execute for routeB to be blocked by cooldown on targetA") + } + if calls := executor.Calls(); len(calls) != 1 { + t.Fatalf("expected second Execute for routeB not to call upstream again, got calls = %v", calls) + } + }) + + t.Run("atomic-multi-auth-migration-while-first-auth-save-is-blocked", func(t *testing.T) { + const ( + authID1 = "auth-issue7360-atomic-1" + authID2 = "auth-issue7360-atomic-2" + ) + saveBlockedCh := make(chan struct{}) + saveReleaseCh := make(chan struct{}) + var releaseOnce sync.Once + releaseSave := func() { releaseOnce.Do(func() { close(saveReleaseCh) }) } + t.Cleanup(releaseSave) + var blockSaves sync.Once + var shouldBlockSaves sync.Mutex + blockEnabled := false + + store := &blockingSelectiveAuthStore{ + onSave: func(_ *Auth) { + shouldBlockSaves.Lock() + enabled := blockEnabled + shouldBlockSaves.Unlock() + if !enabled { + return + } + blockSaves.Do(func() { + close(saveBlockedCh) + <-saveReleaseCh + }) + }, + } + + manager := NewManager(store, nil, nil) + executor := &stub429CooldownExecutor{id: provider, retryAfter: time.Hour} + manager.RegisterExecutor(executor) + + retryUntil := time.Now().Add(time.Hour) + for _, id := range []string{authID1, authID2} { + auth := &Auth{ + ID: id, + Provider: provider, + Status: StatusActive, + Metadata: map[string]any{"type": provider}, + ModelStates: map[string]*ModelState{ + aliasModel: { + Unavailable: true, + Status: StatusError, + StatusMessage: "quota", + NextRetryAfter: retryUntil, + Quota: QuotaState{ + Exceeded: true, + Reason: "quota", + NextRecoverAt: retryUntil, + }, + }, + }, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("register %s: %v", id, errReg) + } + } + + reg := registry.GetGlobalRegistry() + for _, id := range []string{authID1, authID2} { + reg.RegisterClient(id, provider, []*registry.ModelInfo{{ID: lowerCaseModel}}) + } + t.Cleanup(func() { + reg.UnregisterClient(authID1) + reg.UnregisterClient(authID2) + }) + manager.RefreshSchedulerEntry(authID1) + manager.RefreshSchedulerEntry(authID2) + + shouldBlockSaves.Lock() + blockEnabled = true + shouldBlockSaves.Unlock() + + aliasDoneCh := make(chan struct{}) + go func() { + manager.SetOAuthModelAlias(map[string][]internalconfig.OAuthModelAlias{ + provider: {{ + Name: lowerCaseModel, + Alias: aliasModel, + Fork: true, + }}, + }) + close(aliasDoneCh) + }() + + <-saveBlockedCh + // While the first credential's store persistence is blocked, both credentials + // must already have migrated their in-memory cooldowns atomically with the alias table. + _, errExecDuringSave := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: aliasModel}, cliproxyexecutor.Options{}) + if errExecDuringSave == nil { + t.Fatal("expected Execute during SetOAuthModelAlias persistence to be blocked by migrated cooldowns on both credentials") + } + if calls := executor.Calls(); len(calls) != 0 { + t.Fatalf("expected 0 upstream calls during blocked persistence, got %v", calls) + } + + releaseSave() + <-aliasDoneCh + }) + + t.Run("concurrent-load-and-alias-publication-preserves-cooldown", func(t *testing.T) { + const authID = "auth-issue7360-load-race" + listBlockedCh := make(chan struct{}) + listReleaseCh := make(chan struct{}) + var releaseOnce sync.Once + releaseList := func() { releaseOnce.Do(func() { close(listReleaseCh) }) } + t.Cleanup(releaseList) + + retryUntil := time.Now().Add(time.Hour) + diskSnapshot := &Auth{ + ID: authID, + Provider: provider, + Status: StatusActive, + Metadata: map[string]any{"type": provider}, + ModelStates: map[string]*ModelState{ + aliasModel: { + Unavailable: true, + Status: StatusError, + StatusMessage: "quota", + NextRetryAfter: retryUntil, + Quota: QuotaState{ + Exceeded: true, + Reason: "quota", + NextRecoverAt: retryUntil, + }, + }, + }, + } + + var listOnce sync.Once + store := &blockingSelectiveAuthStore{ + onList: func() ([]*Auth, error) { + listOnce.Do(func() { + close(listBlockedCh) + <-listReleaseCh + }) + return []*Auth{diskSnapshot.Clone()}, nil + }, + } + + manager := NewManager(store, nil, nil) + executor := &stub429CooldownExecutor{id: provider, retryAfter: time.Hour} + manager.RegisterExecutor(executor) + if _, errReg := manager.Register(context.Background(), diskSnapshot.Clone()); errReg != nil { + t.Fatalf("register auth: %v", errReg) + } + + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, provider, []*registry.ModelInfo{{ID: lowerCaseModel}}) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + manager.RefreshSchedulerEntry(authID) + + loadDoneCh := make(chan error, 1) + go func() { + loadDoneCh <- manager.Load(context.Background()) + }() + + <-listBlockedCh + aliasDoneCh := make(chan struct{}) + go func() { + manager.SetOAuthModelAlias(map[string][]internalconfig.OAuthModelAlias{ + provider: {{ + Name: lowerCaseModel, + Alias: aliasModel, + Fork: true, + }}, + }) + close(aliasDoneCh) + }() + + releaseList() + if errLoad := <-loadDoneCh; errLoad != nil { + t.Fatalf("manager.Load failed: %v", errLoad) + } + <-aliasDoneCh + + for _, modelSpelling := range []string{aliasModel, lowerCaseModel} { + _, errExec := manager.Execute(context.Background(), []string{provider}, cliproxyexecutor.Request{Model: modelSpelling}, cliproxyexecutor.Options{}) + if errExec == nil { + t.Fatalf("expected Execute(%q) after concurrent Load and SetOAuthModelAlias to be blocked by cooldown", modelSpelling) + } + } + if calls := executor.Calls(); len(calls) != 0 { + t.Fatalf("expected 0 upstream calls after concurrent Load and SetOAuthModelAlias, got %v", calls) + } + }) +} + +type blockingSelectiveAuthStore struct { + onSave func(auth *Auth) + onList func() ([]*Auth, error) +} + +func (s *blockingSelectiveAuthStore) List(context.Context) ([]*Auth, error) { + if s.onList != nil { + return s.onList() + } + return nil, nil +} + +func (s *blockingSelectiveAuthStore) Save(_ context.Context, auth *Auth) (string, error) { + if s.onSave != nil { + s.onSave(auth) + } + if auth != nil { + return auth.ID, nil + } + return "", nil +} + +func (s *blockingSelectiveAuthStore) Delete(context.Context, string) error { + return nil +} diff --git a/sdk/cliproxy/auth/conductor_persistence.go b/sdk/cliproxy/auth/conductor_persistence.go index fef0e160024..6fac5a37ece 100644 --- a/sdk/cliproxy/auth/conductor_persistence.go +++ b/sdk/cliproxy/auth/conductor_persistence.go @@ -2,9 +2,11 @@ package auth import ( "context" + "maps" "reflect" "sync" "sync/atomic" + "time" log "github.com/sirupsen/logrus" ) @@ -277,6 +279,11 @@ func mergeAuthSaveDelta(target, before, after *Auth, preserveConcurrent bool) { if d.IsNil() { d.Set(reflect.MakeMap(d.Type())) } + if field.Name == "ModelStates" && newValue.IsValid() && !newValue.IsNil() { + if ms, ok := newValue.Interface().(*ModelState); ok { + newValue = reflect.ValueOf(ms.Clone()) + } + } d.SetMapIndex(key, newValue) } continue @@ -285,6 +292,43 @@ func mergeAuthSaveDelta(target, before, after *Auth, preserveConcurrent bool) { d.Set(n) } } + mergeRuntimeCooldownSaveDelta(target, before, after, preserveConcurrent) +} + +func mergeRuntimeCooldownSaveDelta(target, before, after *Auth, preserveConcurrent bool) { + if target == nil || before == nil || after == nil { + return + } + if !after.forceCooldownUntil.Equal(before.forceCooldownUntil) && (!preserveConcurrent || target.forceCooldownUntil.Equal(before.forceCooldownUntil)) { + target.forceCooldownUntil = after.forceCooldownUntil + } + if !after.credQuotaForceUntil.Equal(before.credQuotaForceUntil) && (!preserveConcurrent || target.credQuotaForceUntil.Equal(before.credQuotaForceUntil)) { + target.credQuotaForceUntil = after.credQuotaForceUntil + } + if !after.credentialRetryAfter.Equal(before.credentialRetryAfter) && (!preserveConcurrent || target.credentialRetryAfter.Equal(before.credentialRetryAfter)) { + target.credentialRetryAfter = after.credentialRetryAfter + } + if after.forceCooldownSeeded != before.forceCooldownSeeded && (!preserveConcurrent || target.forceCooldownSeeded == before.forceCooldownSeeded) { + target.forceCooldownSeeded = after.forceCooldownSeeded + } + if after.cooldownRecordedSeq != before.cooldownRecordedSeq && (!preserveConcurrent || target.cooldownRecordedSeq == before.cooldownRecordedSeq) { + target.cooldownRecordedSeq = after.cooldownRecordedSeq + } + if !maps.Equal(after.Quota.cooldownSignals, before.Quota.cooldownSignals) && (!preserveConcurrent || maps.Equal(target.Quota.cooldownSignals, before.Quota.cooldownSignals)) { + target.Quota.cooldownSignals = maps.Clone(after.Quota.cooldownSignals) + } + if after.Quota.cooldownEvaluated != before.Quota.cooldownEvaluated && (!preserveConcurrent || target.Quota.cooldownEvaluated == before.Quota.cooldownEvaluated) { + target.Quota.cooldownEvaluated = after.Quota.cooldownEvaluated + } + if (before.Unavailable || before.Quota.Exceeded) && + after.Unavailable == before.Unavailable && + after.NextRetryAfter.Equal(before.NextRetryAfter) && + !target.Unavailable && target.NextRetryAfter.IsZero() && + (!target.Quota.Exceeded || target.Quota.NextRecoverAt.IsZero()) { + target.forceCooldownUntil = time.Time{} + target.credQuotaForceUntil = time.Time{} + target.credentialRetryAfter = time.Time{} + } } func equalSaveValue(a, b reflect.Value) bool { diff --git a/sdk/cliproxy/auth/conductor_pinned_test.go b/sdk/cliproxy/auth/conductor_pinned_test.go new file mode 100644 index 00000000000..0f183bc6ebe --- /dev/null +++ b/sdk/cliproxy/auth/conductor_pinned_test.go @@ -0,0 +1,96 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "net/http" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +func TestManagerNonWeightedPinnedSelection(t *testing.T) { + for _, mixed := range []bool{false, true} { + for _, affinity := range []bool{false, true} { + for _, strategy := range []string{"round-robin", "fill-first"} { + t.Run(fmt.Sprintf("mixed=%t/affinity=%t/%s", mixed, affinity, strategy), func(t *testing.T) { + var selector Selector = &RoundRobinSelector{} + if strategy == "fill-first" { + selector = &FillFirstSelector{} + } + if affinity { + sticky := NewSessionAffinitySelector(selector) + t.Cleanup(sticky.Stop) + selector = sticky + } + manager := NewManager(nil, selector, nil) + const provider, model = "pinned-non-weighted", "pinned-model" + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + pinnedID := t.Name() + "-pinned" + for i := range 32 { + auth := &Auth{ + ID: fmt.Sprintf("%s-other-%02d", t.Name(), i), Provider: provider, Status: StatusActive, + Attributes: map[string]string{AttributeAuthKind: AuthKindAPIKey, "priority": "10"}, + } + if i == 0 { + auth.ID = pinnedID + auth.Attributes["priority"] = "0" + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + if _, errRegister := manager.Register(WithSkipPersist(t.Context()), auth); errRegister != nil { + t.Fatal(errRegister) + } + } + // Normalize the legacy selection signatures for the same pinning checks. + pick := func(ctx context.Context, id string, tried map[string]struct{}) (*Auth, error) { + opts := cliproxyexecutor.Options{ + Headers: http.Header{"Session_id": {"non-weighted-pinned"}}, + Metadata: map[string]any{cliproxyexecutor.PinnedAuthMetadataKey: id}, + } + if mixed { + auth, _, _, errPick := manager.pickNextMixedLegacy(ctx, []string{provider}, model, opts, tried) + return auth, errPick + } + auth, _, errPick := manager.pickNextLegacy(ctx, provider, model, opts, tried) + return auth, errPick + } + ctx := withRequiredAuthKind(t.Context(), AuthKindAPIKey) + for range 3 { + if auth, errPick := pick(ctx, pinnedID, nil); errPick != nil || auth == nil || auth.ID != pinnedID { + t.Fatalf("lower-priority pin not enforced: auth=%v err=%v", auth, errPick) + } + } + for _, tc := range []struct { + name string + ctx context.Context + id string + tried map[string]struct{} + }{ + {name: "missing pin", ctx: ctx, id: "missing"}, + {name: "already tried", ctx: ctx, id: pinnedID, tried: map[string]struct{}{pinnedID: {}}}, + {name: "ineligible kind", ctx: withRequiredAuthKind(t.Context(), AuthKindOAuth), id: pinnedID}, + } { + auth, errPick := pick(tc.ctx, tc.id, tc.tried) + var authErr *Error + if auth != nil || !errors.As(errPick, &authErr) || authErr.Code != "auth_not_found" { + t.Fatalf("%s: auth=%v err=%v, want auth_not_found", tc.name, auth, errPick) + } + } + if sticky, ok := selector.(*SessionAffinitySelector); ok { + namespace := provider + if mixed { + namespace = "mixed" + } + id := CanonicalSessionID(http.Header{"Session_id": {"non-weighted-pinned"}}, nil, nil) + if binding, found := sticky.cache.Get(namespace + "::" + id + "::" + model); !found || binding != pinnedID { + t.Fatalf("pinning checks changed the sticky binding: %q, found=%t", binding, found) + } + } + }) + } + } + } +} diff --git a/sdk/cliproxy/auth/conductor_pool_cooldown_test.go b/sdk/cliproxy/auth/conductor_pool_cooldown_test.go new file mode 100644 index 00000000000..87302417c2b --- /dev/null +++ b/sdk/cliproxy/auth/conductor_pool_cooldown_test.go @@ -0,0 +1,459 @@ +package auth + +import ( + "context" + "errors" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +const issue7521PoolModel = "claude-sonnet-4-6-issue-7521" + +func newIssue7521Manager( + t *testing.T, + selector Selector, + exec ProviderExecutor, + auths ...*Auth, +) *Manager { + t.Helper() + withQuotaCooldownEnabled(t) + if selector == nil { + selector = &RoundRobinSelector{} + } + manager := NewManager(nil, selector, nil) + manager.SetRetryConfig(2, 30*time.Second, 0) + manager.RegisterExecutor(exec) + reg := registry.GetGlobalRegistry() + for _, auth := range auths { + authID := auth.ID + reg.RegisterClient(authID, auth.Provider, []*registry.ModelInfo{{ID: issue7521PoolModel}}) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatalf("register auth %s: %v", authID, errRegister) + } + } + return manager +} + +func newIssue7521Auth(id string) *Auth { + return &Auth{ + ID: id, + Provider: "claude", + Status: StatusActive, + Attributes: map[string]string{"api_key": "key-" + id}, + } +} + +func newIssue7521Upstream429(msg string, retryAfter time.Duration) error { + hint := retryAfter + return customStatusError{ + code: http.StatusTooManyRequests, + msg: msg, + retryAfter: &hint, + } +} + +func assertIssue7521PoolCooldownError(t *testing.T, err error, wantMessage string, wantDeadline time.Duration) { + t.Helper() + if err == nil { + t.Fatal("expected terminal 429 error, got nil") + } + if got := statusCodeFromError(err); got != http.StatusTooManyRequests { + t.Fatalf("status = %d, want 429", got) + } + if !strings.Contains(err.Error(), wantMessage) { + t.Fatalf("error = %q, want upstream message %q preserved", err.Error(), wantMessage) + } + var marker interface{ IsModelCooldown() bool } + if !errors.As(err, &marker) || marker == nil || !marker.IsModelCooldown() { + t.Fatalf("error %T (%v) must report IsModelCooldown() == true", err, err) + } + if !HasTrustedRetryDeadline(err) { + t.Fatal("HasTrustedRetryDeadline(err) = false, want true") + } + retryAfter := SafeResponseHeaders(err).Get("Retry-After") + seconds, errParse := strconv.ParseInt(retryAfter, 10, 64) + if errParse != nil || seconds <= 0 { + t.Fatalf("Retry-After = %q, want positive integer seconds", retryAfter) + } + gotDuration := time.Duration(seconds) * time.Second + if gotDuration > wantDeadline+10*time.Second || gotDuration < wantDeadline-10*time.Second { + t.Fatalf("Retry-After = %ds (%s), want near pool recovery %s", seconds, gotDuration, wantDeadline) + } +} + +// Variant 2: fresh start where every candidate credential is tried in the same +// round and returns 429; no modelCooldownError is built during selection, yet +// the terminal 429 must report IsModelCooldown() and carry the earliest pool reset. +func TestExecuteLastCredential429CarriesEarliestPoolReset(t *testing.T) { + first := newIssue7521Auth("7521-exec-a") + second := newIssue7521Auth("7521-exec-b") + shortHint := 90 * time.Minute + longHint := 3 * time.Hour + + var attempts []string + exec := &customStreamMockExecutor{ + identifier: "claude", + mockCustomErrorExecutor: mockCustomErrorExecutor{ + identifier: "claude", + executeFn: func(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + attempts = append(attempts, auth.ID) + if auth.ID == first.ID { + return cliproxyexecutor.Response{}, newIssue7521Upstream429("first credential rate limited", shortHint) + } + return cliproxyexecutor.Response{}, newIssue7521Upstream429("monthly spend limit reached", longHint) + }, + }, + } + manager := newIssue7521Manager(t, nil, exec, first, second) + + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{}) + assertIssue7521PoolCooldownError(t, errExec, "monthly spend limit reached", shortHint) + if len(attempts) != 2 { + t.Fatalf("attempts = %v, want 2 credentials tried", attempts) + } +} + +func TestExecuteSingleCredentialSubFloorHintReportsActualPoolRecovery(t *testing.T) { + single := newIssue7521Auth("7521-subfloor-a") + hint := 7 * time.Second + exec := &customStreamMockExecutor{ + identifier: "claude", + mockCustomErrorExecutor: mockCustomErrorExecutor{ + identifier: "claude", + executeFn: func(ctx context.Context, _ *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return cliproxyexecutor.Response{}, newIssue7521Upstream429("try later", hint) + }, + }, + } + manager := newIssue7521Manager(t, nil, exec, single) + manager.SetRetryConfig(0, 0, 0) + + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{}) + if errExec == nil { + t.Fatal("expected terminal 429 error") + } + // MarkResult clamps the 7s hint up to minQuotaCooldownFloor (10s), so the + // pool's actual recovery is 10s out. The wrap must advertise that real + // deadline, not the shorter per-attempt hint. + if got := SafeResponseHeaders(errExec).Get("Retry-After"); got != "10" { + t.Fatalf("Retry-After = %q, want 10 (minQuotaCooldownFloor)", got) + } + var marker interface{ IsModelCooldown() bool } + if !errors.As(errExec, &marker) || marker == nil || !marker.IsModelCooldown() { + t.Fatalf("error %T must report IsModelCooldown() == true", errExec) + } +} + +// Variant 1: one credential is already cooling down; the remaining credential +// returns 429 and the next pick fails with modelCooldownError, which is +// replaced by preferredExecutionAttemptError. The terminal 429 must still keep +// the upstream text and carry the earliest pool cooldown reset. +func TestExecuteLastUsableCredential429KeepsExistingCooldownReset(t *testing.T) { + first := newIssue7521Auth("7521-var1-a") + second := newIssue7521Auth("7521-var1-b") + existingCooldown := 75 * time.Minute + freshHint := 3 * time.Hour + + exec := &customStreamMockExecutor{ + identifier: "claude", + mockCustomErrorExecutor: mockCustomErrorExecutor{ + identifier: "claude", + executeFn: func(ctx context.Context, _ *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return cliproxyexecutor.Response{}, newIssue7521Upstream429("second credential rate limited", freshHint) + }, + }, + } + manager := newIssue7521Manager(t, nil, exec, first, second) + manager.MarkResult(context.Background(), Result{ + AuthID: first.ID, + Provider: "claude", + Model: issue7521PoolModel, + Success: false, + RetryAfter: &existingCooldown, + CredentialScope: true, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "already cooling"}, + }) + + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{}) + assertIssue7521PoolCooldownError(t, errExec, "second credential rate limited", existingCooldown) +} + +func TestExecuteCountLastCredential429CarriesEarliestPoolReset(t *testing.T) { + first := newIssue7521Auth("7521-count-a") + second := newIssue7521Auth("7521-count-b") + shortHint := 85 * time.Minute + longHint := 4 * time.Hour + + exec := &customStreamMockExecutor{ + identifier: "claude", + mockCustomErrorExecutor: mockCustomErrorExecutor{ + identifier: "claude", + countFn: func(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + if auth.ID == first.ID { + return cliproxyexecutor.Response{}, newIssue7521Upstream429("count first limited", shortHint) + } + return cliproxyexecutor.Response{}, newIssue7521Upstream429("count second limited", longHint) + }, + }, + } + manager := newIssue7521Manager(t, nil, exec, first, second) + + _, errCount := manager.ExecuteCount(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{}) + assertIssue7521PoolCooldownError(t, errCount, "count second limited", shortHint) +} + +func TestExecuteStreamLastCredential429CarriesEarliestPoolReset(t *testing.T) { + shortHint := 80 * time.Minute + longHint := 3 * time.Hour + + t.Run("direct stream error", func(t *testing.T) { + first := newIssue7521Auth("7521-stream-direct-a") + second := newIssue7521Auth("7521-stream-direct-b") + exec := &customStreamMockExecutor{ + identifier: "claude", + streamFn: func(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + if auth.ID == first.ID { + return nil, newIssue7521Upstream429("stream first limited", shortHint) + } + return nil, newIssue7521Upstream429("stream second limited", longHint) + }, + } + manager := newIssue7521Manager(t, nil, exec, first, second) + + _, errStream := manager.ExecuteStream(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{Stream: true}) + assertIssue7521PoolCooldownError(t, errStream, "stream second limited", shortHint) + }) + + t.Run("bootstrap chunk error", func(t *testing.T) { + first := newIssue7521Auth("7521-stream-boot-a") + second := newIssue7521Auth("7521-stream-boot-b") + exec := &customStreamMockExecutor{ + identifier: "claude", + streamFn: func(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + chunks := make(chan cliproxyexecutor.StreamChunk, 1) + if auth.ID == first.ID { + chunks <- cliproxyexecutor.StreamChunk{Err: newIssue7521Upstream429("bootstrap first limited", shortHint)} + } else { + chunks <- cliproxyexecutor.StreamChunk{Err: newIssue7521Upstream429("bootstrap second limited", longHint)} + } + close(chunks) + return &cliproxyexecutor.StreamResult{Chunks: chunks}, nil + }, + } + manager := newIssue7521Manager(t, nil, exec, first, second) + + streamRes, errStream := manager.ExecuteStream(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{Stream: true}) + if errStream != nil { + t.Fatalf("expected streamErrorResult, got direct err: %v", errStream) + } + chunk, ok := <-streamRes.Chunks + if !ok { + t.Fatal("expected error chunk on bootstrap failure") + } + assertIssue7521PoolCooldownError(t, chunk.Err, "bootstrap second limited", shortHint) + }) +} + +func TestExecute429LeavesOrdinary429UnchangedWhenCandidateAvailable(t *testing.T) { + first := newIssue7521Auth("7521-avail-a") + second := newIssue7521Auth("7521-avail-b") + hint := time.Hour + + exec := &customStreamMockExecutor{ + identifier: "claude", + mockCustomErrorExecutor: mockCustomErrorExecutor{ + identifier: "claude", + executeFn: func(ctx context.Context, _ *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return cliproxyexecutor.Response{}, newIssue7521Upstream429("single attempt 429", hint) + }, + }, + } + manager := newIssue7521Manager(t, nil, exec, first, second) + // Stop after 1 credential attempt with 0 retries so the second credential remains unblocked. + manager.SetRetryConfig(0, 0, 1) + + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{}) + if errExec == nil { + t.Fatal("expected 429 error") + } + if got := statusCodeFromError(errExec); got != http.StatusTooManyRequests { + t.Fatalf("status = %d, want 429", got) + } + var marker interface{ IsModelCooldown() bool } + if errors.As(errExec, &marker) && marker != nil && marker.IsModelCooldown() { + t.Fatalf("ordinary 429 must not report IsModelCooldown() when another candidate is still available: %T (%v)", errExec, errExec) + } +} + +func TestExecuteLastCredential429IgnoresZeroWeightCandidateUnderWeightedSelector(t *testing.T) { + active := newIssue7521Auth("7521-weight-active") + drained := newIssue7521Auth("7521-weight-zero") + drained.Attributes["weight"] = "0" + hint := 70 * time.Minute + + exec := &customStreamMockExecutor{ + identifier: "claude", + mockCustomErrorExecutor: mockCustomErrorExecutor{ + identifier: "claude", + executeFn: func(ctx context.Context, _ *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return cliproxyexecutor.Response{}, newIssue7521Upstream429("active credential exhausted", hint) + }, + }, + } + selector := NewSessionAffinitySelector(&WeightedRoundRobinSelector{}) + manager := newIssue7521Manager(t, selector, exec, active, drained) + + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{}) + assertIssue7521PoolCooldownError(t, errExec, "active credential exhausted", hint) +} + +func TestAnnotatePoolCooldownSelectionFallbackAndUnblockedGuard(t *testing.T) { + now := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) + fallbackDeadline := now.Add(42 * time.Minute) + lastAttemptHint := 3 * time.Hour + baseErr := withTrustedRetryAfter(newIssue7521Upstream429("upstream rate limited", lastAttemptHint), &lastAttemptHint) + + t.Run("falls back to selection cooldown when no candidate unblocked", func(t *testing.T) { + manager := NewManager(nil, nil, nil) + wrapped := manager.annotatePoolCooldownTerminalErrorAt( + context.Background(), + []string{"claude"}, + issue7521PoolModel, + cliproxyexecutor.Options{}, + baseErr, + fallbackDeadline, + now, + ) + poolErr, ok := wrapped.(*poolCooldownTerminalError) + if !ok || poolErr == nil { + t.Fatalf("wrapped = %T, want *poolCooldownTerminalError", wrapped) + } + if !poolErr.deadline.Equal(fallbackDeadline) { + t.Fatalf("deadline = %v, want %v", poolErr.deadline, fallbackDeadline) + } + if !poolErr.IsModelCooldown() { + t.Fatal("IsModelCooldown() = false, want true") + } + }) + + t.Run("does not fall back when an eligible candidate is unblocked", func(t *testing.T) { + avail := newIssue7521Auth("7521-fallback-avail") + exec := &customStreamMockExecutor{identifier: "claude"} + manager := newIssue7521Manager(t, nil, exec, avail) + + got := manager.annotatePoolCooldownTerminalErrorAt( + context.Background(), + []string{"claude"}, + issue7521PoolModel, + cliproxyexecutor.Options{}, + baseErr, + fallbackDeadline, + now, + ) + var marker interface{ IsModelCooldown() bool } + if errors.As(got, &marker) && marker != nil && marker.IsModelCooldown() { + t.Fatalf("must not wrap as model cooldown when a candidate is unblocked: %T", got) + } + }) + + t.Run("expired pool deadline suppresses raw header and falls back for retryAfterFromError", func(t *testing.T) { + cause := headerCarryingError{headers: http.Header{"X-Trace": {"1"}, "Retry-After": {"999"}}} + expired := &poolCooldownTerminalError{ + cause: cause, + deadline: time.Now().Add(-time.Second), + } + if !HasTrustedRetryDeadline(expired) { + t.Fatal("HasTrustedRetryDeadline(expired) = false, want true") + } + if got := SafeResponseHeaders(expired).Get("Retry-After"); got != "" { + t.Fatalf("SafeResponseHeaders(expired) Retry-After = %q, want empty", got) + } + if got := expired.Headers().Get("X-Trace"); got != "1" { + t.Fatalf("Headers() X-Trace = %q, want 1", got) + } + agg := 2 * time.Second + homeTerminal := markHomeRetryRoundExhausted(&poolCooldownTerminalError{ + cause: cause, + deadline: time.Now().Add(time.Hour), + }, &agg, false) + if got := SafeResponseHeaders(homeTerminal).Get("Retry-After"); got != "2" { + t.Fatalf("Home aggregate Retry-After = %q, want 2", got) + } + }) +} + +// Regression for the review finding: a short transient non-cooldown block on a +// sibling credential must pull the pool reset forward instead of being ignored, +// so the wrapped terminal 429 never advertises a longer wait than the pool's +// earliest auto-recovery. +func TestExecutePoolCooldownIncludesTransientNonCooldownBlock(t *testing.T) { + longQuotaCooldown := 3 * time.Hour + shortTransient := 90 * time.Second + + quotaAuth := newIssue7521Auth("7521-mixed-quota") + transientAuth := newIssue7521Auth("7521-mixed-transient") + execAuth := newIssue7521Auth("7521-mixed-exec") + + exec := &customStreamMockExecutor{ + identifier: "claude", + mockCustomErrorExecutor: mockCustomErrorExecutor{ + identifier: "claude", + executeFn: func(ctx context.Context, _ *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return cliproxyexecutor.Response{}, newIssue7521Upstream429("last credential rate limited", 2*time.Hour) + }, + }, + } + manager := newIssue7521Manager(t, nil, exec, quotaAuth, transientAuth, execAuth) + + // Credential A: genuine quota cooldown recovering in 3h. + manager.MarkResult(context.Background(), Result{ + AuthID: quotaAuth.ID, + Provider: "claude", + Model: issue7521PoolModel, + Success: false, + RetryAfter: &longQuotaCooldown, + CredentialScope: true, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "quota exhausted"}, + }) + + // Credential B: transient non-cooldown block recovering in 90s. Recording + // a transient_rate_limit result (non-credential scope) marks only the + // reporting model unavailable without a quota label, so the scan + // classifies it as blockReasonOther rather than blockReasonCooldown. + manager.MarkResult(context.Background(), Result{ + AuthID: transientAuth.ID, + Provider: "claude", + Model: issue7521PoolModel, + Success: false, + RetryAfter: &shortTransient, + Error: &Error{ + Code: ErrorCodeTransientRateLimit, + HTTPStatus: http.StatusTooManyRequests, + Message: "transient capacity rejection", + }, + }) + + // Credential C is the only unblocked candidate; it fails and joins the + // pool cooldown. The pool's earliest recovery is B's +90s, not A's +3h nor + // the attempt's own 2h hint. + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: issue7521PoolModel}, cliproxyexecutor.Options{}) + assertIssue7521PoolCooldownError(t, errExec, "last credential rate limited", shortTransient) +} diff --git a/sdk/cliproxy/auth/conductor_refresh.go b/sdk/cliproxy/auth/conductor_refresh.go index 9fedd9420b3..343957ec39f 100644 --- a/sdk/cliproxy/auth/conductor_refresh.go +++ b/sdk/cliproxy/auth/conductor_refresh.go @@ -1014,13 +1014,34 @@ func applyDevinQuotaRestoration(auth, existing *Auth, now time.Time) bool { } resetModelState(state, now) } - auth.Status = StatusActive - auth.StatusMessage = "" - auth.LastError = nil - auth.Unavailable = false - auth.NextRetryAfter = time.Time{} + independentForce := effectiveAuthForceUntil(existing) + auth.credQuotaForceUntil = time.Time{} + auth.forceCooldownSeeded = true + if independentForce.After(now) { + auth.forceCooldownUntil = independentForce + auth.Unavailable = true + auth.NextRetryAfter = independentForce + auth.Status = StatusError + if isForceCooldownError(existing.LastError) { + auth.LastError = cloneError(existing.LastError) + auth.StatusMessage = existing.StatusMessage + } else { + auth.LastError = nil + auth.StatusMessage = ErrorCodeForceCooldown + } + } else { + auth.forceCooldownUntil = time.Time{} + auth.Status = StatusActive + auth.StatusMessage = "" + auth.LastError = nil + auth.Unavailable = false + auth.NextRetryAfter = time.Time{} + } if len(auth.ModelStates) > 0 { updateAggregatedAvailability(auth, now) + if auth.Unavailable && auth.Status == StatusActive { + auth.Status = StatusError + } } return true } @@ -1123,6 +1144,12 @@ func (m *Manager) RefreshHomeSelectionAfterUnauthorized(ctx context.Context, sel return current, false, nil } +// RefreshAfterUnauthorized refreshes a local credential once after an upstream 401 +// using the same rejection-marking and single-refresh rules as request execution. +func (m *Manager) RefreshAfterUnauthorized(ctx context.Context, auth *Auth, execErr error, alreadyTried bool, clientHeaders ...http.Header) (*Auth, bool) { + return m.tryRefreshAfterUnauthorized(ctx, auth, execErr, alreadyTried, clientHeaders...) +} + // tryRefreshAfterUnauthorized refreshes local OAuth credentials once after a // 401 so the current auth can be retried before fallback/suspend. func (m *Manager) tryRefreshAfterUnauthorized(ctx context.Context, auth *Auth, execErr error, alreadyTried bool, clientHeaders ...http.Header) (*Auth, bool) { @@ -1135,7 +1162,7 @@ func (m *Manager) tryRefreshAfterUnauthorized(ctx context.Context, auth *Auth, e return auth, false } // A 401 matched by a configured request-scoped rule is the rule's to handle: no rejection, no refresh. - if _, ruleMatched := matchRequestScopedErrorAction(auth, execErr, m.runtimeConfigSnapshot()); ruleMatched { + if _, ruleMatched := matchRequestScopedErrorAction(auth, execErr, m.requestScopedErrorConfig(ctx)); ruleMatched { return auth, false } failedToken := authAccessTokenForRequest(ctx, auth, clientHeaders...) @@ -1370,6 +1397,10 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc current.LastError = refreshAccessError(current, msg, accessTokenRejected, wasTerminalUnauthorized) if current.LastError.Code == "refresh_outcome_unknown" { current.StatusMessage = current.LastError.Message + if current.Status != StatusDisabled { + // Job completion reschedules this recovery state, so retain a positive delay. + current.NextRefreshAfter = checkNow.Add(refreshCheckInterval) + } } m.auths[id] = current if m.scheduler != nil { @@ -1387,12 +1418,34 @@ func (m *Manager) refreshAuthForRequestAtEpoch(ctx context.Context, id, failedAc base := auth.Clone() updated, err := exec.Refresh(ctx, base.Clone()) now := time.Now() - if err != nil && errors.Is(err, context.Canceled) && !codex.IsRefreshOutcomeUnknown(err) { + refreshCanceled := (errors.Is(err, context.Canceled) || errors.Is(err, codex.ErrSIWCRefreshDeferred)) && !codex.IsRefreshOutcomeUnknown(err) + if refreshCanceled { + var partitions interface { + OuterRefreshError() error + SIWCRefreshError() error + } + if errors.As(err, &partitions) { + for _, partitionErr := range []error{partitions.OuterRefreshError(), partitions.SIWCRefreshError()} { + if partitionErr != nil && !errors.Is(partitionErr, context.Canceled) && !errors.Is(partitionErr, codex.ErrSIWCRefreshDeferred) { + refreshCanceled = false + break + } + } + } + } + if refreshCanceled { log.Debugf("refresh canceled for %s, %s", auth.Provider, auth.ID) + backoff := time.Second + if errors.Is(err, codex.ErrSIWCRefreshDeferred) { + backoff = refreshCheckInterval + } + retryAfter := now.Add(backoff) m.mu.Lock() if current := m.auths[id]; current != nil { - if current.NextRefreshAfter.IsZero() || current.NextRefreshAfter.Before(now) { - current.NextRefreshAfter = now.Add(time.Second) + pendingJob := m.refreshJobs[id] + isJobPending := pendingJob != nil && current.NextRefreshAfter.Equal(pendingJob.pendingUntil) + if isJobPending || current.NextRefreshAfter.IsZero() || current.NextRefreshAfter.Before(retryAfter) { + current.NextRefreshAfter = retryAfter } m.auths[id] = current if m.scheduler != nil { diff --git a/sdk/cliproxy/auth/conductor_refresh_outcome_test.go b/sdk/cliproxy/auth/conductor_refresh_outcome_test.go index 3f7f2c53cac..a7f37901581 100644 --- a/sdk/cliproxy/auth/conductor_refresh_outcome_test.go +++ b/sdk/cliproxy/auth/conductor_refresh_outcome_test.go @@ -2,6 +2,8 @@ package auth import ( "context" + "fmt" + "net/http" "testing" "time" @@ -35,3 +37,169 @@ func TestUnknownRefreshOutcomeRequiresRecoveryWithoutDiscardingAccess(t *testing } } } + +func TestRejectedRefreshJobDoesNotImmediatelyReschedule(t *testing.T) { + lead := time.Minute + setRefreshLeadFactory(t, "codex", func() *time.Duration { return &lead }) + for _, tc := range []struct { + name string + missingAccess bool + diagnostic401 bool + disabled bool + statusDisabled bool + }{ + {name: "expired"}, + {name: "missing", missingAccess: true}, + {name: "diagnostic-401", diagnostic401: true}, + {name: "disabled-during-job", disabled: true}, + {name: "status-disabled-during-job", statusDisabled: true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + manager := NewManager(nil, nil, nil) + executor := &unauthorizedRefreshExecutor{id: "codex"} + manager.RegisterExecutor(executor) + // The JWT expired in 2020 even though the file metadata claims a future expiry. + auth := &Auth{ + ID: "expired-rejected-refresh", Provider: "codex", Status: StatusActive, + RequiresSignIn: true, RejectedRefreshToken: "rejected-grant", + RefreshError: &Error{Code: "refresh_outcome_unknown", Message: "refresh_outcome_unknown: transport", HTTPStatus: http.StatusServiceUnavailable}, + Metadata: map[string]any{ + "access_token": "eyJhbGciOiJub25lIn0.eyJleHAiOjE1Nzc4MzY4MDB9.sig", + "refresh_token": "rejected-grant", + "expired": time.Now().Add(time.Hour).Format(time.RFC3339), + }, + } + if tc.missingAccess { + delete(auth.Metadata, "access_token") + } + if tc.diagnostic401 { + auth.RefreshError.HTTPStatus = http.StatusUnauthorized + } + if _, errRegister := manager.Register(ctx, auth); errRegister != nil { + t.Fatal(errRegister) + } + loop := newAuthAutoRefreshLoop(manager, refreshCheckInterval, 1) + manager.refreshLoop = loop + now := time.Now() + loop.rebuild(now) + loop.handleDue(ctx, now) + + var job *authRefreshJob + select { + case job = <-loop.jobs: + default: + t.Fatal("expected expired credential to settle its unavailable state") + } + wantStatus := StatusError + if tc.disabled || tc.statusDisabled { + pending, _ := manager.GetByID(auth.ID) + pending.Disabled = tc.disabled + if tc.statusDisabled { + pending.Status = StatusDisabled + } + if _, errUpdate := manager.Update(ctx, pending); errUpdate != nil { + t.Fatal(errUpdate) + } + wantStatus = StatusDisabled + } + if !manager.beginRefreshJob(ctx, job) { + t.Fatal("expected refresh job to begin") + } + if _, errRefresh := manager.refreshAuthForRequestAtEpoch(ctx, job.id, "", job.registrationEpoch); errRefresh == nil { + t.Fatal("expected the previously rejected refresh error") + } + manager.finishRefreshJob(job, time.Time{}, false) + current, _ := manager.GetByID(auth.ID) + if !current.Unavailable || current.Status != wantStatus || !current.RequiresSignIn { + t.Fatalf("expired credential must remain unavailable and require sign-in with status %s", wantStatus) + } + if current.LastError == nil || current.LastError.Code != "refresh_outcome_unknown" || current.LastError.HTTPStatus != http.StatusServiceUnavailable { + t.Fatalf("unknown refresh outcome must not become an access-token rejection: %#v", current.LastError) + } + if executor.RefreshCalls() != 0 { + t.Fatal("already rejected refresh grant was submitted upstream") + } + + loop.applyDirty(current.UpdatedAt) + if next, scheduled := loop.peek(); scheduled { + if wantStatus == StatusDisabled { + t.Fatal("disabled credential must not remain scheduled") + } + if next.Before(current.UpdatedAt.Add(refreshCheckInterval)) { + t.Fatalf("completed rejected refresh was immediately requeued at %v; want at least one check interval after %v", next, current.UpdatedAt) + } + } + loop.handleDue(ctx, current.UpdatedAt) + if len(loop.jobs) != 0 { + t.Fatal("completed rejected refresh was dispatched again without waiting") + } + if wantStatus == StatusDisabled { + return + } + + // A replacement grant must bypass the old recovery backoff immediately. + replacement := current.Clone() + replacement.Metadata["access_token"] = "replacement-access" + replacement.Metadata["refresh_token"] = "replacement-grant" + replacement.Metadata["expired"] = current.UpdatedAt.Add(-time.Hour).Format(time.RFC3339) + updated, errUpdate := manager.Update(ctx, replacement) + if errUpdate != nil { + t.Fatal(errUpdate) + } + loop.applyDirty(updated.UpdatedAt) + loop.handleDue(ctx, updated.UpdatedAt) + if len(loop.jobs) != 1 { + t.Fatal("replacement grant did not restore refresh scheduling") + } + }) + } +} + +func TestAutoRefreshDeferralDoesNotClearPendingBackoffToZero(t *testing.T) { + ctx := context.Background() + manager := NewManager(nil, nil, nil) + deferredErr := fmt.Errorf("Codex renewal deferred until interactive macOS wake: %w", codex.ErrSIWCRefreshDeferred) + executor := &unauthorizedRefreshExecutor{id: "codex", refreshErr: deferredErr} + manager.RegisterExecutor(executor) + + now := time.Now() + auth := &Auth{ + ID: "wake-deferred-job", + Provider: "codex", + Status: StatusActive, + Metadata: map[string]any{ + "access_token": "valid-access", + "refresh_token": "ordinary-refresh", + "expired": now.Add(24 * time.Hour).Format(time.RFC3339), + }, + } + registered, errRegister := manager.Register(ctx, auth) + if errRegister != nil { + t.Fatal(errRegister) + } + loop := newAuthAutoRefreshLoop(manager, refreshCheckInterval, 1) + job := manager.markRefreshPending(loop, registered.ID, registered.RegistrationEpoch, now) + if job == nil { + t.Fatal("expected pending refresh job") + } + if !manager.beginRefreshJob(ctx, job) { + t.Fatal("expected refresh job to start") + } + _, errRefresh := manager.refreshAuthForRequestAtEpoch(ctx, job.id, "", job.registrationEpoch) + if errRefresh == nil { + t.Fatal("expected deferred refresh error") + } + manager.finishRefreshJob(job, time.Time{}, false) + + updated, ok := manager.GetByID(registered.ID) + if !ok || updated == nil { + t.Fatal("credential missing after deferred refresh") + } + if updated.RequiresSignIn || updated.RejectedRefreshToken != "" { + t.Fatalf("wake deferral marked credential as requiring sign-in: %+v", updated) + } + if updated.NextRefreshAfter.IsZero() || !updated.NextRefreshAfter.After(now) { + t.Fatalf("NextRefreshAfter = %v, want a positive backoff after %v to avoid a tight loop", updated.NextRefreshAfter, now) + } +} diff --git a/sdk/cliproxy/auth/conductor_request_scoped_errors.go b/sdk/cliproxy/auth/conductor_request_scoped_errors.go index 41a14ec8def..3abcfbc8610 100644 --- a/sdk/cliproxy/auth/conductor_request_scoped_errors.go +++ b/sdk/cliproxy/auth/conductor_request_scoped_errors.go @@ -1,6 +1,7 @@ package auth import ( + "context" "encoding/json" "errors" "regexp" @@ -11,6 +12,31 @@ import ( cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" ) +type requestScopedErrorConfigContextKey struct{} + +// WithRequestScopedErrorConfig stores the runtime config snapshot on ctx so +// usage reporters can evaluate request-scoped error rules when publishing +// attempt failures. +func WithRequestScopedErrorConfig(ctx context.Context, cfg *internalconfig.Config) context.Context { + if ctx == nil { + ctx = context.Background() + } + if cfg == nil { + return ctx + } + return context.WithValue(ctx, requestScopedErrorConfigContextKey{}, cfg) +} + +// RequestScopedErrorConfigFromContext retrieves the runtime config snapshot +// stored by WithRequestScopedErrorConfig. +func RequestScopedErrorConfigFromContext(ctx context.Context) *internalconfig.Config { + if ctx == nil { + return nil + } + cfg, _ := ctx.Value(requestScopedErrorConfigContextKey{}).(*internalconfig.Config) + return cfg +} + // Request-scoped error actions. const ( RequestScopedActionStop = "stop" @@ -57,6 +83,74 @@ func wrapRequestStopError(err error) error { return requestStopError{error: unwrapRequestStopError(err)} } +type schedulerRejectError struct { + error +} + +func (e schedulerRejectError) Unwrap() error { + return e.error +} + +func (e schedulerRejectError) IsSchedulerReject() bool { + return true +} + +func isSchedulerRejectError(err error) bool { + if err == nil { + return false + } + type rejectChecker interface { + IsSchedulerReject() bool + } + var rc rejectChecker + return errors.As(err, &rc) && rc != nil && rc.IsSchedulerReject() +} + +func unwrapSchedulerRejectError(err error) error { + var rejectErr schedulerRejectError + if errors.As(err, &rejectErr) { + return rejectErr.error + } + return err +} + +func wrapSchedulerRejectError(err error) error { + if err == nil { + return nil + } + return schedulerRejectError{error: unwrapSchedulerRejectError(err)} +} + +type roundEndedBySchedulerRejectError struct { + cause error +} + +func (e *roundEndedBySchedulerRejectError) Error() string { + if e == nil || e.cause == nil { + return "" + } + return e.cause.Error() +} + +func (e *roundEndedBySchedulerRejectError) Unwrap() error { + if e == nil { + return nil + } + return e.cause +} + +func hasRoundEndedBySchedulerReject(err error) bool { + var marked *roundEndedBySchedulerRejectError + return errors.As(err, &marked) && marked != nil +} + +func markRoundEndedBySchedulerReject(err error) error { + if err == nil || hasRoundEndedBySchedulerReject(err) { + return err + } + return &roundEndedBySchedulerRejectError{cause: err} +} + func (m *Manager) runtimeConfigSnapshot() *internalconfig.Config { if m == nil { return nil @@ -65,6 +159,92 @@ func (m *Manager) runtimeConfigSnapshot() *internalconfig.Config { return cfg } +func (m *Manager) requestScopedErrorConfig(ctx context.Context) *internalconfig.Config { + if cfg := RequestScopedErrorConfigFromContext(ctx); cfg != nil { + return cfg + } + return m.runtimeConfigSnapshot() +} + +func cloneRequestScopedErrorRules(rules []internalconfig.RequestScopedErrorRule) []internalconfig.RequestScopedErrorRule { + if len(rules) == 0 { + return nil + } + out := make([]internalconfig.RequestScopedErrorRule, len(rules)) + for i, r := range rules { + out[i] = internalconfig.RequestScopedErrorRule{ + Status: r.Status, + Action: r.Action, + } + if len(r.Match) > 0 { + out[i].Match = append([]string(nil), r.Match...) + } + if len(r.MatchRegexr) > 0 { + out[i].MatchRegexr = append([]string(nil), r.MatchRegexr...) + } + } + return out +} + +// ResolveRequestScopedErrorRules extracts and deep-copies the effective +// RequestScopedErrorRule list for an auth and config snapshot. +func ResolveRequestScopedErrorRules(auth *Auth, cfg *internalconfig.Config) []internalconfig.RequestScopedErrorRule { + return cloneRequestScopedErrorRules(extractRequestScopedErrorRules(auth, cfg)) +} + +// MatchRequestScopedErrorRules evaluates an error against a pre-resolved rule list. +func MatchRequestScopedErrorRules(rules []internalconfig.RequestScopedErrorRule, err error) (string, bool) { + if err == nil || len(rules) == 0 || cliproxyexecutor.IsUpstreamWebsocketTurnError(err) { + return "", false + } + + statusCode := statusCodeFromError(err) + body := extractErrorBody(err) + + for _, rule := range rules { + if rule.Status <= 0 || rule.Status != statusCode { + continue + } + if len(rule.Match) == 0 && len(rule.MatchRegexr) == 0 { + continue + } + + matched := false + for _, substr := range rule.Match { + if substr != "" && strings.Contains(body, substr) { + matched = true + break + } + } + if !matched { + for _, pattern := range rule.MatchRegexr { + if pattern != "" { + if re, errCompile := regexp.Compile(pattern); errCompile == nil && re.MatchString(body) { + matched = true + break + } + } + } + } + if !matched { + continue + } + + action := strings.ToLower(strings.TrimSpace(rule.Action)) + switch action { + case RequestScopedActionStop, + RequestScopedActionStopAndCooldown, + RequestScopedActionContinue, + RequestScopedActionContinueAndCooldown: + return action, true + default: + continue + } + } + + return "", false +} + // extractRequestScopedErrorRules retrieves the configured RequestScopedErrorRule list for an auth. func extractRequestScopedErrorRules(auth *Auth, cfg *internalconfig.Config) []internalconfig.RequestScopedErrorRule { if auth != nil && auth.Metadata != nil { @@ -181,63 +361,18 @@ func extractErrorBody(err error) string { return err.Error() } -// matchRequestScopedErrorAction evaluates an error against the auth's RequestScopedErrors rules. +// MatchRequestScopedErrorAction evaluates an error against the auth's RequestScopedErrors rules. // If a rule matches, it returns (action, true). // If no rule matches, it returns ("", false). +func MatchRequestScopedErrorAction(auth *Auth, err error, cfg *internalconfig.Config) (string, bool) { + return matchRequestScopedErrorAction(auth, err, cfg) +} + func matchRequestScopedErrorAction(auth *Auth, err error, cfg *internalconfig.Config) (string, bool) { if err == nil || cliproxyexecutor.IsUpstreamWebsocketTurnError(err) { return "", false } - rules := extractRequestScopedErrorRules(auth, cfg) - if len(rules) == 0 { - return "", false - } - - statusCode := statusCodeFromError(err) - body := extractErrorBody(err) - - for _, rule := range rules { - if rule.Status <= 0 || rule.Status != statusCode { - continue - } - if len(rule.Match) == 0 && len(rule.MatchRegexr) == 0 { - continue - } - - matched := false - for _, substr := range rule.Match { - if substr != "" && strings.Contains(body, substr) { - matched = true - break - } - } - if !matched { - for _, pattern := range rule.MatchRegexr { - if pattern != "" { - if re, errCompile := regexp.Compile(pattern); errCompile == nil && re.MatchString(body) { - matched = true - break - } - } - } - } - if !matched { - continue - } - - action := strings.ToLower(strings.TrimSpace(rule.Action)) - switch action { - case RequestScopedActionStop, - RequestScopedActionStopAndCooldown, - RequestScopedActionContinue, - RequestScopedActionContinueAndCooldown: - return action, true - default: - continue - } - } - - return "", false + return MatchRequestScopedErrorRules(extractRequestScopedErrorRules(auth, cfg), err) } func applyRequestScopedActionToResult(action string, okAction bool, result *Result) { @@ -251,6 +386,18 @@ func applyRequestScopedActionToResult(action string, okAction bool, result *Resu } } +// ApplyRequestScopedErrorResult evaluates request-scoped error rules for auth +// and applies any matched action code onto result before MarkResult. +func (m *Manager) ApplyRequestScopedErrorResult(ctx context.Context, auth *Auth, err error, result *Result) (string, bool) { + var cfg *internalconfig.Config + if m != nil { + cfg = m.requestScopedErrorConfig(ctx) + } + action, okAction := matchRequestScopedErrorAction(auth, err, cfg) + applyRequestScopedActionToResult(action, okAction, result) + return action, okAction +} + func isRequestScopedStop(action string, okAction bool) bool { return okAction && (action == RequestScopedActionStop || action == RequestScopedActionStopAndCooldown) } diff --git a/sdk/cliproxy/auth/conductor_request_scoped_errors_test.go b/sdk/cliproxy/auth/conductor_request_scoped_errors_test.go index b587b83cb46..0504c9e4836 100644 --- a/sdk/cliproxy/auth/conductor_request_scoped_errors_test.go +++ b/sdk/cliproxy/auth/conductor_request_scoped_errors_test.go @@ -9,6 +9,7 @@ import ( internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executionregistry" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" ) @@ -67,6 +68,9 @@ func TestUnwrapExecutionBoundaryErrorRemovesInternalMarkers(t *testing.T) { }{ {name: "attempt inside stop", err: wrapRequestStopError(markUpstreamExecutionAttempt(base))}, {name: "stop inside attempt", err: markUpstreamExecutionAttempt(wrapRequestStopError(base))}, + {name: "scheduler reject", err: wrapSchedulerRejectError(base)}, + {name: "attempt inside round scheduler reject", err: markRoundEndedBySchedulerReject(markUpstreamExecutionAttempt(base))}, + {name: "round scheduler reject inside attempt", err: markUpstreamExecutionAttempt(markRoundEndedBySchedulerReject(base))}, } { t.Run(test.name, func(t *testing.T) { if got := unwrapExecutionBoundaryError(test.err); got != base { @@ -1286,3 +1290,51 @@ func TestRequestScopedErrors_ResponseBodyProvider_MatchesUnderlyingPayload(t *te t.Fatal("expected auth1 to be in cooldown when matching ResponseBody()") } } + +func TestHomeExecutionAttachesRequestScopedErrorConfigToContext(t *testing.T) { + cfg := &internalconfig.Config{ + Home: internalconfig.HomeConfig{Enabled: true}, + OAuthRequestScopedErrors: map[string][]internalconfig.RequestScopedErrorRule{ + "codex": { + { + Status: http.StatusNotFound, + Match: []string{"model_not_found_on_route"}, + Action: RequestScopedActionStop, + }, + }, + }, + } + m := NewManager(nil, nil, nil) + m.SetConfig(cfg) + + var observedAction string + var observedMatched bool + exec := &mockCustomErrorExecutor{ + identifier: "codex", + executeFn: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + err := customStatusError{code: http.StatusNotFound, msg: "model_not_found_on_route"} + observedAction, observedMatched = MatchRequestScopedErrorAction(auth, err, RequestScopedErrorConfigFromContext(ctx)) + return cliproxyexecutor.Response{}, err + }, + } + m.RegisterExecutor(exec) + + executions := executionregistry.New() + dispatcher := &accountedHomeExecutionDispatcher{ + auths: []Auth{{ + ID: "home-oauth-1", + Provider: "codex", + Status: StatusActive, + Attributes: map[string]string{"auth_kind": "oauth"}, + }}, + } + m.PublishHomeDispatch(dispatcher, executions, 1) + + _, errExec := m.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: "gpt-5.4"}, cliproxyexecutor.Options{}) + if errExec == nil { + t.Fatal("expected error, got nil") + } + if !observedMatched || observedAction != RequestScopedActionStop { + t.Fatalf("executor context did not match request-scoped rule: matched=%v action=%q", observedMatched, observedAction) + } +} diff --git a/sdk/cliproxy/auth/conductor_selection.go b/sdk/cliproxy/auth/conductor_selection.go index 80e6c1de9f0..fccb0fffdfe 100644 --- a/sdk/cliproxy/auth/conductor_selection.go +++ b/sdk/cliproxy/auth/conductor_selection.go @@ -237,72 +237,23 @@ func (m *Manager) ReconcileRegistryModelStates(ctx context.Context, authID strin supportedModels, regEpoch = globalReg.GetModelsAndEpochForClient(authID) candidateAuth := &Auth{ ID: auth.ID, + Prefix: auth.Prefix, Provider: auth.Provider, Attributes: auth.Attributes, + Metadata: auth.Metadata, ModelStates: cloneModelStates(auth.ModelStates), } - candidateChanged := normalizeModelStates(candidateAuth) - - // Historical alias migration: - // Migrate legacy alias state strictly based on registered route keys from supportedModels. - // Two-phase safe migration: - // Phase 1: Collect authoritative target keys and route-to-target mappings. - if len(candidateAuth.ModelStates) > 0 && len(supportedModels) > 0 { - authoritativeTargets := make(map[string]bool, len(supportedModels)) - routeToTarget := make(map[string]string, len(supportedModels)) - for _, sm := range supportedModels { - if sm == nil || strings.TrimSpace(sm.ID) == "" { - continue - } - routeID := strings.TrimSpace(sm.ID) - canonicalRoute := canonicalModelKey(routeID) - targetKey := m.selectionModelKeyForAuth(auth, routeID) - if targetKey == "" { - targetKey = canonicalRoute - } - if targetKey != "" { - authoritativeTargets[targetKey] = true - } - if canonicalRoute != "" { - routeToTarget[canonicalRoute] = targetKey - } - } + candidateChanged := m.migrateAuthAliasModelStatesLocked(candidateAuth, supportedModels, now, true) - // Phase 2: For each registered routeKey, migrate legacy state to target ONLY if - // routeKey != target AND routeKey is not itself an authoritative target for any route. - for _, sm := range supportedModels { - if sm == nil || strings.TrimSpace(sm.ID) == "" { - continue - } - routeID := strings.TrimSpace(sm.ID) - canonicalRoute := canonicalModelKey(routeID) - targetKey := routeToTarget[canonicalRoute] - if targetKey == "" || canonicalRoute == "" { - continue - } - if canonicalRoute != targetKey && !authoritativeTargets[canonicalRoute] { - aliasKeys := []string{canonicalRoute} - if routeID != canonicalRoute { - aliasKeys = append(aliasKeys, routeID) - } - for _, aliasKey := range aliasKeys { - if state, hasAliasState := candidateAuth.ModelStates[aliasKey]; hasAliasState { - if state != nil && (!modelStateIsClean(state) || isModelStateActiveCooldown(state, now)) { - if existingTarget, exists := candidateAuth.ModelStates[targetKey]; exists && existingTarget != nil { - candidateAuth.ModelStates[targetKey] = mergeModelState(existingTarget, state) - } else { - candidateAuth.ModelStates[targetKey] = state.Clone() - } - } - delete(candidateAuth.ModelStates, aliasKey) - candidateChanged = true - } - } + supported := make(map[string]struct{}, len(supportedModels)) + if len(supportedModels) > 0 { + authoritativeTargets, _ := m.buildAliasMigrationMapsLocked(candidateAuth, supportedModels, true) + for targetLookup := range authoritativeTargets { + if targetLookup != "" { + supported[targetLookup] = struct{}{} } } } - - supported := make(map[string]struct{}, len(supportedModels)) for _, model := range supportedModels { if model == nil || strings.TrimSpace(model.ID) == "" { continue @@ -311,17 +262,17 @@ func (m *Manager) ReconcileRegistryModelStates(ctx context.Context, authID strin if stateKey == "" { stateKey = canonicalModelKey(model.ID) } - if stateKey != "" { - supported[stateKey] = struct{}{} + if lookupKey := canonicalModelLookupKey(stateKey); lookupKey != "" { + supported[lookupKey] = struct{}{} } } for modelKey, state := range candidateAuth.ModelStates { - baseModel := canonicalModelKey(modelKey) - if baseModel == "" { - baseModel = strings.TrimSpace(modelKey) + lookupKey := canonicalModelLookupKey(modelKey) + if lookupKey == "" { + lookupKey = strings.ToLower(strings.TrimSpace(modelKey)) } - if _, isSupported := supported[baseModel]; !isSupported { + if _, isSupported := supported[lookupKey]; !isSupported { // Drop state for models that disappeared from the current registry // snapshot and are not reachable via any alias route. delete(candidateAuth.ModelStates, modelKey) @@ -394,6 +345,356 @@ func (m *Manager) ReconcileRegistryModelStates(ctx context.Context, authID strin } } +func compactModelSpellingKey(model string) string { + key := canonicalModelLookupKey(model) + if key == "" { + return "" + } + var b strings.Builder + b.Grow(len(key)) + for i := 0; i < len(key); i++ { + ch := key[i] + if (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') { + b.WriteByte(ch) + } + } + return b.String() +} + +func isSameUnderlyingModelSpelling(a, b string) bool { + ca := compactModelSpellingKey(a) + cb := compactModelSpellingKey(b) + if ca == "" || cb == "" { + return false + } + return ca == cb || strings.HasPrefix(ca, cb) || strings.HasPrefix(cb, ca) +} + +func (m *Manager) buildAliasMigrationMapsLocked(auth *Auth, supportedModels []*registry.ModelInfo, fromExplicitReconcile bool) (map[string]string, map[string]string) { + if m == nil || auth == nil { + return nil, nil + } + if !fromExplicitReconcile && len(supportedModels) == 0 && auth.ID != "" { + supportedModels = registry.GetGlobalRegistry().GetModelsForClient(auth.ID) + } + + allRegistered := make(map[string]struct{}, len(supportedModels)) + nativeRegistered := make(map[string]struct{}, len(supportedModels)) + for _, sm := range supportedModels { + if sm == nil || strings.TrimSpace(sm.ID) == "" { + continue + } + key := canonicalModelLookupKey(sm.ID) + if key == "" { + continue + } + allRegistered[key] = struct{}{} + if strings.TrimSpace(sm.MetadataModelID) != "" && !sameCanonicalModelKey(sm.ID, sm.MetadataModelID) { + continue + } + nativeRegistered[key] = struct{}{} + } + + authoritativeTargets := make(map[string]string, len(supportedModels)) + routeToTarget := make(map[string]string, len(supportedModels)) + for _, sm := range supportedModels { + if sm == nil || strings.TrimSpace(sm.ID) == "" { + continue + } + routeID := strings.TrimSpace(sm.ID) + canonicalRoute := canonicalModelKey(routeID) + routeLookup := canonicalModelLookupKey(canonicalRoute) + targetKey := m.selectionModelKeyForAuth(auth, routeID) + if targetKey == "" { + targetKey = canonicalRoute + } + targetLookup := canonicalModelLookupKey(targetKey) + if !fromExplicitReconcile && routeLookup != "" && targetLookup != "" && routeLookup != targetLookup { + _, routeIsNative := nativeRegistered[routeLookup] + _, targetIsNative := nativeRegistered[targetLookup] + if routeIsNative && targetIsNative && !isSameUnderlyingModelSpelling(canonicalRoute, targetKey) { + authoritativeTargets[routeLookup] = canonicalRoute + routeToTarget[routeLookup] = canonicalRoute + continue + } + } + if targetLookup != "" { + authoritativeTargets[targetLookup] = targetKey + } + if routeLookup != "" && targetKey != "" { + routeToTarget[routeLookup] = targetKey + } + } + for _, route := range m.configuredOAuthAliasRoutes(auth) { + aliasLookup := canonicalModelLookupKey(route.aliasKey) + targetLookup := canonicalModelLookupKey(route.targetKey) + if aliasLookup == "" || targetLookup == "" || aliasLookup == targetLookup { + continue + } + if !fromExplicitReconcile { + _, routeIsNative := nativeRegistered[aliasLookup] + _, targetIsNative := nativeRegistered[targetLookup] + if routeIsNative && targetIsNative && !isSameUnderlyingModelSpelling(route.aliasKey, route.targetKey) { + continue + } + } + reachable := len(supportedModels) == 0 + if !reachable { + _, aliasRegistered := allRegistered[aliasLookup] + _, targetRegistered := allRegistered[targetLookup] + reachable = aliasRegistered || targetRegistered + } + if !reachable { + continue + } + if _, exists := authoritativeTargets[targetLookup]; !exists { + authoritativeTargets[targetLookup] = route.targetKey + } + if _, exists := routeToTarget[aliasLookup]; !exists { + routeToTarget[aliasLookup] = route.targetKey + } + } + return authoritativeTargets, routeToTarget +} + +func (m *Manager) resolveMarkResultModelKeyLocked(auth *Auth, modelKey, routeModel string) string { + canonicalModel := canonicalModelKey(modelKey) + if canonicalModel == "" || m == nil || auth == nil { + return canonicalModel + } + canonicalRoute := canonicalModelKey(routeModel) + if canonicalRoute != "" && !sameCanonicalModelKey(canonicalModel, canonicalRoute) { + if routeTarget := m.selectionModelKeyForAuth(auth, canonicalRoute); sameCanonicalModelKey(canonicalModel, routeTarget) { + return canonicalModel + } + } + lookupKey := canonicalModelLookupKey(canonicalModel) + authoritativeTargets, routeToTarget := m.buildAliasMigrationMapsLocked(auth, nil, false) + if authTarget, isAuthTarget := authoritativeTargets[lookupKey]; isAuthTarget && authTarget != "" { + return authTarget + } + targetKey := routeToTarget[lookupKey] + if targetKey == "" { + targetKey = m.selectionModelKeyForAuth(auth, canonicalModel) + } + if targetKey != "" && !sameCanonicalModelKey(canonicalModel, targetKey) { + if authTarget, isAuthTarget := authoritativeTargets[canonicalModelLookupKey(targetKey)]; isAuthTarget && authTarget != "" { + targetKey = authTarget + } + return targetKey + } + return canonicalModel +} + +func (m *Manager) migrateAuthAliasModelStatesLocked(auth *Auth, supportedModels []*registry.ModelInfo, now time.Time, fromExplicitReconcile bool) bool { + if auth == nil { + return false + } + changed := normalizeModelStates(auth) + if m == nil || len(auth.ModelStates) == 0 { + return changed + } + authoritativeTargets, routeToTarget := m.buildAliasMigrationMapsLocked(auth, supportedModels, fromExplicitReconcile) + + existingKeys := make([]string, 0, len(auth.ModelStates)) + for stateKey := range auth.ModelStates { + existingKeys = append(existingKeys, stateKey) + } + if len(existingKeys) > 1 { + sort.Strings(existingKeys) + } + + var working *Auth + for _, stateKey := range existingKeys { + sourceStates := auth.ModelStates + if working != nil { + sourceStates = working.ModelStates + } + state, exists := sourceStates[stateKey] + if !exists { + continue + } + canonicalRoute := canonicalModelKey(stateKey) + routeLookup := canonicalModelLookupKey(canonicalRoute) + if routeLookup == "" { + continue + } + if _, isAuthTarget := authoritativeTargets[routeLookup]; isAuthTarget { + continue + } + targetKey := routeToTarget[routeLookup] + if targetKey == "" { + targetKey = m.selectionModelKeyForAuth(auth, stateKey) + } + if targetKey == "" || sameCanonicalModelKey(canonicalRoute, targetKey) { + continue + } + if authTarget, isAuthTarget := authoritativeTargets[canonicalModelLookupKey(targetKey)]; isAuthTarget && authTarget != "" { + targetKey = authTarget + } + if working == nil { + working = &Auth{ModelStates: cloneModelStates(auth.ModelStates)} + } + if state != nil && (!modelStateIsClean(state) || isModelStateActiveCooldown(state, now)) { + mergeOrSetModelState(working, targetKey, state) + } + delete(working.ModelStates, stateKey) + changed = true + } + if working != nil { + if len(working.ModelStates) == 0 { + auth.ModelStates = nil + } else { + auth.ModelStates = working.ModelStates + } + } + return changed +} + +func mergeOrSetModelState(auth *Auth, targetKey string, state *ModelState) { + if auth == nil || targetKey == "" || state == nil { + return + } + if auth.ModelStates == nil { + auth.ModelStates = make(map[string]*ModelState) + } + if existingTarget, exists := auth.ModelStates[targetKey]; exists && existingTarget != nil { + auth.ModelStates[targetKey] = mergeModelState(existingTarget, state) + return + } + targetLookup := canonicalModelLookupKey(targetKey) + for existingKey, existingState := range auth.ModelStates { + if canonicalModelLookupKey(existingKey) != targetLookup { + continue + } + if existingState != nil { + auth.ModelStates[existingKey] = mergeModelState(existingState, state) + } else { + auth.ModelStates[existingKey] = state.Clone() + } + return + } + auth.ModelStates[targetKey] = state.Clone() +} + +func (m *Manager) publishOAuthModelAliasAndReconcileStates(ctx context.Context, table *oauthModelAliasTable) { + if m == nil { + return + } + if ctx == nil { + ctx = context.Background() + } + if table == nil { + table = &oauthModelAliasTable{} + } + + globalReg := registry.GetGlobalRegistry() + type reconciledAuthItem struct { + authID string + snapshot *Auth + supportedModels []*registry.ModelInfo + regEpoch uint64 + changed bool + } + + loadGateAcquired := m.authLoadGate.Acquire(ctx, 1) == nil + now := time.Now() + cooldownStateChanged := false + + m.mu.Lock() + m.oauthModelAlias.Store(table) + trackCooldownState := m.cooldownStore != nil + items := make([]reconciledAuthItem, 0, len(m.auths)) + for authID, auth := range m.auths { + if auth == nil || authID == "" { + continue + } + var cooldownRecordsBefore []CooldownStateRecord + if trackCooldownState { + cooldownRecordsBefore = m.cooldownStateRecordsForAuthLocked(auth, now) + } + supportedModels, regEpoch := globalReg.GetModelsAndEpochForClient(authID) + candidateChanged := m.migrateAuthAliasModelStatesLocked(auth, supportedModels, now, false) + if candidateChanged { + updateAggregatedAvailability(auth, now) + if !hasModelError(auth, now) && !hasUnauthorizedAuthFailure(auth) { + auth.LastError = nil + auth.StatusMessage = "" + auth.Status = StatusActive + } + auth.Generation++ + auth.UpdatedAt = now + } + if trackCooldownState { + cooldownRecordsAfter := m.cooldownStateRecordsForAuthLocked(auth, now) + if candidateChanged || !cooldownStateRecordsEqual(cooldownRecordsBefore, cooldownRecordsAfter) { + cooldownStateChanged = true + } + } + snapshot := auth.Clone() + if m.scheduler != nil { + m.scheduler.upsertAuth(snapshot.Clone()) + } + items = append(items, reconciledAuthItem{ + authID: authID, + snapshot: snapshot, + supportedModels: supportedModels, + regEpoch: regEpoch, + changed: candidateChanged, + }) + } + if len(items) > 0 { + m.structuralEpoch.Add(1) + } + m.mu.Unlock() + if loadGateAcquired { + m.authLoadGate.Release(1) + } + + for _, item := range items { + if len(item.supportedModels) > 0 && item.snapshot != nil { + projections := make([]registry.ClientModelProjection, 0, len(item.supportedModels)) + for _, sm := range item.supportedModels { + if sm == nil || strings.TrimSpace(sm.ID) == "" { + continue + } + projections = append(projections, m.clientModelProjectionForAuth(item.snapshot, sm.ID, now)) + } + globalReg.ApplyClientModelProjections(item.authID, item.regEpoch, item.snapshot.Generation, projections) + } + if item.changed { + releaseMutation := m.lockAuthMutation(item.authID) + m.mu.Lock() + if current, ok := m.auths[item.authID]; ok && current != nil { + if errPersist := m.persistLocked(context.Background(), current); errPersist != nil { + logEntryWithRequestID(ctx).WithField("auth_id", current.ID).Warnf("failed to persist auth changes during alias state reconciliation: %v", errPersist) + } + postNow := time.Now() + if m.migrateAuthAliasModelStatesLocked(current, nil, postNow, false) { + updateAggregatedAvailability(current, postNow) + if !hasModelError(current, postNow) && !hasUnauthorizedAuthFailure(current) { + current.LastError = nil + current.StatusMessage = "" + current.Status = StatusActive + } + current.Generation++ + current.UpdatedAt = postNow + if m.scheduler != nil { + m.scheduler.upsertAuth(current.Clone()) + } + m.structuralEpoch.Add(1) + cooldownStateChanged = true + } + } + m.mu.Unlock() + releaseMutation() + } + } + if cooldownStateChanged { + m.persistCooldownStates(context.Background()) + } +} + func cloneModelStates(states map[string]*ModelState) map[string]*ModelState { if len(states) == 0 { return nil @@ -608,7 +909,10 @@ func (m *Manager) availableAuthsForRouteModelForRequest(ctx context.Context, aut if resetIn < 0 { resetIn = 0 } - return nil, newModelCooldownErrorWithCause(routeModel, providerForError, resetIn, lastCandidateErr) + claudeCooldown, claudeSignals := claudeCooldownMetadataForAuths(ctx, auths, func(candidate *Auth) string { + return m.selectionModelForAuth(candidate, routeModel) + }, now, clientHeaders...) + return nil, newModelCooldownErrorForCandidates(routeModel, providerForError, resetIn, lastCandidateErr, claudeCooldown, claudeSignals) } if unauthorizedCount == len(auths) && len(auths) > 0 { terminalCause := latestUnauthorizedCandidateError(auths) @@ -634,6 +938,11 @@ func (m *Manager) availableAuthsForRouteModelForRequest(ctx context.Context, aut // or scheduler additionally receives lower priority tiers. func (m *Manager) availableAuthsForSelector(ctx context.Context, selector Selector, auths []*Auth, provider, routeModel string, now time.Time, schedulerAcross bool, clientHeaders ...http.Header) (priorityAuths, selectorAuths []*Auth, err error) { _, sessionAffinity := selector.(*SessionAffinitySelector) + if _, weighted := selector.(*WeightedRoundRobinSelector); weighted { + // Exclude zero-weight credentials before priority selection, just as the + // scheduler predicate does, including when only a lower tier has weight. + auths = positiveWeightAuths(auths) + } if !sessionAffinity && !schedulerAcross { priorityAuths, err = m.availableAuthsForRouteModelForRequest(ctx, auths, provider, routeModel, now, false, clientHeaders...) @@ -688,7 +997,7 @@ func selectorContextForAvailableAuths(ctx context.Context, selector Selector, ro func (m *Manager) transientlyUnavailableSessionAffinityAuthIDs(ctx context.Context, selector Selector, affinityCandidates []*Auth, routeModel string, now time.Time, clientHeaders ...http.Header) map[string]struct{} { affinity, ok := selector.(*SessionAffinitySelector) - if !ok || affinity == nil || !affinity.rebindOnQuotaOnly || len(affinityCandidates) == 0 { + if !ok || affinity == nil || (!affinity.rebindOnQuotaOnly && !affinity.rebindOnNever) || len(affinityCandidates) == 0 { return nil } if _, weighted := affinity.fallback.(*WeightedRoundRobinSelector); weighted { @@ -718,7 +1027,14 @@ func restoreModelCooldownErrorModel(err error, requestedModel string) error { if !errors.As(err, &cooldownErr) || cooldownErr == nil || cooldownErr.model != "" { return err } - return newModelCooldownErrorWithCause(requestedModel, cooldownErr.provider, cooldownErr.resetIn, cooldownErr.cause) + return newModelCooldownErrorForCandidates( + requestedModel, + cooldownErr.provider, + cooldownErr.resetIn, + cooldownErr.cause, + cooldownErr.claudeCooldown, + cooldownErr.claudeSignals, + ) } func latestUnauthorizedCandidateError(auths []*Auth) error { @@ -762,15 +1078,7 @@ func latestCandidateErrorForModel(auths []*Auth, selectionModelFunc func(*Auth) var modelErr error var modelTime time.Time if len(candidate.ModelStates) > 0 { - if state, ok := candidate.ModelStates[checkModel]; ok && state != nil { - if state.LastError != nil { - modelErr = state.LastError - modelTime = state.UpdatedAt - } else if strings.TrimSpace(state.StatusMessage) != "" { - modelErr = errors.New(state.StatusMessage) - modelTime = state.UpdatedAt - } - } else if state, ok := candidate.ModelStates[canonicalModelKey(checkModel)]; ok && state != nil { + if state := existingModelState(candidate, checkModel); state != nil { if state.LastError != nil { modelErr = state.LastError modelTime = state.UpdatedAt @@ -1039,7 +1347,7 @@ func (m *Manager) pickViaPluginScheduler(ctx context.Context, scheduler PluginSc if rejectMessage == "" { rejectMessage = "scheduler rejected candidate selection" } - return nil, true, wrapRequestStopError(&Error{Code: rejectCode, Message: rejectMessage}) + return nil, true, wrapSchedulerRejectError(&Error{Code: rejectCode, Message: rejectMessage}) } if selected := pickSchedulerAuthByID(candidates, resp.AuthID); selected != nil { keepSelectionID = true @@ -1069,7 +1377,7 @@ func (m *Manager) authSupportsRouteModel(registryRef *registry.ModelRegistry, au return true } selectionKey := m.selectionModelKeyForAuth(auth, routeModel) - return selectionKey != "" && selectionKey != routeKey && registryRef.ClientSupportsModel(auth.ID, selectionKey) + return selectionKey != "" && !sameCanonicalModelKey(selectionKey, routeKey) && registryRef.ClientSupportsModel(auth.ID, selectionKey) } func (m *Manager) normalizeProviders(providers []string) []string { @@ -1201,11 +1509,11 @@ func retryRoundAvailabilityForAuthForRequest(ctx context.Context, auth *Auth, mo return credentialRetryRoundStateEligible(auth.LastError, true), next } - modelKey := canonicalModelKey(model) + modelKey := canonicalModelLookupKey(model) if modelKey != "" && len(auth.ModelStates) > 0 { matchedBlocked := false for stateModel, state := range auth.ModelStates { - if state == nil || canonicalModelKey(stateModel) != modelKey { + if state == nil || canonicalModelLookupKey(stateModel) != modelKey { continue } if state.Status == StatusDisabled { @@ -1245,7 +1553,7 @@ func hasLiveQuotaCooldown(auth *Auth, model string, now time.Time) bool { if auth.Quota.Reason == "credential_quota" && quotaLive(auth.Quota) { return true } - modelKey := canonicalModelKey(model) + modelKey := canonicalModelLookupKey(model) if modelKey == "" { return quotaLive(auth.Quota) } @@ -1253,7 +1561,7 @@ func hasLiveQuotaCooldown(auth *Auth, model string, now time.Time) bool { if state == nil { continue } - if canonicalModelKey(stateModel) == modelKey && quotaLive(state.Quota) { + if canonicalModelLookupKey(stateModel) == modelKey && quotaLive(state.Quota) { return true } } @@ -1267,11 +1575,8 @@ func hasTransientZeroWaitEligibility(auth *Auth, model string) bool { if auth == nil { return false } - modelKey := canonicalModelKey(model) - if modelKey != "" && len(auth.ModelStates) > 0 { - if state := auth.ModelStates[modelKey]; state != nil { - return isTransientRateLimitResultError(state.LastError) - } + if state := existingModelState(auth, model); state != nil { + return isTransientRateLimitResultError(state.LastError) } return isTransientRateLimitResultError(auth.LastError) } @@ -1474,7 +1779,7 @@ func (m *Manager) shouldRetryAfterErrorWithAttempted(ctx context.Context, opts c if status == http.StatusOK { return 0, false } - if isRequestInvalidError(err) || isRequestStopError(err) { + if isRequestInvalidError(err) || isRequestStopError(err) || isSchedulerRejectError(err) { return 0, false } if m.HomeEnabled() { @@ -1513,6 +1818,21 @@ func (m *Manager) shouldRetryAfterErrorWithAttempted(ctx context.Context, opts c } eligibility := authSelectionEligibilityForRequest(ctx, opts) pinnedAuthID := pinnedAuthIDFromMetadata(opts.Metadata) + if affinity, ok := m.Selector().(*SessionAffinitySelector); ok && affinity != nil && affinity.rebindOnNever { + var authErr *Error + if errors.As(err, &authErr) && authErr != nil && authErr.Code == "session_auth_unavailable" { + return 0, false + } + if boundAuthID, okBound := affinity.boundAuthForRequest(providers, model, opts); okBound { + if pinnedAuthID != "" && pinnedAuthID != boundAuthID { + return 0, false + } + if shouldRebindSessionAffinityOnError(resultErrorFromError(err)) { + return 0, false + } + pinnedAuthID = boundAuthID + } + } if !isRequestRetryRoundError(err) || !m.retryAllowedForRequest(ctx, attempt, providers, model, eligibility, pinnedAuthID, defaultRequestRetry, opts.Headers) { return 0, false } @@ -1907,7 +2227,7 @@ func (m *Manager) routeAwareSelectionRequired(auth *Auth, routeModel string) boo if auth == nil || strings.TrimSpace(routeModel) == "" { return false } - return m.selectionModelKeyForAuth(auth, routeModel) != canonicalModelKey(routeModel) + return !sameCanonicalModelKey(m.selectionModelForAuth(auth, routeModel), routeModel) } func requestAwareCredSelectionRequired(ctx context.Context, auth *Auth, clientHeaders ...http.Header) bool { @@ -1952,8 +2272,13 @@ func (m *Manager) pickNextLegacy(ctx context.Context, provider, model string, op registryRef := registry.GetGlobalRegistry() targetKey := canonicalSchedulingProvider(provider) affinitySelector, hasAffinity := selector.(*SessionAffinitySelector) - trackTransientAffinity := hasAffinity && affinitySelector != nil && affinitySelector.rebindOnQuotaOnly - var affinityCandidates []*Auth + trackTransientAffinity := hasAffinity && affinitySelector != nil && (affinitySelector.rebindOnQuotaOnly || affinitySelector.rebindOnNever) + _, weighted := selector.(*WeightedRoundRobinSelector) + if hasAffinity && affinitySelector != nil { + _, weighted = affinitySelector.fallback.(*WeightedRoundRobinSelector) + } + trackPinnedAccounting := pinnedAuthID != "" && weighted + var accountingCandidates, affinityCandidates []*Auth if trackTransientAffinity { affinityCandidates = make([]*Auth, 0, len(m.auths)) } @@ -1961,7 +2286,7 @@ func (m *Manager) pickNextLegacy(ctx context.Context, provider, model string, op if candidate == nil || canonicalSchedulingProvider(executorKeyFromAuth(candidate)) != targetKey || candidate.Disabled { continue } - if pinnedAuthID != "" && candidate.ID != pinnedAuthID { + if !trackPinnedAccounting && pinnedAuthID != "" && candidate.ID != pinnedAuthID { continue } if !eligibility.allows(candidate) { @@ -1970,24 +2295,49 @@ func (m *Manager) pickNextLegacy(ctx context.Context, provider, model string, op if modelKey != "" && !m.authSupportsRouteModel(registryRef, candidate, model) { continue } + _, used := tried[candidate.ID] + // Pinning restricts selection, not the eligible pool used for accounting. + if trackPinnedAccounting && !used { + accountingCandidates = append(accountingCandidates, candidate) + } + if pinnedAuthID != "" && candidate.ID != pinnedAuthID { + continue + } if trackTransientAffinity { affinityCandidates = append(affinityCandidates, candidate) } - if _, used := tried[candidate.ID]; used { + if used { continue } candidates = append(candidates, candidate) } - if len(candidates) == 0 { + canInspectUnavailableAffinity := hasAffinity && affinitySelector != nil && affinitySelector.rebindOnNever && pluginScheduler == nil + if len(candidates) == 0 && !canInspectUnavailableAffinity { m.mu.RUnlock() return nil, nil, &Error{Code: "auth_not_found", Message: "no auth available"} } now := time.Now() - available, selectorAuths, errAvailable := m.availableAuthsForSelector(ctx, selector, candidates, provider, model, now, schedulerAcross, opts.Headers) - if errAvailable != nil { - m.mu.RUnlock() - m.warnLogAuthUnavailable(ctx, []string{provider}, model, opts, tried, errAvailable) - return nil, nil, errAvailable + var ( + available []*Auth + selectorAuths []*Auth + errAvailable error + ) + if len(candidates) > 0 { + available, selectorAuths, errAvailable = m.availableAuthsForSelector(ctx, selector, candidates, provider, model, now, schedulerAcross, opts.Headers) + if errAvailable != nil && !canInspectUnavailableAffinity { + m.mu.RUnlock() + m.warnLogAuthUnavailable(ctx, []string{provider}, model, opts, tried, errAvailable) + return nil, nil, errAvailable + } + } + var accountingAuths []*Auth + if trackPinnedAccounting && len(candidates) > 0 && errAvailable == nil { + fullAvailable, _, errAccounting := m.availableAuthsForSelector(ctx, selector, accountingCandidates, provider, model, now, true, opts.Headers) + if errAccounting != nil { + m.mu.RUnlock() + return nil, nil, errAccounting + } + accountingAuths = fullAvailable } transientAuthIDs := m.transientlyUnavailableSessionAffinityAuthIDs(ctx, selector, affinityCandidates, model, now, opts.Headers) m.mu.RUnlock() @@ -2000,8 +2350,18 @@ func (m *Manager) pickNextLegacy(ctx context.Context, provider, model string, op if !handled { selectorCtx := selectorContextForAvailableAuths(ctx, selector, model) selectorCtx = withSessionAffinityTransientAuthIDs(selectorCtx, transientAuthIDs) + if accountingAuths != nil { + selectorCtx = context.WithValue(selectorCtx, weightedAccountingPoolKey{}, accountingAuths) + } selected, errPick = selector.Pick(selectorCtx, provider, selectionArgForSelector(selector, model), opts, selectorAuths) if errPick != nil { + if isAuthNotFoundError(errPick) { + if errAvailable != nil { + errPick = errAvailable + } else if len(candidates) == 0 { + errPick = &Error{Code: "auth_not_found", Message: "no auth available"} + } + } if isBuiltInSelector(selector) { errPick = restoreModelCooldownErrorModel(errPick, model) } @@ -2027,10 +2387,16 @@ func (m *Manager) pickNextLegacy(ctx context.Context, provider, model string, op // SelectAuth selects one credential through the configured scheduling strategy. // It does not execute or alter the selected credential's result state. func (m *Manager) SelectAuth(ctx context.Context, provider, model string, opts cliproxyexecutor.Options) (*Auth, error) { + return m.SelectAuthExcluding(ctx, provider, model, opts, nil) +} + +// SelectAuthExcluding selects one credential through the configured scheduling strategy +// while excluding any credential IDs present in tried. +func (m *Manager) SelectAuthExcluding(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, tried map[string]struct{}) (*Auth, error) { if m != nil && m.HomeEnabled() { return nil, &Error{Code: "home_unavailable", Message: "legacy auth selection is unavailable while Home is enabled", HTTPStatus: http.StatusServiceUnavailable} } - selected, _, errPick := m.pickNextLegacy(ctx, provider, model, opts, nil) + selected, _, errPick := m.pickNextLegacy(ctx, provider, model, opts, tried) if errPick != nil { return nil, unwrapExecutionBoundaryError(errPick) } @@ -2040,6 +2406,14 @@ func (m *Manager) SelectAuth(ctx context.Context, provider, model string, opts c return selected, nil } +// MaxRetryCredentials returns the configured per-request credential retry cap (0 means unlimited). +func (m *Manager) MaxRetryCredentials() int { + if m == nil { + return 0 + } + return int(m.maxRetryCredentials.Load()) +} + // SelectAuthByKind selects one credential of the required kind through the // configured scheduling strategy. Credentials of other kinds are skipped. func (m *Manager) SelectAuthByKind(ctx context.Context, provider, model, requiredKind string, opts cliproxyexecutor.Options) (*Auth, error) { @@ -2357,8 +2731,13 @@ func (m *Manager) pickNextMixedLegacy(ctx context.Context, providers []string, m } registryRef := registry.GetGlobalRegistry() affinitySelector, hasAffinity := selector.(*SessionAffinitySelector) - trackTransientAffinity := hasAffinity && affinitySelector != nil && affinitySelector.rebindOnQuotaOnly - var affinityCandidates []*Auth + trackTransientAffinity := hasAffinity && affinitySelector != nil && (affinitySelector.rebindOnQuotaOnly || affinitySelector.rebindOnNever) + _, weighted := selector.(*WeightedRoundRobinSelector) + if hasAffinity && affinitySelector != nil { + _, weighted = affinitySelector.fallback.(*WeightedRoundRobinSelector) + } + trackPinnedAccounting := pinnedAuthID != "" && weighted + var accountingCandidates, affinityCandidates []*Auth if trackTransientAffinity { affinityCandidates = make([]*Auth, 0, len(m.auths)) } @@ -2366,7 +2745,7 @@ func (m *Manager) pickNextMixedLegacy(ctx context.Context, providers []string, m if candidate == nil || candidate.Disabled { continue } - if pinnedAuthID != "" && candidate.ID != pinnedAuthID { + if !trackPinnedAccounting && pinnedAuthID != "" && candidate.ID != pinnedAuthID { continue } if !eligibility.allows(candidate) { @@ -2385,24 +2764,49 @@ func (m *Manager) pickNextMixedLegacy(ctx context.Context, providers []string, m if modelKey != "" && !m.authSupportsRouteModel(registryRef, candidate, model) { continue } + _, used := tried[candidate.ID] + // Pinning restricts selection, not the eligible pool used for accounting. + if trackPinnedAccounting && !used { + accountingCandidates = append(accountingCandidates, candidate) + } + if pinnedAuthID != "" && candidate.ID != pinnedAuthID { + continue + } if trackTransientAffinity { affinityCandidates = append(affinityCandidates, candidate) } - if _, used := tried[candidate.ID]; used { + if used { continue } candidates = append(candidates, candidate) } - if len(candidates) == 0 { + canInspectUnavailableAffinity := hasAffinity && affinitySelector != nil && affinitySelector.rebindOnNever && pluginScheduler == nil + if len(candidates) == 0 && !canInspectUnavailableAffinity { m.mu.RUnlock() return nil, nil, "", &Error{Code: "auth_not_found", Message: "no auth available"} } now := time.Now() - available, selectorAuths, errAvailable := m.availableAuthsForSelector(ctx, selector, candidates, "mixed", model, now, schedulerAcross, opts.Headers) - if errAvailable != nil { - m.mu.RUnlock() - m.warnLogAuthUnavailable(ctx, providers, model, opts, tried, errAvailable) - return nil, nil, "", errAvailable + var ( + available []*Auth + selectorAuths []*Auth + errAvailable error + ) + if len(candidates) > 0 { + available, selectorAuths, errAvailable = m.availableAuthsForSelector(ctx, selector, candidates, "mixed", model, now, schedulerAcross, opts.Headers) + if errAvailable != nil && !canInspectUnavailableAffinity { + m.mu.RUnlock() + m.warnLogAuthUnavailable(ctx, providers, model, opts, tried, errAvailable) + return nil, nil, "", errAvailable + } + } + var accountingAuths []*Auth + if trackPinnedAccounting && len(candidates) > 0 && errAvailable == nil { + fullAvailable, _, errAccounting := m.availableAuthsForSelector(ctx, selector, accountingCandidates, "mixed", model, now, true, opts.Headers) + if errAccounting != nil { + m.mu.RUnlock() + return nil, nil, "", errAccounting + } + accountingAuths = fullAvailable } transientAuthIDs := m.transientlyUnavailableSessionAffinityAuthIDs(ctx, selector, affinityCandidates, model, now, opts.Headers) m.mu.RUnlock() @@ -2415,8 +2819,36 @@ func (m *Manager) pickNextMixedLegacy(ctx context.Context, providers []string, m if !handled { selectorCtx := selectorContextForAvailableAuths(ctx, selector, model) selectorCtx = withSessionAffinityTransientAuthIDs(selectorCtx, transientAuthIDs) + if accountingAuths != nil { + selectorCtx = context.WithValue(selectorCtx, weightedAccountingPoolKey{}, accountingAuths) + } + if _, bareWeighted := selector.(*WeightedRoundRobinSelector); bareWeighted { + // Match the scheduler's single-provider transport preference after + // excluding providers without an executor. + singleProvider := "" + for providerKey := range providerSet { + if _, okExecutor := m.Executor(providerKey); !okExecutor { + continue + } + if singleProvider != "" { + singleProvider = "" + break + } + singleProvider = providerKey + } + if singleProvider != "" { + selectorCtx = context.WithValue(selectorCtx, weightedTransportProviderKey{}, singleProvider) + } + } selected, errPick = selector.Pick(selectorCtx, "mixed", selectionArgForSelector(selector, model), opts, selectorAuths) if errPick != nil { + if isAuthNotFoundError(errPick) { + if errAvailable != nil { + errPick = errAvailable + } else if len(candidates) == 0 { + errPick = &Error{Code: "auth_not_found", Message: "no auth available"} + } + } if isBuiltInSelector(selector) { errPick = restoreModelCooldownErrorModel(errPick, model) } @@ -2533,6 +2965,14 @@ func (m *Manager) pickNextMixed(ctx context.Context, providers []string, model s return authCopy, executor, providerKey, nil } +func isAuthNotFoundError(err error) bool { + if err == nil { + return false + } + var authErr *Error + return errors.As(err, &authErr) && authErr != nil && authErr.Code == "auth_not_found" +} + func isAuthUnavailableError(err error) bool { if err == nil { return false @@ -2555,9 +2995,7 @@ func authCoolingSummary(auth *Auth, model string, next time.Time, now time.Time) ident := formatAuthIdentity(auth, auth.Provider) reason := "" if model != "" && len(auth.ModelStates) > 0 { - if state, ok := auth.ModelStates[model]; ok && state != nil { - reason = cooldownReason(state.StatusMessage, state.Quota, state.LastError) - } else if state, ok := auth.ModelStates[canonicalModelKey(model)]; ok && state != nil { + if state := existingModelState(auth, model); state != nil { reason = cooldownReason(state.StatusMessage, state.Quota, state.LastError) } } @@ -2574,6 +3012,144 @@ func authCoolingSummary(auth *Auth, model string, next time.Time, now time.Time) return fmt.Sprintf("[%s, reason=%s, remaining=%s]", ident, reason, remaining) } +func selectorExcludesZeroWeight(selector Selector) bool { + if _, weighted := selector.(*WeightedRoundRobinSelector); weighted { + return true + } + if affinity, ok := selector.(*SessionAffinitySelector); ok && affinity != nil { + _, weighted := affinity.fallback.(*WeightedRoundRobinSelector) + return weighted + } + return false +} + +// earliestPoolCooldownForModelAt scans the model's candidate credentials with +// the same filters selection uses. It reports: +// - earliest: the earliest active timed cooldown recovery instant +// - hasUnblocked: true when at least one eligible candidate is still available +// - ok: true when no candidate is available and at least one is in a timed cooldown +func (m *Manager) earliestPoolCooldownForModelAt(ctx context.Context, providers []string, model string, opts cliproxyexecutor.Options, now time.Time) (earliest time.Time, hasUnblocked bool, ok bool) { + if m == nil { + return time.Time{}, false, false + } + excludeZeroWeight := selectorExcludesZeroWeight(m.Selector()) + m.mu.RLock() + defer m.mu.RUnlock() + eligibility := authSelectionEligibilityForRequest(ctx, opts) + pinnedAuthID := pinnedAuthIDFromMetadata(opts.Metadata) + providerSet := make(map[string]struct{}, len(providers)) + for _, p := range providers { + if norm := canonicalSchedulingProvider(p); norm != "" && norm != "mixed" { + providerSet[norm] = struct{}{} + } + } + registryRef := registry.GetGlobalRegistry() + trimmedModel := strings.TrimSpace(model) + + totalCandidates := 0 + cooling := 0 + for _, candidate := range m.auths { + if candidate == nil || candidate.Disabled { + continue + } + if excludeZeroWeight && authWeight(candidate) <= 0 { + continue + } + rawProvider := executorKeyFromAuth(candidate) + providerKey := canonicalSchedulingProvider(rawProvider) + if providerKey == "" { + continue + } + if len(providerSet) > 0 { + if _, match := providerSet[providerKey]; !match { + continue + } + } + if _, hasExec := m.executorLocked(rawProvider); !hasExec { + if _, hasNormExec := m.executorLocked(providerKey); !hasNormExec { + continue + } + } + if pinnedAuthID != "" && candidate.ID != pinnedAuthID { + continue + } + if !eligibility.allows(candidate) { + continue + } + if trimmedModel != "" && !m.authSupportsRouteModel(registryRef, candidate, model) { + continue + } + totalCandidates++ + checkModel := m.selectionModelForAuth(candidate, model) + blocked, reason, next := isAuthBlockedForModelForRequest(ctx, candidate, checkModel, now, opts.Headers) + if !blocked { + return time.Time{}, true, false + } + if reason == blockReasonCooldown { + cooling++ + } + // Count every timed auto-recovery toward the pool's earliest reset, + // including transient non-cooldown blocks (e.g. a short capacity 429), + // matching how selection computes the earliest availability. + if reason != blockReasonDisabled && !next.IsZero() && next.After(now) { + if earliest.IsZero() || next.Before(earliest) { + earliest = next + } + } + } + if totalCandidates > 0 && cooling > 0 && !earliest.IsZero() { + return earliest, false, true + } + return time.Time{}, false, false +} + +func observeSelectionCooldownDeadline(dst *time.Time, err error, now time.Time) { + if dst == nil || err == nil { + return + } + var cooldown *modelCooldownError + if !errors.As(err, &cooldown) || cooldown == nil || cooldown.resetIn <= 0 { + return + } + candidate := now.Add(cooldown.resetIn) + if dst.IsZero() || candidate.Before(*dst) { + *dst = candidate + } +} + +func (m *Manager) annotatePoolCooldownTerminalError(ctx context.Context, providers []string, model string, opts cliproxyexecutor.Options, lastErr error, selectionCooldownDeadline time.Time) error { + return m.annotatePoolCooldownTerminalErrorAt(ctx, providers, model, opts, lastErr, selectionCooldownDeadline, time.Now()) +} + +func (m *Manager) annotatePoolCooldownTerminalErrorAt(ctx context.Context, providers []string, model string, opts cliproxyexecutor.Options, lastErr error, selectionCooldownDeadline time.Time, now time.Time) error { + if m == nil || lastErr == nil { + return lastErr + } + if statusCodeFromError(lastErr) != http.StatusTooManyRequests { + return lastErr + } + var marker interface{ IsModelCooldown() bool } + if errors.As(lastErr, &marker) && marker != nil && marker.IsModelCooldown() { + return lastErr + } + var existing *poolCooldownTerminalError + if errors.As(lastErr, &existing) && existing != nil { + return lastErr + } + deadline, hasUnblocked, ok := m.earliestPoolCooldownForModelAt(ctx, providers, model, opts, now) + if hasUnblocked { + return lastErr + } + if !ok && !selectionCooldownDeadline.IsZero() && selectionCooldownDeadline.After(now) { + deadline = selectionCooldownDeadline + ok = true + } + if !ok { + return lastErr + } + return &poolCooldownTerminalError{cause: lastErr, deadline: deadline} +} + func (m *Manager) warnLogAuthUnavailable(ctx context.Context, providers []string, model string, opts cliproxyexecutor.Options, tried map[string]struct{}, err error) { if m == nil || err == nil || !isAuthUnavailableError(err) { return diff --git a/sdk/cliproxy/auth/conductor_selection_cooldown_test.go b/sdk/cliproxy/auth/conductor_selection_cooldown_test.go index 95217a98704..a63dcda4538 100644 --- a/sdk/cliproxy/auth/conductor_selection_cooldown_test.go +++ b/sdk/cliproxy/auth/conductor_selection_cooldown_test.go @@ -3,10 +3,13 @@ package auth import ( "context" "errors" + "net/http" + "strconv" "strings" "testing" "time" + internallogging "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" ) @@ -813,3 +816,1197 @@ func TestErrorWithCause_ErrorDirectFormat(t *testing.T) { t.Fatalf("Error() = %q, want containing upstream error summary", got) } } + +func TestModelCooldownError_ClaudeUnifiedRateLimitHeaders(t *testing.T) { + t.Parallel() + + t.Run("preserves observed 7d claim under 5h remaining across affinity and scheduler paths", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + name := "scheduler" + if useAffinity { + name = "session_affinity" + } + t.Run(name, func(t *testing.T) { + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + manager := NewManager(nil, selector, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + const model = "issue-7417-claude-7d-short-" + modelID := model + name + authID := "issue-7417-auth-" + name + registry.GetGlobalRegistry().RegisterClient(authID, "claude", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: authID, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + retryDelay := 2 * time.Hour + upstreamReset := time.Now().Add(retryDelay - 15*time.Second).Unix() + markCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(markCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Reset": {strconv.FormatInt(upstreamReset, 10)}, + "Anthropic-Ratelimit-Unified-5h-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"seven_day"}, + "Anthropic-Ratelimit-Unified-Overage-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(upstreamReset, 10)}, + }) + manager.MarkResult(markCtx, Result{ + AuthID: authID, + Provider: "claude", + Model: modelID, + Success: false, + CredentialScope: true, + RetryAfter: &retryDelay, + Error: &Error{Code: ErrorCodeCredentialQuota, Message: "rate_limit_error", HTTPStatus: http.StatusTooManyRequests}, + }) + + _, errExecute := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + if errExecute == nil { + t.Fatal("expected cooldown error, got nil") + } + + var cooldownErr *modelCooldownError + if !errors.As(errExecute, &cooldownErr) { + t.Fatalf("Execute() error = %T (%v), want *modelCooldownError", errExecute, errExecute) + } + + before := time.Now().Unix() + headers := cooldownErr.Headers() + after := time.Now().Unix() + retrySeconds, errSeconds := strconv.ParseInt(headers.Get("Retry-After"), 10, 64) + if errSeconds != nil || retrySeconds <= 0 { + t.Fatalf("Retry-After = %q, want positive seconds", headers.Get("Retry-After")) + } + if got := headers.Get("Anthropic-Ratelimit-Unified-Status"); got != "rejected" { + t.Fatalf("Anthropic-Ratelimit-Unified-Status = %q, want rejected", got) + } + if got := headers.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "seven_day" { + t.Fatalf("Anthropic-Ratelimit-Unified-Representative-Claim = %q, want seven_day", got) + } + if got := headers.Get("Anthropic-Ratelimit-Unified-7d-Status"); got != "rejected" { + t.Fatalf("Anthropic-Ratelimit-Unified-7d-Status = %q, want rejected", got) + } + if got := headers.Get("Anthropic-Ratelimit-Unified-5h-Status"); got != "allowed" { + t.Fatalf("Anthropic-Ratelimit-Unified-5h-Status = %q, want allowed", got) + } + if got := headers.Get("Anthropic-Ratelimit-Unified-Overage-Status"); got != "rejected" { + t.Fatalf("Anthropic-Ratelimit-Unified-Overage-Status = %q, want rejected", got) + } + + unifiedReset, errReset := strconv.ParseInt(headers.Get("Anthropic-Ratelimit-Unified-Reset"), 10, 64) + if errReset != nil { + t.Fatalf("Anthropic-Ratelimit-Unified-Reset = %q, want unix epoch", headers.Get("Anthropic-Ratelimit-Unified-Reset")) + } + if unifiedReset < before+retrySeconds || unifiedReset > after+retrySeconds { + t.Fatalf("Anthropic-Ratelimit-Unified-Reset = %d, want in [%d, %d] aligned with Retry-After %d", unifiedReset, before+retrySeconds, after+retrySeconds, retrySeconds) + } + if got := headers.Get("Anthropic-Ratelimit-Unified-7d-Reset"); got != strconv.FormatInt(unifiedReset, 10) { + t.Fatalf("Anthropic-Ratelimit-Unified-7d-Reset = %q, want %d", got, unifiedReset) + } + + safeHeaders := SafeResponseHeaders(errExecute) + if got := safeHeaders.Get("Anthropic-Ratelimit-Unified-Status"); got != "" { + t.Fatalf("SafeResponseHeaders leaked unified header %q", got) + } + }) + } + }) + + t.Run("infers claim from duration when signals are absent", func(t *testing.T) { + errFiveHour := newModelCooldownError("claude-haiku-4-5-20251001", "claude", 2*time.Hour) + h5 := errFiveHour.Headers() + if got := h5.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "five_hour" { + t.Fatalf("5h fallback claim = %q, want five_hour", got) + } + if got := h5.Get("Anthropic-Ratelimit-Unified-5h-Status"); got != "rejected" { + t.Fatalf("5h fallback status = %q, want rejected", got) + } + if got := h5.Get("Anthropic-Ratelimit-Unified-Overage-Status"); got != "rejected" { + t.Fatalf("5h fallback overage status = %q, want rejected", got) + } + + errSevenDay := newModelCooldownError("claude-haiku-4-5-20251001", "claude", 6*time.Hour) + h7 := errSevenDay.Headers() + if got := h7.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "seven_day" { + t.Fatalf("7d fallback claim = %q, want seven_day", got) + } + if got := h7.Get("Anthropic-Ratelimit-Unified-7d-Status"); got != "rejected" { + t.Fatalf("7d fallback status = %q, want rejected", got) + } + }) + + t.Run("preserves allowed shared windows on overage claim and aligns model-family window resets", func(t *testing.T) { + overageErr := newModelCooldownErrorForCandidates("claude-sonnet-4-5-20250929", "claude", 30*time.Second, nil, true, map[string]string{ + "Anthropic-Ratelimit-Unified-Status": "rejected", + "Anthropic-Ratelimit-Unified-Representative-Claim": "overage", + "Anthropic-Ratelimit-Unified-5h-Status": "allowed", + "Anthropic-Ratelimit-Unified-7d-Status": "allowed", + "Anthropic-Ratelimit-Unified-Overage-Status": "rejected", + }) + overageHeaders := overageErr.Headers() + if got := overageHeaders.Get("Anthropic-Ratelimit-Unified-5h-Status"); got != "allowed" { + t.Fatalf("overage cooldown overwrote 5h status = %q, want allowed", got) + } + if got := overageHeaders.Get("Anthropic-Ratelimit-Unified-7d-Status"); got != "allowed" { + t.Fatalf("overage cooldown overwrote 7d status = %q, want allowed", got) + } + if got := overageHeaders.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "overage" { + t.Fatalf("overage cooldown claim = %q, want overage", got) + } + + sonnetErr := newModelCooldownErrorForCandidates("claude-sonnet-4-5-20250929", "claude", 2*time.Hour, nil, true, map[string]string{ + "Anthropic-Ratelimit-Unified-Status": "rejected", + "Anthropic-Ratelimit-Unified-Representative-Claim": "seven_day_sonnet", + "Anthropic-Ratelimit-Unified-5h-Status": "allowed", + "Anthropic-Ratelimit-Unified-7d-Status": "allowed", + "Anthropic-Ratelimit-Unified-7d_sonnet-Status": "rejected", + "Anthropic-Ratelimit-Unified-7d_sonnet-Reset": "1700000000", + "Anthropic-Ratelimit-Unified-Overage-Status": "rejected", + }) + sonnetHeaders := sonnetErr.Headers() + if got := sonnetHeaders.Get("Anthropic-Ratelimit-Unified-5h-Status"); got != "allowed" { + t.Fatalf("7d_sonnet cooldown overwrote 5h status = %q, want allowed", got) + } + if got := sonnetHeaders.Get("Anthropic-Ratelimit-Unified-7d_sonnet-Reset"); got != sonnetHeaders.Get("Anthropic-Ratelimit-Unified-Reset") { + t.Fatalf("7d_sonnet reset = %q, want %q", got, sonnetHeaders.Get("Anthropic-Ratelimit-Unified-Reset")) + } + + overageNoClaimErr := newModelCooldownErrorForCandidates("claude-sonnet-4-5-20250929", "claude", 30*time.Second, nil, true, map[string]string{ + "Anthropic-Ratelimit-Unified-Status": "rejected", + "Anthropic-Ratelimit-Unified-5h-Status": "allowed", + "Anthropic-Ratelimit-Unified-7d-Status": "allowed", + "Anthropic-Ratelimit-Unified-Overage-Status": "rejected", + }) + overageNoClaimHeaders := overageNoClaimErr.Headers() + if got := overageNoClaimHeaders.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "overage" { + t.Fatalf("overage without claim inferred %q, want overage", got) + } + if got := overageNoClaimHeaders.Get("Anthropic-Ratelimit-Unified-5h-Status"); got != "allowed" { + t.Fatalf("overage without claim 5h status = %q, want allowed", got) + } + + sonnetNoClaimErr := newModelCooldownErrorForCandidates("claude-sonnet-4-5-20250929", "claude", 2*time.Hour, nil, true, map[string]string{ + "Anthropic-Ratelimit-Unified-Status": "rejected", + "Anthropic-Ratelimit-Unified-5h-Status": "allowed", + "Anthropic-Ratelimit-Unified-7d-Status": "allowed", + "Anthropic-Ratelimit-Unified-7d_sonnet-Status": "rejected", + "Anthropic-Ratelimit-Unified-Overage-Status": "rejected", + }) + sonnetNoClaimHeaders := sonnetNoClaimErr.Headers() + if got := sonnetNoClaimHeaders.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "seven_day_sonnet" { + t.Fatalf("7d_sonnet without claim inferred %q, want seven_day_sonnet", got) + } + + fiveAllowedOnlyErr := newModelCooldownErrorForCandidates("claude-sonnet-4-5-20250929", "claude", 2*time.Hour, nil, true, map[string]string{ + "Anthropic-Ratelimit-Unified-Status": "rejected", + "Anthropic-Ratelimit-Unified-5h-Status": "allowed", + }) + fiveAllowedOnlyHeaders := fiveAllowedOnlyErr.Headers() + if got := fiveAllowedOnlyHeaders.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "seven_day" { + t.Fatalf("5h=allowed with 2h reset inferred %q, want seven_day", got) + } + if got := fiveAllowedOnlyHeaders.Get("Anthropic-Ratelimit-Unified-7d-Status"); got != "rejected" { + t.Fatalf("5h=allowed with 2h reset 7d status = %q, want rejected", got) + } + }) + + t.Run("does not emit unified headers for non-Claude or cloudflare cooldowns", func(t *testing.T) { + manager := NewManager(nil, NewSessionAffinitySelector(&RoundRobinSelector{}), nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "codex"}) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + const codexModel = "issue-7417-codex-model" + const codexAuthID = "issue-7417-codex-auth" + const cfModel = "issue-7417-cf-model" + const cfAuthID = "issue-7417-cf-auth" + next := time.Now().Add(30 * time.Minute) + + registry.GetGlobalRegistry().RegisterClient(codexAuthID, "codex", []*registry.ModelInfo{{ID: codexModel}}) + registry.GetGlobalRegistry().RegisterClient(cfAuthID, "claude", []*registry.ModelInfo{{ID: cfModel}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(codexAuthID) + registry.GetGlobalRegistry().UnregisterClient(cfAuthID) + }) + + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: codexAuthID, + Provider: "codex", + Status: StatusActive, + Unavailable: true, + NextRetryAfter: next, + Quota: QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: next}, + }); errRegister != nil { + t.Fatalf("register codex auth: %v", errRegister) + } + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: cfAuthID, + Provider: "claude", + Status: StatusActive, + Unavailable: true, + NextRetryAfter: next, + ModelStates: map[string]*ModelState{ + cfModel: { + Status: StatusError, + Unavailable: true, + NextRetryAfter: next, + Quota: QuotaState{Exceeded: true, Reason: "cloudflare challenge", NextRecoverAt: next}, + }, + }, + }); errRegister != nil { + t.Fatalf("register cloudflare auth: %v", errRegister) + } + + _, errCodex := manager.Execute(context.Background(), []string{"codex"}, cliproxyexecutor.Request{Model: codexModel}, cliproxyexecutor.Options{}) + var codexCooldown *modelCooldownError + if !errors.As(errCodex, &codexCooldown) { + t.Fatalf("codex Execute() error = %T (%v), want *modelCooldownError", errCodex, errCodex) + } + if codexCooldown.provider != "" { + t.Fatalf("codex cooldown provider = %q, want empty mixed provider", codexCooldown.provider) + } + if got := codexCooldown.Headers().Get("Anthropic-Ratelimit-Unified-Status"); got != "" { + t.Fatalf("codex cooldown leaked Anthropic-Ratelimit-Unified-Status = %q", got) + } + + _, errCF := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: cfModel}, cliproxyexecutor.Options{}) + var cfCooldown *modelCooldownError + if !errors.As(errCF, &cfCooldown) { + t.Fatalf("cloudflare Execute() error = %T (%v), want *modelCooldownError", errCF, errCF) + } + if got := cfCooldown.Headers().Get("Anthropic-Ratelimit-Unified-Status"); got != "" { + t.Fatalf("cloudflare challenge cooldown leaked Anthropic-Ratelimit-Unified-Status = %q", got) + } + }) + + t.Run("does not synthesize unified headers for ordinary per-minute rate limits across affinity and scheduler paths", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + pathName := "scheduler" + if useAffinity { + pathName = "session_affinity" + } + t.Run(pathName, func(t *testing.T) { + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + manager := NewManager(nil, selector, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + allowedWindowModel := "issue-7417-rpm-allowed-" + pathName + allowedWindowAuth := "issue-7417-rpm-allowed-auth-" + pathName + plainRPMModel := "issue-7417-rpm-plain-" + pathName + plainRPMAuth := "issue-7417-rpm-plain-auth-" + pathName + modelQuotaModel := "issue-7417-model-unified-" + pathName + modelQuotaAuth := "issue-7417-model-unified-auth-" + pathName + + registry.GetGlobalRegistry().RegisterClient(allowedWindowAuth, "claude", []*registry.ModelInfo{{ID: allowedWindowModel}}) + registry.GetGlobalRegistry().RegisterClient(plainRPMAuth, "claude", []*registry.ModelInfo{{ID: plainRPMModel}}) + registry.GetGlobalRegistry().RegisterClient(modelQuotaAuth, "claude", []*registry.ModelInfo{{ID: modelQuotaModel}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(allowedWindowAuth) + registry.GetGlobalRegistry().UnregisterClient(plainRPMAuth) + registry.GetGlobalRegistry().UnregisterClient(modelQuotaAuth) + }) + + for _, id := range []string{allowedWindowAuth, plainRPMAuth, modelQuotaAuth} { + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: id, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register %s: %v", id, errRegister) + } + } + + shortRetry := 30 * time.Second + rpmBody := `{"type":"error","error":{"type":"rate_limit_error","message":"This request would exceed the requests per minute rate limit. Please try again later."}}` + + // 1. Per-minute 429 with allowed 5h window and future unified reset. + allowedCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(allowedCtx, http.Header{ + "Retry-After": {"30"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(4*time.Hour).Unix(), 10)}, + }) + manager.MarkResult(allowedCtx, Result{ + AuthID: allowedWindowAuth, + Provider: "claude", + Model: allowedWindowModel, + Success: false, + CredentialScope: false, + RetryAfter: &shortRetry, + Error: &Error{Code: "rate_limit_error", Message: rpmBody, HTTPStatus: http.StatusTooManyRequests}, + }) + + // 2. Per-minute 429 with only Retry-After and no unified rejection headers. + plainCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(plainCtx, http.Header{ + "Retry-After": {"30"}, + }) + manager.MarkResult(plainCtx, Result{ + AuthID: plainRPMAuth, + Provider: "claude", + Model: plainRPMModel, + Success: false, + CredentialScope: false, + RetryAfter: &shortRetry, + Error: &Error{Code: "rate_limit_error", Message: rpmBody, HTTPStatus: http.StatusTooManyRequests}, + }) + + // 3. Model-level cooling (e.g. API-key upstream) that explicitly reports unified 5h rejection. + fiveHourDelay := 2 * time.Hour + rejectedCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(rejectedCtx, http.Header{ + "Retry-After": {"7200"}, + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(fiveHourDelay).Unix(), 10)}, + }) + manager.MarkResult(rejectedCtx, Result{ + AuthID: modelQuotaAuth, + Provider: "claude", + Model: modelQuotaModel, + Success: false, + CredentialScope: false, + RetryAfter: &fiveHourDelay, + Error: &Error{Code: "rate_limit_error", Message: "quota exhausted", HTTPStatus: http.StatusTooManyRequests}, + }) + + for _, modelID := range []string{allowedWindowModel, plainRPMModel} { + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + var cdErr *modelCooldownError + if !errors.As(errExec, &cdErr) { + t.Fatalf("%s Execute() error = %T (%v), want *modelCooldownError", modelID, errExec, errExec) + } + hdr := cdErr.Headers() + if got := hdr.Get("Retry-After"); got == "" { + t.Fatalf("%s Retry-After = empty, want positive seconds", modelID) + } + for key := range hdr { + if strings.HasPrefix(strings.ToLower(key), "anthropic-ratelimit-unified-") { + t.Fatalf("%s ordinary rate-limit cooldown leaked unified header %s=%q", modelID, key, hdr.Get(key)) + } + } + } + + _, errModelQuota := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelQuotaModel}, cliproxyexecutor.Options{}) + var modelQuotaCooldown *modelCooldownError + if !errors.As(errModelQuota, &modelQuotaCooldown) { + t.Fatalf("modelQuota Execute() error = %T (%v), want *modelCooldownError", errModelQuota, errModelQuota) + } + if got := modelQuotaCooldown.Headers().Get("Anthropic-Ratelimit-Unified-Status"); got != "rejected" { + t.Fatalf("modelQuota Anthropic-Ratelimit-Unified-Status = %q, want rejected", got) + } + if got := modelQuotaCooldown.Headers().Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "five_hour" { + t.Fatalf("modelQuota Representative-Claim = %q, want five_hour", got) + } + }) + } + }) + + t.Run("retains unified headers when late success refreshes passive signals during active cooldown", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + pathName := "scheduler" + if useAffinity { + pathName = "session_affinity" + } + t.Run(pathName, func(t *testing.T) { + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + manager := NewManager(nil, selector, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + credModel := "issue-7417-late-cred-" + pathName + credAuth := "issue-7417-late-cred-auth-" + pathName + restoredModel := "issue-7417-late-restored-" + pathName + restoredAuth := "issue-7417-late-restored-auth-" + pathName + modelScopedModel := "issue-7417-late-model-" + pathName + modelScopedAuth := "issue-7417-late-model-auth-" + pathName + + registry.GetGlobalRegistry().RegisterClient(credAuth, "claude", []*registry.ModelInfo{{ID: credModel}}) + registry.GetGlobalRegistry().RegisterClient(restoredAuth, "claude", []*registry.ModelInfo{{ID: restoredModel}}) + registry.GetGlobalRegistry().RegisterClient(modelScopedAuth, "claude", []*registry.ModelInfo{{ID: modelScopedModel}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(credAuth) + registry.GetGlobalRegistry().UnregisterClient(restoredAuth) + registry.GetGlobalRegistry().UnregisterClient(modelScopedAuth) + }) + + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: credAuth, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register credAuth: %v", errRegister) + } + recoverAt := time.Now().Add(2 * time.Hour) + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: restoredAuth, + Provider: "claude", + Status: StatusError, + Unavailable: true, + NextRetryAfter: recoverAt, + Quota: QuotaState{ + Exceeded: true, + Reason: "credential_quota", + NextRecoverAt: recoverAt, + }, + }); errRegister != nil { + t.Fatalf("register restoredAuth: %v", errRegister) + } + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: modelScopedAuth, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register modelScopedAuth: %v", errRegister) + } + + delay := 2 * time.Hour + rejectedCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(rejectedCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"seven_day"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(delay).Unix(), 10)}, + }) + + // Step 1: Record subscription 429 on credAuth and modelScopedAuth. + staleSeq := manager.nextExecutionSeq() + failureSeq := manager.nextExecutionSeq() + manager.MarkResult(rejectedCtx, Result{ + AuthID: credAuth, + Provider: "claude", + Model: credModel, + Success: false, + CredentialScope: true, + RetryAfter: &delay, + ExecutionSeq: failureSeq, + Error: &Error{Code: ErrorCodeCredentialQuota, Message: "rate_limit_error", HTTPStatus: http.StatusTooManyRequests}, + }) + manager.MarkResult(rejectedCtx, Result{ + AuthID: modelScopedAuth, + Provider: "claude", + Model: modelScopedModel, + Success: false, + CredentialScope: false, + RetryAfter: &delay, + ExecutionSeq: failureSeq, + Error: &Error{Code: "rate_limit_error", Message: "rate_limit_error", HTTPStatus: http.StatusTooManyRequests}, + }) + + // Step 2: Earlier in-flight requests complete with 200 OK and allowed unified headers. + allowedCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(allowedCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"allowed"}, + }) + manager.MarkResult(allowedCtx, Result{ + AuthID: credAuth, + Provider: "claude", + Model: credModel, + Success: true, + ExecutionSeq: staleSeq, + }) + manager.MarkResult(allowedCtx, Result{ + AuthID: restoredAuth, + Provider: "claude", + Model: restoredModel, + Success: true, + ExecutionSeq: staleSeq, + }) + manager.MarkResult(allowedCtx, Result{ + AuthID: modelScopedAuth, + Provider: "claude", + Model: modelScopedModel, + Success: true, + ExecutionSeq: staleSeq, + }) + + // Step 3: Subsequent requests during active cooldown still emit unified rate-limit headers. + for _, tc := range []struct { + model string + wantClaim string + }{ + {model: credModel, wantClaim: "seven_day"}, + {model: restoredModel, wantClaim: "five_hour"}, + {model: modelScopedModel, wantClaim: "seven_day"}, + } { + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: tc.model}, cliproxyexecutor.Options{}) + var cdErr *modelCooldownError + if !errors.As(errExec, &cdErr) { + t.Fatalf("%s Execute() error = %T (%v), want *modelCooldownError", tc.model, errExec, errExec) + } + hdr := cdErr.Headers() + if got := hdr.Get("Anthropic-Ratelimit-Unified-Status"); got != "rejected" { + t.Fatalf("%s Anthropic-Ratelimit-Unified-Status = %q, want rejected", tc.model, got) + } + if got := hdr.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != tc.wantClaim { + t.Fatalf("%s Representative-Claim = %q, want %s", tc.model, got, tc.wantClaim) + } + } + }) + } + }) + + t.Run("does not emit stale unified headers when 503 follows expired model quota cooldown", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + pathName := "scheduler" + if useAffinity { + pathName = "session_affinity" + } + t.Run(pathName, func(t *testing.T) { + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + manager := NewManager(nil, selector, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + modelID := "issue-7417-expired-503-" + pathName + authID := "issue-7417-expired-503-auth-" + pathName + registry.GetGlobalRegistry().RegisterClient(authID, "claude", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: authID, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + // 1. Model-scoped unified 429 records rejected signals. + quotaDelay := time.Hour + rejectedCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(rejectedCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"five_hour"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(quotaDelay).Unix(), 10)}, + }) + manager.MarkResult(rejectedCtx, Result{ + AuthID: authID, + Provider: "claude", + Model: modelID, + Success: false, + CredentialScope: false, + RetryAfter: "aDelay, + Error: &Error{Code: "rate_limit_error", Message: "quota", HTTPStatus: http.StatusTooManyRequests}, + }) + + // 2. Simulate natural expiry of the quota deadline without wall-clock sleep. + past := time.Now().Add(-time.Minute) + if _, okModify, errModify := manager.Modify(context.Background(), authID, 0, func(a *Auth) error { + a.NextRetryAfter = past + if state := a.ModelStates[modelID]; state != nil { + state.NextRetryAfter = past + state.Quota.NextRecoverAt = past + } + a.Quota.NextRecoverAt = past + return nil + }); errModify != nil || !okModify { + t.Fatalf("Modify() ok=%v err=%v", okModify, errModify) + } + + // 3. Subsequent request fails with 503 Service Unavailable and Retry-After. + serverDelay := 45 * time.Second + manager.MarkResult(context.Background(), Result{ + AuthID: authID, + Provider: "claude", + Model: modelID, + Success: false, + RetryAfter: &serverDelay, + Error: &Error{Code: "server_error", Message: "overloaded", HTTPStatus: http.StatusServiceUnavailable}, + }) + + // 4. Subsequent selection error must not advertise unified subscription exhaustion. + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + if errExec == nil { + t.Fatal("expected unavailable/cooldown error after 503, got nil") + } + if carrier, ok := errExec.(interface{ Headers() http.Header }); ok && carrier != nil { + for key := range carrier.Headers() { + if strings.HasPrefix(strings.ToLower(key), "anthropic-ratelimit-unified-") { + t.Fatalf("%s post-expiry 503 leaked unified header %s=%q", pathName, key, carrier.Headers().Get(key)) + } + } + } + }) + } + }) + + t.Run("persists and restores model-scoped unified cooldown headers across restart", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + pathName := "scheduler" + if useAffinity { + pathName = "session_affinity" + } + t.Run(pathName, func(t *testing.T) { + store := NewFileCooldownStateStore(t.TempDir()) + modelID := "issue-7417-restart-model-" + pathName + authID := "issue-7417-restart-auth-" + pathName + registry.GetGlobalRegistry().RegisterClient(authID, "claude", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + writerMgr := NewManager(nil, nil, nil) + writerMgr.SetCooldownStateStore(store) + if _, errRegister := writerMgr.Register(context.Background(), &Auth{ + ID: authID, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("writer Register: %v", errRegister) + } + + delay := 2 * time.Hour + rejectedCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(rejectedCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"seven_day"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(delay).Unix(), 10)}, + }) + writerMgr.MarkResult(rejectedCtx, Result{ + AuthID: authID, + Provider: "claude", + Model: modelID, + Success: false, + CredentialScope: false, + RetryAfter: &delay, + Error: &Error{Code: "rate_limit_error", Message: "quota", HTTPStatus: http.StatusTooManyRequests}, + }) + writerMgr.PersistCooldownStates(context.Background()) + + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + restoredMgr := NewManager(nil, selector, nil) + restoredMgr.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + restoredMgr.SetCooldownStateStore(store) + if _, errRegister := restoredMgr.Register(context.Background(), &Auth{ + ID: authID, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("restored Register: %v", errRegister) + } + if errRestore := restoredMgr.RestoreCooldownStates(context.Background()); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + + _, errExec := restoredMgr.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + var cdErr *modelCooldownError + if !errors.As(errExec, &cdErr) { + t.Fatalf("%s Execute() error = %T (%v), want *modelCooldownError", pathName, errExec, errExec) + } + hdr := cdErr.Headers() + if got := hdr.Get("Anthropic-Ratelimit-Unified-Status"); got != "rejected" { + t.Fatalf("%s restored Anthropic-Ratelimit-Unified-Status = %q, want rejected", pathName, got) + } + if got := hdr.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "seven_day" { + t.Fatalf("%s restored Representative-Claim = %q, want seven_day", pathName, got) + } + if got := hdr.Get("Anthropic-Ratelimit-Unified-7d-Status"); got != "rejected" { + t.Fatalf("%s restored 7d-Status = %q, want rejected", pathName, got) + } + if got := hdr.Get("Anthropic-Ratelimit-Unified-5h-Status"); got != "allowed" { + t.Fatalf("%s restored 5h-Status = %q, want allowed", pathName, got) + } + }) + } + }) + + t.Run("keeps longer cooldown window signals when shorter out-of-order 429 completes later", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + pathName := "scheduler" + if useAffinity { + pathName = "session_affinity" + } + t.Run(pathName, func(t *testing.T) { + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + manager := NewManager(nil, selector, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + credModelA := "issue-7417-ooo-cred-a-" + pathName + credModelB := "issue-7417-ooo-cred-b-" + pathName + credAuth := "issue-7417-ooo-cred-auth-" + pathName + modelScopedModel := "issue-7417-ooo-model-" + pathName + modelScopedAuth := "issue-7417-ooo-model-auth-" + pathName + rpmFirstModel := "issue-7417-ooo-rpm-" + pathName + rpmFirstAuth := "issue-7417-ooo-rpm-auth-" + pathName + + registry.GetGlobalRegistry().RegisterClient(credAuth, "claude", []*registry.ModelInfo{{ID: credModelA}, {ID: credModelB}}) + registry.GetGlobalRegistry().RegisterClient(modelScopedAuth, "claude", []*registry.ModelInfo{{ID: modelScopedModel}}) + registry.GetGlobalRegistry().RegisterClient(rpmFirstAuth, "claude", []*registry.ModelInfo{{ID: rpmFirstModel}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(credAuth) + registry.GetGlobalRegistry().UnregisterClient(modelScopedAuth) + registry.GetGlobalRegistry().UnregisterClient(rpmFirstAuth) + }) + + for _, id := range []string{credAuth, modelScopedAuth, rpmFirstAuth} { + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: id, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register %s: %v", id, errRegister) + } + } + + longDelay := 2 * time.Hour + shortDelay := time.Hour + sevenDayCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(sevenDayCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"seven_day"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(longDelay).Unix(), 10)}, + }) + fiveHourCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(fiveHourCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"five_hour"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(shortDelay).Unix(), 10)}, + }) + + // Credential-scoped: 2h seven_day on model A, then shorter 1h five_hour on model B. + manager.MarkResult(sevenDayCtx, Result{ + AuthID: credAuth, + Provider: "claude", + Model: credModelA, + Success: false, + CredentialScope: true, + RetryAfter: &longDelay, + Error: &Error{Code: ErrorCodeCredentialQuota, Message: "7d quota", HTTPStatus: http.StatusTooManyRequests}, + }) + manager.MarkResult(fiveHourCtx, Result{ + AuthID: credAuth, + Provider: "claude", + Model: credModelB, + Success: false, + CredentialScope: true, + RetryAfter: &shortDelay, + Error: &Error{Code: ErrorCodeCredentialQuota, Message: "5h quota", HTTPStatus: http.StatusTooManyRequests}, + }) + + // Model-scoped: 2h seven_day, then shorter 1h five_hour. + manager.MarkResult(sevenDayCtx, Result{ + AuthID: modelScopedAuth, + Provider: "claude", + Model: modelScopedModel, + Success: false, + CredentialScope: false, + RetryAfter: &longDelay, + Error: &Error{Code: "rate_limit_error", Message: "7d quota", HTTPStatus: http.StatusTooManyRequests}, + }) + manager.MarkResult(fiveHourCtx, Result{ + AuthID: modelScopedAuth, + Provider: "claude", + Model: modelScopedModel, + Success: false, + CredentialScope: false, + RetryAfter: &shortDelay, + Error: &Error{Code: "rate_limit_error", Message: "5h quota", HTTPStatus: http.StatusTooManyRequests}, + }) + + // Longer ordinary 10m RPM 429 followed by shorter 1m unified 429: governing deadline stays ordinary RPM. + rpmLong := 10 * time.Minute + unifiedShort := time.Minute + rpmCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(rpmCtx, http.Header{"Retry-After": {"600"}}) + manager.MarkResult(rpmCtx, Result{ + AuthID: rpmFirstAuth, + Provider: "claude", + Model: rpmFirstModel, + Success: false, + CredentialScope: false, + RetryAfter: &rpmLong, + Error: &Error{Code: "rate_limit_error", Message: "rpm", HTTPStatus: http.StatusTooManyRequests}, + }) + manager.MarkResult(fiveHourCtx, Result{ + AuthID: rpmFirstAuth, + Provider: "claude", + Model: rpmFirstModel, + Success: false, + CredentialScope: false, + RetryAfter: &unifiedShort, + Error: &Error{Code: "rate_limit_error", Message: "5h", HTTPStatus: http.StatusTooManyRequests}, + }) + + for _, m := range []string{credModelA, credModelB, modelScopedModel} { + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: m}, cliproxyexecutor.Options{}) + var cdErr *modelCooldownError + if !errors.As(errExec, &cdErr) { + t.Fatalf("%s Execute() error = %T (%v), want *modelCooldownError", m, errExec, errExec) + } + if got := cdErr.Headers().Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "seven_day" { + t.Fatalf("%s Representative-Claim = %q, want seven_day (from governing 2h deadline)", m, got) + } + if got := cdErr.Headers().Get("Anthropic-Ratelimit-Unified-7d-Status"); got != "rejected" { + t.Fatalf("%s 7d-Status = %q, want rejected", m, got) + } + } + + _, errRPM := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: rpmFirstModel}, cliproxyexecutor.Options{}) + var rpmCdErr *modelCooldownError + if !errors.As(errRPM, &rpmCdErr) { + t.Fatalf("%s Execute() error = %T (%v), want *modelCooldownError", rpmFirstModel, errRPM, errRPM) + } + if got := rpmCdErr.Headers().Get("Anthropic-Ratelimit-Unified-Status"); got != "" { + t.Fatalf("%s leaked unified status %q while 10m ordinary RPM deadline still governs", rpmFirstModel, got) + } + }) + } + }) + + t.Run("reverts to independent model layer after propagated credential quota expires", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + pathName := "scheduler" + if useAffinity { + pathName = "session_affinity" + } + t.Run(pathName, func(t *testing.T) { + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + manager := NewManager(nil, selector, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + modelA := "issue-7417-shadow-a-" + pathName + modelB := "issue-7417-shadow-b-" + pathName + authID := "issue-7417-shadow-auth-" + pathName + registry.GetGlobalRegistry().RegisterClient(authID, "claude", []*registry.ModelInfo{{ID: modelA}, {ID: modelB}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: authID, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + // 1. Model A enters a 10m ordinary RPM cooldown (no unified rejection headers). + rpmDelay := 10 * time.Minute + rpmCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(rpmCtx, http.Header{"Retry-After": {"600"}}) + manager.MarkResult(rpmCtx, Result{ + AuthID: authID, + Provider: "claude", + Model: modelA, + Success: false, + CredentialScope: false, + RetryAfter: &rpmDelay, + Error: &Error{Code: "rate_limit_error", Message: "rpm", HTTPStatus: http.StatusTooManyRequests}, + }) + + // 2. Model B triggers a shorter 1m credential-wide 5h quota cooldown. + credDelay := time.Minute + fiveHourCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(fiveHourCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"five_hour"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(credDelay).Unix(), 10)}, + }) + manager.MarkResult(fiveHourCtx, Result{ + AuthID: authID, + Provider: "claude", + Model: modelB, + Success: false, + CredentialScope: true, + RetryAfter: &credDelay, + Error: &Error{Code: ErrorCodeCredentialQuota, Message: "5h quota", HTTPStatus: http.StatusTooManyRequests}, + }) + + // 3. Expire the 1m credential-wide quota deterministically while Model A's 10m RPM block remains live. + past := time.Now().Add(-time.Second) + manager.mu.Lock() + curAuth := manager.auths[authID] + curAuth.Quota.NextRecoverAt = past + curAuth.NextRetryAfter = past + if sb := curAuth.ModelStates[modelB]; sb != nil { + sb.NextRetryAfter = past + sb.Quota.NextRecoverAt = past + } + snapshot := curAuth.Clone() + manager.mu.Unlock() + if manager.scheduler != nil { + manager.scheduler.upsertAuth(snapshot) + } + + // 4. Model A is still cooling down from its independent 10m RPM error and must not emit 5h unified headers. + _, errExecA := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelA}, cliproxyexecutor.Options{}) + var cdErrA *modelCooldownError + if !errors.As(errExecA, &cdErrA) { + t.Fatalf("%s modelA Execute() error = %T (%v), want *modelCooldownError", pathName, errExecA, errExecA) + } + for key := range cdErrA.Headers() { + if strings.HasPrefix(strings.ToLower(key), "anthropic-ratelimit-unified-") { + t.Fatalf("%s modelA leaked expired credential-quota header %s=%q", pathName, key, cdErrA.Headers().Get(key)) + } + } + }) + } + }) + + t.Run("matches longer independent model quota signals and deadline beneath shorter credential quota", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + pathName := "scheduler" + if useAffinity { + pathName = "session_affinity" + } + t.Run(pathName, func(t *testing.T) { + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + manager := NewManager(nil, selector, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + modelA := "issue-7417-dual-quota-a-" + pathName + modelB := "issue-7417-dual-quota-b-" + pathName + authID := "issue-7417-dual-quota-auth-" + pathName + registry.GetGlobalRegistry().RegisterClient(authID, "claude", []*registry.ModelInfo{{ID: modelA}, {ID: modelB}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: authID, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register auth: %v", errRegister) + } + + // 1. Model A enters a 2h independent model-scoped seven_day quota cooldown. + twoHours := 2 * time.Hour + sevenDayCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(sevenDayCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"seven_day"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(twoHours).Unix(), 10)}, + }) + manager.MarkResult(sevenDayCtx, Result{ + AuthID: authID, + Provider: "claude", + Model: modelA, + Success: false, + CredentialScope: false, + RetryAfter: &twoHours, + Error: &Error{Code: "rate_limit_error", Message: "7d model quota", HTTPStatus: http.StatusTooManyRequests}, + }) + + // 2. Model B triggers a shorter 1h credential-scoped five_hour quota cooldown. + oneHour := time.Hour + fiveHourCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(fiveHourCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"five_hour"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(oneHour).Unix(), 10)}, + }) + manager.MarkResult(fiveHourCtx, Result{ + AuthID: authID, + Provider: "claude", + Model: modelB, + Success: false, + CredentialScope: true, + RetryAfter: &oneHour, + Error: &Error{Code: ErrorCodeCredentialQuota, Message: "5h cred quota", HTTPStatus: http.StatusTooManyRequests}, + }) + + // Model A must report seven_day AND ~2h Retry-After / reset (not 1h). + _, errExecA := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelA}, cliproxyexecutor.Options{}) + var cdErrA *modelCooldownError + if !errors.As(errExecA, &cdErrA) { + t.Fatalf("%s modelA Execute() error = %T (%v), want *modelCooldownError", pathName, errExecA, errExecA) + } + hdrA := cdErrA.Headers() + if got := hdrA.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "seven_day" { + t.Fatalf("%s modelA claim = %q, want seven_day", pathName, got) + } + retrySecA, errSecA := strconv.ParseInt(hdrA.Get("Retry-After"), 10, 64) + if errSecA != nil || retrySecA < 7100 { + t.Fatalf("%s modelA Retry-After = %q, want ~7200s (>= 7100s) matching 2h independent deadline", pathName, hdrA.Get("Retry-After")) + } + + // Model B must report five_hour AND ~1h Retry-After. + _, errExecB := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelB}, cliproxyexecutor.Options{}) + var cdErrB *modelCooldownError + if !errors.As(errExecB, &cdErrB) { + t.Fatalf("%s modelB Execute() error = %T (%v), want *modelCooldownError", pathName, errExecB, errExecB) + } + hdrB := cdErrB.Headers() + if got := hdrB.Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "five_hour" { + t.Fatalf("%s modelB claim = %q, want five_hour", pathName, got) + } + retrySecB, errSecB := strconv.ParseInt(hdrB.Get("Retry-After"), 10, 64) + if errSecB != nil || retrySecB > 3660 || retrySecB < 3500 { + t.Fatalf("%s modelB Retry-After = %q, want ~3600s", pathName, hdrB.Get("Retry-After")) + } + }) + } + }) + + t.Run("keeps active cooldown signals when hintless RetryAfter nil 429 reuses existing deadline", func(t *testing.T) { + for _, useAffinity := range []bool{true, false} { + pathName := "scheduler" + if useAffinity { + pathName = "session_affinity" + } + t.Run(pathName, func(t *testing.T) { + var selector Selector + if useAffinity { + selector = NewSessionAffinitySelector(&RoundRobinSelector{}) + } + manager := NewManager(nil, selector, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: "claude"}) + + credModel := "issue-7417-nilhint-cred-" + pathName + credAuth := "issue-7417-nilhint-cred-auth-" + pathName + modelScopedModel := "issue-7417-nilhint-model-" + pathName + modelScopedAuth := "issue-7417-nilhint-model-auth-" + pathName + authOnlyModel := "issue-7417-nilhint-authonly-" + pathName + authOnlyID := "issue-7417-nilhint-authonly-auth-" + pathName + + registry.GetGlobalRegistry().RegisterClient(credAuth, "claude", []*registry.ModelInfo{{ID: credModel}}) + registry.GetGlobalRegistry().RegisterClient(modelScopedAuth, "claude", []*registry.ModelInfo{{ID: modelScopedModel}}) + registry.GetGlobalRegistry().RegisterClient(authOnlyID, "claude", []*registry.ModelInfo{{ID: authOnlyModel}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(credAuth) + registry.GetGlobalRegistry().UnregisterClient(modelScopedAuth) + registry.GetGlobalRegistry().UnregisterClient(authOnlyID) + }) + + for _, id := range []string{credAuth, modelScopedAuth, authOnlyID} { + if _, errRegister := manager.Register(context.Background(), &Auth{ + ID: id, + Provider: "claude", + Status: StatusActive, + }); errRegister != nil { + t.Fatalf("register %s: %v", id, errRegister) + } + } + + twoHours := 2 * time.Hour + sevenDayCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(sevenDayCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"seven_day"}, + "Anthropic-Ratelimit-Unified-Reset": {strconv.FormatInt(time.Now().Add(twoHours).Unix(), 10)}, + }) + fiveHourNoHintCtx := internallogging.WithResponseHeadersHolder(context.Background()) + internallogging.SetResponseHeaders(fiveHourNoHintCtx, http.Header{ + "Anthropic-Ratelimit-Unified-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-5h-Status": {"rejected"}, + "Anthropic-Ratelimit-Unified-7d-Status": {"allowed"}, + "Anthropic-Ratelimit-Unified-Representative-Claim": {"five_hour"}, + }) + + manager.MarkResult(sevenDayCtx, Result{ + AuthID: credAuth, + Provider: "claude", + Model: credModel, + Success: false, + CredentialScope: true, + RetryAfter: &twoHours, + Error: &Error{Code: ErrorCodeCredentialQuota, Message: "7d", HTTPStatus: http.StatusTooManyRequests}, + }) + manager.MarkResult(fiveHourNoHintCtx, Result{ + AuthID: credAuth, + Provider: "claude", + Model: credModel, + Success: false, + CredentialScope: true, + RetryAfter: nil, + Error: &Error{Code: ErrorCodeCredentialQuota, Message: "5h no hint", HTTPStatus: http.StatusTooManyRequests}, + }) + + manager.MarkResult(sevenDayCtx, Result{ + AuthID: modelScopedAuth, + Provider: "claude", + Model: modelScopedModel, + Success: false, + CredentialScope: false, + RetryAfter: &twoHours, + Error: &Error{Code: "rate_limit_error", Message: "7d", HTTPStatus: http.StatusTooManyRequests}, + }) + manager.MarkResult(fiveHourNoHintCtx, Result{ + AuthID: modelScopedAuth, + Provider: "claude", + Model: modelScopedModel, + Success: false, + CredentialScope: false, + RetryAfter: nil, + Error: &Error{Code: "rate_limit_error", Message: "5h no hint", HTTPStatus: http.StatusTooManyRequests}, + }) + + manager.MarkResult(sevenDayCtx, Result{ + AuthID: authOnlyID, + Provider: "claude", + Success: false, + RetryAfter: &twoHours, + Error: &Error{Code: "rate_limit_error", Message: "7d", HTTPStatus: http.StatusTooManyRequests}, + }) + manager.MarkResult(fiveHourNoHintCtx, Result{ + AuthID: authOnlyID, + Provider: "claude", + Success: false, + RetryAfter: nil, + Error: &Error{Code: "rate_limit_error", Message: "5h no hint", HTTPStatus: http.StatusTooManyRequests}, + }) + + for _, m := range []string{credModel, modelScopedModel, authOnlyModel} { + _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: m}, cliproxyexecutor.Options{}) + var cdErr *modelCooldownError + if !errors.As(errExec, &cdErr) { + t.Fatalf("%s Execute() error = %T (%v), want *modelCooldownError", m, errExec, errExec) + } + if got := cdErr.Headers().Get("Anthropic-Ratelimit-Unified-Representative-Claim"); got != "seven_day" { + t.Fatalf("%s Representative-Claim = %q, want seven_day", m, got) + } + } + }) + } + }) +} diff --git a/sdk/cliproxy/auth/conductor_stream.go b/sdk/cliproxy/auth/conductor_stream.go index 47f87de43f9..5b310acb406 100644 --- a/sdk/cliproxy/auth/conductor_stream.go +++ b/sdk/cliproxy/auth/conductor_stream.go @@ -137,7 +137,7 @@ func (m *Manager) recordCanceledUpstreamCooldown(ctx context.Context, auth *Auth if m == nil || auth == nil || retryAfter == nil { return } - action, okAction := matchRequestScopedErrorAction(auth, err, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(auth, err, m.requestScopedErrorConfig(ctx)) result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(err), Options: opts, RetryAfter: retryAfter, AccessToken: authAccessTokenForRequest(ctx, auth, opts.Headers), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch, ExecutionSeq: executionSeq} result.CredentialScope = isCredentialScopedError(err) applyRequestScopedActionToResult(action, okAction, &result) @@ -165,7 +165,7 @@ func (m *Manager) wrapStreamResult(ctx context.Context, auth *Auth, provider, re entry := logEntryWithRequestID(ctx) warnLogUpstreamFailure(ctx, entry, provider, resultModel, auth, time.Since(streamStart), chunk.Err) rerr := resultErrorFromError(chunk.Err) - action, okAction := matchRequestScopedErrorAction(auth, chunk.Err, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(auth, chunk.Err, m.requestScopedErrorConfig(ctx)) result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: opts, AccessToken: accessToken, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch, ExecutionSeq: executionSeq} result.RetryAfter = retryAfterFromError(chunk.Err) result.CredentialScope = isCredentialScopedError(chunk.Err) @@ -346,7 +346,7 @@ func jsonObjectCompletionFlags(rawJSON []byte) (completed, incomplete bool) { continue } switch strings.ToUpper(strings.TrimSpace(fr)) { - case "MAX_TOKENS", "SAFETY", "RECITATION", "OTHER": + case "MAX_TOKENS", "SAFETY", "RECITATION", "OTHER", "MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "MALFORMED_RESPONSE": incomplete = true case "STOP": completed = true @@ -412,7 +412,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi var upstreamErr error didRefreshOnUnauthorized := false for idx, execModel := range execModels { - ctx = newUpstreamAttemptContext(ctx) + ctx = m.newUpstreamAttemptContext(ctx) resultModel := m.stateModelForExecution(auth, routeModel, execModel, pooled) execReq := req execReq.Model = execModel @@ -456,7 +456,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi auth = refreshed publishSelectedAuthMetadata(execOpts.Metadata, auth) didRefreshOnUnauthorized = true - ctx = newUpstreamAttemptContext(ctx) + ctx = m.newUpstreamAttemptContext(ctx) ctx = syncMetadataSessionToContext(ctx, execOpts.Metadata) executionSeq = m.nextExecutionSeq() startRetry := time.Now() @@ -489,7 +489,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi errStream = markUpstreamExecutionAttemptFromContext(ctx, errStream) if errStream != nil { rerr := resultErrorFromError(errStream) - action, okAction := matchRequestScopedErrorAction(auth, errStream, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(auth, errStream, m.requestScopedErrorConfig(ctx)) result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch, ExecutionSeq: executionSeq} result.RetryAfter = retryAfterFromError(errStream) if isCredentialScopedError(errStream) { @@ -538,7 +538,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi auth = refreshed publishSelectedAuthMetadata(execOpts.Metadata, auth) didRefreshOnUnauthorized = true - ctx = newUpstreamAttemptContext(ctx) + ctx = m.newUpstreamAttemptContext(ctx) executionSeq = m.nextExecutionSeq() startRetry := time.Now() retryStream, retryErr := executor.ExecuteStream(ctx, auth, execReq, execOpts) @@ -578,7 +578,7 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi } } if bootstrapErr != nil { - action, okAction := matchRequestScopedErrorAction(auth, bootstrapErr, m.runtimeConfigSnapshot()) + action, okAction := matchRequestScopedErrorAction(auth, bootstrapErr, m.requestScopedErrorConfig(ctx)) if okAction { rerr := resultErrorFromError(bootstrapErr) result := Result{AuthID: auth.ID, Provider: provider, Model: resultModel, RouteModel: routeModel, Success: false, Error: rerr, Options: execOpts, CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch, ExecutionSeq: executionSeq} diff --git a/sdk/cliproxy/auth/conductor_tos_violation_test.go b/sdk/cliproxy/auth/conductor_tos_violation_test.go new file mode 100644 index 00000000000..7ab5e4ab7a3 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_tos_violation_test.go @@ -0,0 +1,223 @@ +package auth + +import ( + "context" + "net/http" + "testing" +) + +// TestMarkResult_TOSViolation_DisablesCredential verifies that a 403 +// PERMISSION_DENIED carrying the tos_violation error code (produced by the +// Antigravity executor on the verbatim issue #7515 signature) deactivates the +// credential instead of applying the generic 30-minute 403 cooldown, while a +// non-TOS 403 keeps the existing cooldown behavior. +func TestMarkResult_TOSViolation_DisablesCredential(t *testing.T) { + manager := NewManager(nil, nil, nil) + ctx := context.Background() + + auth := &Auth{ID: "tos-cred", Provider: "antigravity", Status: StatusActive} + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatalf("register auth: %v", err) + } + + // The executor carries the appeal detail on the result error via + // Error.Metadata; the conductor persists it onto the credential record. + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, + Provider: "antigravity", + Model: "gemini-3-pro", + Success: false, + CredentialScope: true, + Error: &Error{ + HTTPStatus: http.StatusForbidden, + Code: "tos_violation", + Message: "TOS_VIOLATION", + Metadata: map[string]string{"tos_appeal_url": "https://forms.gle/hGzM9MEUv2azZsrb9", "tos_appeal_url_text": "Submit Appeal"}, + }, + }) + + updated, ok := manager.GetByID(auth.ID) + if !ok || updated == nil { + t.Fatal("auth not found after MarkResult") + } + if updated.Status != StatusDisabled { + t.Fatalf("auth.Status = %q, want %q (terminal TOS suspension must deactivate)", updated.Status, StatusDisabled) + } + if !updated.Disabled { + t.Fatal("auth.Disabled = false, want true (terminal state must persist via the file store)") + } + if !updated.Unavailable { + t.Fatal("auth.Unavailable = false, want true") + } + if updated.StatusMessage != "tos_violation" { + t.Fatalf("auth.StatusMessage = %q, want %q", updated.StatusMessage, "tos_violation") + } + if !updated.NextRetryAfter.IsZero() { + t.Fatalf("auth.NextRetryAfter = %v, want zero (terminal, not a timed cooldown)", updated.NextRetryAfter) + } + if appeal, _ := updated.Metadata["tos_appeal_url"].(string); appeal != "https://forms.gle/hGzM9MEUv2azZsrb9" { + t.Fatalf("auth.Metadata[tos_appeal_url] = %q, want appeal URL preserved", appeal) + } +} + +// TestMarkResult_NonTOS403_StillCools confirms the generic 403 path is +// unchanged: a plain PERMISSION_DENIED without the tos_violation code must +// continue to apply the 30-minute cooldown rather than deactivating. +func TestMarkResult_NonTOS403_StillCools(t *testing.T) { + manager := NewManager(nil, nil, nil) + ctx := context.Background() + + auth := &Auth{ID: "plain-403", Provider: "antigravity", Status: StatusActive} + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatalf("register auth: %v", err) + } + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, + Provider: "antigravity", + Model: "gemini-3-pro", + Success: false, + Error: &Error{HTTPStatus: http.StatusForbidden, Message: "permission denied"}, + }) + + updated, _ := manager.GetByID(auth.ID) + if updated.Status == StatusDisabled { + t.Fatal("plain 403 must not deactivate the credential") + } + if updated.NextRetryAfter.IsZero() { + t.Fatal("plain 403 must keep the 30-minute cooldown") + } +} + +// TestMarkResult_TOSViolation_LateResultDoesNotRevive verifies that a +// success or ordinary failure recorded after the TOS suspension does not bring +// the disabled credential back into rotation. +func TestMarkResult_TOSViolation_LateResultDoesNotRevive(t *testing.T) { + manager := NewManager(nil, nil, nil) + ctx := context.Background() + auth := &Auth{ID: "tos-late", Provider: "antigravity", Status: StatusActive} + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatalf("register auth: %v", err) + } + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, Provider: "antigravity", Model: "gemini-3-pro", + Success: false, CredentialScope: true, + Error: &Error{HTTPStatus: http.StatusForbidden, Code: "tos_violation"}, + }) + // A stale success arriving after the suspension must not reactivate it. + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, Provider: "antigravity", Model: "gemini-3-pro", Success: true, + }) + updated, _ := manager.GetByID(auth.ID) + if updated.Status != StatusDisabled || !updated.Disabled { + t.Fatalf("late success revived credential: status=%q disabled=%v", updated.Status, updated.Disabled) + } +} + +// TestMarkResult_TOSViolation_LateAuthLevelFailure verifies that an auth-level +// (model-less) failure arriving after the TOS suspension cannot overwrite the +// terminal state or arm a new cooldown. +func TestMarkResult_TOSViolation_LateAuthLevelFailure(t *testing.T) { + manager := NewManager(nil, nil, nil) + ctx := context.Background() + auth := &Auth{ID: "tos-late-auth", Provider: "antigravity", Status: StatusActive} + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatalf("register auth: %v", err) + } + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, Provider: "antigravity", Success: false, CredentialScope: true, + Error: &Error{HTTPStatus: http.StatusForbidden, Code: "tos_violation"}, + }) + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, Provider: "antigravity", Success: false, + Error: &Error{HTTPStatus: http.StatusForbidden, Message: "plain 403"}, + }) + updated, _ := manager.GetByID(auth.ID) + if updated.Status != StatusDisabled || !updated.Disabled { + t.Fatalf("late auth-level failure overwrote terminal state: status=%q disabled=%v", updated.Status, updated.Disabled) + } + if updated.StatusMessage != "tos_violation" { + t.Fatalf("StatusMessage = %q, want tos_violation preserved", updated.StatusMessage) + } +} + +// TestMarkResult_TOSViolation_NotDroppedByCredentialVersionBumps verifies that +// a TOS result dispatched before an OAuth token refresh is not discarded as +// stale when the refresh bumps CredentialVersion first. The suspension is +// service-scoped and applies to the account, not the token generation. +func TestMarkResult_TOSViolation_NotDroppedByCredentialVersionBumps(t *testing.T) { + manager := NewManager(nil, nil, nil) + ctx := context.Background() + auth := &Auth{ID: "tos-stale", Provider: "antigravity", Status: StatusActive, CredentialVersion: 2} + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatalf("register auth: %v", err) + } + // A result recorded under credential version 1 (i.e. dispatched before a + // refresh) still carries a valid terminal TOS signal. + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, Provider: "antigravity", Success: false, CredentialScope: true, + CredentialVersion: 1, + Error: &Error{HTTPStatus: http.StatusForbidden, Code: "tos_violation", Metadata: map[string]string{"tos_appeal_url": "https://forms.gle/x"}}, + }) + updated, _ := manager.GetByID(auth.ID) + if updated.Status != StatusDisabled || !updated.Disabled { + t.Fatalf("TOS result dropped as stale after version bump: status=%q disabled=%v", updated.Status, updated.Disabled) + } + if got := updated.Metadata["tos_appeal_url"]; got != "https://forms.gle/x" { + t.Fatalf("appeal metadata lost on stale-guarded path: %v", got) + } +} + +// TestMarkResult_TOSViolation_RejectedAfterCredentialReplacement verifies that +// a TOS result from a request issued under a previous credential is dropped as +// stale after the credential is genuinely replaced (refresh token swapped), +// rather than disabling the fresh credential. +func TestMarkResult_TOSViolation_RejectedAfterCredentialReplacement(t *testing.T) { + manager := NewManager(nil, nil, nil) + ctx := context.Background() + auth := &Auth{ + ID: "tos-replaced", Provider: "antigravity", Status: StatusActive, CredentialVersion: 2, + Metadata: map[string]any{"access_token": "new-access", "refresh_token": "new-refresh"}, + } + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatalf("register auth: %v", err) + } + // Result dispatched under the OLD credential: old access token, old refresh + // token, older credential version. Refresh token differs -> different account. + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, Provider: "antigravity", Success: false, CredentialScope: true, + AccessToken: "old-access", RefreshToken: "old-refresh", CredentialVersion: 1, + Error: &Error{HTTPStatus: http.StatusForbidden, Code: "tos_violation"}, + }) + updated, _ := manager.GetByID(auth.ID) + if updated.Status == StatusDisabled || updated.Disabled { + t.Fatalf("stale TOS result disabled fresh credential: status=%q disabled=%v", updated.Status, updated.Disabled) + } +} + +// TestMarkResult_TOSViolation_SameAccountRefreshApplies verifies that a TOS +// result issued before a same-account OAuth refresh (access token rotated, +// refresh token retained) is NOT dropped as stale: the refresh token proves it +// is the same account, so the terminal state is applied. +func TestMarkResult_TOSViolation_SameAccountRefreshApplies(t *testing.T) { + manager := NewManager(nil, nil, nil) + ctx := context.Background() + // Current credential after a same-account refresh: new access token, SAME + // refresh token, bumped credential version. + auth := &Auth{ + ID: "tos-same-acct", Provider: "antigravity", Status: StatusActive, CredentialVersion: 2, + Metadata: map[string]any{"access_token": "new-access", "refresh_token": "same-refresh"}, + } + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatalf("register auth: %v", err) + } + // Old request: old access token (no longer matches), same refresh token. + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, Provider: "antigravity", Success: false, CredentialScope: true, + AccessToken: "old-access", RefreshToken: "same-refresh", CredentialVersion: 1, + Error: &Error{HTTPStatus: http.StatusForbidden, Code: "tos_violation"}, + }) + updated, _ := manager.GetByID(auth.ID) + if updated.Status != StatusDisabled || !updated.Disabled { + t.Fatalf("same-account TOS result dropped after refresh: status=%q disabled=%v", updated.Status, updated.Disabled) + } +} diff --git a/sdk/cliproxy/auth/conductor_weighted_pinned_routing_test.go b/sdk/cliproxy/auth/conductor_weighted_pinned_routing_test.go new file mode 100644 index 00000000000..4406b509c1d --- /dev/null +++ b/sdk/cliproxy/auth/conductor_weighted_pinned_routing_test.go @@ -0,0 +1,121 @@ +package auth + +import ( + "context" + "fmt" + "maps" + "net/http" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +func TestManagerWeightedPinsShareCreditsWithoutAffinity(t *testing.T) { + for _, scenario := range []string{"single", "mixed-single", "mixed-providers", "lower-priority", "websocket", "http-pin", "mixed-single-websocket", "xai-websocket", "mixed-single-xai"} { + t.Run(scenario, func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + manager := NewManager(nil, weighted, nil) + const model = "weighted-pin-routing" + providers := []string{"codex"} + if scenario == "xai-websocket" || scenario == "mixed-single-xai" { + providers[0] = "xai" + } + mixed := scenario == "mixed-single" || scenario == "mixed-providers" || scenario == "mixed-single-websocket" || scenario == "mixed-single-xai" + if scenario == "mixed-providers" { + providers = append(providers, "openai") + } + for _, provider := range providers { + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + } + a := &Auth{ID: t.Name() + "-a", Provider: providers[0], Attributes: map[string]string{AttributeWeight: "3"}} + b := &Auth{ID: t.Name() + "-b", Provider: providers[len(providers)-1], Attributes: map[string]string{AttributeWeight: "1"}} + auths := []*Auth{a, b} + // A zero-weight higher tier must not hide eligible positive-weight peers. + auths = append(auths, &Auth{ID: t.Name() + "-zero", Provider: providers[0], Attributes: map[string]string{AttributeWeight: "0", "priority": "100"}}) + if scenario == "lower-priority" { + auths = append(auths, &Auth{ID: t.Name() + "-higher", Provider: providers[0], Attributes: map[string]string{"priority": "1"}}) + } + ctx := t.Context() + if scenario == "websocket" || scenario == "http-pin" || scenario == "mixed-single-websocket" || scenario == "xai-websocket" || scenario == "mixed-single-xai" { + ctx = cliproxyexecutor.WithDownstreamWebsocket(ctx) + a.Attributes["websockets"] = "true" + b.Attributes["websockets"] = "true" + otherWebsocket := "false" + if scenario == "http-pin" { + a.Attributes["websockets"] = "false" + b.Attributes["websockets"] = "false" + otherWebsocket = "true" + } + auths = append(auths, &Auth{ID: t.Name() + "-other-transport", Provider: providers[0], Attributes: map[string]string{"websockets": otherWebsocket}}) + } + for _, auth := range auths { + auth.Status = StatusActive + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + if _, errRegister := manager.Register(WithSkipPersist(ctx), auth); errRegister != nil { + t.Fatal(errRegister) + } + } + // Normalize single/mixed entrypoints while retaining their real routing decisions. + pick := func(ctx context.Context, opts cliproxyexecutor.Options) *Auth { + t.Helper() + var auth *Auth + var errPick error + if mixed { + auth, _, _, errPick = manager.pickNextMixed(ctx, append([]string{"missing-executor"}, providers...), model, opts, nil) + } else { + auth, _, errPick = manager.pickNext(ctx, providers[0], model, opts, nil) + } + if errPick != nil || auth == nil { + t.Fatalf("selection failed: auth=%v err=%v", auth, errPick) + } + return auth + } + for range 4 { + if auth := pick(ctx, cliproxyexecutor.Options{Metadata: map[string]any{cliproxyexecutor.PinnedAuthMetadataKey: b.ID}}); auth.ID != b.ID { + t.Fatalf("pin escaped: got %q, want %q", auth.ID, b.ID) + } + } + namespace := providers[0] + if mixed { + namespace = "mixed" + } + state := weightedStateForTest(t, weighted, namespace+":"+model, a.ID, b.ID) + if !maps.Equal(state.currentForTest(), map[string]int64{a.ID: 12, b.ID: -12}) || state.inFlight != 0 { + t.Fatalf("wrong pin accounting: current=%v inFlight=%d", state.currentForTest(), state.inFlight) + } + if scenario == "lower-priority" || scenario == "http-pin" { + // Traffic in a different priority/transport pool must not repay this pool. + for range 4 { + pick(ctx, cliproxyexecutor.Options{}) + } + if !maps.Equal(state.currentForTest(), map[string]int64{a.ID: 12, b.ID: -12}) { + t.Fatalf("unrelated pool consumed pin debt: %v", state.currentForTest()) + } + if scenario == "lower-priority" { + manager.Remove(WithSkipPersist(ctx), t.Name()+"-higher") + } else { + manager.Remove(WithSkipPersist(ctx), t.Name()+"-other-transport") + } + } + for i := range 12 { + // Headers must not enable sticky bindings when affinity is disabled. + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {fmt.Sprintf("fresh-%d", i)}}} + if auth := pick(ctx, opts); auth.ID != a.ID { + t.Fatalf("request %d failed to repay pinned debt: got %q, want %q", i, auth.ID, a.ID) + } + } + if !maps.Equal(state.currentForTest(), map[string]int64{a.ID: 0, b.ID: 0}) || len(state.pendingForTest()) != 0 || state.inFlight != 0 { + t.Fatalf("unsettled compensation: current=%v pending=%v inFlight=%d", state.currentForTest(), state.pendingForTest(), state.inFlight) + } + counts := map[string]int{} + for range 40 { + counts[pick(ctx, cliproxyexecutor.Options{}).ID]++ + } + if counts[a.ID] != 30 || counts[b.ID] != 10 { + t.Fatalf("ordinary routing lost 3:1 ratio after repayment: %v", counts) + } + }) + } +} diff --git a/sdk/cliproxy/auth/conductor_weighted_pinned_test.go b/sdk/cliproxy/auth/conductor_weighted_pinned_test.go new file mode 100644 index 00000000000..c3a213872cc --- /dev/null +++ b/sdk/cliproxy/auth/conductor_weighted_pinned_test.go @@ -0,0 +1,172 @@ +package auth + +import ( + "fmt" + "maps" + "net/http" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestManagerWeightedPinnedSessionCompensation(t *testing.T) { + for _, mixed := range []bool{false, true} { + for _, mode := range []string{"sticky", "cold", "no-session", "lcp", "no-affinity", "no-affinity-legacy"} { + t.Run(fmt.Sprintf("mixed=%t/%s", mixed, mode), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + manager := NewManager(nil, selector, nil) + if mode == "no-affinity" || mode == "no-affinity-legacy" { + manager.SetSelector(weighted) + } + const provider, model = "weighted-pinned", "weighted-pinned-model" + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + ctx := withRequiredAuthKind(t.Context(), AuthKindAPIKey) + aID, bID := t.Name()+"-a", t.Name()+"-b" + triedID := t.Name() + "-tried" + excluded := []*Auth{ + {ID: t.Name() + "-disabled", Disabled: true}, + {ID: t.Name() + "-zero", Attributes: map[string]string{AttributeWeight: "0"}}, + {ID: t.Name() + "-cooldown", ModelStates: map[string]*ModelState{ + model: {Unavailable: true, NextRetryAfter: time.Now().Add(time.Hour)}, + }}, + {ID: t.Name() + "-wrong-model"}, + {ID: t.Name() + "-wrong-kind", Attributes: map[string]string{AttributeAuthKind: AuthKindOAuth}}, + {ID: t.Name() + "-wrong-provider", Provider: "other-provider"}, + {ID: t.Name() + "-no-executor", Provider: "no-executor"}, + {ID: t.Name() + "-lower-priority", Attributes: map[string]string{"priority": "0"}}, + {ID: triedID}, + } + auths := append([]*Auth{ + {ID: aID, Attributes: map[string]string{AttributeWeight: "3", "priority": "1"}}, + {ID: bID, Attributes: map[string]string{AttributeWeight: "1", "priority": "1"}}, + }, excluded...) + for _, auth := range auths { + if auth.Provider == "" { + auth.Provider = provider + } + auth.Status = StatusActive + if auth.Attributes == nil { + auth.Attributes = make(map[string]string) + } + if _, ok := auth.Attributes[AttributeWeight]; !ok { + auth.Attributes[AttributeWeight] = "100" + } + if _, ok := auth.Attributes["priority"]; !ok { + auth.Attributes["priority"] = "2" + } + if _, ok := auth.Attributes[AttributeAuthKind]; !ok { + auth.Attributes[AttributeAuthKind] = AuthKindAPIKey + } + registeredModel := model + if auth.ID == t.Name()+"-wrong-model" { + registeredModel = "other-model" + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: registeredModel}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + if _, errRegister := manager.Register(WithSkipPersist(ctx), auth); errRegister != nil { + t.Fatal(errRegister) + } + } + namespace := provider + if mixed { + namespace = "mixed" + } + stickyHeaders := http.Header{"Session_id": {"pinned-session"}} + id := CanonicalSessionID(stickyHeaders, nil, nil) + bindingKey := namespace + "::" + id + "::" + model + if mode == "sticky" { + selector.cache.Set(bindingKey, bID) + } + tried := map[string]struct{}{triedID: {}} + // Exercise the production entrypoints as well as direct legacy selection. + pick := func(opts cliproxyexecutor.Options) (*Auth, error) { + if mode == "no-affinity" { + if mixed { + auth, _, _, errPick := manager.pickNextMixed(ctx, []string{provider, "no-executor"}, model, opts, tried) + return auth, errPick + } + auth, _, errPick := manager.pickNext(ctx, provider, model, opts, tried) + return auth, errPick + } + if mixed { + auth, _, _, errPick := manager.pickNextMixedLegacy(ctx, []string{provider, "no-executor"}, model, opts, tried) + return auth, errPick + } + auth, _, errPick := manager.pickNextLegacy(ctx, provider, model, opts, tried) + return auth, errPick + } + for i := range 4 { + opts := cliproxyexecutor.Options{Metadata: map[string]any{cliproxyexecutor.PinnedAuthMetadataKey: bID}} + switch mode { + case "sticky", "cold": + opts.Headers = stickyHeaders + case "lcp": + opts.SourceFormat = sdktranslator.FormatOpenAI + opts.OriginalRequest = []byte(`{"messages":[{"role":"user","content":"pinned conversation"}]}`) + opts.Metadata[cliproxyexecutor.CallerScopeMetadataKey] = "pinned-caller" + } + if auth, errPick := pick(opts); errPick != nil || auth == nil || auth.ID != bID { + t.Fatalf("pinned request %d: auth=%v err=%v, want %q", i, auth, errPick, bID) + } + } + state := weightedStateForTest(t, weighted, namespace+":"+model, aID, bID) + if state == nil || !maps.Equal(state.currentForTest(), map[string]int64{aID: 12, bID: -12}) || len(state.pendingForTest()) != 0 { + t.Fatalf("pinned traffic did not consume the eligible pool's credit: %#v", state) + } + counts := map[string]int{} + for i := range 12 { + auth, errPick := pick(cliproxyexecutor.Options{Headers: http.Header{"Session_id": {fmt.Sprintf("fresh-%d", i)}}}) + if errPick != nil || auth == nil { + t.Fatalf("fresh request %d: auth=%v err=%v", i, auth, errPick) + } + counts[auth.ID]++ + } + if counts[aID] != 12 || counts[bID] != 0 { + t.Fatalf("fresh distribution = %v, want a=12 b=0", counts) + } + if !maps.Equal(state.currentForTest(), map[string]int64{aID: 0, bID: 0}) || len(state.pendingForTest()) != 0 { + t.Fatalf("compensation did not balance: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } + if mode == "sticky" || mode == "cold" { + if binding, ok := selector.cache.Get(bindingKey); !ok || binding != bID { + t.Fatalf("compensation changed pinned binding: %q, found=%t", binding, ok) + } + } + // A broader accounting pool must never make an invalid pin selectable. + for _, pinnedID := range []string{excluded[0].ID, excluded[1].ID, excluded[2].ID, excluded[3].ID, excluded[4].ID, excluded[5].ID, excluded[6].ID, triedID, "missing"} { + opts := cliproxyexecutor.Options{ + Headers: stickyHeaders, + Metadata: map[string]any{cliproxyexecutor.PinnedAuthMetadataKey: pinnedID}, + } + if auth, errPick := pick(opts); errPick == nil || auth != nil { + t.Fatalf("invalid pin %q escaped pinning checks: auth=%v err=%v", pinnedID, auth, errPick) + } + if !maps.Equal(state.currentForTest(), map[string]int64{aID: 0, bID: 0}) || len(state.pendingForTest()) != 0 { + t.Fatalf("invalid pin %q changed accounting: current=%v pending=%v", pinnedID, state.currentForTest(), state.pendingForTest()) + } + } + // A valid lower-priority pin still wins without charging another tier. + lowerID := t.Name() + "-lower-priority" + lowerOpts := cliproxyexecutor.Options{ + Headers: http.Header{"Session_id": {"lower-pinned-session"}}, + Metadata: map[string]any{cliproxyexecutor.PinnedAuthMetadataKey: lowerID}, + } + if auth, errPick := pick(lowerOpts); errPick != nil || auth == nil || auth.ID != lowerID { + t.Fatalf("lower-priority pin was not enforced: auth=%v err=%v", auth, errPick) + } + if !maps.Equal(state.currentForTest(), map[string]int64{aID: 0, bID: 0}) || len(state.pendingForTest()) != 0 { + t.Fatalf("lower-priority pin changed higher-tier credits: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } + lowerState := weightedStateForTest(t, weighted, namespace+":"+model, lowerID) + if !maps.Equal(lowerState.currentForTest(), map[string]int64{lowerID: 0}) || len(lowerState.pendingForTest()) != 0 { + t.Fatalf("lower-priority pin accounted the wrong pool: %#v", lowerState) + } + }) + } + } +} diff --git a/sdk/cliproxy/auth/cooldown_state.go b/sdk/cliproxy/auth/cooldown_state.go index 28c9c91f048..6609508d8d9 100644 --- a/sdk/cliproxy/auth/cooldown_state.go +++ b/sdk/cliproxy/auth/cooldown_state.go @@ -34,6 +34,27 @@ type CooldownStateRecord struct { // CredentialQuotaPropagated preserves wrap provenance for models that // carry no independent layer (e.g. the reporting model itself). CredentialQuotaPropagated bool `json:"credential_quota_propagated,omitempty"` + // CooldownSignals persists bounded rejected quota headers captured when + // this cooldown was recorded without touching passive Quota.Signals watermarks. + CooldownSignals map[string]string `json:"cooldown_signals,omitempty"` + // IndependentCooldownSignals persists CooldownSignals for IndependentState. + IndependentCooldownSignals map[string]string `json:"independent_cooldown_signals,omitempty"` + // ForceCooldownUntil persists the exact outer ErrorCodeForceCooldown deadline + // (credQuotaForceUntil for wrapped model records, model/auth forceCooldownUntil otherwise), + // preventing longer ordinary extensions or sibling shadows from inflating it on restore. + ForceCooldownUntil time.Time `json:"force_cooldown_until,omitempty"` + // CredQuotaForceCooldownUntil persists auth-level credential_quota force provenance + // independently from model-less auth ForceCooldownUntil when both coexist on an auth. + CredQuotaForceCooldownUntil time.Time `json:"cred_quota_force_cooldown_until,omitempty"` + // IndependentForceCooldownUntil persists the exact ErrorCodeForceCooldown deadline + // for IndependentState beneath a credential_quota wrap. + IndependentForceCooldownUntil time.Time `json:"independent_force_cooldown_until,omitempty"` + // ForceCooldownEvaluated marks records produced by provenance-aware versions so + // a zero ForceCooldownUntil means "explicitly ordinary" rather than legacy unknown. + ForceCooldownEvaluated bool `json:"force_cooldown_evaluated,omitempty"` + // CredentialRetryAfter persists a non-429 credential-wide retry deadline so + // restart recovery blocks all models even when ModelStates also exist. + CredentialRetryAfter time.Time `json:"credential_retry_after,omitempty"` } // CooldownStateStore persists runtime cooldown state independently from auth tokens. diff --git a/sdk/cliproxy/auth/cooldown_view.go b/sdk/cliproxy/auth/cooldown_view.go index 48324fe0493..9ad5fc2968a 100644 --- a/sdk/cliproxy/auth/cooldown_view.go +++ b/sdk/cliproxy/auth/cooldown_view.go @@ -51,31 +51,38 @@ func CooldownSnapshotForAuth(auth *Auth, now time.Time) []CooldownView { for _, key := range keys { state := auth.ModelStates[key] model := canonicalModelKey(key) - if state == nil || model == "" { + lookupKey := canonicalModelLookupKey(model) + if state == nil || model == "" || lookupKey == "" { continue } blocked, reason, next := availabilityBlock(state.Unavailable, state.Quota.Exceeded, state.NextRetryAfter, state.Quota.NextRecoverAt, now) if !blocked || !next.After(now) { continue } - if previous, ok := byModel[model]; ok { + modelName := model + if previous, ok := byModel[lookupKey]; ok { + if previous.view.ModelKey != "" { + modelName = previous.view.ModelKey + } preferQuotaTie := next.Equal(previous.view.RetryAt) && reason == blockReasonCooldown && previous.reason != blockReasonCooldown if !next.After(previous.view.RetryAt) && !preferQuotaTie { continue } } - byModel[model] = modelCooldown{ - view: newCooldownView("model", model, next, now, state.Quota, state.StatusMessage, state.LastError), + byModel[lookupKey] = modelCooldown{ + view: newCooldownView("model", modelName, next, now, state.Quota, state.StatusMessage, state.LastError), reason: reason, } } models := make([]string, 0, len(byModel)) - for model := range byModel { - models = append(models, model) - } - sort.Strings(models) - for _, model := range models { - views = append(views, byModel[model].view) + for lookupKey := range byModel { + models = append(models, lookupKey) + } + sort.Slice(models, func(i, j int) bool { + return byModel[models[i]].view.ModelKey < byModel[models[j]].view.ModelKey + }) + for _, lookupKey := range models { + views = append(views, byModel[lookupKey].view) } return views } diff --git a/sdk/cliproxy/auth/error_events.go b/sdk/cliproxy/auth/error_events.go index aa85220c0fe..5f18053b322 100644 --- a/sdk/cliproxy/auth/error_events.go +++ b/sdk/cliproxy/auth/error_events.go @@ -104,7 +104,7 @@ func errorEventModelStatusFrom(model string, authSnapshot *Auth) *errorEventMode if model == "" || authSnapshot == nil || authSnapshot.ModelStates == nil { return nil } - state := authSnapshot.ModelStates[model] + state := existingModelState(authSnapshot, model) if state == nil { return nil } diff --git a/sdk/cliproxy/auth/errors.go b/sdk/cliproxy/auth/errors.go index b54e14b78b2..d2798b5e3a1 100644 --- a/sdk/cliproxy/auth/errors.go +++ b/sdk/cliproxy/auth/errors.go @@ -47,6 +47,12 @@ const ErrorCodeTransientRateLimit = "transient_rate_limit" const transientRateLimitErrorCode = ErrorCodeTransientRateLimit +// ErrorCodeCredentialQuota marks a rate-limit/quota refusal that applies to the +// entire credential across all models rather than only the reporting model. +const ErrorCodeCredentialQuota = "credential_quota" + +const credentialQuotaErrorCode = ErrorCodeCredentialQuota + // Error describes an authentication related failure in a provider agnostic format. type Error struct { // Code is a short machine readable identifier. @@ -57,6 +63,26 @@ type Error struct { Retryable bool `json:"retryable"` // HTTPStatus optionally records an HTTP-like status code for the error. HTTPStatus int `json:"http_status,omitempty"` + // Metadata carries optional provider-specific detail extracted from the + // upstream failure (for example an Antigravity TOS appeal URL) so the + // conductor can persist it on the credential record for operator tooling. + Metadata map[string]string `json:"metadata,omitempty"` +} + +// Clone returns an independent copy of the error, deep-copying the Metadata +// map so snapshots cannot share mutable state with the original. +func (e *Error) Clone() *Error { + if e == nil { + return nil + } + out := *e + if e.Metadata != nil { + out.Metadata = make(map[string]string, len(e.Metadata)) + for key, value := range e.Metadata { + out.Metadata[key] = value + } + } + return &out } // IsTerminalAuthError checks if err or any error in its chain represents a permanent upstream auth failure. @@ -352,6 +378,87 @@ func (e *authUnavailableError) Headers() http.Header { return safeRetryAfterHeader(e.retryAfter) } +// poolCooldownTerminalError wraps a terminal upstream 429 when every eligible +// candidate credential for the requested model is blocked and at least one is +// in a timed cooldown. It keeps the upstream error text, body, status, and +// passthrough headers while marking the error as a model cooldown and exposing +// the pool's earliest recovery deadline via Retry-After. +type poolCooldownTerminalError struct { + cause error + deadline time.Time +} + +func (e *poolCooldownTerminalError) Error() string { + if e == nil || e.cause == nil { + return "" + } + return e.cause.Error() +} + +func (e *poolCooldownTerminalError) Unwrap() error { + if e == nil { + return nil + } + return e.cause +} + +func (e *poolCooldownTerminalError) As(target any) bool { + if e == nil { + return false + } + if t, ok := target.(**Error); ok { + var base *Error + if errors.As(e.cause, &base) && base != nil { + *t = base + return true + } + } + return false +} + +func (e *poolCooldownTerminalError) IsModelCooldown() bool { + return e != nil && !e.deadline.IsZero() +} + +func (e *poolCooldownTerminalError) StatusCode() int { + if e == nil { + return 0 + } + return statusCodeFromError(e.cause) +} + +func (e *poolCooldownTerminalError) RetryAfter() *time.Duration { + if e == nil || e.deadline.IsZero() { + return nil + } + remaining := time.Until(e.deadline) + if remaining <= 0 { + return nil + } + return &remaining +} + +func (e *poolCooldownTerminalError) SafeResponseHeaders() http.Header { + if e == nil || e.deadline.IsZero() { + return nil + } + return safeRetryAfterHeader(time.Until(e.deadline)) +} + +func (e *poolCooldownTerminalError) Headers() http.Header { + if e == nil || e.cause == nil { + return nil + } + for cur := e.cause; cur != nil; cur = errors.Unwrap(cur) { + if carrier, ok := cur.(interface{ Headers() http.Header }); ok && carrier != nil { + if hdr := carrier.Headers(); len(hdr) > 0 { + return hdr + } + } + } + return nil +} + // trustedRetryAfterError annotates a terminal upstream rejection whose // locally recorded cooldown deadline governs the client-visible Retry-After. // The wrapped error keeps its own status, body, identity and retry hint; the @@ -501,6 +608,10 @@ func HasTrustedRetryDeadline(err error) bool { if SafeResponseHeaders(err).Get("Retry-After") != "" { return true } + var poolCooldown *poolCooldownTerminalError + if errors.As(err, &poolCooldown) && poolCooldown != nil && !poolCooldown.deadline.IsZero() { + return true + } var trusted *trustedRetryAfterError return errors.As(err, &trusted) && trusted != nil && !trusted.deadline.IsZero() } @@ -512,6 +623,12 @@ func trustedRetryAfterFromError(err error) *time.Duration { if err == nil { return nil } + var poolCooldown *poolCooldownTerminalError + if errors.As(err, &poolCooldown) && poolCooldown != nil { + if remaining := poolCooldown.RetryAfter(); remaining != nil && *remaining > 0 { + return remaining + } + } var trusted *trustedRetryAfterError if errors.As(err, &trusted) && trusted != nil { if remaining := trusted.RetryAfter(); remaining != nil && *remaining > 0 { diff --git a/sdk/cliproxy/auth/errors_compat_test.go b/sdk/cliproxy/auth/errors_compat_test.go index 39449b410d7..60901c5175f 100644 --- a/sdk/cliproxy/auth/errors_compat_test.go +++ b/sdk/cliproxy/auth/errors_compat_test.go @@ -8,7 +8,7 @@ import ( ) func TestErrorLegacyUnkeyedLiteralCompatibility(t *testing.T) { - err := cliproxyauth.Error{"code", "message", false, http.StatusRequestTimeout} + err := cliproxyauth.Error{"code", "message", false, http.StatusRequestTimeout, nil} if err.Code != "code" || err.Message != "message" || err.Retryable || err.HTTPStatus != http.StatusRequestTimeout { t.Fatalf("unexpected error fields: %#v", err) diff --git a/sdk/cliproxy/auth/file_snapshot_traffic_test.go b/sdk/cliproxy/auth/file_snapshot_traffic_test.go index f0c2eef666a..b5765cabbe7 100644 --- a/sdk/cliproxy/auth/file_snapshot_traffic_test.go +++ b/sdk/cliproxy/auth/file_snapshot_traffic_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "maps" "os" "path/filepath" "testing" @@ -134,7 +135,7 @@ func assertResultRuntimeState(t *testing.T, got, want *coreauth.Auth) { t.Fatalf("auth state = %q %q unavailable=%v retry=%v, want %q %q unavailable=%v retry=%v", got.Status, got.StatusMessage, got.Unavailable, got.NextRetryAfter, want.Status, want.StatusMessage, want.Unavailable, want.NextRetryAfter) } - if got.LastError == nil || *got.LastError != *want.LastError { + if got.LastError == nil || !errorsEqual(got.LastError, want.LastError) { t.Fatalf("last error = %v, want %v", got.LastError, want.LastError) } if got.Quota.Exceeded != want.Quota.Exceeded || got.Quota.Reason != want.Quota.Reason || !got.Quota.NextRecoverAt.Equal(want.Quota.NextRecoverAt) || got.Quota.BackoffLevel != want.Quota.BackoffLevel { @@ -146,7 +147,7 @@ func assertResultRuntimeState(t *testing.T, got, want *coreauth.Auth) { for model, wantState := range want.ModelStates { gotState := got.ModelStates[model] if gotState == nil || gotState.Status != wantState.Status || gotState.Unavailable != wantState.Unavailable || - !gotState.NextRetryAfter.Equal(wantState.NextRetryAfter) || gotState.LastError == nil || *gotState.LastError != *wantState.LastError || + !gotState.NextRetryAfter.Equal(wantState.NextRetryAfter) || gotState.LastError == nil || !errorsEqual(gotState.LastError, wantState.LastError) || gotState.Quota.Exceeded != wantState.Quota.Exceeded || !gotState.Quota.NextRecoverAt.Equal(wantState.Quota.NextRecoverAt) { t.Fatalf("model state %s = %+v, want %+v", model, gotState, wantState) } @@ -327,3 +328,11 @@ func TestFileSnapshotFencedByWriteOutsideManager(t *testing.T) { t.Fatalf("runtime prefix = %q, disk %v, want pfx-login", got.Prefix, diskField(t, path, "prefix")) } } + +func errorsEqual(a, b *coreauth.Error) bool { + if a == nil || b == nil { + return a == b + } + return a.Code == b.Code && a.Message == b.Message && a.Retryable == b.Retryable && + a.HTTPStatus == b.HTTPStatus && maps.Equal(a.Metadata, b.Metadata) +} diff --git a/sdk/cliproxy/auth/home_concurrency.go b/sdk/cliproxy/auth/home_concurrency.go index 15d5c291d58..9c3082b6b99 100644 --- a/sdk/cliproxy/auth/home_concurrency.go +++ b/sdk/cliproxy/auth/home_concurrency.go @@ -292,6 +292,10 @@ func SafeResponseHeaders(err error) http.Header { } return nil } + var poolCooldown *poolCooldownTerminalError + if errors.As(err, &poolCooldown) && poolCooldown != nil { + return poolCooldown.SafeResponseHeaders() + } var trusted *trustedRetryAfterError if errors.As(err, &trusted) && trusted != nil { return trusted.SafeResponseHeaders() @@ -310,7 +314,7 @@ func SafeResponseHeaders(err error) http.Header { } var modelCooldown *modelCooldownError if errors.As(err, &modelCooldown) && modelCooldown != nil { - return modelCooldown.Headers() + return modelCooldown.SafeResponseHeaders() } var unavailable *authUnavailableError if errors.As(err, &unavailable) && unavailable != nil { diff --git a/sdk/cliproxy/auth/home_session_kind_test.go b/sdk/cliproxy/auth/home_session_kind_test.go new file mode 100644 index 00000000000..76203a8bf14 --- /dev/null +++ b/sdk/cliproxy/auth/home_session_kind_test.go @@ -0,0 +1,59 @@ +package auth + +import ( + "context" + "net/http" + "testing" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +type sessionKindCaptureDispatcher struct { + fixtureHomeDispatcher + headers http.Header + sessionID string + parentSessionID string +} + +func (d *sessionKindCaptureDispatcher) RPopAuthWithSessionHierarchy(_ context.Context, _ string, sessionID, parentSessionID string, headers http.Header, _ int, _ string, _ *int, _ []string, _ string) ([]byte, error) { + d.headers = headers.Clone() + d.sessionID = sessionID + d.parentSessionID = parentSessionID + return d.payload, nil +} + +func TestHomeDispatchPreservesForkAndCompactionKind(t *testing.T) { + for _, tc := range []struct { + name string + body string + metadata map[string]any + want string + }{ + {name: "body fork", body: `{"thread_id":"child","metadata":{"forked_from_thread_id":"parent"}}`, want: "fork"}, + {name: "compaction", body: `{"session_id":"child","parent_session_id":"parent"}`, metadata: map[string]any{cliproxyexecutor.NodeKindMetadataKey: "compaction"}, want: "compaction"}, + {name: "ordinary child", body: `{"session_id":"child","parent_session_id":"parent"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + dispatcher := &sessionKindCaptureDispatcher{fixtureHomeDispatcher: fixtureHomeDispatcher{payload: []byte(`{"auth":{"id":"kind-auth","provider":"kind-provider"}}`)}} + manager := newHomeSelectionTestManager(t, dispatcher) + manager.RegisterExecutor(schedulerTestExecutor{provider: "kind-provider"}) + headers := http.Header{"User-Agent": {"test-client"}} + opts := cliproxyexecutor.Options{Headers: headers, OriginalRequest: []byte(tc.body), Metadata: tc.metadata} + opts.EnsureMetadata() + selection, errSelection := manager.pickHomeDispatchSelection(t.Context(), "model", opts) + if errSelection != nil { + t.Fatal(errSelection) + } + selection.End("test_complete") + if dispatcher.sessionID == "" || dispatcher.parentSessionID == "" || dispatcher.sessionID == dispatcher.parentSessionID { + t.Fatalf("lost session hierarchy: child=%q parent=%q", dispatcher.sessionID, dispatcher.parentSessionID) + } + if got := dispatcher.headers.Get("X-Node-Kind"); got != tc.want { + t.Fatalf("node kind=%q, want %q", got, tc.want) + } + if got := headers.Get("X-Node-Kind"); got != "" { + t.Fatalf("caller headers mutated: %q", got) + } + }) + } +} diff --git a/sdk/cliproxy/auth/home_usage_accounting_test.go b/sdk/cliproxy/auth/home_usage_accounting_test.go new file mode 100644 index 00000000000..e84a7141eeb --- /dev/null +++ b/sdk/cliproxy/auth/home_usage_accounting_test.go @@ -0,0 +1,76 @@ +package auth + +import ( + "context" + "testing" + + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executionregistry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" +) + +type homeUsageAccountingExecutor struct { + retainingHomeExecutionExecutor + observed []*coreusage.HomeSelection +} + +func (e *homeUsageAccountingExecutor) Execute(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + e.observed = append(e.observed, coreusage.HomeSelectionFromContext(ctx)) + return e.retainingHomeExecutionExecutor.Execute(ctx, auth, req, opts) +} + +func (e *homeUsageAccountingExecutor) ExecuteStream(ctx context.Context, _ *Auth, _ cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + e.observed = append(e.observed, coreusage.HomeSelectionFromContext(ctx)) + if lifecycle, ok := opts.ExecutionLifecycle.(interface{ Retain() }); ok { + lifecycle.Retain() + } + chunks := make(chan cliproxyexecutor.StreamChunk, 1) + chunks <- cliproxyexecutor.StreamChunk{Payload: []byte(`{"type":"response.completed","response":{"id":"test"}}`)} + close(chunks) + return &cliproxyexecutor.StreamResult{Chunks: chunks}, nil +} + +func TestHomeUsageMarksOnlyReusedExecutions(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(map[bool]string{false: "execute", true: "stream"}[stream], func(t *testing.T) { + dispatcher := &retainingHomeExecutionDispatcher{} + manager := NewManager(nil, nil, nil) + manager.SetConfig(&internalconfig.Config{Home: internalconfig.HomeConfig{Enabled: true}}) + manager.PublishHomeDispatch(dispatcher, executionregistry.New(), 1) + executor := &homeUsageAccountingExecutor{} + manager.RegisterExecutor(executor) + t.Cleanup(func() { manager.CloseExecutionSession("usage-session") }) + ctx := cliproxyexecutor.WithDownstreamWebsocket(t.Context()) + opts := cliproxyexecutor.Options{Metadata: map[string]any{cliproxyexecutor.ExecutionSessionMetadataKey: "usage-session"}} + for _, model := range []string{"model-a", "model-a", "model-a", "model-b"} { + if stream { + result, errExecute := manager.ExecuteStream(ctx, []string{"home-execution"}, cliproxyexecutor.Request{Model: model}, opts) + if errExecute != nil { + t.Fatal(errExecute) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, errExecute := manager.Execute(ctx, []string{"home-execution"}, cliproxyexecutor.Request{Model: model}, opts); errExecute != nil { + t.Fatal(errExecute) + } + } + if dispatcher.calls.Load() != 2 || len(executor.observed) != 4 { + t.Fatalf("dispatch=%d executions=%d", dispatcher.calls.Load(), len(executor.observed)) + } + for i, want := range []bool{false, true, true, false} { + got := executor.observed[i] + wantModel := "model-a" + if i == 3 { + wantModel = "model-b" + } + if got == nil || got.Reused != want || got.Model != wantModel { + t.Fatalf("turn %d: got=%+v want reused=%t model=%s", i, got, want, wantModel) + } + } + }) + } +} diff --git a/sdk/cliproxy/auth/issue7513_completion_flags_test.go b/sdk/cliproxy/auth/issue7513_completion_flags_test.go new file mode 100644 index 00000000000..6e1ed50a38e --- /dev/null +++ b/sdk/cliproxy/auth/issue7513_completion_flags_test.go @@ -0,0 +1,18 @@ +package auth + +import "testing" + +func TestIssue7513_JSONObjectCompletionFlagsRejectsGeminiAbnormalFinishes(t *testing.T) { + for _, reason := range []string{"MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "MALFORMED_RESPONSE"} { + t.Run(reason, func(t *testing.T) { + payload := []byte(`{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"` + reason + `"}]}`) + completed, incomplete := jsonObjectCompletionFlags(payload) + if completed || !incomplete { + t.Fatalf("jsonObjectCompletionFlags(%s) = (completed=%v, incomplete=%v), want (false, true)", reason, completed, incomplete) + } + if isCompletedExecutionPayload(payload) { + t.Fatalf("isCompletedExecutionPayload(%s) = true, want false", reason) + } + }) + } +} diff --git a/sdk/cliproxy/auth/issue_7431_regression_test.go b/sdk/cliproxy/auth/issue_7431_regression_test.go new file mode 100644 index 00000000000..d3e7c23af4b --- /dev/null +++ b/sdk/cliproxy/auth/issue_7431_regression_test.go @@ -0,0 +1,2575 @@ +package auth + +import ( + "context" + "fmt" + "net/http" + "sync" + "testing" + "time" + + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/util" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +func TestIssue7431_LargeWeightedPoolRotatesAcrossTransientExclusionsAndCooldowns(t *testing.T) { + for _, withAffinity := range []bool{false, true} { + name := "scheduler-fast-path" + if withAffinity { + name = "session-affinity-legacy" + } + t.Run(name, func(t *testing.T) { + const ( + totalCreds = 1080 + model = "issue-7431-large-wrr-model" + compatName = "issue-7431-pool" + totalPicks = 1120 + failingEvery = 40 + ) + providerKey := util.OpenAICompatibleProviderKey(compatName) + disableCooling := true + retryCount := 4 + cfg := &internalconfig.Config{ + RequestRetry: retryCount, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: compatName, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCooling, + Models: []internalconfig.OpenAICompatibilityModel{{Name: model, Alias: model}}, + RequestScopedErrors: []internalconfig.RequestScopedErrorRule{{ + Status: http.StatusTooManyRequests, + Match: []string{"server_busy"}, + Action: RequestScopedActionContinueAndCooldown, + }}, + }}, + } + + weighted := &WeightedRoundRobinSelector{} + var selector Selector = weighted + if withAffinity { + affinity := NewSessionAffinitySelector(weighted) + t.Cleanup(affinity.Stop) + selector = affinity + } + + manager := NewManager(nil, selector, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(retryCount, 0, 0) + + reg := registry.GetGlobalRegistry() + authIDs := make([]string, totalCreds) + failSet := make(map[string]bool) + for i := 0; i < totalCreds; i++ { + id := fmt.Sprintf("thk-%s-%04d", name, i) + authIDs[i] = id + // First 4 IDs and every 40th ID fail with 429 so transient exclusions churn continuously. + if i < 4 || i%failingEvery == 0 { + failSet[id] = true + } + auth := &Auth{ + ID: id, + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{ + "auth_kind": "apikey", + "api_key": fmt.Sprintf("key-%04d", i), + "compat_name": compatName, + "provider_key": providerKey, + }, + } + reg.RegisterClient(id, providerKey, []*registry.ModelInfo{{ID: model}}) + if _, errReg := manager.Register(WithSkipPersist(t.Context()), auth); errReg != nil { + t.Fatalf("register %s: %v", id, errReg) + } + } + t.Cleanup(func() { + for _, id := range authIDs { + reg.UnregisterClient(id) + } + }) + + selectedCounts := make(map[string]int, totalCreds) + manager.RegisterExecutor(&mockCustomErrorExecutor{ + identifier: providerKey, + executeFn: func(_ context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + selectedCounts[auth.ID]++ + if failSet[auth.ID] { + return cliproxyexecutor.Response{}, customStatusError{ + code: http.StatusTooManyRequests, + msg: "server_busy", + } + } + return cliproxyexecutor.Response{Payload: []byte(`{"ok":true}`)}, nil + }, + }) + + for reqIdx := 0; reqIdx < totalPicks; reqIdx++ { + opts := cliproxyexecutor.Options{} + if withAffinity { + opts.Headers = http.Header{"Session_id": {fmt.Sprintf("req-session-%d", reqIdx)}} + } + if _, errExec := manager.Execute(t.Context(), []string{providerKey}, cliproxyexecutor.Request{Model: model}, opts); errExec != nil { + t.Fatalf("request %d failed: %v", reqIdx, errExec) + } + } + + healthySelected := 0 + for _, id := range authIDs { + if !failSet[id] && selectedCounts[id] > 0 { + healthySelected++ + } + } + wantMinHealthy := totalCreds - len(failSet) - 10 + if healthySelected < wantMinHealthy { + t.Fatalf("large WRR pool collapsed: only %d/%d healthy credentials selected across %d requests", healthySelected, totalCreds-len(failSet), totalPicks) + } + }) + } +} + +func TestIssue7431_SmoothWeightedStateLargePoolRetainsTransientlyExcludedCredits(t *testing.T) { + const members = 2131 + state := &smoothWeightedState{} + full := make(map[string]int64, members) + for i := 0; i < members; i++ { + full[fmt.Sprintf("cred-%04d", i)] = 1 + } + state.prepare(full) + state.current["cred-0000"] = -(members - 1) + + subset := make(map[string]int64, members-1) + for i := 1; i < members; i++ { + subset[fmt.Sprintf("cred-%04d", i)] = 1 + } + state.prepare(subset) + + if got := state.current["cred-0000"]; got != -(members - 1) { + t.Fatalf("transiently excluded credential credit = %d, want %d", got, -(members - 1)) + } +} + +func TestIssue7431_SchedulerRebuildPreservesUnchangedShardCursors(t *testing.T) { + ctx := t.Context() + manager := NewManager(nil, &RoundRobinSelector{}, nil) + manager.RegisterExecutor(schedulerProviderTestExecutor{provider: "openai"}) + manager.RegisterExecutor(schedulerProviderTestExecutor{provider: "claude"}) + + const model = "issue-7431-rebuild-cursor-model" + reg := registry.GetGlobalRegistry() + var ids []string + for i := 0; i < 5; i++ { + id := fmt.Sprintf("rr-auth-%02d", i) + ids = append(ids, id) + auth := &Auth{ID: id, Provider: "openai", Status: StatusActive} + if _, errReg := manager.Register(WithSkipPersist(ctx), auth); errReg != nil { + t.Fatalf("register %s: %v", id, errReg) + } + reg.RegisterClient(id, "openai", []*registry.ModelInfo{{ID: model}}) + manager.RefreshSchedulerEntry(id) + } + otherAuth := &Auth{ID: "claude-other-01", Provider: "claude", Status: StatusActive} + if _, errReg := manager.Register(WithSkipPersist(ctx), otherAuth); errReg != nil { + t.Fatalf("register other auth: %v", errReg) + } + reg.RegisterClient(otherAuth.ID, "claude", []*registry.ModelInfo{{ID: model}}) + manager.RefreshSchedulerEntry(otherAuth.ID) + t.Cleanup(func() { + for _, id := range ids { + reg.UnregisterClient(id) + } + reg.UnregisterClient(otherAuth.ID) + }) + + for wantIdx := 0; wantIdx < 3; wantIdx++ { + picked, _, errPick := manager.pickNext(ctx, "openai", model, cliproxyexecutor.Options{}, nil) + if errPick != nil || picked == nil { + t.Fatalf("pick %d failed: auth=%v err=%v", wantIdx, picked, errPick) + } + if picked.ID != ids[wantIdx] { + t.Fatalf("pick %d = %q, want %q", wantIdx, picked.ID, ids[wantIdx]) + } + } + + // Simulate scheduler rebuild triggered by unrelated config/provider updates. + manager.scheduler.rebuild(manager.snapshotAuths()) + + pickedAfter, _, errPick := manager.pickNext(ctx, "openai", model, cliproxyexecutor.Options{}, nil) + if errPick != nil || pickedAfter == nil { + t.Fatalf("pick after rebuild failed: auth=%v err=%v", pickedAfter, errPick) + } + if pickedAfter.ID != ids[3] { + t.Fatalf("pick after rebuild reset rotation to %q, want %q", pickedAfter.ID, ids[3]) + } +} + +func TestIssue7431_DisableCoolingPreservesActiveForceCooldownOnReloadAndUpdate(t *testing.T) { + ctx := WithSkipPersist(t.Context()) + const ( + compatName = "issue-7431-force-cool" + model = "issue-7431-force-cool-model" + ) + providerKey := util.OpenAICompatibleProviderKey(compatName) + disableCooling := true + buildConfig := func(extraClaudeKey string) *internalconfig.Config { + cfg := &internalconfig.Config{ + RequestRetry: 2, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: compatName, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCooling, + Models: []internalconfig.OpenAICompatibilityModel{{Name: model, Alias: model}}, + RequestScopedErrors: []internalconfig.RequestScopedErrorRule{{ + Status: http.StatusTooManyRequests, + Match: []string{"rate_limited"}, + Action: RequestScopedActionContinueAndCooldown, + }}, + }}, + } + if extraClaudeKey != "" { + cfg.ClaudeKey = []internalconfig.ClaudeKey{{APIKey: extraClaudeKey}} + } + return cfg + } + + store := &recordingCooldownStateStore{} + manager := NewManager(nil, &RoundRobinSelector{}, nil) + manager.SetCooldownStateStore(store) + manager.SetConfig(buildConfig("")) + manager.SetRetryConfig(2, 0, 0) + + reg := registry.GetGlobalRegistry() + auth0 := &Auth{ + ID: "force-cool-auth-0", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{ + "auth_kind": "apikey", + "api_key": "k0", + "compat_name": compatName, + "provider_key": providerKey, + }, + } + auth1 := &Auth{ + ID: "force-cool-auth-1", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{ + "auth_kind": "apikey", + "api_key": "k1", + "compat_name": compatName, + "provider_key": providerKey, + }, + } + for _, a := range []*Auth{auth0, auth1} { + reg.RegisterClient(a.ID, providerKey, []*registry.ModelInfo{{ID: model}}) + if _, errReg := manager.Register(ctx, a); errReg != nil { + t.Fatalf("register %s: %v", a.ID, errReg) + } + manager.RefreshSchedulerEntry(a.ID) + } + t.Cleanup(func() { + reg.UnregisterClient(auth0.ID) + reg.UnregisterClient(auth1.ID) + }) + + manager.RegisterExecutor(&mockCustomErrorExecutor{ + identifier: providerKey, + executeFn: func(_ context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + if auth.ID == auth0.ID { + return cliproxyexecutor.Response{}, customStatusError{ + code: http.StatusTooManyRequests, + msg: "rate_limited", + } + } + return cliproxyexecutor.Response{Payload: []byte(`{"ok":true}`)}, nil + }, + }) + + if _, errExec := manager.Execute(ctx, []string{providerKey}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}); errExec != nil { + t.Fatalf("initial execute failed: %v", errExec) + } + + now := time.Now() + got0, ok := manager.GetByID(auth0.ID) + if !ok || IsAuthAvailableForModel(got0, model, now) { + t.Fatalf("expected %s to enter force cooldown before reload", auth0.ID) + } + + // 1. Unrelated config reload must NOT erase active ErrorCodeForceCooldown under disable-cooling: true. + manager.SetConfig(buildConfig("sk-ant-unrelated")) + got0AfterReload, _ := manager.GetByID(auth0.ID) + if IsAuthAvailableForModel(got0AfterReload, model, now) { + t.Fatalf("SetConfig erased active ErrorCodeForceCooldown on %s when disable-cooling: true", auth0.ID) + } + pickedAfterReload, _, errPick := manager.pickNext(ctx, providerKey, model, cliproxyexecutor.Options{}, nil) + if errPick != nil || pickedAfterReload == nil || pickedAfterReload.ID != auth1.ID { + t.Fatalf("scheduler selected %v (err=%v) after config reload, want %s while %s is force-cooled", pickedAfterReload, errPick, auth1.ID, auth0.ID) + } + + // 2. Non-credential metadata update on auth0 must NOT erase active ErrorCodeForceCooldown. + updatedAuth0 := got0AfterReload.Clone() + updatedAuth0.Attributes["label_note"] = "reloaded" + if _, errUpd := manager.Update(ctx, updatedAuth0); errUpd != nil { + t.Fatalf("Update(%s) failed: %v", auth0.ID, errUpd) + } + got0AfterUpdate, _ := manager.GetByID(auth0.ID) + if IsAuthAvailableForModel(got0AfterUpdate, model, now) { + t.Fatalf("Update() erased active ErrorCodeForceCooldown on %s when disable-cooling: true", auth0.ID) + } + + // 3. CooldownStateStore persistence & restore must also retain active ErrorCodeForceCooldown under disable-cooling: true. + manager.PersistCooldownStates(ctx) + if len(store.savedRecords()) == 0 { + t.Fatalf("expected active ErrorCodeForceCooldown record to be persisted even with disable-cooling: true") + } + + restoredManager := NewManager(nil, &RoundRobinSelector{}, nil) + restoredManager.SetCooldownStateStore(&recordingCooldownStateStore{load: store.savedRecords()}) + restoredManager.SetConfig(buildConfig("sk-ant-unrelated")) + freshAuth0 := &Auth{ + ID: auth0.ID, + Provider: providerKey, + Status: StatusActive, + Attributes: auth0.Attributes, + } + if _, errReg := restoredManager.Register(ctx, freshAuth0); errReg != nil { + t.Fatalf("register freshAuth0: %v", errReg) + } + if errRestore := restoredManager.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates failed: %v", errRestore) + } + got0Restored, _ := restoredManager.GetByID(auth0.ID) + if IsAuthAvailableForModel(got0Restored, model, now) { + t.Fatalf("RestoreCooldownStates dropped active ErrorCodeForceCooldown under disable-cooling: true") + } +} + +func TestIssue7431_LargeWeightedPoolEdgeCases(t *testing.T) { + ctx := context.Background() + + t.Run("small-subset-does-not-clamp-absent-member-debt", func(t *testing.T) { + sel := &WeightedRoundRobinSelector{} + route := "openai-compatible-edge:model-a" + full := make([]*Auth, 1050) + for i := range full { + w := 10 + if i == 0 { + w = 500 + } + full[i] = &Auth{ + ID: fmt.Sprintf("edge-auth-%04d", i), + Provider: "openai-compatible-edge", + Status: StatusActive, + Attributes: map[string]string{"weight": fmt.Sprintf("%d", w)}, + } + } + picked, res := sel.reserve(route, full, "") + if picked == nil || picked.ID != "edge-auth-0000" { + t.Fatalf("first pick = %v, want edge-auth-0000", picked) + } + res.finish(true) + + // Shrink temporarily to just 2 low-weight members; edge-auth-0000 is absent (e.g. cooled). + subset := []*Auth{full[1], full[2]} + pickedSub, resSub := sel.reserve(route, subset, "") + if pickedSub == nil { + t.Fatal("subset pick returned nil") + } + resSub.finish(true) + + // When edge-auth-0000 returns, its large negative debt (-10490) must still hold it back, + // rather than having been clamped to -200 (subsetTotal=20 * 10). + pickedNext, resNext := sel.reserve(route, full, "") + if pickedNext == nil { + t.Fatal("next full pick returned nil") + } + resNext.finish(true) + if pickedNext.ID == "edge-auth-0000" { + t.Fatalf("edge-auth-0000 was reselected immediately after 2-auth subset; absent debt was prematurely clamped") + } + }) + + t.Run("priority-buckets-isolated-and-forget-auth-prunes-dynamic-pool", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-prio" + const model = "issue-7431-prio-model" + sel := &WeightedRoundRobinSelector{} + manager := NewManager(nil, sel, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: providerKey}) + reg := registry.GetGlobalRegistry() + + for i := 0; i < 1030; i++ { + id := fmt.Sprintf("prio-hi-%04d", i) + auth := &Auth{ + ID: id, + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{ + "provider_key": providerKey, + "priority": "10", + "weight": "5", + }, + } + if _, errReg := manager.Register(ctx, auth); errReg != nil { + t.Fatalf("register %s: %v", id, errReg) + } + reg.RegisterClient(id, providerKey, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + } + lowAuth := &Auth{ + ID: "prio-lo-0000", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{ + "provider_key": providerKey, + "priority": "0", + "weight": "5", + }, + } + if _, errReg := manager.Register(ctx, lowAuth); errReg != nil { + t.Fatalf("register lowAuth: %v", errReg) + } + reg.RegisterClient(lowAuth.ID, providerKey, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(lowAuth.ID) }) + + picked, _, errPick := manager.pickNext(ctx, providerKey, model, cliproxyexecutor.Options{}, nil) + if errPick != nil || picked == nil || picked.ID != "prio-hi-0000" { + t.Fatalf("pick = %v (err=%v), want prio-hi-0000", picked, errPick) + } + + // Deregistering prio-hi-0000 must prune it from largeStates via ForgetAuth. + if !manager.RemoveIf(ctx, "prio-hi-0000", nil) { + t.Fatalf("RemoveIf(prio-hi-0000) returned false") + } + sel.mu.Lock() + for _, state := range sel.largeStates { + if _, found := state.findMember("prio-hi-0000"); found { + sel.mu.Unlock() + t.Fatalf("ForgetAuth failed to prune removed auth prio-hi-0000 from largeStates") + } + if _, foundLow := state.findMember("prio-lo-0000"); foundLow { + sel.mu.Unlock() + t.Fatalf("priority 0 auth leaked into priority 10 largeStates bucket") + } + } + sel.mu.Unlock() + }) +} + +func TestIssue7431_ForceCooldownEdgeCases(t *testing.T) { + ctx := context.Background() + now := time.Now() + + t.Run("mixed-ordinary-and-force-cooldowns-plus-wrapped-shadow-and-reset-quota", func(t *testing.T) { + disableCooling := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{ + { + Name: "openai-compatible-issue-7431-edge", + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCooling, + }, + }, + } + manager := NewManager(nil, &RoundRobinSelector{}, nil) + manager.SetConfig(cfg) + + auth := &Auth{ + ID: "force-edge-auth", + Provider: "openai-compatible-issue-7431-edge", + Status: StatusError, + Attributes: map[string]string{ + "provider_key": "openai-compatible-issue-7431-edge", + }, + Unavailable: true, + NextRetryAfter: now.Add(5 * time.Minute), + Quota: QuotaState{ + Exceeded: true, + Reason: "credential_quota", + NextRecoverAt: now.Add(5 * time.Minute), + }, + LastError: &Error{Code: credentialQuotaErrorCode, HTTPStatus: 429, Message: "daily limit"}, + ModelStates: map[string]*ModelState{ + "model-force": { + Unavailable: true, + Status: StatusError, + NextRetryAfter: now.Add(5 * time.Minute), + Quota: QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: now.Add(5 * time.Minute)}, + credentialQuotaPropagated: true, + credentialQuotaShadow: &ModelState{ + Unavailable: true, + Status: StatusError, + NextRetryAfter: now.Add(2 * time.Minute), + Quota: QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: now.Add(2 * time.Minute)}, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 429, Message: "force model cooldown"}, + UpdatedAt: now, + }, + UpdatedAt: now, + }, + "model-ordinary": { + Unavailable: true, + Status: StatusError, + NextRetryAfter: now.Add(5 * time.Minute), + Quota: QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: now.Add(5 * time.Minute)}, + credentialQuotaPropagated: true, + credentialQuotaShadow: &ModelState{ + Unavailable: true, + Status: StatusError, + NextRetryAfter: now.Add(2 * time.Minute), + Quota: QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: now.Add(2 * time.Minute)}, + LastError: &Error{HTTPStatus: 429, Message: "normal model cooldown"}, + UpdatedAt: now, + }, + UpdatedAt: now, + }, + "model-expired-force": { + Unavailable: true, + Status: StatusError, + NextRetryAfter: now.Add(-time.Second), + Quota: QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: now.Add(-time.Second)}, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 429, Message: "expired force"}, + UpdatedAt: now.Add(-time.Minute), + }, + }, + } + if _, errReg := manager.Register(ctx, auth); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + got, _ := manager.GetByID(auth.ID) + if IsAuthAvailableForModel(got, "model-force", now) { + t.Fatal("expected wrapped active ErrorCodeForceCooldown shadow on model-force to survive Register under disable-cooling") + } + if !IsAuthAvailableForModel(got, "model-ordinary", now) { + t.Fatal("expected ordinary non-force cooldown on model-ordinary to be cleared under disable-cooling") + } + if !IsAuthAvailableForModel(got, "model-expired-force", now) { + t.Fatal("expected expired ErrorCodeForceCooldown on model-expired-force to be cleared") + } + + // Explicit admin ResetQuota must still clear ErrorCodeForceCooldown. + if _, _, errReset := manager.ResetQuota(ctx, auth.ID); errReset != nil { + t.Fatalf("ResetQuota: %v", errReset) + } + gotAfterReset, _ := manager.GetByID(auth.ID) + if !IsAuthAvailableForModel(gotAfterReset, "model-force", now) { + t.Fatal("expected explicit ResetQuota to clear ErrorCodeForceCooldown") + } + + // Auth-level (Model == "") ErrorCodeForceCooldown recorded alongside existing ModelStates + // must also survive SetConfig reload under disable-cooling: true. + retry := 2 * time.Minute + manager.MarkResult(ctx, Result{ + AuthID: auth.ID, + Provider: auth.Provider, + Success: false, + RetryAfter: &retry, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "force auth cooldown"}, + }) + manager.SetConfig(cfg) + gotAuthForce, _ := manager.GetByID(auth.ID) + if IsAuthAvailableForModel(gotAuthForce, "", now) { + t.Fatal("expected model-less auth-level ErrorCodeForceCooldown to survive SetConfig reload alongside ModelStates") + } + }) + + t.Run("mark-result-interleaving-does-not-corrupt-force-credential-cooldown-provenance", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-provenance" + disableCoolingTrue := true + disableCoolingFalse := false + cfgCoolingOff := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + cfgCoolingOn := &internalconfig.Config{ + DisableCooling: false, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingFalse, + }}, + } + + // Order A: Force credential_quota first, followed by ordinary model error overwriting auth.LastError. + mgrA := NewManager(nil, &RoundRobinSelector{}, nil) + mgrA.SetConfig(cfgCoolingOff) + authA := &Auth{ + ID: "prov-auth-a", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + } + if _, errReg := mgrA.Register(ctx, authA); errReg != nil { + t.Fatalf("Register authA: %v", errReg) + } + fiveMin := 5 * time.Minute + mgrA.MarkResult(ctx, Result{ + AuthID: authA.ID, + Provider: providerKey, + Model: "model-1", + Success: false, + CredentialScope: true, + RetryAfter: &fiveMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force account limit"}, + }) + mgrA.MarkResult(ctx, Result{ + AuthID: authA.ID, + Provider: providerKey, + Model: "model-2", + Success: false, + Error: &Error{Code: "server_error", HTTPStatus: http.StatusInternalServerError, Message: "ordinary 500"}, + }) + mgrA.SetConfig(cfgCoolingOff) + gotA, _ := mgrA.GetByID(authA.ID) + checkTime := time.Now() + if IsAuthAvailableForModel(gotA, "model-1", checkTime) || IsAuthAvailableForModel(gotA, "model-2", checkTime) { + t.Fatalf("ordinary model error overwrote auth.LastError and caused SetConfig to erase active force credential_quota: quota=%+v", gotA.Quota) + } + + // Order B: Ordinary credential_quota first (cooling enabled), followed by model-scoped force cooldown, + // then reload enabling disable-cooling: true. + mgrB := NewManager(nil, &RoundRobinSelector{}, nil) + mgrB.SetConfig(cfgCoolingOn) + authB := &Auth{ + ID: "prov-auth-b", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + } + if _, errReg := mgrB.Register(ctx, authB); errReg != nil { + t.Fatalf("Register authB: %v", errReg) + } + mgrB.MarkResult(ctx, Result{ + AuthID: authB.ID, + Provider: providerKey, + Model: "model-1", + Success: false, + CredentialScope: true, + RetryAfter: &fiveMin, + Error: &Error{Code: credentialQuotaErrorCode, HTTPStatus: http.StatusTooManyRequests, Message: "ordinary account limit"}, + }) + twoMin := 2 * time.Minute + mgrB.MarkResult(ctx, Result{ + AuthID: authB.ID, + Provider: providerKey, + Model: "model-2", + Success: false, + RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force model limit"}, + }) + mgrB.SetConfig(cfgCoolingOff) + gotB, _ := mgrB.GetByID(authB.ID) + checkTimeB := time.Now() + if !IsAuthAvailableForModel(gotB, "model-1", checkTimeB) { + t.Fatalf("model-scoped force error overwrote auth.LastError and falsely preserved ordinary credential_quota on model-1: quota=%+v", gotB.Quota) + } + if IsAuthAvailableForModel(gotB, "model-2", checkTimeB) { + t.Fatal("expected model-2's independent force cooldown to survive after ordinary credential_quota was cleared") + } + + // Persistence + restore after auth.LastError was overwritten in Order A must also preserve force credential_quota. + storeA := &recordingCooldownStateStore{} + mgrA.SetCooldownStateStore(storeA) + mgrA.PersistCooldownStates(ctx) + mgrARestored := NewManager(nil, &RoundRobinSelector{}, nil) + mgrARestored.SetCooldownStateStore(&recordingCooldownStateStore{load: storeA.savedRecords()}) + mgrARestored.SetConfig(cfgCoolingOff) + if _, errReg := mgrARestored.Register(ctx, &Auth{ + ID: authA.ID, + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register restored authA: %v", errReg) + } + if errRestore := mgrARestored.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates authA: %v", errRestore) + } + gotARestored, _ := mgrARestored.GetByID(authA.ID) + if IsAuthAvailableForModel(gotARestored, "model-1", time.Now()) || IsAuthAvailableForModel(gotARestored, "model-2", time.Now()) { + t.Fatalf("RestoreCooldownStates lost force credential_quota after auth.LastError overwrite: quota=%+v", gotARestored.Quota) + } + }) +} + +func TestIssue7431_DynamicPoolBoundsAndReservationLifecycle(t *testing.T) { + ctx := context.Background() + + t.Run("large-states-enforces-max-keys-capacity-bound", func(t *testing.T) { + sel := &WeightedRoundRobinSelector{maxKeys: 4} + pool := make([]*Auth, 1030) + for i := range pool { + pool[i] = &Auth{ + ID: fmt.Sprintf("cap-auth-%04d", i), + Provider: "openai-compatible-cap", + Status: StatusActive, + Attributes: map[string]string{"weight": "1"}, + } + } + _, inFlightRes := sel.reserve("openai-compatible-cap:route-0", pool, "") + if inFlightRes == nil { + t.Fatal("expected reservation on route-0") + } + for r := 1; r <= 6; r++ { + _, res := sel.reserve(fmt.Sprintf("openai-compatible-cap:route-%d", r), pool, "") + res.finish(true) + } + sel.mu.Lock() + gotLargeLen := len(sel.largeStates) + sel.mu.Unlock() + if gotLargeLen > 4 { + t.Fatalf("len(sel.largeStates) = %d, want <= maxKeys (4)", gotLargeLen) + } + inFlightRes.finish(false) + + // All-in-flight eviction must isolate stale reservations from newly created state for the same route. + sel2 := &WeightedRoundRobinSelector{maxKeys: 2} + _, evictResA := sel2.reserve("openai-compatible-cap:a", pool, "") + _, evictResB := sel2.reserve("openai-compatible-cap:b", pool, "") + _, evictResC := sel2.reserve("openai-compatible-cap:c", pool, "") + evictResB.finish(true) + evictResC.finish(true) + // Re-create route "a" and commit one clean pick, then roll back stale evictResA. + _, freshResA := sel2.reserve("openai-compatible-cap:a", pool, "") + freshResA.finish(true) + evictResA.finish(false) + sel2.mu.Lock() + stateA := sel2.largeStates["openai-compatible-cap:a"] + for _, m := range stateA.members { + if m.pending != 0 { + sel2.mu.Unlock() + t.Fatalf("evicted reservation rollback corrupted fresh route state: member %s pending=%d", m.id, m.pending) + } + } + sel2.mu.Unlock() + }) + + t.Run("forget-and-reregister-same-id-does-not-pollute-pending-credit", func(t *testing.T) { + sel := &WeightedRoundRobinSelector{} + const route = "openai-compatible-epoch:model-x" + pool := make([]*Auth, 1030) + for i := range pool { + pool[i] = &Auth{ + ID: fmt.Sprintf("epoch-auth-%04d", i), + Provider: "openai-compatible-epoch", + Status: StatusActive, + Attributes: map[string]string{"weight": "1"}, + } + } + picked1, staleRes := sel.reserve(route, pool, "") + if picked1 == nil || picked1.ID != "epoch-auth-0000" { + t.Fatalf("first pick = %v, want epoch-auth-0000", picked1) + } + + // Permanently remove epoch-auth-0000 while staleRes is still in-flight, + // then re-register a fresh credential with the same ID. + sel.ForgetAuth("epoch-auth-0000") + _, freshRes := sel.reserve(route, pool, "") + freshRes.finish(true) + + // Roll back staleRes; it must NOT write +1029 pending credit onto the newly registered epoch-auth-0000. + staleRes.finish(false) + + sel.mu.Lock() + state := sel.largeStates[route] + var nonZeroPendingID string + var nonZeroPendingVal int64 + if state != nil { + for _, m := range state.members { + if m.pending != 0 { + nonZeroPendingID = m.id + nonZeroPendingVal = m.pending + break + } + } + } + sel.mu.Unlock() + if nonZeroPendingID != "" { + t.Fatalf("member %s has leaked pending=%d after stale reservation rollback across ForgetAuth+re-register, want 0", nonZeroPendingID, nonZeroPendingVal) + } + }) + + t.Run("large-weighted-pool-preserves-progress-across-scheduler-rebuild", func(t *testing.T) { + const ( + providerA = "openai-compatible-wrr-rebuild-a" + providerB = "openai-compatible-wrr-rebuild-b" + model = "issue-7431-wrr-rebuild-model" + ) + sel := &WeightedRoundRobinSelector{} + manager := NewManager(nil, sel, nil) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: providerA}) + manager.RegisterExecutor(&mockCustomErrorExecutor{identifier: providerB}) + reg := registry.GetGlobalRegistry() + + allAuths := make([]*Auth, 0, 1031) + for i := 0; i < 1030; i++ { + id := fmt.Sprintf("wrr-reb-%04d", i) + a := &Auth{ + ID: id, + Provider: providerA, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerA, "weight": "1"}, + } + reg.RegisterClient(id, providerA, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + registered, errReg := manager.Register(WithSkipPersist(ctx), a) + if errReg != nil { + t.Fatalf("Register %s: %v", id, errReg) + } + allAuths = append(allAuths, registered) + } + + for i := 0; i < 3; i++ { + picked, _, errPick := manager.pickNext(ctx, providerA, model, cliproxyexecutor.Options{}, nil) + if errPick != nil || picked == nil || picked.ID != fmt.Sprintf("wrr-reb-%04d", i) { + t.Fatalf("pick %d before rebuild = %v (err=%v), want wrr-reb-%04d", i, picked, errPick, i) + } + } + + unrelated := &Auth{ + ID: "unrelated-b-0000", + Provider: providerB, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerB, "weight": "1"}, + } + reg.RegisterClient(unrelated.ID, providerB, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(unrelated.ID) }) + regB, errReg := manager.Register(WithSkipPersist(ctx), unrelated) + if errReg != nil { + t.Fatalf("Register unrelated: %v", errReg) + } + allAuths = append(allAuths, regB) + manager.scheduler.rebuild(allAuths) + + pickedAfter, _, errPick := manager.pickNext(ctx, providerA, model, cliproxyexecutor.Options{}, nil) + if errPick != nil || pickedAfter == nil || pickedAfter.ID != "wrr-reb-0003" { + t.Fatalf("pick after rebuild = %v (err=%v), want wrr-reb-0003", pickedAfter, errPick) + } + }) +} + +func TestIssue7431_SameLayerForceCooldownAndPersistenceAndEpochRaces(t *testing.T) { + ctx := context.Background() + + t.Run("same-layer-ordinary-error-does-not-clear-active-force-cooldown", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-samelayer" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetConfig(cfg) + + authModel := &Auth{ + ID: "samelayer-model-auth", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + } + authGlobal := &Auth{ + ID: "samelayer-global-auth", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + } + if _, errReg := mgr.Register(WithSkipPersist(ctx), authModel); errReg != nil { + t.Fatalf("register authModel: %v", errReg) + } + if _, errReg := mgr.Register(WithSkipPersist(ctx), authGlobal); errReg != nil { + t.Fatalf("register authGlobal: %v", errReg) + } + + twoMin := 2 * time.Minute + // 1. Same model: force 503 followed by in-flight ordinary 500 under disable-cooling: true. + mgr.MarkResult(ctx, Result{ + AuthID: authModel.ID, + Provider: providerKey, + Model: "model-same", + Success: false, + RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "force 503"}, + }) + mgr.MarkResult(ctx, Result{ + AuthID: authModel.ID, + Provider: providerKey, + Model: "model-same", + Success: false, + Error: &Error{Code: "server_error", HTTPStatus: http.StatusInternalServerError, Message: "ordinary 500"}, + }) + now := time.Now() + gotModel, _ := mgr.GetByID(authModel.ID) + if IsAuthAvailableForModel(gotModel, "model-same", now) { + t.Fatalf("ordinary 500 on same model cleared active force cooldown immediately: state=%+v", gotModel.ModelStates["model-same"]) + } + mgr.SetConfig(cfg) + gotModelAfterReload, _ := mgr.GetByID(authModel.ID) + if IsAuthAvailableForModel(gotModelAfterReload, "model-same", now) { + t.Fatalf("SetConfig after ordinary 500 on same model cleared active force cooldown: state=%+v", gotModelAfterReload.ModelStates["model-same"]) + } + + // 2. Model-less auth level (Model == ""): force 503 followed by in-flight ordinary 500 under disable-cooling: true. + mgr.MarkResult(ctx, Result{ + AuthID: authGlobal.ID, + Provider: providerKey, + Success: false, + RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "force 503"}, + }) + mgr.MarkResult(ctx, Result{ + AuthID: authGlobal.ID, + Provider: providerKey, + Success: false, + Error: &Error{Code: "server_error", HTTPStatus: http.StatusInternalServerError, Message: "ordinary 500"}, + }) + gotGlobal, _ := mgr.GetByID(authGlobal.ID) + if IsAuthAvailableForModel(gotGlobal, "", now) { + t.Fatalf("ordinary 500 on model-less auth cleared active force cooldown immediately: RetryAfter=%v", gotGlobal.NextRetryAfter) + } + mgr.SetConfig(cfg) + gotGlobalAfterReload, _ := mgr.GetByID(authGlobal.ID) + if IsAuthAvailableForModel(gotGlobalAfterReload, "", now) { + t.Fatalf("SetConfig after ordinary 500 on model-less auth cleared active force cooldown: RetryAfter=%v", gotGlobalAfterReload.NextRetryAfter) + } + }) + + t.Run("persisted-force-deadlines-preserve-exact-unequal-bounds-across-disk-roundtrip", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-disk" + disableCoolingFalse := false + disableCoolingTrue := true + cfgOn := &internalconfig.Config{ + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingFalse, + }}, + } + cfgOff := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + + cdsDir := t.TempDir() + fileStore := NewFileCooldownStateStore(cdsDir) + mgr1 := NewManager(nil, &RoundRobinSelector{}, nil) + mgr1.SetCooldownStateStore(fileStore) + mgr1.SetConfig(cfgOn) + + // Auth 1: 2m force cooldown on model-x, then extended to 10m by an ordinary 429. + a1 := &Auth{ID: "disk-auth-1", Provider: providerKey, Status: StatusActive, Attributes: map[string]string{"provider_key": providerKey}} + // Auth 2: 2m force credential_quota on model-a + 10m force independent shadow on model-b. + a2 := &Auth{ID: "disk-auth-2", Provider: providerKey, Status: StatusActive, Attributes: map[string]string{"provider_key": providerKey}} + if _, errReg := mgr1.Register(WithSkipPersist(ctx), a1); errReg != nil { + t.Fatalf("register a1: %v", errReg) + } + if _, errReg := mgr1.Register(WithSkipPersist(ctx), a2); errReg != nil { + t.Fatalf("register a2: %v", errReg) + } + + twoMin := 2 * time.Minute + tenMin := 10 * time.Minute + mgr1.MarkResult(ctx, Result{ + AuthID: a1.ID, Provider: providerKey, Model: "model-x", RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force 2m"}, + }) + mgr1.MarkResult(ctx, Result{ + AuthID: a1.ID, Provider: providerKey, Model: "model-x", RetryAfter: &tenMin, + Error: &Error{Code: "rate_limited", HTTPStatus: http.StatusTooManyRequests, Message: "ordinary 10m"}, + }) + + mgr1.MarkResult(ctx, Result{ + AuthID: a2.ID, Provider: providerKey, Model: "model-a", CredentialScope: true, RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force cred 2m"}, + }) + mgr1.MarkResult(ctx, Result{ + AuthID: a2.ID, Provider: providerKey, Model: "model-b", RetryAfter: &tenMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force model-b 10m"}, + }) + mgr1.PersistCooldownStates(ctx) + + // Restart with disable-cooling: true and restore from real .cds files on disk. + mgr2 := NewManager(nil, &RoundRobinSelector{}, nil) + mgr2.SetCooldownStateStore(NewFileCooldownStateStore(cdsDir)) + mgr2.SetConfig(cfgOff) + for _, id := range []string{a1.ID, a2.ID} { + if _, errReg := mgr2.Register(WithSkipPersist(ctx), &Auth{ + ID: id, Provider: providerKey, Status: StatusActive, Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("register %s in mgr2: %v", id, errReg) + } + } + if errRestore := mgr2.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + + baseNow := time.Now() + gotA1, _ := mgr2.GetByID(a1.ID) + if IsAuthAvailableForModel(gotA1, "model-x", baseNow.Add(time.Minute)) { + t.Fatal("expected disk-auth-1 model-x to remain blocked within 2m force deadline") + } + if !IsAuthAvailableForModel(gotA1, "model-x", baseNow.Add(3*time.Minute)) { + t.Fatalf("disk-auth-1 model-x remained blocked at +3m; 10m ordinary extension inflated restored force deadline: %+v", gotA1.ModelStates["model-x"]) + } + + gotA2, _ := mgr2.GetByID(a2.ID) + if IsAuthAvailableForModel(gotA2, "model-a", baseNow.Add(time.Minute)) { + t.Fatal("expected disk-auth-2 model-a to remain blocked within 2m force credential_quota") + } + if !IsAuthAvailableForModel(gotA2, "model-a", baseNow.Add(3*time.Minute)) { + t.Fatalf("disk-auth-2 model-a remained blocked at +3m; model-b 10m shadow inflated credQuotaForceUntil: quota=%+v", gotA2.Quota) + } + if IsAuthAvailableForModel(gotA2, "model-b", baseNow.Add(5*time.Minute)) { + t.Fatal("expected disk-auth-2 model-b to remain blocked by its 10m independent force shadow at +5m") + } + }) + + t.Run("concurrent-load-persist-and-get-has-no-data-race", func(t *testing.T) { + now := time.Now() + loadStore := &blockingSelectiveAuthStore{ + onList: func() ([]*Auth, error) { + return []*Auth{{ + ID: "load-race-auth", + Provider: "xai", + Status: StatusError, + Unavailable: true, + NextRetryAfter: now.Add(5 * time.Minute), + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "force"}, + ModelStates: map[string]*ModelState{ + "grok-4": { + Unavailable: true, + Status: StatusError, + NextRetryAfter: now.Add(5 * time.Minute), + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "force"}, + UpdatedAt: now, + }, + }, + }}, nil + }, + } + cdsStore := &recordingCooldownStateStore{} + mgr := NewManager(loadStore, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(cdsStore) + if errLoad := mgr.Load(ctx); errLoad != nil { + t.Fatalf("Load: %v", errLoad) + } + start := make(chan struct{}) + var wg sync.WaitGroup + for range 8 { + wg.Add(3) + go func() { + defer wg.Done() + <-start + _ = mgr.Load(ctx) + }() + go func() { + defer wg.Done() + <-start + mgr.PersistCooldownStates(ctx) + }() + go func() { + defer wg.Done() + <-start + _, _ = mgr.GetByID("load-race-auth") + }() + } + close(start) + wg.Wait() + }) + + t.Run("delayed-forget-after-remove-does-not-wipe-reregistered-auth", func(t *testing.T) { + const ( + providerKey = "openai-compatible-issue-7431-forget-race" + model = "issue-7431-forget-race-model" + ) + sel := &WeightedRoundRobinSelector{} + aff := NewSessionAffinitySelector(sel) + t.Cleanup(aff.Stop) + mgr := NewManager(nil, aff, nil) + mgr.RegisterExecutor(&mockCustomErrorExecutor{identifier: providerKey}) + reg := registry.GetGlobalRegistry() + + for i := 0; i < 1030; i++ { + id := fmt.Sprintf("fr-auth-%04d", i) + reg.RegisterClient(id, providerKey, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: id, Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey, "weight": "1"}, + }); errReg != nil { + t.Fatalf("register %s: %v", id, errReg) + } + } + + // Pick once so fr-auth-0000 (epoch 1) enters largeStates. + picked1, _, errPick1 := mgr.pickNext(ctx, providerKey, model, cliproxyexecutor.Options{}, nil) + if errPick1 != nil || picked1 == nil || picked1.ID != "fr-auth-0000" { + t.Fatalf("first pick = %v (err=%v), want fr-auth-0000", picked1, errPick1) + } + + // Remove fr-auth-0000, then immediately re-register fr-auth-0000 (higher RegistrationEpoch) + // and select again so the new instance is active in largeStates with credit. + if !mgr.RemoveIf(ctx, "fr-auth-0000", nil) { + t.Fatal("RemoveIf(fr-auth-0000) returned false") + } + reRegistered, errReReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "fr-auth-0000", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey, "weight": "1"}, + }) + if errReReg != nil { + t.Fatalf("re-register fr-auth-0000: %v", errReReg) + } + // Pick on the pool so re-registered fr-auth-0000 (epoch >= 3) is tracked in largeStates. + if _, _, errPick2 := mgr.pickNext(ctx, providerKey, model, cliproxyexecutor.Options{}, nil); errPick2 != nil { + t.Fatalf("second pick failed: %v", errPick2) + } + + // Simulate a delayed ForgetAuth from the prior RemoveIf (whose tombstoneEpoch < reRegistered.RegistrationEpoch). + staleTombstoneEpoch := reRegistered.RegistrationEpoch - 1 + mgr.forgetWeightedAuthUpTo("fr-auth-0000", staleTombstoneEpoch, ^uint64(0)) + + sel.mu.Lock() + var foundNew bool + for _, state := range sel.largeStates { + if idx, ok := state.findMember("fr-auth-0000"); ok && state.members[idx].current != 0 { + foundNew = true + } + } + sel.mu.Unlock() + if !foundNew { + t.Fatal("delayed forget from earlier RemoveIf wiped re-registered fr-auth-0000 state") + } + }) + + t.Run("ordinary-credential-scope-error-does-not-clear-active-model-force-cooldown", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-cred-ordinary" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + cdsDir := t.TempDir() + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(NewFileCooldownStateStore(cdsDir)) + mgr.SetConfig(cfg) + + a := &Auth{ + ID: "cred-ordinary-over-model-force", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + } + if _, errReg := mgr.Register(WithSkipPersist(ctx), a); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + twoMin := 2 * time.Minute + mgr.MarkResult(ctx, Result{ + AuthID: a.ID, + Provider: providerKey, + Model: "model-1", + RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "force 503"}, + }) + mgr.MarkResult(ctx, Result{ + AuthID: a.ID, + Provider: providerKey, + Model: "model-1", + CredentialScope: true, + Error: &Error{Code: credentialQuotaErrorCode, HTTPStatus: http.StatusTooManyRequests, Message: "ordinary cred 429"}, + }) + + now := time.Now() + gotImmediate, _ := mgr.GetByID(a.ID) + if IsAuthAvailableForModel(gotImmediate, "model-1", now) { + t.Fatalf("ordinary CredentialScope 429 erased active model force cooldown immediately: state=%+v", gotImmediate.ModelStates["model-1"]) + } + mgr.SetConfig(cfg) + gotAfterReload, _ := mgr.GetByID(a.ID) + if IsAuthAvailableForModel(gotAfterReload, "model-1", now) { + t.Fatalf("SetConfig after ordinary CredentialScope 429 erased active model force cooldown: state=%+v", gotAfterReload.ModelStates["model-1"]) + } + mgr.PersistCooldownStates(ctx) + mgrRestored := NewManager(nil, &RoundRobinSelector{}, nil) + mgrRestored.SetCooldownStateStore(NewFileCooldownStateStore(cdsDir)) + mgrRestored.SetConfig(cfg) + if _, errReg := mgrRestored.Register(WithSkipPersist(ctx), &Auth{ + ID: a.ID, Provider: providerKey, Status: StatusActive, Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register restored: %v", errReg) + } + if errRestore := mgrRestored.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + gotRestored, _ := mgrRestored.GetByID(a.ID) + if IsAuthAvailableForModel(gotRestored, "model-1", now) { + t.Fatalf("RestoreCooldownStates lost active model force cooldown after ordinary CredentialScope 429: state=%+v", gotRestored.ModelStates["model-1"]) + } + }) + + t.Run("mixed-transport-large-websocket-pool-keeps-credits-when-http-peer-excluded", func(t *testing.T) { + const model = "gpt-5-ws-mixed" + wsCtx := cliproxyexecutor.WithDownstreamWebsocket(ctx) + + // 1. Direct selector / legacy path: excluding the sole HTTP peer in tried must not switch dynamic pool keys. + sel := &WeightedRoundRobinSelector{} + all := make([]*Auth, 0, 1031) + wsOnly := make([]*Auth, 0, 1030) + httpAuth := &Auth{ + ID: "codex-http-0000", + Provider: "codex", + Status: StatusActive, + Attributes: map[string]string{ + "weight": "1", + "websockets": "false", + }, + } + all = append(all, httpAuth) + for i := 0; i < 1030; i++ { + a := &Auth{ + ID: fmt.Sprintf("codex-ws-%04d", i), + Provider: "codex", + Status: StatusActive, + Attributes: map[string]string{ + "weight": "1", + "websockets": "true", + }, + } + all = append(all, a) + wsOnly = append(wsOnly, a) + } + + for i := 0; i < 3; i++ { + picked, errPick := sel.Pick(wsCtx, "codex", model, cliproxyexecutor.Options{}, all) + if errPick != nil || picked == nil || picked.ID != fmt.Sprintf("codex-ws-%04d", i) { + t.Fatalf("selector pick %d with HTTP peer present = %v (err=%v), want codex-ws-%04d", i, picked, errPick, i) + } + } + pickedWithoutHTTP, errPick := sel.Pick(wsCtx, "codex", model, cliproxyexecutor.Options{}, wsOnly) + if errPick != nil || pickedWithoutHTTP == nil || pickedWithoutHTTP.ID != "codex-ws-0003" { + t.Fatalf("selector pick after HTTP peer excluded = %v (err=%v), want codex-ws-0003", pickedWithoutHTTP, errPick) + } + + // 2. Scheduler fast path: cooling the sole HTTP peer must not switch dynamic pool keys. + schedSel := &WeightedRoundRobinSelector{} + mgr := NewManager(nil, schedSel, nil) + mgr.RegisterExecutor(&mockCustomErrorExecutor{identifier: "codex"}) + reg := registry.GetGlobalRegistry() + for _, a := range all { + id := a.ID + reg.RegisterClient(id, "codex", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + if _, errReg := mgr.Register(WithSkipPersist(ctx), a.Clone()); errReg != nil { + t.Fatalf("Register %s: %v", id, errReg) + } + } + for i := 0; i < 3; i++ { + picked, _, errPickSched := mgr.pickNext(wsCtx, "codex", model, cliproxyexecutor.Options{}, nil) + if errPickSched != nil || picked == nil || picked.ID != fmt.Sprintf("codex-ws-%04d", i) { + t.Fatalf("scheduler pick %d before HTTP cooldown = %v (err=%v), want codex-ws-%04d", i, picked, errPickSched, i) + } + } + oneMin := time.Minute + mgr.MarkResult(ctx, Result{ + AuthID: httpAuth.ID, + Provider: "codex", + Model: model, + RetryAfter: &oneMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "http down"}, + }) + pickedAfterCool, _, errPickAfter := mgr.pickNext(wsCtx, "codex", model, cliproxyexecutor.Options{}, nil) + if errPickAfter != nil || pickedAfterCool == nil || pickedAfterCool.ID != "codex-ws-0003" { + t.Fatalf("scheduler pick after HTTP peer cooled = %v (err=%v), want codex-ws-0003", pickedAfterCool, errPickAfter) + } + }) + + t.Run("small-exact-pool-isolates-inflight-reservations-across-register-replacement-and-load", func(t *testing.T) { + const ( + providerKey = "openai-compatible-issue-7431-small-epoch" + route = providerKey + ":small-model" + ) + loadItems := []*Auth{ + {ID: "small-0", Provider: providerKey, Status: StatusActive, Attributes: map[string]string{"provider_key": providerKey, "weight": "1"}}, + {ID: "small-1", Provider: providerKey, Status: StatusActive, Attributes: map[string]string{"provider_key": providerKey, "weight": "1"}}, + {ID: "small-2", Provider: providerKey, Status: StatusActive, Attributes: map[string]string{"provider_key": providerKey, "weight": "1"}}, + } + store := &schedulerLoadStore{auths: []*Auth{loadItems[0].Clone(), loadItems[1].Clone(), loadItems[2].Clone()}} + sel := &WeightedRoundRobinSelector{} + mgr := NewManager(store, sel, nil) + if errLoad := mgr.Load(ctx); errLoad != nil { + t.Fatalf("initial Load: %v", errLoad) + } + + currentPool := func() []*Auth { + out := make([]*Auth, 0, 3) + for _, id := range []string{"small-0", "small-1", "small-2"} { + a, _ := mgr.GetByID(id) + out = append(out, a) + } + return out + } + + // 1. In-place Register replacement (without RemoveIf) advances small-0's RegistrationEpoch. + pickedStale, staleRegRes := sel.reserve(route, currentPool(), "") + if pickedStale == nil || pickedStale.ID != "small-0" { + t.Fatalf("initial pick = %v, want small-0", pickedStale) + } + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "small-0", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey, "weight": "1"}, + }); errReg != nil { + t.Fatalf("in-place Register replacement: %v", errReg) + } + // New small-0 (epoch 2) must not inherit staleRegRes's -2 pending debt, and a delayed + // commit of staleRegRes must be ignored rather than charging the new small-0. + pickedFresh, freshRegRes := sel.reserve(route, currentPool(), "") + if pickedFresh == nil || pickedFresh.ID != "small-0" { + t.Fatalf("pick after in-place Register replacement = %v, want fresh small-0 (not suppressed by stale pending)", pickedFresh) + } + freshRegRes.finish(false) + staleRegRes.finish(true) + + sel.mu.Lock() + for _, head := range sel.states { + for st := head; st != nil; st = st.next { + for _, m := range st.members { + if m.pending != 0 || (m.id == "small-0" && m.current != 0) { + sel.mu.Unlock() + t.Fatalf("in-place Register replacement failed to isolate stale reservation: member %s current=%d pending=%d", m.id, m.current, m.pending) + } + } + } + } + sel.mu.Unlock() + + // 2. Manager.Load advances RegistrationEpoch across retained IDs while a reservation is in-flight. + _, staleLoadRes := sel.reserve(route, currentPool(), "") + store.auths = []*Auth{loadItems[0].Clone(), loadItems[1].Clone(), loadItems[2].Clone()} + if errLoad := mgr.Load(ctx); errLoad != nil { + t.Fatalf("second Load: %v", errLoad) + } + pickedAfterLoad, freshLoadRes := sel.reserve(route, currentPool(), "") + if pickedAfterLoad == nil || pickedAfterLoad.ID != "small-0" { + t.Fatalf("pick after Load = %v, want small-0", pickedAfterLoad) + } + freshLoadRes.finish(false) + staleLoadRes.finish(true) + + sel.mu.Lock() + for _, head := range sel.states { + for st := head; st != nil; st = st.next { + for _, m := range st.members { + if m.pending != 0 || m.current != 0 { + sel.mu.Unlock() + t.Fatalf("Load epoch bump failed to isolate stale reservation: member %s current=%d pending=%d", m.id, m.current, m.pending) + } + } + } + } + sel.mu.Unlock() + }) + + t.Run("consecutive-force-429-without-retry-after-preserves-escalated-backoff-across-reload", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-backoff" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetConfig(cfg) + + past := time.Now().Add(-time.Minute) + // Pre-seed BackoffLevel=3 (expired window) so next escalated quota backoff is 1s * 2^3 = 8s (>> 1s base). + authModel := &Auth{ + ID: "backoff-model-auth", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + ModelStates: map[string]*ModelState{ + "m1": { + Status: StatusActive, + Quota: QuotaState{BackoffLevel: 3, NextRecoverAt: past}, + }, + }, + } + authCred := &Auth{ + ID: "backoff-cred-auth", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + Quota: QuotaState{Exceeded: true, Reason: "credential_quota", BackoffLevel: 3, NextRecoverAt: past}, + } + authGlobal := &Auth{ + ID: "backoff-global-auth", + Provider: providerKey, + Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + Quota: QuotaState{BackoffLevel: 3, NextRecoverAt: past}, + } + for _, a := range []*Auth{authModel, authCred, authGlobal} { + if _, errReg := mgr.Register(WithSkipPersist(ctx), a); errReg != nil { + t.Fatalf("Register %s: %v", a.ID, errReg) + } + } + // Restore BackoffLevel=3 in runtime after initial Register cleared expired QuotaState. + mgr.mu.Lock() + mgr.auths[authModel.ID].ModelStates["m1"].Quota.BackoffLevel = 3 + mgr.auths[authCred.ID].Quota.Exceeded = true + mgr.auths[authCred.ID].Quota.Reason = "credential_quota" + mgr.auths[authCred.ID].Quota.BackoffLevel = 3 + mgr.auths[authGlobal.ID].Quota.BackoffLevel = 3 + mgr.mu.Unlock() + + beforeMark := time.Now() + mgr.MarkResult(ctx, Result{ + AuthID: authModel.ID, Provider: providerKey, Model: "m1", + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force 429 no hint"}, + }) + mgr.MarkResult(ctx, Result{ + AuthID: authCred.ID, Provider: providerKey, Model: "m1", CredentialScope: true, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force cred 429 no hint"}, + }) + mgr.MarkResult(ctx, Result{ + AuthID: authGlobal.ID, Provider: providerKey, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force global 429 no hint"}, + }) + + mgr.SetConfig(cfg) + probeAt := beforeMark.Add(4 * time.Second) // > 1s base floor, < 8s escalated backoff + gotModel, _ := mgr.GetByID(authModel.ID) + if IsAuthAvailableForModel(gotModel, "m1", probeAt) { + t.Fatalf("SetConfig truncated escalated model force 429 backoff to <=4s (want ~8s): state=%+v", gotModel.ModelStates["m1"]) + } + gotCred, _ := mgr.GetByID(authCred.ID) + if IsAuthAvailableForModel(gotCred, "m1", probeAt) { + t.Fatalf("SetConfig truncated escalated credential_quota force 429 backoff to <=4s (want ~8s): quota=%+v", gotCred.Quota) + } + gotGlobal, _ := mgr.GetByID(authGlobal.ID) + if IsAuthAvailableForModel(gotGlobal, "", probeAt) { + t.Fatalf("SetConfig truncated escalated auth-level force 429 backoff to <=4s (want ~8s): NextRetryAfter=%v", gotGlobal.NextRetryAfter) + } + }) + + t.Run("http-bound-large-pool-keeps-credits-when-last-websocket-peer-excluded", func(t *testing.T) { + const model = "gpt-5-http-bound" + wsCtx := cliproxyexecutor.WithDownstreamWebsocket(ctx) + + // 1. Legacy SessionAffinitySelector path: HTTP-bound session charges 1030 HTTP peers; + // excluding the sole WS peer must keep charging the same "http" dynamic pool. + baseSel := &WeightedRoundRobinSelector{} + affSel := NewSessionAffinitySelector(baseSel) + t.Cleanup(affSel.Stop) + + all := make([]*Auth, 0, 1031) + httpOnly := make([]*Auth, 0, 1030) + wsPeer := &Auth{ + ID: "codex-ws-sole", + Provider: "codex", + Status: StatusActive, + Attributes: map[string]string{ + "weight": "1", + "websockets": "true", + }, + } + all = append(all, wsPeer) + for i := 0; i < 1030; i++ { + a := &Auth{ + ID: fmt.Sprintf("codex-http-%04d", i), + Provider: "codex", + Status: StatusActive, + Attributes: map[string]string{ + "weight": "1", + "websockets": "false", + }, + } + all = append(all, a) + httpOnly = append(httpOnly, a) + } + + stickyOpts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"http-sticky-sess"}}} + // Bind session to codex-http-0000 on an HTTP request first, then send downstream WS requests. + if _, errBind := affSel.Pick(ctx, "codex", model, stickyOpts, httpOnly); errBind != nil { + t.Fatalf("bind HTTP session: %v", errBind) + } + if _, errPickWS1 := affSel.Pick(wsCtx, "codex", model, stickyOpts, all); errPickWS1 != nil { + t.Fatalf("WS pick with WS peer present: %v", errPickWS1) + } + if _, errPickWS2 := affSel.Pick(wsCtx, "codex", model, stickyOpts, httpOnly); errPickWS2 != nil { + t.Fatalf("WS pick after WS peer excluded: %v", errPickWS2) + } + httpBucketKey := dynamicWeightedPoolKey("codex:"+model, 0, "http") + baseSel.mu.Lock() + largeBucketCount := len(baseSel.largeStates) + httpBucket := baseSel.largeStates[httpBucketKey] + var httpBoundDebt int64 + if httpBucket != nil { + if idx, ok := httpBucket.findMember("codex-http-0000"); ok { + httpBoundDebt = httpBucket.members[idx].current + } + } + baseSel.mu.Unlock() + if largeBucketCount != 2 || httpBoundDebt != -2*1029 { + t.Fatalf("expected HTTP-bound WS traffic to accumulate both picks in 'http' bucket (debt=%d, want %d; buckets=%d, want 2)", httpBoundDebt, -2*1029, largeBucketCount) + } + + // 2. Scheduler fast path: pinned HTTP auth on downstream WS keeps using the same "http" dynamic pool after sole WS peer cools. + schedSel := &WeightedRoundRobinSelector{} + mgr := NewManager(nil, schedSel, nil) + mgr.RegisterExecutor(&mockCustomErrorExecutor{identifier: "codex"}) + reg := registry.GetGlobalRegistry() + for _, a := range all { + id := a.ID + reg.RegisterClient(id, "codex", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + if _, errReg := mgr.Register(WithSkipPersist(ctx), a.Clone()); errReg != nil { + t.Fatalf("Register %s: %v", id, errReg) + } + } + pinOpts := cliproxyexecutor.Options{Metadata: map[string]any{cliproxyexecutor.PinnedAuthMetadataKey: "codex-http-0000"}} + if _, _, errP1 := mgr.pickNext(wsCtx, "codex", model, pinOpts, nil); errP1 != nil { + t.Fatalf("scheduler pinned pick before WS cooldown: %v", errP1) + } + oneMin := time.Minute + mgr.MarkResult(ctx, Result{ + AuthID: wsPeer.ID, Provider: "codex", Model: model, RetryAfter: &oneMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "ws down"}, + }) + if _, _, errP2 := mgr.pickNext(wsCtx, "codex", model, pinOpts, nil); errP2 != nil { + t.Fatalf("scheduler pinned pick after WS cooldown: %v", errP2) + } + schedSel.mu.Lock() + schedBucketCount := len(schedSel.largeStates) + schedSel.mu.Unlock() + if schedBucketCount != 1 { + t.Fatalf("scheduler switched dynamic buckets when sole WS peer cooled: got %d buckets, want 1", schedBucketCount) + } + }) + + t.Run("delayed-store-restore-does-not-shorten-newer-live-auth-force-cooldown", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-delayed-restore" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + baseNow := time.Now() + staleRetry := baseNow.Add(2 * time.Minute) + loadEntered := make(chan struct{}) + loadRelease := make(chan struct{}) + slowStore := &issue7431BlockingLoadCooldownStore{ + records: []CooldownStateRecord{{ + Provider: providerKey, + AuthID: "delayed-auth-0", + Status: "cooling", + NextRetryAfter: staleRetry, + Reason: ErrorCodeForceCooldown, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "older 2m force"}, + UpdatedAt: baseNow.Add(-time.Minute), + ForceCooldownUntil: staleRetry, + ForceCooldownEvaluated: true, + }}, + entered: loadEntered, + release: loadRelease, + } + + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(slowStore) + mgr.SetConfig(cfg) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "delayed-auth-0", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + restoreDone := make(chan error, 1) + go func() { + restoreDone <- mgr.RestoreCooldownStates(ctx) + }() + <-loadEntered + + // Record a newer 10-minute auth-level force cooldown while store.Load is in flight. + tenMin := 10 * time.Minute + mgr.MarkResult(ctx, Result{ + AuthID: "delayed-auth-0", Provider: providerKey, RetryAfter: &tenMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "newer 10m force"}, + }) + close(loadRelease) + if errRestore := <-restoreDone; errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + + got, _ := mgr.GetByID("delayed-auth-0") + if IsAuthAvailableForModel(got, "", baseNow.Add(5*time.Minute)) { + t.Fatalf("delayed RestoreCooldownStates shortened newer 10m auth-level force cooldown to %v", got.NextRetryAfter) + } + }) + + t.Run("dynamic-pool-prunes-churned-members-and-shrinks-backing-array-despite-inflight-reservation", func(t *testing.T) { + sel := &WeightedRoundRobinSelector{} + const route = "openai-compatible-churn:model-c" + makeBatch := func(batch int) []*Auth { + out := make([]*Auth, 1030) + for i := range out { + out[i] = &Auth{ + ID: fmt.Sprintf("churn-b%02d-%04d", batch, i), + Provider: "openai-compatible-churn", + Status: StatusActive, + Attributes: map[string]string{"weight": "1"}, + } + } + return out + } + + _, pinnedInFlight := sel.reserve(route, makeBatch(0), "") + if pinnedInFlight == nil { + t.Fatal("expected in-flight reservation on batch 0") + } + for b := 1; b <= 12; b++ { + _, res := sel.reserve(route, makeBatch(b), "") + res.finish(true) + } + + sel.mu.Lock() + state := sel.largeStates[route] + gotLen := len(state.members) + gotCap := cap(state.members) + sel.mu.Unlock() + if gotLen > 3200 || gotCap > 4096 { + t.Fatalf("dynamic pool members grew unbounded while 1 reservation remained in-flight: len=%d cap=%d", gotLen, gotCap) + } + + pinnedInFlight.finish(false) + sel.mu.Lock() + for _, m := range state.members { + if m.pending != 0 { + sel.mu.Unlock() + t.Fatalf("member %s has non-zero pending=%d after pinned reservation rollback", m.id, m.pending) + } + } + sel.mu.Unlock() + }) + + t.Run("ordinary-modelless-429-does-not-wipe-credential-scoped-force-cooldown", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-modelless-429" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + cdsPath := t.TempDir() + "/modelless-429.cds" + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + mgr.SetConfig(cfg) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "ml429-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + baseNow := time.Now() + fiveMin := 5 * time.Minute + mgr.MarkResult(ctx, Result{ + AuthID: "ml429-auth", Provider: providerKey, Model: "m1", CredentialScope: true, RetryAfter: &fiveMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force cred 429"}, + }) + // Ordinary model-less 429 under disable-cooling must not clobber credential_quota force state. + mgr.MarkResult(ctx, Result{ + AuthID: "ml429-auth", Provider: providerKey, + Error: &Error{Code: "rate_limited", HTTPStatus: http.StatusTooManyRequests, Message: "ordinary global 429"}, + }) + + gotAfterMark, _ := mgr.GetByID("ml429-auth") + if IsAuthAvailableForModel(gotAfterMark, "m1", baseNow.Add(2*time.Minute)) || IsAuthAvailableForModel(gotAfterMark, "", baseNow.Add(2*time.Minute)) { + t.Fatalf("ordinary model-less 429 cleared active credential-scoped force cooldown: auth=%+v", gotAfterMark) + } + + mgr.SetConfig(cfg) + gotAfterReload, _ := mgr.GetByID("ml429-auth") + if IsAuthAvailableForModel(gotAfterReload, "m1", baseNow.Add(2*time.Minute)) || IsAuthAvailableForModel(gotAfterReload, "", baseNow.Add(2*time.Minute)) { + t.Fatalf("SetConfig after ordinary model-less 429 cleared credential-scoped force cooldown: auth=%+v", gotAfterReload) + } + + mgr.PersistCooldownStates(ctx) + mgr2 := NewManager(nil, &RoundRobinSelector{}, nil) + mgr2.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + mgr2.SetConfig(cfg) + if _, errReg := mgr2.Register(WithSkipPersist(ctx), &Auth{ + ID: "ml429-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register mgr2: %v", errReg) + } + if errRestore := mgr2.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + gotRestored, _ := mgr2.GetByID("ml429-auth") + if IsAuthAvailableForModel(gotRestored, "m1", baseNow.Add(2*time.Minute)) || IsAuthAvailableForModel(gotRestored, "", baseNow.Add(2*time.Minute)) { + t.Fatalf("restored auth lost credential-scoped force cooldown after ordinary model-less 429: auth=%+v", gotRestored) + } + }) + + t.Run("coexisting-credential-and-auth-force-cooldowns-preserve-longer-deadline-across-reload-and-disk", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-dual-force" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + cdsPath := t.TempDir() + "/dual-force.cds" + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + mgr.SetConfig(cfg) + for _, id := range []string{"dual-short-cred-long-auth", "dual-long-cred-short-auth"} { + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: id, Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register %s: %v", id, errReg) + } + } + + baseNow := time.Now() + twoMin := 2 * time.Minute + tenMin := 10 * time.Minute + + // Order A: 2m credential-scoped force 429, then 10m model-less force 503. + mgr.MarkResult(ctx, Result{ + AuthID: "dual-short-cred-long-auth", Provider: providerKey, Model: "m1", CredentialScope: true, RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "2m cred force"}, + }) + mgr.MarkResult(ctx, Result{ + AuthID: "dual-short-cred-long-auth", Provider: providerKey, RetryAfter: &tenMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "10m auth force"}, + }) + + // Order B: 10m credential-scoped force 429, then 2m model-less force 429. + mgr.MarkResult(ctx, Result{ + AuthID: "dual-long-cred-short-auth", Provider: providerKey, Model: "m1", CredentialScope: true, RetryAfter: &tenMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "10m cred force"}, + }) + mgr.MarkResult(ctx, Result{ + AuthID: "dual-long-cred-short-auth", Provider: providerKey, RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "2m auth force"}, + }) + + mgr.SetConfig(cfg) + for _, id := range []string{"dual-short-cred-long-auth", "dual-long-cred-short-auth"} { + got, _ := mgr.GetByID(id) + if IsAuthAvailableForModel(got, "", baseNow.Add(5*time.Minute)) { + t.Fatalf("%s truncated longer 10m force deadline on SetConfig: NextRetryAfter=%v", id, got.NextRetryAfter) + } + } + if gotLongCred, _ := mgr.GetByID("dual-long-cred-short-auth"); IsAuthAvailableForModel(gotLongCred, "m1", baseNow.Add(5*time.Minute)) { + t.Fatalf("dual-long-cred-short-auth lost 10m model wrap on SetConfig: %+v", gotLongCred) + } + + mgr.PersistCooldownStates(ctx) + mgr2 := NewManager(nil, &RoundRobinSelector{}, nil) + mgr2.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + mgr2.SetConfig(cfg) + for _, id := range []string{"dual-short-cred-long-auth", "dual-long-cred-short-auth"} { + if _, errReg := mgr2.Register(WithSkipPersist(ctx), &Auth{ + ID: id, Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register mgr2 %s: %v", id, errReg) + } + } + if errRestore := mgr2.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + mgr2.SetConfig(cfg) + for _, id := range []string{"dual-short-cred-long-auth", "dual-long-cred-short-auth"} { + got, _ := mgr2.GetByID(id) + if IsAuthAvailableForModel(got, "", baseNow.Add(5*time.Minute)) { + t.Fatalf("%s lost longer 10m force deadline across disk persistence + SetConfig: NextRetryAfter=%v", id, got.NextRetryAfter) + } + } + if gotLongCred2, _ := mgr2.GetByID("dual-long-cred-short-auth"); IsAuthAvailableForModel(gotLongCred2, "m1", baseNow.Add(5*time.Minute)) { + t.Fatalf("dual-long-cred-short-auth lost 10m model wrap across disk persistence + SetConfig: %+v", gotLongCred2) + } + }) + + t.Run("concurrent-restore-during-update-save-preserves-force-provenance-across-reload", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-update-save" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + saveEntered := make(chan struct{}) + saveRelease := make(chan struct{}) + var saveOnce sync.Once + authStore := &blockingSelectiveAuthStore{ + onSave: func(a *Auth) { + if a != nil && a.ID == "save-race-auth" { + saveOnce.Do(func() { + close(saveEntered) + <-saveRelease + }) + } + }, + } + baseNow := time.Now() + tenMinUntil := baseNow.Add(10 * time.Minute) + cdsStore := &recordingCooldownStateStore{ + load: []CooldownStateRecord{{ + Provider: providerKey, + AuthID: "save-race-auth", + Status: "cooling", + NextRetryAfter: tenMinUntil, + Reason: ErrorCodeForceCooldown, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "restored 10m force"}, + UpdatedAt: baseNow, + ForceCooldownUntil: tenMinUntil, + ForceCooldownEvaluated: true, + }}, + } + + mgr := NewManager(authStore, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(cdsStore) + mgr.SetConfig(cfg) + initial, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "save-race-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + Metadata: map[string]any{"rev": "1"}, + }) + if errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + upd := initial.Clone() + upd.Metadata["rev"] = "2" + updateDone := make(chan error, 1) + go func() { + _, errUpd := mgr.Update(ctx, upd) + updateDone <- errUpd + }() + <-saveEntered + + if errRestore := mgr.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates during Update save: %v", errRestore) + } + close(saveRelease) + if errUpd := <-updateDone; errUpd != nil { + t.Fatalf("Update: %v", errUpd) + } + + // Reload config: restored 10m force provenance must have survived mergeAuthSaveDelta. + mgr.SetConfig(cfg) + got, _ := mgr.GetByID("save-race-auth") + if IsAuthAvailableForModel(got, "", baseNow.Add(5*time.Minute)) { + t.Fatalf("RestoreCooldownStates force provenance lost during concurrent Update Store.Save + SetConfig: %+v", got) + } + }) + + t.Run("modelless-force-cooldown-survives-ordinary-model-error-reload-and-restore", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-agg-force" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + cdsPath := t.TempDir() + "/agg-force.cds" + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + mgr.SetConfig(cfg) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "agg-force-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + baseNow := time.Now() + tenMin := 10 * time.Minute + mgr.MarkResult(ctx, Result{ + AuthID: "agg-force-auth", Provider: providerKey, RetryAfter: &tenMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "10m auth force"}, + }) + gotBeforeModelErr, _ := mgr.GetByID("agg-force-auth") + wantDeadline := gotBeforeModelErr.NextRetryAfter + + // Subsequent ordinary model-level 500 under disable-cooling must not clear auth-level force cooldown. + mgr.MarkResult(ctx, Result{ + AuthID: "agg-force-auth", Provider: providerKey, Model: "m1", + Error: &Error{Code: "upstream_500", HTTPStatus: http.StatusInternalServerError, Message: "ordinary 500"}, + }) + gotAfterModelErr, _ := mgr.GetByID("agg-force-auth") + if IsAuthAvailableForModel(gotAfterModelErr, "", baseNow.Add(5*time.Minute)) || + IsAuthAvailableForModel(gotAfterModelErr, "m1", baseNow.Add(5*time.Minute)) || + !gotAfterModelErr.NextRetryAfter.Equal(wantDeadline) { + t.Fatalf("ordinary model 500 wiped/altered 10m auth-level force cooldown: got=%v want=%v unavailable=%v", gotAfterModelErr.NextRetryAfter, wantDeadline, gotAfterModelErr.Unavailable) + } + + mgr.SetConfig(cfg) + gotAfterReload, _ := mgr.GetByID("agg-force-auth") + if IsAuthAvailableForModel(gotAfterReload, "", baseNow.Add(5*time.Minute)) || + IsAuthAvailableForModel(gotAfterReload, "m1", baseNow.Add(5*time.Minute)) || + !gotAfterReload.NextRetryAfter.Equal(wantDeadline) { + t.Fatalf("SetConfig after ordinary model 500 lost 10m auth-level force cooldown: got=%v want=%v", gotAfterReload.NextRetryAfter, wantDeadline) + } + + mgr.PersistCooldownStates(ctx) + mgr2 := NewManager(nil, &RoundRobinSelector{}, nil) + mgr2.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + mgr2.SetConfig(cfg) + if _, errReg := mgr2.Register(WithSkipPersist(ctx), &Auth{ + ID: "agg-force-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register mgr2: %v", errReg) + } + if errRestore := mgr2.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + gotRestored, _ := mgr2.GetByID("agg-force-auth") + if IsAuthAvailableForModel(gotRestored, "", baseNow.Add(5*time.Minute)) || + IsAuthAvailableForModel(gotRestored, "m1", baseNow.Add(5*time.Minute)) || + !gotRestored.NextRetryAfter.Equal(wantDeadline) { + t.Fatalf("restored auth lost 10m auth-level force cooldown: got=%v want=%v", gotRestored.NextRetryAfter, wantDeadline) + } + }) + + t.Run("forget-auth-shrinks-large-dynamic-pool-backing-array-with-inflight-reservation", func(t *testing.T) { + sel := &WeightedRoundRobinSelector{} + const route = "openai-compatible-shrink:model-s" + hugePool := make([]*Auth, 5000) + for i := range hugePool { + hugePool[i] = &Auth{ + ID: fmt.Sprintf("shrink-auth-%04d", i), + Provider: "openai-compatible-shrink", + Status: StatusActive, + Attributes: map[string]string{"weight": "1"}, + } + } + + // Hold an in-flight reservation on the retained 1030 prefix while seeding 5000 members. + _, seedRes := sel.reserve(route, hugePool, "") + seedRes.finish(true) + _, inFlightRes := sel.reserve(route, hugePool[:1030], "") + if inFlightRes == nil { + t.Fatal("expected in-flight reservation on retained 1030 subset") + } + + // Permanently remove 3970 credentials so 1030 (> 1024) remain. + for i := 1030; i < len(hugePool); i++ { + sel.ForgetAuth(hugePool[i].ID) + } + + sel.mu.Lock() + state := sel.largeStates[route] + gotLen := len(state.members) + gotCap := cap(state.members) + sel.mu.Unlock() + if gotLen != 1030 || gotCap > 2060 { + t.Fatalf("ForgetAuth left oversized backing array after shrinking 5000->1030: len=%d cap=%d (want len=1030, cap<=2060)", gotLen, gotCap) + } + + inFlightRes.finish(false) + sel.mu.Lock() + for _, m := range state.members { + if m.pending != 0 || m.inFlight != 0 { + sel.mu.Unlock() + t.Fatalf("member %s has leaked pending=%d inFlight=%d after rollback", m.id, m.pending, m.inFlight) + } + } + sel.mu.Unlock() + }) + + t.Run("ordinary-credential-quota-plus-longer-auth-force-preserves-auth-force-across-disk-restore", func(t *testing.T) { + cdsPath := t.TempDir() + "/ord-cred-long-force.cds" + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "ord-cred-force-auth", Provider: "xai", Status: StatusActive, + }); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + baseNow := time.Now() + twoMin := 2 * time.Minute + tenMin := 10 * time.Minute + // 1. Ordinary 2m credential-scoped 429 on m1 (CredQuotaForceCooldownUntil == zero). + mgr.MarkResult(ctx, Result{ + AuthID: "ord-cred-force-auth", Provider: "xai", Model: "m1", CredentialScope: true, RetryAfter: &twoMin, + Error: &Error{Code: "rate_limited", HTTPStatus: http.StatusTooManyRequests, Message: "ordinary 2m cred quota"}, + }) + // 2. Independent 10m model-less force 503 (ForceCooldownUntil == +10m). + mgr.MarkResult(ctx, Result{ + AuthID: "ord-cred-force-auth", Provider: "xai", RetryAfter: &tenMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "10m auth force"}, + }) + mgr.PersistCooldownStates(ctx) + + mgr2 := NewManager(nil, &RoundRobinSelector{}, nil) + mgr2.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + if _, errReg := mgr2.Register(WithSkipPersist(ctx), &Auth{ + ID: "ord-cred-force-auth", Provider: "xai", Status: StatusActive, + }); errReg != nil { + t.Fatalf("Register mgr2: %v", errReg) + } + if errRestore := mgr2.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + + // At +3m: 2m ordinary credential_quota has expired, but 10m independent auth force must still block m1 and "". + got, _ := mgr2.GetByID("ord-cred-force-auth") + if IsAuthAvailableForModel(got, "m1", baseNow.Add(3*time.Minute)) || IsAuthAvailableForModel(got, "", baseNow.Add(3*time.Minute)) { + t.Fatalf("restored auth lost 10m independent auth force after 2m ordinary credential_quota expired: %+v", got) + } + }) + + t.Run("devin-quota-restoration-preserves-independent-modelless-force-cooldown", func(t *testing.T) { + now := time.Now() + existing := &Auth{ + ID: "devin-dual-auth", + Provider: "devin", + Status: StatusError, + Unavailable: true, + UpdatedAt: now, + NextRetryAfter: now.Add(10 * time.Minute), + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "10m force 503"}, + StatusMessage: "transient upstream error", + Quota: QuotaState{ + Exceeded: true, + Reason: "credential_quota", + NextRecoverAt: now.Add(2 * time.Minute), + ObservedAt: now.Add(-time.Minute), + }, + forceCooldownUntil: now.Add(10 * time.Minute), + credQuotaForceUntil: now.Add(2 * time.Minute), + forceCooldownSeeded: true, + ModelStates: map[string]*ModelState{ + "devin-m1": { + Status: StatusError, + Unavailable: true, + NextRetryAfter: now.Add(2 * time.Minute), + Quota: QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: now.Add(2 * time.Minute)}, + credentialQuotaPropagated: true, + }, + }, + } + refreshed := existing.Clone() + refreshed.Quota.ObservedAt = now.Add(time.Second) + refreshed.Quota.Signals = map[string]string{ + "daily_quota_remaining_percent": "80", + "weekly_quota_remaining_percent": "90", + } + + evalNow := now.Add(2 * time.Second) + if !applyDevinQuotaRestoration(refreshed, existing, evalNow) { + t.Fatal("expected applyDevinQuotaRestoration to return true") + } + if IsAuthAvailableForModel(refreshed, "devin-m1", now.Add(5*time.Minute)) || + IsAuthAvailableForModel(refreshed, "", now.Add(5*time.Minute)) { + t.Fatalf("applyDevinQuotaRestoration wiped unrelated 10m independent auth force cooldown: %+v", refreshed) + } + }) + + t.Run("long-ordinary-credential-cooldown-plus-short-auth-force-clears-ordinary-tail-on-disable-cooling-reload", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-long-ord-short-force" + disableCoolingFalse := false + disableCoolingTrue := true + cfgCoolOn := &internalconfig.Config{ + DisableCooling: false, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingFalse, + }}, + } + cfgCoolOff := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + + cdsPath := t.TempDir() + "/long-ord-short-force.cds" + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + mgr.SetConfig(cfgCoolOn) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "reverse-dual-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + baseNow := time.Now() + twentyMin := 20 * time.Minute + twoMin := 2 * time.Minute + + // 1. Ordinary 20m credential-scoped 429 while cooling is enabled. + mgr.MarkResult(ctx, Result{ + AuthID: "reverse-dual-auth", Provider: providerKey, Model: "m1", CredentialScope: true, RetryAfter: &twentyMin, + Error: &Error{Code: "rate_limited", HTTPStatus: http.StatusTooManyRequests, Message: "ordinary 20m cred 429"}, + }) + // 2. Independent 2m model-less force 503. + mgr.MarkResult(ctx, Result{ + AuthID: "reverse-dual-auth", Provider: providerKey, RetryAfter: &twoMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusServiceUnavailable, Message: "2m auth force 503"}, + }) + mgr.PersistCooldownStates(ctx) + + // 3. Reload with disable-cooling: true: 2m force must stay active at +1m, 20m ordinary tail must clear by +3m. + mgr.SetConfig(cfgCoolOff) + gotReload, _ := mgr.GetByID("reverse-dual-auth") + if IsAuthAvailableForModel(gotReload, "m1", baseNow.Add(time.Minute)) || IsAuthAvailableForModel(gotReload, "", baseNow.Add(time.Minute)) { + t.Fatalf("2m auth force cooldown prematurely cleared at +1m: %+v", gotReload) + } + if !IsAuthAvailableForModel(gotReload, "m1", baseNow.Add(3*time.Minute)) || !IsAuthAvailableForModel(gotReload, "", baseNow.Add(3*time.Minute)) { + t.Fatalf("20m ordinary credential cooldown survived disable-cooling reload past 2m force window (+3m): NextRetryAfter=%v Quota=%+v", gotReload.NextRetryAfter, gotReload.Quota) + } + + // 4. Also verify restoring pre-reload .cds directly into a disable-cooling: true manager clamps to 2m. + mgr2 := NewManager(nil, &RoundRobinSelector{}, nil) + mgr2.SetCooldownStateStore(NewFileCooldownStateStore(cdsPath)) + mgr2.SetConfig(cfgCoolOff) + if _, errReg := mgr2.Register(WithSkipPersist(ctx), &Auth{ + ID: "reverse-dual-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register mgr2: %v", errReg) + } + if errRestore := mgr2.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + gotRestored, _ := mgr2.GetByID("reverse-dual-auth") + if IsAuthAvailableForModel(gotRestored, "m1", baseNow.Add(time.Minute)) || IsAuthAvailableForModel(gotRestored, "", baseNow.Add(time.Minute)) { + t.Fatalf("restored 2m auth force cooldown prematurely cleared at +1m: %+v", gotRestored) + } + if !IsAuthAvailableForModel(gotRestored, "m1", baseNow.Add(3*time.Minute)) || !IsAuthAvailableForModel(gotRestored, "", baseNow.Add(3*time.Minute)) { + t.Fatalf("restored 20m ordinary credential cooldown survived disable-cooling restore past 2m force window (+3m): NextRetryAfter=%v Quota=%+v", gotRestored.NextRetryAfter, gotRestored.Quota) + } + }) + + t.Run("delayed-store-restore-preserves-longer-persisted-independent-shadow-force-deadline", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-delayed-shadow" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + baseNow := time.Now() + twoMinUntil := baseNow.Add(2 * time.Minute) + tenMinUntil := baseNow.Add(10 * time.Minute) + + loadEntered := make(chan struct{}) + loadRelease := make(chan struct{}) + slowStore := &issue7431BlockingLoadCooldownStore{ + records: []CooldownStateRecord{ + { + Provider: providerKey, + AuthID: "delayed-shadow-auth", + Status: "cooling", + NextRetryAfter: twoMinUntil, + Reason: "credential_quota", + Quota: QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: twoMinUntil}, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 429, Message: "2m cred force"}, + UpdatedAt: baseNow.Add(-time.Minute), + CredQuotaForceCooldownUntil: twoMinUntil, + ForceCooldownEvaluated: true, + }, + { + Provider: providerKey, + AuthID: "delayed-shadow-auth", + Model: "m1", + Status: "cooling", + NextRetryAfter: tenMinUntil, + Reason: "credential_quota", + Quota: QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: twoMinUntil}, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 429, Message: "2m cred force"}, + UpdatedAt: baseNow.Add(-time.Minute), + CredentialQuotaPropagated: true, + IndependentState: &ModelState{ + Status: StatusError, + Unavailable: true, + NextRetryAfter: tenMinUntil, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "older 10m model force"}, + UpdatedAt: baseNow.Add(-2 * time.Minute), + }, + ForceCooldownUntil: twoMinUntil, + IndependentForceCooldownUntil: tenMinUntil, + ForceCooldownEvaluated: true, + }, + }, + entered: loadEntered, + release: loadRelease, + } + + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(slowStore) + mgr.SetConfig(cfg) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "delayed-shadow-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + restoreDone := make(chan error, 1) + go func() { + restoreDone <- mgr.RestoreCooldownStates(ctx) + }() + <-loadEntered + + // Newer 3m model force arrives while store.Load is blocked. + threeMin := 3 * time.Minute + mgr.MarkResult(ctx, Result{ + AuthID: "delayed-shadow-auth", Provider: providerKey, Model: "m1", RetryAfter: &threeMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "newer 3m model force"}, + }) + close(loadRelease) + if errRestore := <-restoreDone; errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + + mgr.SetConfig(cfg) + got, _ := mgr.GetByID("delayed-shadow-auth") + if IsAuthAvailableForModel(got, "m1", baseNow.Add(5*time.Minute)) { + t.Fatalf("delayed RestoreCooldownStates truncated 10m persisted independent shadow force deadline to %v", got.ModelStates["m1"].NextRetryAfter) + } + + recStore := &recordingCooldownStateStore{} + mgr.SetCooldownStateStore(recStore) + mgr.PersistCooldownStates(ctx) + foundTenMin := false + for _, rec := range recStore.savedRecords() { + if rec.Model == "m1" && rec.NextRetryAfter.Equal(tenMinUntil) && rec.IndependentForceCooldownUntil.Equal(tenMinUntil) { + foundTenMin = true + } + } + if !foundTenMin { + t.Fatalf("re-persisted records lost 10m independent force deadline: %+v", recStore.savedRecords()) + } + }) + + t.Run("delayed-restore-with-stale-model-and-auth-records-preserves-newer-credential-force-cooldown", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-stale-model-auth" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + baseNow := time.Now() + twoMinUntil := baseNow.Add(2 * time.Minute) + threeMinUntil := baseNow.Add(3 * time.Minute) + + loadEntered := make(chan struct{}) + loadRelease := make(chan struct{}) + slowStore := &issue7431BlockingLoadCooldownStore{ + records: []CooldownStateRecord{ + { + Provider: providerKey, + AuthID: "stale-combo-auth", + Model: "m-stale", + Status: "cooling", + NextRetryAfter: twoMinUntil, + Reason: ErrorCodeForceCooldown, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "older 2m model force"}, + UpdatedAt: baseNow.Add(-2 * time.Minute), + ForceCooldownUntil: twoMinUntil, + ForceCooldownEvaluated: true, + }, + { + Provider: providerKey, + AuthID: "stale-combo-auth", + Status: "cooling", + NextRetryAfter: threeMinUntil, + Reason: "quota", + Quota: QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: threeMinUntil}, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 429, Message: "older 3m auth force 429"}, + UpdatedAt: baseNow.Add(-time.Minute), + ForceCooldownUntil: threeMinUntil, + ForceCooldownEvaluated: true, + }, + }, + entered: loadEntered, + release: loadRelease, + } + + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(slowStore) + mgr.SetConfig(cfg) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "stale-combo-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + + restoreDone := make(chan error, 1) + go func() { + restoreDone <- mgr.RestoreCooldownStates(ctx) + }() + <-loadEntered + + // Newer 10m credential-scoped force 429 arrives while store.Load is blocked. + tenMin := 10 * time.Minute + mgr.MarkResult(ctx, Result{ + AuthID: "stale-combo-auth", Provider: providerKey, Model: "m-live", CredentialScope: true, RetryAfter: &tenMin, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "newer 10m cred force 429"}, + }) + close(loadRelease) + if errRestore := <-restoreDone; errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + + mgr.SetConfig(cfg) + got, _ := mgr.GetByID("stale-combo-auth") + if IsAuthAvailableForModel(got, "m-live", baseNow.Add(5*time.Minute)) || + IsAuthAvailableForModel(got, "m-other", baseNow.Add(5*time.Minute)) || + IsAuthAvailableForModel(got, "", baseNow.Add(5*time.Minute)) { + t.Fatalf("delayed RestoreCooldownStates shortened newer 10m credential-scoped force cooldown: NextRetryAfter=%v Quota=%+v", got.NextRetryAfter, got.Quota) + } + }) + + t.Run("cooldown-state-record-equal-detects-cred-quota-force-cooldown-until-change", func(t *testing.T) { + now := time.Now().Round(0) + recA := CooldownStateRecord{ + Provider: "xai", + AuthID: "eq-auth", + Status: "cooling", + NextRetryAfter: now.Add(10 * time.Minute), + Reason: "credential_quota", + Quota: QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: now.Add(10 * time.Minute)}, + UpdatedAt: now, + ForceCooldownEvaluated: true, + CredQuotaForceCooldownUntil: time.Time{}, + } + recB := recA + recB.CredQuotaForceCooldownUntil = now.Add(10 * time.Minute) + if cooldownStateRecordEqual(recA, recB) { + t.Fatal("cooldownStateRecordEqual ignored CredQuotaForceCooldownUntil difference") + } + }) + + t.Run("legacy-dual-model-and-aggregated-auth-force-records-do-not-block-healthy-sibling-model", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-legacy-agg" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + baseNow := time.Now() + tenMinUntil := baseNow.Add(10 * time.Minute) + forceErr := &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "model-a force 503"} + + // Legacy store snapshot (ForceCooldownEvaluated == false): + // 1) legacy-dual-auth: model-a failed with force 503 AND old code persisted an aggregated Model=="" record. + // 2) legacy-global-auth: genuine model-less force 503 (only Model=="" record). + legacyStore := &recordingCooldownStateStore{ + load: []CooldownStateRecord{ + { + Provider: providerKey, + AuthID: "legacy-dual-auth", + Model: "model-a", + Status: "cooling", + NextRetryAfter: tenMinUntil, + Reason: ErrorCodeForceCooldown, + LastError: cloneError(forceErr), + UpdatedAt: baseNow, + }, + { + Provider: providerKey, + AuthID: "legacy-dual-auth", + Status: "cooling", + NextRetryAfter: tenMinUntil, + Reason: ErrorCodeForceCooldown, + LastError: cloneError(forceErr), + UpdatedAt: baseNow, + }, + { + Provider: providerKey, + AuthID: "legacy-global-auth", + Status: "cooling", + NextRetryAfter: tenMinUntil, + Reason: ErrorCodeForceCooldown, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "global force 503"}, + UpdatedAt: baseNow, + }, + }, + } + + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(legacyStore) + mgr.SetConfig(cfg) + for _, id := range []string{"legacy-dual-auth", "legacy-global-auth"} { + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: id, Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register %s: %v", id, errReg) + } + } + if errRestore := mgr.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + + gotDual, _ := mgr.GetByID("legacy-dual-auth") + if IsAuthAvailableForModel(gotDual, "model-a", baseNow.Add(2*time.Minute)) { + t.Fatal("expected legacy model-a force cooldown to stay blocked") + } + if !IsAuthAvailableForModel(gotDual, "model-b", baseNow.Add(2*time.Minute)) { + t.Fatalf("legacy aggregated auth record falsely promoted model-a force cooldown to block sibling model-b: %+v", gotDual) + } + // Subsequent success on model-a must clear the credential completely. + mgr.MarkResult(ctx, Result{AuthID: "legacy-dual-auth", Provider: providerKey, Model: "model-a", Success: true}) + gotDualAfterSuccess, _ := mgr.GetByID("legacy-dual-auth") + if !IsAuthAvailableForModel(gotDualAfterSuccess, "model-a", baseNow.Add(2*time.Minute)) || + !IsAuthAvailableForModel(gotDualAfterSuccess, "", baseNow.Add(2*time.Minute)) { + t.Fatalf("model-a success failed to clear legacy-dual-auth: %+v", gotDualAfterSuccess) + } + + // Genuine legacy model-less force record must still block all models. + gotGlobal, _ := mgr.GetByID("legacy-global-auth") + if IsAuthAvailableForModel(gotGlobal, "model-b", baseNow.Add(2*time.Minute)) || + IsAuthAvailableForModel(gotGlobal, "", baseNow.Add(2*time.Minute)) { + t.Fatalf("expected genuine legacy model-less force cooldown to remain blocked: %+v", gotGlobal) + } + }) + + t.Run("legacy-longer-model-force-plus-shorter-independent-auth-force-preserves-auth-block-for-sibling-models", func(t *testing.T) { + const providerKey = "openai-compatible-issue-7431-legacy-coexist" + disableCoolingTrue := true + cfg := &internalconfig.Config{ + DisableCooling: true, + OpenAICompatibility: []internalconfig.OpenAICompatibility{{ + Name: providerKey, + BaseURL: "https://example.invalid/v1", + DisableCooling: &disableCoolingTrue, + }}, + } + baseNow := time.Now() + thirtyMinUntil := baseNow.Add(30 * time.Minute) + tenMinUntil := baseNow.Add(10 * time.Minute) + + legacyStore := &recordingCooldownStateStore{ + load: []CooldownStateRecord{ + { + Provider: providerKey, + AuthID: "legacy-coexist-auth", + Model: "model-a", + Status: "cooling", + NextRetryAfter: thirtyMinUntil, + Reason: ErrorCodeForceCooldown, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "30m model-a force"}, + UpdatedAt: baseNow.Add(-2 * time.Minute), + }, + { + Provider: providerKey, + AuthID: "legacy-coexist-auth", + Status: "cooling", + NextRetryAfter: tenMinUntil, + Reason: ErrorCodeForceCooldown, + LastError: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: 503, Message: "10m auth force"}, + UpdatedAt: baseNow.Add(-time.Minute), + }, + }, + } + + mgr := NewManager(nil, &RoundRobinSelector{}, nil) + mgr.SetCooldownStateStore(legacyStore) + mgr.SetConfig(cfg) + if _, errReg := mgr.Register(WithSkipPersist(ctx), &Auth{ + ID: "legacy-coexist-auth", Provider: providerKey, Status: StatusActive, + Attributes: map[string]string{"provider_key": providerKey}, + }); errReg != nil { + t.Fatalf("Register: %v", errReg) + } + if errRestore := mgr.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + mgr.SetConfig(cfg) + + got, _ := mgr.GetByID("legacy-coexist-auth") + if IsAuthAvailableForModel(got, "model-b", baseNow.Add(5*time.Minute)) { + t.Fatalf("expected 10m legacy independent auth force to block healthy model-b at +5m: %+v", got) + } + if !IsAuthAvailableForModel(got, "model-b", baseNow.Add(15*time.Minute)) { + t.Fatalf("expected model-b to recover once 10m auth force expired at +15m: %+v", got) + } + if IsAuthAvailableForModel(got, "model-a", baseNow.Add(15*time.Minute)) { + t.Fatalf("expected model-a 30m force cooldown to stay blocked at +15m: %+v", got.ModelStates["model-a"]) + } + }) +} + +type issue7431BlockingLoadCooldownStore struct { + records []CooldownStateRecord + entered chan struct{} + release chan struct{} + once sync.Once +} + +func (s *issue7431BlockingLoadCooldownStore) Load(context.Context) ([]CooldownStateRecord, error) { + s.once.Do(func() { + close(s.entered) + <-s.release + }) + return cloneCooldownStateRecords(s.records), nil +} + +func (s *issue7431BlockingLoadCooldownStore) Save(context.Context, []CooldownStateRecord) error { + return nil +} diff --git a/sdk/cliproxy/auth/issue_7508_cooldown_test.go b/sdk/cliproxy/auth/issue_7508_cooldown_test.go new file mode 100644 index 00000000000..a63f187d812 --- /dev/null +++ b/sdk/cliproxy/auth/issue_7508_cooldown_test.go @@ -0,0 +1,371 @@ +package auth + +import ( + "context" + "net/http" + "testing" + "time" + + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" +) + +func TestMarkResult_ForceCredentialQuotaDoesNotInheritOrdinaryLongCooldown(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + m := NewManager(nil, nil, nil) + ctx := context.Background() + cred := &Auth{ + ID: "auth-force-vs-ordinary-429", + Provider: "meta", + Status: StatusActive, + } + if _, errReg := m.Register(ctx, cred); errReg != nil { + t.Fatalf("Register(): %v", errReg) + } + + // 1. Record an ordinary 1h credential-scoped 429. + ordinaryRetry := time.Hour + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + RetryAfter: &ordinaryRetry, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "ordinary 1h quota"}, + }) + + // 2. Record a 1m stop-and-cooldown (ErrorCodeForceCooldown) 429 on top of it. + beforeForce := time.Now() + forceRetry := time.Minute + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + RetryAfter: &forceRetry, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force 1m quota"}, + }) + + mid, _ := m.GetByID(cred.ID) + if mid == nil || mid.credQuotaForceUntil.After(beforeForce.Add(2*time.Minute)) { + t.Fatalf("credQuotaForceUntil inherited ordinary 1h cooldown: %v", mid.credQuotaForceUntil) + } + + // 3. Toggling disable-cooling must clear the ordinary 1h window and clamp down to the ~1m force deadline. + m.SetConfig(&internalconfig.Config{DisableCooling: true}) + afterDisable, _ := m.GetByID(cred.ID) + if afterDisable == nil { + t.Fatal("credential missing after SetConfig") + } + if afterDisable.Quota.NextRecoverAt.After(beforeForce.Add(2*time.Minute)) || afterDisable.NextRetryAfter.After(beforeForce.Add(2*time.Minute)) { + t.Fatalf("disable-cooling failed to clamp ordinary 1h window down to 1m force deadline: quota=%+v nextRetry=%v", + afterDisable.Quota, afterDisable.NextRetryAfter) + } + if !afterDisable.Quota.Exceeded || !afterDisable.Quota.NextRecoverAt.After(beforeForce.Add(30*time.Second)) { + t.Fatalf("expected 1m force quota deadline to remain active, got quota=%+v", afterDisable.Quota) + } +} + +func TestMarkResult_Non429CredentialScopeBlocksStatelessAndStatefulModels(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + m := NewManager(nil, nil, nil) + ctx := context.Background() + cred := &Auth{ + ID: "auth-non429-cred-scope", + Provider: "meta", + Status: StatusActive, + } + registry.GetGlobalRegistry().RegisterClient(cred.ID, "meta", []*registry.ModelInfo{ + {ID: "model-a"}, + {ID: "model-b"}, + }) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(cred.ID) + }) + if _, errReg := m.Register(ctx, cred); errReg != nil { + t.Fatalf("Register(): %v", errReg) + } + + // Create ModelStates entry for model-a only, leaving model-b stateless. + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Model: "model-a", + Success: true, + CompletedResponse: true, + }) + + retry := 2 * time.Minute + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + RetryAfter: &retry, + Error: &Error{HTTPStatus: http.StatusServiceUnavailable, Message: "upstream 503"}, + }) + + snap, _ := m.GetByID(cred.ID) + now := time.Now() + if IsAuthAvailableForModel(snap, "model-a", now) { + t.Fatalf("expected model-a (with ModelState) to be blocked") + } + if IsAuthAvailableForModel(snap, "model-b", now) { + t.Fatalf("expected model-b (without ModelState) to be blocked") + } + + // Toggling disable-cooling clears non-force credentialRetryAfter. + m.SetConfig(&internalconfig.Config{DisableCooling: true}) + cleared, _ := m.GetByID(cred.ID) + if !IsAuthAvailableForModel(cleared, "model-a", now) || !IsAuthAvailableForModel(cleared, "model-b", now) { + t.Fatalf("expected disable-cooling to clear ordinary credentialRetryAfter: %+v", cleared) + } +} + +func TestMarkResult_Non429CredentialScopeDoesNotInheritModelLongCooldown(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + m := NewManager(nil, nil, nil) + ctx := context.Background() + cred := &Auth{ + ID: "auth-model-long-vs-cred-short-503", + Provider: "meta", + Status: StatusActive, + } + if _, errReg := m.Register(ctx, cred); errReg != nil { + t.Fatalf("Register(): %v", errReg) + } + + // 1. model-a suffers a 1h model-level 429 (aggregating auth.NextRetryAfter to 1h). + longRetry := time.Hour + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Model: "model-a", + Success: false, + RetryAfter: &longRetry, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "model-a 1h quota"}, + }) + + // 2. Credential-scoped 503 with 1m RetryAfter arrives. + before503 := time.Now() + shortRetry := time.Minute + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + RetryAfter: &shortRetry, + Error: &Error{HTTPStatus: http.StatusServiceUnavailable, Message: "1m 503"}, + }) + + snap, _ := m.GetByID(cred.ID) + if snap == nil { + t.Fatal("credential missing") + } + if snap.credentialRetryAfter.After(before503.Add(2 * time.Minute)) { + t.Fatalf("credentialRetryAfter inherited model-a 1h cooldown: %v", snap.credentialRetryAfter) + } + // At +30s: both model-a and model-b are blocked. + if IsAuthAvailableForModel(snap, "model-a", before503.Add(30*time.Second)) || IsAuthAvailableForModel(snap, "model-b", before503.Add(30*time.Second)) { + t.Fatalf("expected both models blocked at +30s") + } + // At +2m: credential-level 1m 503 has expired so model-b is available, while model-a remains blocked for 1h. + if !IsAuthAvailableForModel(snap, "model-b", before503.Add(2*time.Minute)) { + t.Fatalf("expected model-b available at +2m after 1m 503 expired; snap=%+v", snap) + } + if IsAuthAvailableForModel(snap, "model-a", before503.Add(2*time.Minute)) { + t.Fatalf("expected model-a to remain blocked for 1h at +2m") + } +} + +func TestReconcileDisableCooling_ClearsCredentialRetryAfterInEarlyReturnBranch(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + m := NewManager(nil, nil, nil) + ctx := context.Background() + cred := &Auth{ + ID: "auth-early-return-disable-cooling", + Provider: "meta", + Status: StatusActive, + } + if _, errReg := m.Register(ctx, cred); errReg != nil { + t.Fatalf("Register(): %v", errReg) + } + + // No ModelStates: ordinary 1h 503 sets credentialRetryAfter, followed by 1m force 429 (credQuotaForceUntil). + long503 := time.Hour + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + RetryAfter: &long503, + Error: &Error{HTTPStatus: http.StatusServiceUnavailable, Message: "ordinary 1h 503"}, + }) + beforeForce := time.Now() + shortForce := time.Minute + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + RetryAfter: &shortForce, + Error: &Error{Code: ErrorCodeForceCooldown, HTTPStatus: http.StatusTooManyRequests, Message: "force 1m 429"}, + }) + + // Disable cooling: early-return branch (len(ModelStates) == 0 && keepCredQuotaForce) must clear ordinary credentialRetryAfter. + m.SetConfig(&internalconfig.Config{DisableCooling: true}) + snap, _ := m.GetByID(cred.ID) + if snap == nil { + t.Fatal("credential missing") + } + if !snap.credentialRetryAfter.IsZero() { + t.Fatalf("expected credentialRetryAfter to be cleared by DisableCooling, got %v", snap.credentialRetryAfter) + } + // At +30s: still blocked by 1m force quota. At +2m: force expired, credential must be selectable again. + if IsAuthAvailableForModel(snap, "m1", beforeForce.Add(30*time.Second)) { + t.Fatalf("expected credential blocked by 1m force quota at +30s") + } + if !IsAuthAvailableForModel(snap, "m1", beforeForce.Add(2*time.Minute)) { + t.Fatalf("expected credential available at +2m once 1m force expired, got snap=%+v", snap) + } +} + +func TestCooldownStore_PersistsAndRestoresCredentialRetryAfterWithMixedModelStates(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + cdsDir := t.TempDir() + ctx := context.Background() + + m1 := NewManager(nil, nil, nil) + m1.SetCooldownStateStore(NewFileCooldownStateStore(cdsDir)) + cred1 := &Auth{ID: "auth-cds-mixed-cred-retry", Provider: "meta", Status: StatusActive} + if _, errReg := m1.Register(WithSkipPersist(ctx), cred1); errReg != nil { + t.Fatalf("Register m1: %v", errReg) + } + + // Record a 2m model-a cooldown AND a 10m credential-scoped 503. + before := time.Now() + modelRetry := 2 * time.Minute + m1.MarkResult(ctx, Result{ + AuthID: cred1.ID, + Provider: "meta", + Model: "model-a", + Success: false, + RetryAfter: &modelRetry, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "model-a 2m"}, + }) + credRetry := 10 * time.Minute + m1.MarkResult(ctx, Result{ + AuthID: cred1.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + RetryAfter: &credRetry, + Error: &Error{HTTPStatus: http.StatusServiceUnavailable, Message: "cred 10m 503"}, + }) + m1.PersistCooldownStates(ctx) + + // Restore into a fresh Manager from the persisted .cds file. + m2 := NewManager(nil, nil, nil) + m2.SetCooldownStateStore(NewFileCooldownStateStore(cdsDir)) + cred2 := &Auth{ID: cred1.ID, Provider: "meta", Status: StatusActive} + if _, errReg := m2.Register(WithSkipPersist(ctx), cred2); errReg != nil { + t.Fatalf("Register m2: %v", errReg) + } + if errRestore := m2.RestoreCooldownStates(ctx); errRestore != nil { + t.Fatalf("RestoreCooldownStates: %v", errRestore) + } + + restored, _ := m2.GetByID(cred1.ID) + if restored == nil { + t.Fatal("restored credential missing") + } + // At +5m (after model-a's 2m expired, while 10m credentialRetryAfter is still active): + // both model-a and stateless model-b must remain blocked. + checkAt := before.Add(5 * time.Minute) + if IsAuthAvailableForModel(restored, "model-a", checkAt) { + t.Fatalf("expected model-a to remain blocked at +5m by restored credentialRetryAfter: %+v", restored) + } + if IsAuthAvailableForModel(restored, "model-b", checkAt) { + t.Fatalf("expected model-b to remain blocked at +5m by restored credentialRetryAfter: %+v", restored) + } + if !IsAuthAvailableForModel(restored, "model-a", before.Add(11*time.Minute)) || !IsAuthAvailableForModel(restored, "model-b", before.Add(11*time.Minute)) { + t.Fatalf("expected both models available at +11m after credentialRetryAfter expired") + } +} + +func TestMarkResult_CredentialScoped429DoesNotInheritModelLongCooldown(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + m := NewManager(nil, nil, nil) + ctx := context.Background() + cred := &Auth{ + ID: "auth-model-1h-vs-cred-1m-429", + Provider: "meta", + Status: StatusActive, + } + if _, errReg := m.Register(ctx, cred); errReg != nil { + t.Fatalf("Register(): %v", errReg) + } + + // 1. model-a suffers a 1h model-level 429 (aggregating auth.Quota to 1h with reason "quota"). + longRetry := time.Hour + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Model: "model-a", + Success: false, + RetryAfter: &longRetry, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "model-a 1h quota"}, + }) + + // 2. Credential-scoped 429 with 1m RetryAfter arrives. + before429 := time.Now() + shortRetry := time.Minute + m.MarkResult(ctx, Result{ + AuthID: cred.ID, + Provider: "meta", + Success: false, + CredentialScope: true, + RetryAfter: &shortRetry, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "cred 1m quota"}, + }) + + snap, _ := m.GetByID(cred.ID) + if snap == nil { + t.Fatal("credential missing") + } + if snap.Quota.Reason != ErrorCodeCredentialQuota { + t.Fatalf("auth.Quota.Reason = %q, want credential_quota", snap.Quota.Reason) + } + if snap.Quota.NextRecoverAt.After(before429.Add(2*time.Minute)) || snap.NextRetryAfter.After(before429.Add(2*time.Minute)) { + t.Fatalf("credential-scoped 429 inherited model-a 1h cooldown: quota=%+v nextRetry=%v", snap.Quota, snap.NextRetryAfter) + } + // At +30s: both model-a and healthy model-b are blocked by the 1m credential_quota. + if IsAuthAvailableForModel(snap, "model-a", before429.Add(30*time.Second)) || IsAuthAvailableForModel(snap, "model-b", before429.Add(30*time.Second)) { + t.Fatalf("expected both models blocked at +30s") + } + // At +2m: 1m credential_quota has expired so healthy model-b is available, while model-a stays blocked for 1h. + if !IsAuthAvailableForModel(snap, "model-b", before429.Add(2*time.Minute)) { + t.Fatalf("expected model-b available at +2m after 1m credential_quota expired; snap=%+v", snap) + } + if IsAuthAvailableForModel(snap, "model-a", before429.Add(2*time.Minute)) { + t.Fatalf("expected model-a to remain blocked for 1h at +2m") + } +} diff --git a/sdk/cliproxy/auth/oauth_model_alias.go b/sdk/cliproxy/auth/oauth_model_alias.go index c9e1af41914..279433cf377 100644 --- a/sdk/cliproxy/auth/oauth_model_alias.go +++ b/sdk/cliproxy/auth/oauth_model_alias.go @@ -89,7 +89,55 @@ func (m *Manager) SetOAuthModelAlias(aliases map[string][]internalconfig.OAuthMo if table == nil { table = &oauthModelAliasTable{} } - m.oauthModelAlias.Store(table) + m.publishOAuthModelAliasAndReconcileStates(nil, table) +} + +type oauthResolvedAliasRoute struct { + aliasKey string + targetKey string +} + +func (m *Manager) configuredOAuthAliasRoutes(auth *Auth) []oauthResolvedAliasRoute { + if m == nil || auth == nil { + return nil + } + channel := modelAliasChannel(auth) + if channel == "" { + return nil + } + seenAliases := make(map[string]struct{}) + var routes []oauthResolvedAliasRoute + addAlias := func(alias string) { + alias = strings.TrimSpace(alias) + if alias == "" { + return + } + aliasLookup := canonicalModelLookupKey(alias) + if aliasLookup == "" { + return + } + if _, exists := seenAliases[aliasLookup]; exists { + return + } + seenAliases[aliasLookup] = struct{}{} + aliasKey := canonicalModelKey(alias) + if targetKey := m.selectionModelKeyForAuth(auth, alias); targetKey != "" && !sameCanonicalModelKey(aliasKey, targetKey) { + routes = append(routes, oauthResolvedAliasRoute{ + aliasKey: aliasKey, + targetKey: targetKey, + }) + } + } + for _, entry := range OAuthModelAliasesFromAttributes(authAttributes(auth)) { + addAlias(entry.Alias) + } + raw := m.oauthModelAlias.Load() + if table, _ := raw.(*oauthModelAliasTable); table != nil && table.reverse != nil { + for _, entry := range table.reverse[channel] { + addAlias(entry.configAlias) + } + } + return routes } // applyOAuthModelAlias resolves the upstream model from OAuth model alias. diff --git a/sdk/cliproxy/auth/quota_signals.go b/sdk/cliproxy/auth/quota_signals.go index fea368e5319..071158c6226 100644 --- a/sdk/cliproxy/auth/quota_signals.go +++ b/sdk/cliproxy/auth/quota_signals.go @@ -1,6 +1,7 @@ package auth import ( + "maps" "net/http" "sort" "strings" @@ -86,6 +87,32 @@ func applyCooldownFields(dst *QuotaState, cooldown QuotaState) { dst.Reason = cooldown.Reason dst.NextRecoverAt = cooldown.NextRecoverAt dst.BackoffLevel = cooldown.BackoffLevel + dst.cooldownSignals = maps.Clone(cooldown.cooldownSignals) + dst.cooldownEvaluated = cooldown.Exceeded || cooldown.cooldownEvaluated +} + +func rejectedClaudeSignalsForCooldown(provider string, headers http.Header) map[string]string { + if !strings.EqualFold(strings.TrimSpace(provider), "claude") { + return nil + } + signals := collectQuotaSignals("claude", headers) + if !hasRejectedClaudeUnifiedSignals(signals) { + return nil + } + return signals +} + +func sanitizePersistedClaudeCooldownSignals(raw map[string]string) map[string]string { + if len(raw) == 0 { + return nil + } + headers := make(http.Header, len(raw)) + for key, val := range raw { + if strings.HasPrefix(strings.ToLower(strings.TrimSpace(key)), "anthropic-ratelimit-unified-") { + headers.Set(key, val) + } + } + return rejectedClaudeSignalsForCooldown("claude", headers) } // collectQuotaSignals builds the bounded snapshot for a single response. diff --git a/sdk/cliproxy/auth/scheduler.go b/sdk/cliproxy/auth/scheduler.go index 752a52d7d57..5e101452d09 100644 --- a/sdk/cliproxy/auth/scheduler.go +++ b/sdk/cliproxy/auth/scheduler.go @@ -45,6 +45,7 @@ type scheduledGenerationMeta struct { type authScheduler struct { mu sync.Mutex strategy schedulerStrategy + weightedSelector *WeightedRoundRobinSelector providers map[string]*providerScheduler authProviders map[string]string authGenerations map[string]scheduledGenerationMeta @@ -115,6 +116,7 @@ type readyBucketCursorState struct { func snapshotReadyViewCursors(view readyView) readyViewCursorState { state := readyViewCursorState{lastPicked: view.lastPicked} + state.weightedState.peak = view.weightedState.peak if len(view.weightedState.current) > 0 { state.weightedState.current = make(map[string]int64, len(view.weightedState.current)) for authID, current := range view.weightedState.current { @@ -135,6 +137,7 @@ func restoreReadyViewCursors(view *readyView, state readyViewCursorState) { return } view.lastPicked = state.lastPicked + view.weightedState.peak = max(state.weightedState.peak, len(view.flat)) weights := scheduledWeightVector(view.flat) if len(state.weightedState.current) == 0 || weightsConfigChanged(state.weightedState.weights, weights) { return @@ -153,8 +156,10 @@ func restoreReadyViewCursors(view *readyView, state readyViewCursorState) { // newAuthScheduler constructs an empty scheduler configured for the supplied selector strategy. func newAuthScheduler(selector Selector) *authScheduler { + weighted := UnwrapWeightedRoundRobinSelector(selector) return &authScheduler{ strategy: selectorStrategy(selector), + weightedSelector: weighted, providers: make(map[string]*providerScheduler), authProviders: make(map[string]string), authGenerations: make(map[string]scheduledGenerationMeta), @@ -185,6 +190,7 @@ func (s *authScheduler) setSelector(selector Selector) { s.mu.Lock() defer s.mu.Unlock() s.strategy = selectorStrategy(selector) + s.weightedSelector = UnwrapWeightedRoundRobinSelector(selector) clear(s.mixedCursors) clear(s.mixedWeightedStates) } @@ -277,10 +283,11 @@ func (s *authScheduler) rebuild(auths []*Auth) { s.mu.Lock() defer s.mu.Unlock() - // Capture existing auth metadata so that in-flight MarkResult updates (which advanced - // Generation and updated cooldown/quota states) are preserved during rebuild. + // Capture existing auth metadata and model-shard cursors so that in-flight MarkResult + // updates and rotation progress for unchanged shards survive rebuilds. existingMetas := make(map[string]*scheduledAuthMeta) - for _, pState := range s.providers { + existingShardCursors := make(map[string]map[string]map[int]readyBucketCursorState, len(s.providers)) + for providerKey, pState := range s.providers { if pState == nil { continue } @@ -289,19 +296,78 @@ func (s *authScheduler) rebuild(auths []*Auth) { existingMetas[id] = meta } } + if len(pState.modelShards) > 0 { + modelCursors := make(map[string]map[int]readyBucketCursorState, len(pState.modelShards)) + for modelKey, shard := range pState.modelShards { + if shard == nil || len(shard.readyByPriority) == 0 { + continue + } + bucketCursors := make(map[int]readyBucketCursorState, len(shard.readyByPriority)) + for priority, bucket := range shard.readyByPriority { + if bucket == nil { + continue + } + bucketCursors[priority] = readyBucketCursorState{ + all: snapshotReadyViewCursors(bucket.all), + ws: snapshotReadyViewCursors(bucket.ws), + } + } + if len(bucketCursors) > 0 { + modelCursors[modelKey] = bucketCursors + } + } + if len(modelCursors) > 0 { + existingShardCursors[providerKey] = modelCursors + } + } } + existingMixedCursors := s.mixedCursors s.providers = make(map[string]*providerScheduler) s.authProviders = make(map[string]string) if s.authGenerations == nil { s.authGenerations = make(map[string]scheduledGenerationMeta) } - s.mixedCursors = make(map[string]int) + s.mixedCursors = make(map[string]int, len(existingMixedCursors)) s.mixedWeightedStates = make(map[string]*smoothWeightedState) now := time.Now() for _, auth := range auths { s.upsertAuthRebuildLocked(auth, existingMetas, now) } + for providerKey, modelCursors := range existingShardCursors { + pState := s.providers[providerKey] + if pState == nil { + continue + } + for modelKey, bucketCursors := range modelCursors { + shard := pState.ensureModelLocked(modelKey, now) + if shard == nil { + continue + } + for priority, cursorState := range bucketCursors { + if bucket := shard.readyByPriority[priority]; bucket != nil { + restoreReadyViewCursors(&bucket.all, cursorState.all) + restoreReadyViewCursors(&bucket.ws, cursorState.ws) + } + } + } + } + for cursorKey, cursor := range existingMixedCursors { + providersPart := cursorKey + if colon := strings.IndexByte(cursorKey, ':'); colon >= 0 { + providersPart = cursorKey[:colon] + } + allPresent := providersPart != "" + for _, providerKey := range strings.Split(providersPart, ",") { + if s.providers[providerKey] == nil { + allPresent = false + break + } + } + if allPresent { + s.mixedCursors[cursorKey] = cursor + } + } } // upsertAuth incrementally synchronizes one auth into the scheduler (lifecycle/update). @@ -403,7 +469,7 @@ func (s *authScheduler) pickSingleWithStrategy(ctx context.Context, provider, mo return nil, &Error{Code: "auth_not_found", Message: "no auth available"} } providerKey := canonicalSchedulingProvider(provider) - modelKey := canonicalModelKey(model) + modelKey := canonicalModelLookupKey(model) pinnedAuthID := pinnedAuthIDFromMetadata(opts.Metadata) eligibility := authSelectionEligibilityForRequest(ctx, opts) preferWebsocket := cliproxyexecutor.DownstreamWebsocket(ctx) && providerPrefersWebsocketTransport(providerKey) && pinnedAuthID == "" @@ -422,6 +488,41 @@ func (s *authScheduler) pickSingleWithStrategy(ctx context.Context, provider, mo return nil, &Error{Code: "auth_not_found", Message: "no auth available"} } predicate := scheduledAuthPredicate(eligibility, tried, pinnedAuthID, strategy == schedulerStrategyWeightedRoundRobin) + if strategy == schedulerStrategyWeightedRoundRobin { + if ctx != nil && ctx.Err() != nil { + return nil, ctx.Err() + } + shard.promoteExpiredLocked(time.Now()) + priority, ready := shard.highestReadyPriorityLocked(preferWebsocket, predicate) + if !ready { + return nil, shard.unavailableErrorLocked(provider, model, predicate) + } + // A pin controls selection, not the peers against which traffic is charged. + accountingPredicate := scheduledAuthPredicate(eligibility, tried, "", true) + bucket := shard.readyByPriority[priority] + entries := bucket.all.flat + nonWebsocketOnly := false + transportClass := "" + if cliproxyexecutor.DownstreamWebsocket(ctx) && providerPrefersWebsocketTransport(providerKey) { + if bucket.ws.pickFirst(accountingPredicate) != nil { + if pinnedAuthID != "" && !shard.entries[pinnedAuthID].meta.websocketEnabled { + nonWebsocketOnly = true + transportClass = "http" + } else { + entries = bucket.ws.flat + transportClass = "ws" + } + } else { + transportClass = "http" + } + } + namespace := providerKey + if opts.Metadata[cliproxyexecutor.SessionAffinityProviderMetadataKey] == "mixed" { + namespace = "mixed" + } + route := namespace + ":" + canonicalModelLookupKey(weightedSelectorStateModel(ctx, model)) + return s.pickWeightedPoolLocked(route, priority, transportClass, entries, accountingPredicate, pinnedAuthID, nonWebsocketOnly) + } if picked := shard.pickReadyLocked(preferWebsocket, strategy, predicate); picked != nil { return picked, nil } @@ -465,14 +566,14 @@ func (s *authScheduler) pickMixedWithStrategy(ctx context.Context, providers []s } pinnedAuthID := pinnedAuthIDFromMetadata(opts.Metadata) eligibility := authSelectionEligibilityForRequest(ctx, opts) - modelKey := canonicalModelKey(model) + modelKey := canonicalModelLookupKey(model) s.mu.Lock() defer s.mu.Unlock() if strategy == schedulerStrategyCurrent { strategy = s.strategy } - if pinnedAuthID != "" { + if pinnedAuthID != "" && strategy != schedulerStrategyWeightedRoundRobin { providerKey := s.authProviders[pinnedAuthID] if providerKey == "" || !containsProvider(normalized, providerKey) { return nil, "", &Error{Code: "auth_not_found", Message: "no auth available"} @@ -513,6 +614,22 @@ func (s *authScheduler) pickMixedWithStrategy(ctx context.Context, providers []s hasCandidate = true } } + if pinnedAuthID != "" { + providerKey := s.authProviders[pinnedAuthID] + if providerKey == "" || !containsProvider(normalized, providerKey) { + return nil, "", &Error{Code: "auth_not_found", Message: "no auth available"} + } + shard := s.providers[providerKey].ensureModelLocked(modelKey, now) + if shard == nil { + return nil, "", &Error{Code: "auth_not_found", Message: "no auth available"} + } + pinned := shard.entries[pinnedAuthID] + if pinned == nil || pinned.state != scheduledStateReady || !predicate(pinned) { + pinnedPredicate := scheduledAuthPredicate(eligibility, tried, pinnedAuthID, true) + return nil, "", shard.unavailableErrorLocked("mixed", model, pinnedPredicate) + } + bestPriority, hasCandidate = pinned.meta.priority, true + } if !hasCandidate { return nil, "", s.mixedUnavailableErrorLocked(normalized, model, predicate) } @@ -552,20 +669,15 @@ func (s *authScheduler) pickMixedWithStrategy(ctx context.Context, providers []s } return entries[i].auth.ID < entries[j].auth.ID }) - if s.mixedWeightedStates == nil { - s.mixedWeightedStates = make(map[string]*smoothWeightedState) + if ctx != nil && ctx.Err() != nil { + return nil, "", ctx.Err() } - state := s.mixedWeightedStates[cursorKey] - if state == nil { - state = &smoothWeightedState{} - s.mixedWeightedStates[cursorKey] = state - } - state.prepare(scheduledWeightVectorMatching(entries, predicate)) - picked := pickSmoothWeightedScheduled(entries, state.current, predicate) - if picked != nil && picked.meta != nil { - return picked.auth, picked.meta.providerKey, nil + route := "mixed:" + canonicalModelLookupKey(weightedSelectorStateModel(ctx, model)) + picked, errPick := s.pickWeightedPoolLocked(route, bestPriority, "", entries, predicate, pinnedAuthID, false) + if errPick != nil { + return nil, "", errPick } - return nil, "", s.mixedUnavailableErrorLocked(normalized, model, predicate) + return picked, s.authProviders[picked.ID], nil } weights := make([]int, len(normalized)) @@ -639,12 +751,17 @@ func (s *authScheduler) mixedUnavailableErrorLocked(providers []string, model st var latestAuthID string var latestAuthErr error + allClaude := true + var earliestClaudeTime time.Time + var earliestClaudeID string + var earliestClaudeSignals map[string]string + for _, providerKey := range providers { providerState := s.providers[providerKey] if providerState == nil { continue } - shard := providerState.ensureModelLocked(canonicalModelKey(model), now) + shard := providerState.ensureModelLocked(canonicalModelLookupKey(model), now) if shard == nil { continue } @@ -655,6 +772,18 @@ func (s *authScheduler) mixedUnavailableErrorLocked(providers []string, model st if !localEarliest.IsZero() && (earliest.IsZero() || localEarliest.Before(earliest)) { earliest = localEarliest } + if localTotal > 0 { + localClaude, localClaudeEarliest, localClaudeID, localSignals := shard.claudeCooldownSummaryLocked(providerKey, model, now, predicate) + if !localClaude { + allClaude = false + } else if allClaude && !localClaudeEarliest.IsZero() { + if earliestClaudeTime.IsZero() || localClaudeEarliest.Before(earliestClaudeTime) || (localClaudeEarliest.Equal(earliestClaudeTime) && localClaudeID < earliestClaudeID) { + earliestClaudeTime = localClaudeEarliest + earliestClaudeID = localClaudeID + earliestClaudeSignals = localSignals + } + } + } candModelErr, candModelTime, candModelAuthID, candAuthErr, candAuthTime, candAuthAuthID := shard.candidateErrorsLocked(model, predicate) if candModelErr != nil { if latestModelErr == nil || candModelTime.After(latestModelTime) || (candModelTime.Equal(latestModelTime) && candModelAuthID > latestModelAuthID) { @@ -687,7 +816,11 @@ func (s *authScheduler) mixedUnavailableErrorLocked(providers []string, model st if resetIn < 0 { resetIn = 0 } - return newModelCooldownErrorWithCause(model, "", resetIn, lastCandidateErr) + var claudeSignals map[string]string + if allClaude { + claudeSignals = earliestClaudeSignals + } + return newModelCooldownErrorForCandidates(model, "", resetIn, lastCandidateErr, allClaude, claudeSignals) } if unauthorizedCount == total { terminalCause := latestAuthErr @@ -900,6 +1033,12 @@ func isCredentialBlocked(auth *Auth, supportedModelCount int, now time.Time) boo if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { return true } + if effectiveAuthForceUntil(auth).After(now) && auth.NextRetryAfter.After(now) { + return true + } + if !auth.credentialRetryAfter.IsZero() && auth.credentialRetryAfter.After(now) { + return true + } if len(auth.ModelStates) == 0 { return auth.Unavailable || auth.Quota.Exceeded || (!auth.NextRetryAfter.IsZero() && auth.NextRetryAfter.After(now)) } @@ -1077,7 +1216,7 @@ func supportedModelSetForAuth(authID string) map[string]struct{} { if model == nil { continue } - modelKey := canonicalModelKey(model.ID) + modelKey := canonicalModelLookupKey(model.ID) if modelKey == "" { continue } @@ -1130,7 +1269,7 @@ func (p *providerScheduler) updateTargetShardsLocked(meta *scheduledAuthMeta, ta seen := make(map[string]struct{}, len(targetModels)) for _, m := range targetModels { - modelKey := canonicalModelKey(m) + modelKey := canonicalModelLookupKey(m) if _, ok := seen[modelKey]; ok { continue } @@ -1166,7 +1305,7 @@ func (p *providerScheduler) ensureModelLocked(modelKey string, now time.Time) *m if p == nil { return nil } - modelKey = canonicalModelKey(modelKey) + modelKey = canonicalModelLookupKey(modelKey) if shard, ok := p.modelShards[modelKey]; ok && shard != nil { shard.promoteExpiredLocked(now) return shard @@ -1188,7 +1327,7 @@ func (p *providerScheduler) ensureModelLocked(modelKey string, now time.Time) *m // supportsModel reports whether the auth metadata currently supports modelKey. func (m *scheduledAuthMeta) supportsModel(modelKey string) bool { - modelKey = canonicalModelKey(modelKey) + modelKey = canonicalModelLookupKey(modelKey) if modelKey == "" { return true } @@ -1432,7 +1571,8 @@ func (m *modelScheduler) unavailableErrorLocked(provider, model string, predicat if resetIn < 0 { resetIn = 0 } - return newModelCooldownErrorWithCause(model, providerForError, resetIn, lastCandidateErr) + claudeCooldown, _, _, claudeSignals := m.claudeCooldownSummaryLocked(provider, model, now, predicate) + return newModelCooldownErrorForCandidates(model, providerForError, resetIn, lastCandidateErr, claudeCooldown, claudeSignals) } if unauthorizedCount == total { terminalCause := authErr @@ -1461,7 +1601,6 @@ func (m *modelScheduler) candidateErrorsLocked(model string, predicate func(*sch if m == nil { return nil, time.Time{}, "", nil, time.Time{}, "" } - modelKey := canonicalModelKey(model) for _, entry := range m.entries { if predicate != nil && !predicate(entry) { continue @@ -1473,15 +1612,7 @@ func (m *modelScheduler) candidateErrorsLocked(model string, predicate func(*sch var curModelErr error var curModelTime time.Time if len(auth.ModelStates) > 0 { - if state, ok := auth.ModelStates[model]; ok && state != nil { - if state.LastError != nil { - curModelErr = state.LastError - curModelTime = state.UpdatedAt - } else if strings.TrimSpace(state.StatusMessage) != "" { - curModelErr = errors.New(state.StatusMessage) - curModelTime = state.UpdatedAt - } - } else if state, ok := auth.ModelStates[modelKey]; ok && state != nil { + if state := existingModelState(auth, model); state != nil { if state.LastError != nil { curModelErr = state.LastError curModelTime = state.UpdatedAt @@ -1557,6 +1688,57 @@ func (m *modelScheduler) availabilitySummaryLocked(predicate func(*scheduledAuth return total, cooldownCount, unauthorizedCount, earliest } +func (m *modelScheduler) claudeCooldownSummaryLocked(fallbackProvider, model string, now time.Time, predicate func(*scheduledAuth) bool) (bool, time.Time, string, map[string]string) { + if m == nil { + return false, time.Time{}, "", nil + } + matched := 0 + var earliest time.Time + var earliestID string + var earliestAuth *Auth + var earliestSignals map[string]string + for _, entry := range m.entries { + if predicate != nil && !predicate(entry) { + continue + } + matched++ + if entry == nil || entry.auth == nil { + return false, time.Time{}, "", nil + } + entryProvider := "" + if entry.meta != nil && entry.meta.providerKey != "" { + entryProvider = entry.meta.providerKey + } else if resolved := executorKeyFromAuth(entry.auth); resolved != "" { + entryProvider = resolved + } else { + entryProvider = strings.ToLower(strings.TrimSpace(fallbackProvider)) + } + if entryProvider != "claude" { + return false, time.Time{}, "", nil + } + checkModel := model + if existingModelState(entry.auth, checkModel) == nil && m.modelKey != "" { + checkModel = m.modelKey + } + okClaude, signals := claudeUnifiedCooldownForAuth(entry.auth, checkModel, now) + if !okClaude { + return false, time.Time{}, "", nil + } + if entry.state == scheduledStateCooldown && !entry.nextRetryAt.IsZero() { + if earliestAuth == nil || entry.nextRetryAt.Before(earliest) || (entry.nextRetryAt.Equal(earliest) && entry.auth.ID < earliestID) { + earliest = entry.nextRetryAt + earliestID = entry.auth.ID + earliestAuth = entry.auth + earliestSignals = signals + } + } + } + if matched == 0 || earliestAuth == nil { + return false, time.Time{}, "", nil + } + return true, earliest, earliestID, earliestSignals +} + // rebuildIndexesLocked reconstructs ready and blocked views from the current entry map. func (m *modelScheduler) rebuildIndexesLocked() { cursorStates := make(map[int]readyBucketCursorState, len(m.readyByPriority)) diff --git a/sdk/cliproxy/auth/scheduler_benchmark_test.go b/sdk/cliproxy/auth/scheduler_benchmark_test.go index 85a9014353d..91817fd600e 100644 --- a/sdk/cliproxy/auth/scheduler_benchmark_test.go +++ b/sdk/cliproxy/auth/scheduler_benchmark_test.go @@ -214,3 +214,41 @@ func BenchmarkManagerPickNextAndMarkResult1000(b *testing.B) { manager.MarkResult(ctx, Result{AuthID: auth.ID, Provider: "gemini", Model: model, Success: true}) } } + +func BenchmarkManagerPinnedLegacy1000(b *testing.B) { + for _, mixed := range []bool{false, true} { + b.Run(fmt.Sprintf("mixed=%t", mixed), func(b *testing.B) { + manager, providers, model := benchmarkManagerSetup(b, 1000, mixed, false) + selector := NewSessionAffinitySelector(&RoundRobinSelector{}) + b.Cleanup(selector.Stop) + manager.SetSelector(selector) + ctx := context.Background() + opts := cliproxyexecutor.Options{Metadata: map[string]any{ + cliproxyexecutor.PinnedAuthMetadataKey: "bench-gemini-0000", + }} + // Warm up index assignment and selection metadata outside the timed loop. + if mixed { + if _, _, _, errWarm := manager.pickNextMixedLegacy(ctx, providers, model, opts, nil); errWarm != nil { + b.Fatal(errWarm) + } + } else if _, _, errWarm := manager.pickNextLegacy(ctx, providers[0], model, opts, nil); errWarm != nil { + b.Fatal(errWarm) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if mixed { + auth, exec, provider, errPick := manager.pickNextMixedLegacy(ctx, providers, model, opts, nil) + if errPick != nil || auth == nil || auth.ID != "bench-gemini-0000" || exec == nil || provider != providers[0] { + b.Fatalf("pinned mixed pick failed: auth=%v exec=%v provider=%q err=%v", auth, exec, provider, errPick) + } + } else { + auth, exec, errPick := manager.pickNextLegacy(ctx, providers[0], model, opts, nil) + if errPick != nil || auth == nil || auth.ID != "bench-gemini-0000" || exec == nil { + b.Fatalf("pinned pick failed: auth=%v exec=%v err=%v", auth, exec, errPick) + } + } + } + }) + } +} diff --git a/sdk/cliproxy/auth/scheduler_test.go b/sdk/cliproxy/auth/scheduler_test.go index 59e31aeda4c..7ae060c229e 100644 --- a/sdk/cliproxy/auth/scheduler_test.go +++ b/sdk/cliproxy/auth/scheduler_test.go @@ -3098,6 +3098,515 @@ func TestManagerPluginSchedulerSelectionID(t *testing.T) { }) } +func TestManagerPluginSchedulerRejectAfterFailedAttempt_Issue7434(t *testing.T) { + t.Run("transient_error_reruns_same_credential_in_next_retry_round", func(t *testing.T) { + prevQuota := quotaCooldownDisabled.Load() + prevTransient := transientErrorCooldownSeconds.Load() + quotaCooldownDisabled.Store(false) + SetTransientErrorCooldownSeconds(-1) + t.Cleanup(func() { + quotaCooldownDisabled.Store(prevQuota) + transientErrorCooldownSeconds.Store(prevTransient) + }) + + for _, mode := range []string{"execute", "count", "stream"} { + t.Run(mode, func(t *testing.T) { + manager := NewManager(nil, &FillFirstSelector{}, nil) + manager.SetRetryConfig(1, 0, 0) + + authAID := "issue7434-transient-a-" + mode + authBID := "issue7434-transient-b-" + mode + modelID := "claude-sonnet-4-5" + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authAID, "claude", []*registry.ModelInfo{{ID: modelID}}) + reg.RegisterClient(authBID, "claude", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + reg.UnregisterClient(authAID) + reg.UnregisterClient(authBID) + }) + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authAID, Provider: "claude"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authAID, errRegister) + } + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authBID, Provider: "claude"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authBID, errRegister) + } + + var attemptedAuths []string + manager.executors["claude"] = &callbackSchedulerTestExecutor{ + schedulerTestExecutor: schedulerTestExecutor{provider: "claude"}, + execute: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + attemptedAuths = append(attemptedAuths, auth.ID) + if len(attemptedAuths) == 1 { + return cliproxyexecutor.Response{}, &Error{Code: "upstream_error", Message: "internal server error", HTTPStatus: http.StatusInternalServerError, Retryable: true} + } + return cliproxyexecutor.Response{Payload: []byte(`{"ok":true}`)}, nil + }, + countTokens: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + attemptedAuths = append(attemptedAuths, auth.ID) + if len(attemptedAuths) == 1 { + return cliproxyexecutor.Response{}, &Error{Code: "upstream_error", Message: "internal server error", HTTPStatus: http.StatusInternalServerError, Retryable: true} + } + return cliproxyexecutor.Response{Payload: []byte(`{"input_tokens":12}`)}, nil + }, + executeStream: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + attemptedAuths = append(attemptedAuths, auth.ID) + if len(attemptedAuths) == 1 { + errCh := make(chan cliproxyexecutor.StreamChunk, 1) + errCh <- cliproxyexecutor.StreamChunk{Err: &Error{Code: "upstream_error", Message: "bootstrap stream 500", HTTPStatus: http.StatusInternalServerError, Retryable: true}} + close(errCh) + return &cliproxyexecutor.StreamResult{Chunks: errCh}, nil + } + ch := make(chan cliproxyexecutor.StreamChunk, 1) + ch <- cliproxyexecutor.StreamChunk{Payload: []byte("data: {\"type\":\"message_stop\"}\n\n")} + close(ch) + return &cliproxyexecutor.StreamResult{Chunks: ch}, nil + }, + } + + scheduler := &fakePluginScheduler{ + pick: func(_ context.Context, req pluginapi.SchedulerPickRequest) (pluginapi.SchedulerPickResponse, bool, error) { + if prevSelected, _ := req.Options.Metadata[cliproxyexecutor.SelectedAuthMetadataKey].(string); prevSelected != "" { + return pluginapi.SchedulerPickResponse{ + Handled: true, + Reject: true, + RejectReason: "session pinned to " + prevSelected, + }, true, nil + } + for _, c := range req.Candidates { + if c.ID == authAID { + return pluginapi.SchedulerPickResponse{Handled: true, AuthID: authAID}, true, nil + } + } + return pluginapi.SchedulerPickResponse{Handled: true, Reject: true, RejectReason: "pinned credential missing"}, true, nil + }, + } + manager.SetPluginScheduler(scheduler) + + switch mode { + case "execute": + resp, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + if errExec != nil { + t.Fatalf("Execute() error = %v, want nil", errExec) + } + if string(resp.Payload) != `{"ok":true}` { + t.Fatalf("Execute() payload = %s, want {\"ok\":true}", string(resp.Payload)) + } + case "count": + resp, errCount := manager.ExecuteCount(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + if errCount != nil { + t.Fatalf("ExecuteCount() error = %v, want nil", errCount) + } + if string(resp.Payload) != `{"input_tokens":12}` { + t.Fatalf("ExecuteCount() payload = %s, want {\"input_tokens\":12}", string(resp.Payload)) + } + case "stream": + streamRes, errStream := manager.ExecuteStream(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{Stream: true}) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v, want nil", errStream) + } + for range streamRes.Chunks { + } + } + + if len(attemptedAuths) != 2 || attemptedAuths[0] != authAID || attemptedAuths[1] != authAID { + t.Fatalf("attemptedAuths = %v, want [%s %s]", attemptedAuths, authAID, authAID) + } + if len(scheduler.requests) != 3 { + t.Fatalf("len(scheduler.requests) = %d, want 3 (round0 pick, round0 rejected re-pick, round1 pick)", len(scheduler.requests)) + } + }) + } + }) + + t.Run("rate_limit_429_withholds_cooled_credential_in_next_round_so_plugin_switches", func(t *testing.T) { + prevQuota := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { + quotaCooldownDisabled.Store(prevQuota) + }) + + for _, mode := range []string{"execute", "stream"} { + t.Run(mode, func(t *testing.T) { + manager := NewManager(nil, &FillFirstSelector{}, nil) + manager.SetRetryConfig(1, 0, 0) + + authAID := "issue7434-429-a-" + mode + authBID := "issue7434-429-b-" + mode + modelID := "claude-sonnet-4-5" + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authAID, "claude", []*registry.ModelInfo{{ID: modelID}}) + reg.RegisterClient(authBID, "claude", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + reg.UnregisterClient(authAID) + reg.UnregisterClient(authBID) + }) + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authAID, Provider: "claude"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authAID, errRegister) + } + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authBID, Provider: "claude"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authBID, errRegister) + } + + var attemptedAuths []string + manager.executors["claude"] = &callbackSchedulerTestExecutor{ + schedulerTestExecutor: schedulerTestExecutor{provider: "claude"}, + execute: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + attemptedAuths = append(attemptedAuths, auth.ID) + if auth.ID == authAID { + return cliproxyexecutor.Response{}, &Error{Code: "rate_limited", Message: "rate limit exceeded", HTTPStatus: http.StatusTooManyRequests, Retryable: true} + } + return cliproxyexecutor.Response{Payload: []byte(`{"ok":true}`)}, nil + }, + executeStream: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + attemptedAuths = append(attemptedAuths, auth.ID) + if auth.ID == authAID { + return nil, &Error{Code: "rate_limited", Message: "rate limit exceeded", HTTPStatus: http.StatusTooManyRequests, Retryable: true} + } + ch := make(chan cliproxyexecutor.StreamChunk, 1) + ch <- cliproxyexecutor.StreamChunk{Payload: []byte("data: {\"type\":\"message_stop\"}\n\n")} + close(ch) + return &cliproxyexecutor.StreamResult{Chunks: ch}, nil + }, + } + + scheduler := &fakePluginScheduler{ + pick: func(_ context.Context, req pluginapi.SchedulerPickRequest) (pluginapi.SchedulerPickResponse, bool, error) { + if prevSelected, _ := req.Options.Metadata[cliproxyexecutor.SelectedAuthMetadataKey].(string); prevSelected != "" { + return pluginapi.SchedulerPickResponse{ + Handled: true, + Reject: true, + RejectReason: "do not switch mid-round", + }, true, nil + } + for _, c := range req.Candidates { + if c.ID == authAID { + return pluginapi.SchedulerPickResponse{Handled: true, AuthID: authAID}, true, nil + } + } + return pluginapi.SchedulerPickResponse{Handled: true, AuthID: req.Candidates[0].ID}, true, nil + }, + } + manager.SetPluginScheduler(scheduler) + + if mode == "execute" { + if _, errExec := manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}); errExec != nil { + t.Fatalf("Execute() error = %v, want nil", errExec) + } + } else { + streamRes, errStream := manager.ExecuteStream(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{Stream: true}) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v, want nil", errStream) + } + for range streamRes.Chunks { + } + } + + if len(attemptedAuths) != 2 || attemptedAuths[0] != authAID || attemptedAuths[1] != authBID { + t.Fatalf("attemptedAuths = %v, want [%s %s]", attemptedAuths, authAID, authBID) + } + if len(scheduler.requests) != 3 { + t.Fatalf("len(scheduler.requests) = %d, want 3", len(scheduler.requests)) + } + }) + } + }) + + t.Run("preserves_upstream_429_when_retries_exhausted_or_sticky_plugin_rejects_next_round", func(t *testing.T) { + prevQuota := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { + quotaCooldownDisabled.Store(prevQuota) + }) + + for _, retryRounds := range []int{0, 1} { + name := "request_retry_0" + wantPicks := 2 + if retryRounds == 1 { + name = "request_retry_1_sticky_reject_in_round_1" + wantPicks = 3 + } + t.Run(name, func(t *testing.T) { + for _, mode := range []string{"execute", "count", "stream"} { + t.Run(mode, func(t *testing.T) { + manager := NewManager(nil, &FillFirstSelector{}, nil) + manager.SetRetryConfig(retryRounds, 1, 0) + + authAID := "issue7434-preserve-a-" + name + "-" + mode + authBID := "issue7434-preserve-b-" + name + "-" + mode + modelID := "claude-sonnet-4-5" + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authAID, "claude", []*registry.ModelInfo{{ID: modelID}}) + reg.RegisterClient(authBID, "claude", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + reg.UnregisterClient(authAID) + reg.UnregisterClient(authBID) + }) + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authAID, Provider: "claude"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authAID, errRegister) + } + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authBID, Provider: "claude"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authBID, errRegister) + } + + manager.executors["claude"] = &callbackSchedulerTestExecutor{ + schedulerTestExecutor: schedulerTestExecutor{provider: "claude"}, + execute: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return cliproxyexecutor.Response{}, &Error{Code: "rate_limited", Message: "upstream 429", HTTPStatus: http.StatusTooManyRequests, Retryable: true} + }, + countTokens: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return cliproxyexecutor.Response{}, &Error{Code: "rate_limited", Message: "upstream 429", HTTPStatus: http.StatusTooManyRequests, Retryable: true} + }, + executeStream: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + return nil, &Error{Code: "rate_limited", Message: "upstream 429", HTTPStatus: http.StatusTooManyRequests, Retryable: true} + }, + } + + scheduler := &fakePluginScheduler{ + pick: func(_ context.Context, req pluginapi.SchedulerPickRequest) (pluginapi.SchedulerPickResponse, bool, error) { + for _, c := range req.Candidates { + if c.ID == authAID { + return pluginapi.SchedulerPickResponse{Handled: true, AuthID: authAID}, true, nil + } + } + return pluginapi.SchedulerPickResponse{ + Handled: true, + Reject: true, + RejectReason: "bound credential unavailable", + }, true, nil + }, + } + manager.SetPluginScheduler(scheduler) + + var gotErr error + switch mode { + case "execute": + _, gotErr = manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + case "count": + _, gotErr = manager.ExecuteCount(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + case "stream": + _, gotErr = manager.ExecuteStream(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{Stream: true}) + } + if gotErr == nil { + t.Fatal("error = nil, want upstream 429 error") + } + var authErr *Error + if !errors.As(gotErr, &authErr) { + t.Fatalf("error = %T (%v), want *auth.Error", gotErr, gotErr) + } + if authErr.Code != "rate_limited" || authErr.HTTPStatus != http.StatusTooManyRequests { + t.Fatalf("error = %s (status %d, msg %q), want rate_limited (status 429)", authErr.Code, authErr.HTTPStatus, authErr.Message) + } + if len(scheduler.requests) != wantPicks { + t.Fatalf("len(scheduler.requests) = %d, want %d", len(scheduler.requests), wantPicks) + } + }) + } + }) + } + }) + + t.Run("first_pick_reject_stops_without_retry_and_unwraps_boundary_error", func(t *testing.T) { + for _, mode := range []string{"select", "execute", "count", "stream"} { + t.Run(mode, func(t *testing.T) { + manager := NewManager(nil, &FillFirstSelector{}, nil) + manager.SetRetryConfig(2, 0, 0) + + authID := "issue7434-first-reject-" + mode + modelID := "claude-sonnet-4-5" + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authID, "claude", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authID, Provider: "claude"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authID, errRegister) + } + + execCalled := false + manager.executors["claude"] = &callbackSchedulerTestExecutor{ + schedulerTestExecutor: schedulerTestExecutor{provider: "claude"}, + execute: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + execCalled = true + return cliproxyexecutor.Response{Payload: []byte(`{"ok":true}`)}, nil + }, + countTokens: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + execCalled = true + return cliproxyexecutor.Response{Payload: []byte(`{"input_tokens":1}`)}, nil + }, + executeStream: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + execCalled = true + ch := make(chan cliproxyexecutor.StreamChunk, 1) + close(ch) + return &cliproxyexecutor.StreamResult{Chunks: ch}, nil + }, + } + + scheduler := &fakePluginScheduler{ + resp: pluginapi.SchedulerPickResponse{ + Handled: true, + Reject: true, + RejectCode: "policy_denied", + RejectReason: "connection reset by peer policy guard", + }, + handled: true, + } + manager.SetPluginScheduler(scheduler) + + var gotErr error + switch mode { + case "select": + _, gotErr = manager.SelectAuth(context.Background(), "claude", modelID, cliproxyexecutor.Options{}) + case "execute": + _, gotErr = manager.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + case "count": + _, gotErr = manager.ExecuteCount(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + case "stream": + _, gotErr = manager.ExecuteStream(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{Stream: true}) + } + if gotErr == nil { + t.Fatal("error = nil, want rejection error") + } + authErr, okType := gotErr.(*Error) + if !okType || authErr == nil { + t.Fatalf("error concrete type = %T (%v), want unwrapped *auth.Error", gotErr, gotErr) + } + if authErr.Code != "policy_denied" || authErr.Message != "connection reset by peer policy guard" { + t.Fatalf("error = %s: %s, want policy_denied: connection reset by peer policy guard", authErr.Code, authErr.Message) + } + if execCalled { + t.Fatal("executor was called after first-pick reject") + } + if len(scheduler.requests) != 1 { + t.Fatalf("len(scheduler.requests) = %d, want 1", len(scheduler.requests)) + } + }) + } + }) + + t.Run("antigravity_credits_fallback_not_triggered_after_attempt_failure_and_plugin_reject", func(t *testing.T) { + prevQuota := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { + quotaCooldownDisabled.Store(prevQuota) + }) + + for _, retryRounds := range []int{0, 1} { + roundCase := "request_retry_0" + if retryRounds == 1 { + roundCase = "request_retry_1_sticky_reject_in_round_1" + } + t.Run(roundCase, func(t *testing.T) { + for _, mode := range []string{"execute", "stream"} { + t.Run(mode, func(t *testing.T) { + manager := NewManager(nil, &FillFirstSelector{}, nil) + manager.SetConfig(&internalconfig.Config{ + QuotaExceeded: internalconfig.QuotaExceeded{AntigravityCredits: true}, + }) + manager.SetRetryConfig(retryRounds, 0, 0) + + authAID := "issue7434-ag-a-" + roundCase + "-" + mode + authBID := "issue7434-ag-b-" + roundCase + "-" + mode + modelID := "claude-sonnet-4-5" + reg := registry.GetGlobalRegistry() + reg.RegisterClient(authAID, "antigravity", []*registry.ModelInfo{{ID: modelID}}) + reg.RegisterClient(authBID, "antigravity", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + reg.UnregisterClient(authAID) + reg.UnregisterClient(authBID) + antigravityCreditsHintByAuth.Delete(authAID) + antigravityCreditsHintByAuth.Delete(authBID) + }) + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authAID, Provider: "antigravity"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authAID, errRegister) + } + if _, errRegister := manager.Register(context.Background(), &Auth{ID: authBID, Provider: "antigravity"}); errRegister != nil { + t.Fatalf("Register(%s) error = %v", authBID, errRegister) + } + SetAntigravityCreditsHint(authBID, AntigravityCreditsHint{ + Known: true, + Available: true, + CreditAmount: 100, + UpdatedAt: time.Now(), + }) + + var attemptedAuths []string + creditsRequested := false + manager.executors["antigravity"] = &callbackSchedulerTestExecutor{ + schedulerTestExecutor: schedulerTestExecutor{provider: "antigravity"}, + execute: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + attemptedAuths = append(attemptedAuths, auth.ID) + if AntigravityCreditsRequested(ctx) { + creditsRequested = true + return cliproxyexecutor.Response{Payload: []byte(`{"credits":true}`)}, nil + } + return cliproxyexecutor.Response{}, &Error{Code: "rate_limited", Message: "ag 429", HTTPStatus: http.StatusTooManyRequests, Retryable: true} + }, + executeStream: func(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + cliproxyexecutor.MarkUpstreamAttempt(ctx) + attemptedAuths = append(attemptedAuths, auth.ID) + if AntigravityCreditsRequested(ctx) { + creditsRequested = true + ch := make(chan cliproxyexecutor.StreamChunk, 1) + ch <- cliproxyexecutor.StreamChunk{Payload: []byte("data: ok\n\n")} + close(ch) + return &cliproxyexecutor.StreamResult{Chunks: ch}, nil + } + return nil, &Error{Code: "rate_limited", Message: "ag 429", HTTPStatus: http.StatusTooManyRequests, Retryable: true} + }, + } + + scheduler := &fakePluginScheduler{ + pick: func(_ context.Context, req pluginapi.SchedulerPickRequest) (pluginapi.SchedulerPickResponse, bool, error) { + for _, c := range req.Candidates { + if c.ID == authAID { + return pluginapi.SchedulerPickResponse{Handled: true, AuthID: authAID}, true, nil + } + } + return pluginapi.SchedulerPickResponse{ + Handled: true, + Reject: true, + RejectReason: "do not bypass bound credential via credits fallback", + }, true, nil + }, + } + manager.SetPluginScheduler(scheduler) + + var gotErr error + if mode == "execute" { + _, gotErr = manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{}) + } else { + _, gotErr = manager.ExecuteStream(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: modelID}, cliproxyexecutor.Options{Stream: true}) + } + if creditsRequested { + t.Fatalf("Antigravity credits fallback ran despite scheduler Reject (attemptedAuths=%v)", attemptedAuths) + } + if len(attemptedAuths) != 1 || attemptedAuths[0] != authAID { + t.Fatalf("attemptedAuths = %v, want [%s]", attemptedAuths, authAID) + } + if gotErr == nil { + t.Fatal("error = nil, want upstream 429 error") + } + authErr, okType := gotErr.(*Error) + if !okType || authErr == nil { + t.Fatalf("error concrete type = %T (%v), want unwrapped *auth.Error", gotErr, gotErr) + } + if authErr.Code != "rate_limited" || authErr.HTTPStatus != http.StatusTooManyRequests { + t.Fatalf("error = %s (status %d), want rate_limited (status 429)", authErr.Code, authErr.HTTPStatus) + } + }) + } + }) + } + }) +} + type callbackSchedulerTestExecutor struct { schedulerTestExecutor execute func(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) diff --git a/sdk/cliproxy/auth/scheduler_weighted.go b/sdk/cliproxy/auth/scheduler_weighted.go new file mode 100644 index 00000000000..3b72a7e99e1 --- /dev/null +++ b/sdk/cliproxy/auth/scheduler_weighted.go @@ -0,0 +1,34 @@ +package auth + +// pickWeightedPoolLocked consumes the scheduler's ID-sorted, immutable ready +// snapshots without cloning the whole pool. Legacy and fast-path selections use +// the same selector-owned credits, including pending reservations. +// The scheduler mutex must be held while reading entries and selecting an auth. +func (s *authScheduler) pickWeightedPoolLocked(route string, priority int, transportClass string, entries []*scheduledAuth, predicate func(*scheduledAuth) bool, pinnedAuthID string, nonWebsocketOnly bool) (*Auth, error) { + if s.weightedSelector == nil { + return nil, &Error{Code: "auth_unavailable", Message: "weighted selector is not configured"} + } + auths := make([]*Auth, 0, len(entries)) + ids := make([]string, 0, len(entries)) + weights := make([]int64, 0, len(entries)) + for _, entry := range entries { + if entry == nil || entry.auth == nil || entry.meta == nil || entry.meta.weight <= 0 { + continue + } + if predicate != nil && !predicate(entry) { + continue + } + if nonWebsocketOnly && entry.meta.websocketEnabled { + continue + } + auths = append(auths, entry.auth) + ids = append(ids, entry.auth.ID) + weights = append(weights, entry.meta.weight) + } + picked, reservation := s.weightedSelector.reservePoolScoped(route, priority, transportClass, auths, weights, ids, pinnedAuthID) + if picked == nil { + return nil, &Error{Code: "auth_unavailable", Message: "no auth available with positive weight"} + } + reservation.finish(true) + return picked, nil +} diff --git a/sdk/cliproxy/auth/scheduler_weighted_routing_test.go b/sdk/cliproxy/auth/scheduler_weighted_routing_test.go new file mode 100644 index 00000000000..cd9e5f543b3 --- /dev/null +++ b/sdk/cliproxy/auth/scheduler_weighted_routing_test.go @@ -0,0 +1,161 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +func TestWeightedWebsocketPreferenceAcrossPriorities(t *testing.T) { + for _, provider := range []string{"codex", "xai"} { + for _, mixed := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/mixed=%t", provider, mixed), func(t *testing.T) { + manager := NewManager(nil, &WeightedRoundRobinSelector{}, nil) + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + ctx := cliproxyexecutor.WithDownstreamWebsocket(t.Context()) + const model = "weighted-ws-priority" + for _, auth := range []*Auth{ + {ID: t.Name() + "-http", Provider: provider, Attributes: map[string]string{"priority": "10"}}, + {ID: t.Name() + "-ws", Provider: provider, Attributes: map[string]string{"priority": "0", "websockets": "true"}}, + } { + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + if _, errRegister := manager.Register(WithSkipPersist(ctx), auth); errRegister != nil { + t.Fatal(errRegister) + } + } + for _, routeModel := range []string{"", model} { + var got *Auth + var errPick error + if mixed { + got, _, _, errPick = manager.pickNextMixed(ctx, []string{provider}, routeModel, cliproxyexecutor.Options{}, nil) + } else { + got, _, errPick = manager.pickNext(ctx, provider, routeModel, cliproxyexecutor.Options{}, nil) + } + if errPick != nil || got == nil { + t.Fatalf("model=%q: selection failed: auth=%v err=%v", routeModel, got, errPick) + } + if got.ID != t.Name()+"-ws" { + t.Fatalf("model=%q: got %q, want lower-priority WebSocket auth", routeModel, got.ID) + } + } + }) + } + } +} + +func TestWeightedSchedulerAndLegacyShareCredits(t *testing.T) { + for _, mixed := range []bool{false, true} { + for _, pinViaLegacy := range []bool{false, true} { + t.Run(fmt.Sprintf("mixed=%t/pinViaLegacy=%t", mixed, pinViaLegacy), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + manager := NewManager(nil, weighted, nil) + const provider, model = "weighted-shared", "weighted-shared-model" + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + for _, auth := range []*Auth{ + {ID: t.Name() + "-a", Provider: provider, Attributes: map[string]string{AttributeWeight: "3"}}, + {ID: t.Name() + "-b", Provider: provider, Attributes: map[string]string{AttributeWeight: "1"}}, + } { + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + if _, errRegister := manager.Register(WithSkipPersist(t.Context()), auth); errRegister != nil { + t.Fatal(errRegister) + } + } + if !manager.useSchedulerFastPath() { + t.Fatal("bare weighted routing must retain the scheduler fast path") + } + // Normalize the four entrypoints to verify accounting across boundaries. + pick := func(ctx context.Context, legacy bool, opts cliproxyexecutor.Options) (*Auth, error) { + if mixed { + if legacy { + auth, _, _, errPick := manager.pickNextMixedLegacy(ctx, []string{provider}, model, opts, nil) + return auth, errPick + } + auth, _, _, errPick := manager.pickNextMixed(ctx, []string{provider}, model, opts, nil) + return auth, errPick + } + if legacy { + auth, _, errPick := manager.pickNextLegacy(ctx, provider, model, opts, nil) + return auth, errPick + } + auth, _, errPick := manager.pickNext(ctx, provider, model, opts, nil) + return auth, errPick + } + for range 4 { + opts := cliproxyexecutor.Options{Metadata: map[string]any{cliproxyexecutor.PinnedAuthMetadataKey: t.Name() + "-b"}} + auth, errPick := pick(t.Context(), pinViaLegacy, opts) + if errPick != nil || auth == nil || auth.ID != t.Name()+"-b" { + t.Fatalf("pin failed: auth=%v err=%v", auth, errPick) + } + } + canceled, cancel := context.WithCancel(t.Context()) + cancel() + if auth, errPick := pick(canceled, false, cliproxyexecutor.Options{}); auth != nil || !errors.Is(errPick, context.Canceled) { + t.Fatalf("canceled selection: auth=%v err=%v", auth, errPick) + } + for i := range 12 { + auth, errPick := pick(t.Context(), !pinViaLegacy, cliproxyexecutor.Options{}) + if errPick != nil || auth == nil || auth.ID != t.Name()+"-a" { + t.Fatalf("repayment %d used a different ledger: auth=%v err=%v", i, auth, errPick) + } + } + }) + } + } +} + +func TestWeightedSchedulerSeesPendingReservations(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "pending-a", Provider: "weighted-pending"}, {ID: "pending-b", Provider: "weighted-pending"}} + scheduler := newSchedulerForTest(weighted, auths...) + _, reservation := weighted.reserve("weighted-pending:", auths, auths[0].ID) + t.Cleanup(func() { reservation.finish(false) }) + picked, errPick := scheduler.pickSingle(t.Context(), "weighted-pending", "", cliproxyexecutor.Options{}, nil) + if errPick != nil || picked == nil || picked.ID != auths[1].ID { + t.Fatalf("scheduler ignored pending credit: auth=%v err=%v", picked, errPick) + } + reservation.finish(false) + picked, errPick = scheduler.pickSingle(t.Context(), "weighted-pending", "", cliproxyexecutor.Options{}, nil) + if errPick != nil || picked == nil || picked.ID != auths[0].ID { + t.Fatalf("rollback lost committed credit: auth=%v err=%v", picked, errPick) + } + state := weightedStateForTest(t, weighted, "weighted-pending:", auths[0].ID, auths[1].ID) + if state.inFlight != 0 || len(state.pendingForTest()) != 0 || state.currentForTest()[auths[0].ID] != 0 || state.currentForTest()[auths[1].ID] != 0 { + t.Fatalf("pool did not settle: current=%v pending=%v inFlight=%d", state.currentForTest(), state.pendingForTest(), state.inFlight) + } +} + +func BenchmarkManagerWeighted1000(b *testing.B) { + for _, mixed := range []bool{false, true} { + b.Run(fmt.Sprintf("mixed=%t", mixed), func(b *testing.B) { + manager, providers, model := benchmarkManagerSetup(b, 1000, mixed, false) + manager.SetSelector(&WeightedRoundRobinSelector{}) + ctx := b.Context() + opts := cliproxyexecutor.Options{} + // Warm both the shard indexes and the pool state outside the timed loop. + if mixed { + if _, _, _, errWarm := manager.pickNextMixed(ctx, providers, model, opts, nil); errWarm != nil { + b.Fatal(errWarm) + } + } else if _, _, errWarm := manager.pickNext(ctx, providers[0], model, opts, nil); errWarm != nil { + b.Fatal(errWarm) + } + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + if mixed { + if _, _, _, errPick := manager.pickNextMixed(ctx, providers, model, opts, nil); errPick != nil { + b.Fatal(errPick) + } + } else if _, _, errPick := manager.pickNext(ctx, providers[0], model, opts, nil); errPick != nil { + b.Fatal(errPick) + } + } + }) + } +} diff --git a/sdk/cliproxy/auth/selector.go b/sdk/cliproxy/auth/selector.go index ff1ff298bfd..efce82909a7 100644 --- a/sdk/cliproxy/auth/selector.go +++ b/sdk/cliproxy/auth/selector.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "hash/fnv" + "maps" "math" "net/http" "regexp" @@ -39,14 +40,35 @@ type RoundRobinSelector struct { // WeightedRoundRobinSelector provides smooth weighted round-robin selection. type WeightedRoundRobinSelector struct { - mu sync.Mutex - states map[string]*smoothWeightedState - maxKeys int + mu sync.Mutex + states map[[32]byte]*weightedPoolState + stateCount int + maxKeys int + // largeStates holds one shared dynamic accumulator per (route, priority, transport) + // bucket once a pool exceeds maxExactWeightedPoolMembers, preserving rotation credits + // across transient retry exclusions and cooldowns. + largeStates map[string]*weightedPoolState + largeOrder []string +} + +// UnwrapWeightedRoundRobinSelector extracts the underlying *WeightedRoundRobinSelector +// from a bare selector or a SessionAffinitySelector wrapper. +func UnwrapWeightedRoundRobinSelector(selector Selector) *WeightedRoundRobinSelector { + if weighted, ok := selector.(*WeightedRoundRobinSelector); ok { + return weighted + } + if affinity, ok := selector.(*SessionAffinitySelector); ok && affinity != nil { + if weighted, okFallback := affinity.fallback.(*WeightedRoundRobinSelector); okFallback { + return weighted + } + } + return nil } type smoothWeightedState struct { current map[string]int64 weights map[string]int64 + peak int } type weightedSelectorStateModelKey struct{} @@ -82,10 +104,12 @@ const ( ) type modelCooldownError struct { - model string - resetIn time.Duration - provider string - cause error + model string + resetIn time.Duration + provider string + cause error + claudeCooldown bool + claudeSignals map[string]string } // NewModelCooldownError creates an error representing model-level cooldown. @@ -98,17 +122,27 @@ func newModelCooldownError(model, provider string, resetIn time.Duration) *model } func newModelCooldownErrorWithCause(model, provider string, resetIn time.Duration, cause error) *modelCooldownError { + return newModelCooldownErrorForCandidates(model, provider, resetIn, cause, isClaudeCooldownProvider(provider), nil) +} + +func newModelCooldownErrorForCandidates(model, provider string, resetIn time.Duration, cause error, claudeCooldown bool, claudeSignals map[string]string) *modelCooldownError { if resetIn < 0 { resetIn = 0 } return &modelCooldownError{ - model: model, - provider: provider, - resetIn: resetIn, - cause: cause, + model: model, + provider: provider, + resetIn: resetIn, + cause: cause, + claudeCooldown: claudeCooldown, + claudeSignals: maps.Clone(claudeSignals), } } +func isClaudeCooldownProvider(provider string) bool { + return strings.EqualFold(strings.TrimSpace(provider), "claude") +} + func (e *modelCooldownError) IsModelCooldown() bool { return true } @@ -351,17 +385,419 @@ func (e *modelCooldownError) StatusCode() int { return http.StatusTooManyRequests } -func (e *modelCooldownError) Headers() http.Header { +func (e *modelCooldownError) resetSeconds() int64 { + if e == nil || e.resetIn <= 0 { + return 0 + } + seconds := int64(e.resetIn / time.Second) + if e.resetIn%time.Second > 0 { + seconds++ + } + return seconds +} + +// SafeResponseHeaders exposes only the locally trusted cooldown headers. +func (e *modelCooldownError) SafeResponseHeaders() http.Header { headers := make(http.Header) headers.Set("Content-Type", "application/json") - resetSeconds := int(math.Ceil(e.resetIn.Seconds())) - if resetSeconds < 0 { - resetSeconds = 0 + headers.Set("Retry-After", strconv.FormatInt(e.resetSeconds(), 10)) + return headers +} + +func (e *modelCooldownError) Headers() http.Header { + headers := e.SafeResponseHeaders() + if e != nil && e.claudeCooldown && e.resetIn > 0 { + e.appendClaudeUnifiedHeaders(headers) } - headers.Set("Retry-After", strconv.Itoa(resetSeconds)) return headers } +func (e *modelCooldownError) appendClaudeUnifiedHeaders(headers http.Header) { + resetSeconds := e.resetSeconds() + if resetSeconds <= 0 { + return + } + resetAt := time.Now().Unix() + resetSeconds + resetStr := strconv.FormatInt(resetAt, 10) + + if hasRejectedClaudeUnifiedSignals(e.claudeSignals) { + for key, value := range e.claudeSignals { + if strings.HasPrefix(strings.ToLower(strings.TrimSpace(key)), "anthropic-ratelimit-unified-") { + headers.Set(key, value) + } + } + headers.Set("Anthropic-Ratelimit-Unified-Status", "rejected") + headers.Set("Anthropic-Ratelimit-Unified-Reset", resetStr) + + rejWindows := rejectedClaudeUnifiedWindows(headers) + claim := strings.ToLower(strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-Representative-Claim"))) + if len(rejWindows) == 0 && claim == "" && isClaudeOverageOnlyHeaders(headers) { + claim = "overage" + headers.Set("Anthropic-Ratelimit-Unified-Representative-Claim", claim) + } + if len(rejWindows) == 0 && claim != "overage" { + fallbackWindow := fallbackClaudeWindowForClaim(headers, claim, e.resetIn) + if fallbackWindow != "" { + statusHeader := claudeUnifiedWindowHeader(fallbackWindow, "Status") + if strings.TrimSpace(headers.Get(statusHeader)) == "" { + headers.Set(statusHeader, "rejected") + rejWindows = append(rejWindows, fallbackWindow) + } + } + } + + if len(rejWindows) == 1 { + headers.Set(claudeUnifiedWindowHeader(rejWindows[0], "Reset"), resetStr) + } else if len(rejWindows) > 1 { + latestHeader := "" + var latestEpoch int64 + for _, window := range rejWindows { + resetHeader := claudeUnifiedWindowHeader(window, "Reset") + raw := strings.TrimSpace(headers.Get(resetHeader)) + if raw == "" { + headers.Set(resetHeader, resetStr) + continue + } + if parsed, errParse := strconv.ParseInt(raw, 10, 64); errParse == nil && (latestHeader == "" || parsed >= latestEpoch) { + latestHeader = resetHeader + latestEpoch = parsed + } + } + if latestHeader != "" { + headers.Set(latestHeader, resetStr) + } + } + + if claim == "" { + if inferred := inferClaudeRepresentativeClaim(headers, rejWindows, e.resetIn); inferred != "" { + headers.Set("Anthropic-Ratelimit-Unified-Representative-Claim", inferred) + } + } + if strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-Overage-Status")) == "" { + headers.Set("Anthropic-Ratelimit-Unified-Overage-Status", "rejected") + } + return + } + + claim := "five_hour" + if e.resetIn > 5*time.Hour { + claim = "seven_day" + } + headers.Set("Anthropic-Ratelimit-Unified-Status", "rejected") + headers.Set("Anthropic-Ratelimit-Unified-Reset", resetStr) + headers.Set("Anthropic-Ratelimit-Unified-Representative-Claim", claim) + headers.Set("Anthropic-Ratelimit-Unified-Overage-Status", "rejected") + if claim == "five_hour" { + headers.Set("Anthropic-Ratelimit-Unified-5h-Status", "rejected") + headers.Set("Anthropic-Ratelimit-Unified-5h-Reset", resetStr) + } else { + headers.Set("Anthropic-Ratelimit-Unified-7d-Status", "rejected") + headers.Set("Anthropic-Ratelimit-Unified-7d-Reset", resetStr) + } +} + +func claudeUnifiedWindowName(headerKey string) (string, bool) { + lower := strings.ToLower(strings.TrimSpace(headerKey)) + rest, hasPrefix := strings.CutPrefix(lower, "anthropic-ratelimit-unified-") + if !hasPrefix { + return "", false + } + window, hasSuffix := strings.CutSuffix(rest, "-status") + if !hasSuffix || window == "" || window == "overage" { + return "", false + } + return window, true +} + +func claudeUnifiedWindowHeader(window, field string) string { + return http.CanonicalHeaderKey("Anthropic-Ratelimit-Unified-" + window + "-" + field) +} + +func rejectedClaudeUnifiedWindows(headers http.Header) []string { + var windows []string + for key := range headers { + window, ok := claudeUnifiedWindowName(key) + if ok && strings.EqualFold(strings.TrimSpace(headers.Get(key)), "rejected") { + windows = append(windows, window) + } + } + sort.Strings(windows) + return windows +} + +func isAllowedClaudeWindowStatus(status string) bool { + lower := strings.ToLower(strings.TrimSpace(status)) + return lower == "allowed" || lower == "allowed_warning" +} + +func isClaudeUtilizationBelowCap(raw string) bool { + raw = strings.TrimSpace(raw) + if raw == "" { + return false + } + u, errParse := strconv.ParseFloat(raw, 64) + if errParse != nil || math.IsNaN(u) || math.IsInf(u, 0) { + return false + } + return u >= 0 && u < 1.0 +} + +func isClaudeOverageOnlyHeaders(headers http.Header) bool { + overageRejected := strings.EqualFold(strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-Overage-Status")), "rejected") || + strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-Overage-Disabled-Reason")) != "" + if !overageRejected { + return false + } + status5h := strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-5h-Status")) + status7d := strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-7d-Status")) + allowed5h := isAllowedClaudeWindowStatus(status5h) + allowed7d := isAllowedClaudeWindowStatus(status7d) + if allowed5h && allowed7d { + return true + } + if allowed7d && status5h == "" { + util5h := strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-5h-Utilization")) + if util5h == "" || isClaudeUtilizationBelowCap(util5h) { + return true + } + } + if allowed5h && status7d == "" && isClaudeUtilizationBelowCap(headers.Get("Anthropic-Ratelimit-Unified-7d-Utilization")) { + return true + } + return false +} + +func fallbackClaudeWindowForClaim(headers http.Header, claim string, resetIn time.Duration) string { + switch { + case claim == "seven_day_overage_included": + return "7d_oi" + case strings.HasPrefix(claim, "seven_day_"): + if suffix := strings.TrimPrefix(claim, "seven_day_"); suffix != "" { + return "7d_" + suffix + } + case claim == "seven_day": + return "7d" + case claim == "five_hour": + return "5h" + case claim == "": + allowed5h := isAllowedClaudeWindowStatus(headers.Get("Anthropic-Ratelimit-Unified-5h-Status")) + allowed7d := isAllowedClaudeWindowStatus(headers.Get("Anthropic-Ratelimit-Unified-7d-Status")) + switch { + case allowed5h && allowed7d: + return "" + case allowed5h: + return "7d" + case allowed7d: + return "5h" + case resetIn > 5*time.Hour: + return "7d" + default: + return "5h" + } + } + return "" +} + +func inferClaudeRepresentativeClaim(headers http.Header, windows []string, resetIn time.Duration) string { + has5h := false + has7d := false + has7dOI := false + modelFamily7d := "" + otherWindow := "" + for _, window := range windows { + switch { + case window == "7d_oi": + has7dOI = true + case strings.HasPrefix(window, "7d_"): + if modelFamily7d == "" { + modelFamily7d = "seven_day_" + strings.TrimPrefix(window, "7d_") + } + case window == "7d": + has7d = true + case window == "5h": + has5h = true + default: + if otherWindow == "" { + otherWindow = window + } + } + } + switch { + case has7dOI: + return "seven_day_overage_included" + case modelFamily7d != "": + return modelFamily7d + case has7d: + return "seven_day" + case has5h: + return "five_hour" + case otherWindow != "": + return otherWindow + } + if strings.EqualFold(strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-Overage-Status")), "rejected") || + strings.TrimSpace(headers.Get("Anthropic-Ratelimit-Unified-Overage-Disabled-Reason")) != "" { + return "overage" + } + allowed5h := isAllowedClaudeWindowStatus(headers.Get("Anthropic-Ratelimit-Unified-5h-Status")) + allowed7d := isAllowedClaudeWindowStatus(headers.Get("Anthropic-Ratelimit-Unified-7d-Status")) + switch { + case allowed5h && allowed7d: + return "" + case allowed5h: + return "seven_day" + case allowed7d: + return "five_hour" + case resetIn > 5*time.Hour: + return "seven_day" + default: + return "five_hour" + } +} + +func hasRejectedClaudeUnifiedSignals(signals map[string]string) bool { + if len(signals) == 0 { + return false + } + if strings.EqualFold(strings.TrimSpace(signals["Anthropic-Ratelimit-Unified-Status"]), "rejected") { + return true + } + for key, val := range signals { + if _, ok := claudeUnifiedWindowName(key); ok && strings.EqualFold(strings.TrimSpace(val), "rejected") { + return true + } + } + return false +} + +func claudeSignalsFromEvaluatedQuota(q QuotaState) (bool, map[string]string) { + if hasRejectedClaudeUnifiedSignals(q.cooldownSignals) { + return true, maps.Clone(q.cooldownSignals) + } + if q.cooldownEvaluated { + return false, nil + } + if hasRejectedClaudeUnifiedSignals(q.Signals) { + return true, maps.Clone(q.Signals) + } + return false, nil +} + +func claudeUnifiedCooldownForAuth(auth *Auth, model string, now time.Time) (bool, map[string]string) { + if auth == nil || executorKeyFromAuth(auth) != "claude" { + return false, nil + } + if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { + state := existingModelState(auth, model) + if state != nil && state.NextRetryAfter.After(auth.Quota.NextRecoverAt) { + if shadow := state.credentialQuotaShadow; shadow != nil { + if !shadow.Quota.Exceeded || !shadow.Quota.NextRecoverAt.After(now) || shadow.NextRetryAfter.After(shadow.Quota.NextRecoverAt) { + return false, nil + } + if strings.EqualFold(strings.TrimSpace(shadow.Quota.Reason), "cloudflare challenge") { + return false, nil + } + return claudeSignalsFromEvaluatedQuota(shadow.Quota) + } + return false, nil + } + if ok, signals := claudeSignalsFromEvaluatedQuota(auth.Quota); ok { + return true, signals + } + if state != nil && !state.Quota.NextRecoverAt.Before(auth.Quota.NextRecoverAt) { + if ok, signals := claudeSignalsFromEvaluatedQuota(state.Quota); ok { + return true, signals + } + } + return true, nil + } + if len(auth.ModelStates) > 0 { + if model == "" { + if !auth.Unavailable { + return false, nil + } + keys := make([]string, 0, len(auth.ModelStates)) + for key := range auth.ModelStates { + keys = append(keys, key) + } + sort.Strings(keys) + var earliestRecover time.Time + var earliestSignals map[string]string + found := false + for _, key := range keys { + st := auth.ModelStates[key] + if st != nil && (st.credentialQuotaPropagated || st.Quota.Reason == "credential_quota") { + st = st.credentialQuotaShadow + } + if st == nil || !st.Quota.Exceeded || !st.Quota.NextRecoverAt.After(now) || st.NextRetryAfter.After(st.Quota.NextRecoverAt) { + return false, nil + } + if strings.EqualFold(strings.TrimSpace(st.Quota.Reason), "cloudflare challenge") { + return false, nil + } + okSt, sig := claudeSignalsFromEvaluatedQuota(st.Quota) + if !okSt { + return false, nil + } + if !found || st.Quota.NextRecoverAt.Before(earliestRecover) { + found = true + earliestRecover = st.Quota.NextRecoverAt + earliestSignals = sig + } + } + return found, earliestSignals + } + state := existingModelState(auth, model) + if state != nil && (state.credentialQuotaPropagated || state.Quota.Reason == "credential_quota") { + state = state.credentialQuotaShadow + } + if state == nil || !state.Quota.Exceeded || !state.Quota.NextRecoverAt.After(now) || state.NextRetryAfter.After(state.Quota.NextRecoverAt) { + return false, nil + } + if strings.EqualFold(strings.TrimSpace(state.Quota.Reason), "cloudflare challenge") { + return false, nil + } + return claudeSignalsFromEvaluatedQuota(state.Quota) + } + if !auth.Quota.Exceeded || !auth.Quota.NextRecoverAt.After(now) || auth.NextRetryAfter.After(auth.Quota.NextRecoverAt) { + return false, nil + } + if strings.EqualFold(strings.TrimSpace(auth.Quota.Reason), "cloudflare challenge") { + return false, nil + } + return claudeSignalsFromEvaluatedQuota(auth.Quota) +} + +func claudeCooldownMetadataForAuths(ctx context.Context, auths []*Auth, modelForAuth func(*Auth) string, now time.Time, clientHeaders ...http.Header) (bool, map[string]string) { + if len(auths) == 0 { + return false, nil + } + var earliestAuth *Auth + var earliestSignals map[string]string + var earliestNext time.Time + for _, candidate := range auths { + checkModel := "" + if modelForAuth != nil { + checkModel = modelForAuth(candidate) + } + okClaude, signals := claudeUnifiedCooldownForAuth(candidate, checkModel, now) + if !okClaude { + return false, nil + } + blocked, reason, next := isAuthBlockedForModelForRequest(ctx, candidate, checkModel, now, clientHeaders...) + if blocked && reason == blockReasonCooldown && next.After(now) { + if earliestAuth == nil || next.Before(earliestNext) || (next.Equal(earliestNext) && candidate.ID < earliestAuth.ID) { + earliestAuth = candidate + earliestSignals = signals + earliestNext = next + } + } + } + if earliestAuth == nil { + return false, nil + } + return true, earliestSignals +} + func authPriority(auth *Auth) int { if auth == nil || auth.Attributes == nil { return 0 @@ -411,6 +847,18 @@ func canonicalModelKey(model string) string { return modelName } +func canonicalModelLookupKey(model string) string { + return strings.ToLower(canonicalModelKey(model)) +} + +func sameCanonicalModelKey(left, right string) bool { + leftKey := canonicalModelLookupKey(left) + if leftKey == "" { + return false + } + return leftKey == canonicalModelLookupKey(right) +} + func authWebsocketsEnabled(auth *Auth) bool { if auth == nil { return false @@ -545,7 +993,10 @@ func getAvailableAuthsWithPriorityModeForRequest(ctx context.Context, auths []*A if resetIn < 0 { resetIn = 0 } - return nil, newModelCooldownError(model, providerForError, resetIn) + claudeCooldown, claudeSignals := claudeCooldownMetadataForAuths(ctx, auths, func(*Auth) string { + return model + }, now, clientHeaders...) + return nil, newModelCooldownErrorForCandidates(model, providerForError, resetIn, nil, claudeCooldown, claudeSignals) } return nil, newAuthUnavailableError(earliest, now) } @@ -628,7 +1079,7 @@ func (s *RoundRobinSelector) Pick(ctx context.Context, provider, model string, o return nil, err } available = preferCodexWebsocketAuths(ctx, provider, available) - key := provider + ":" + canonicalModelKey(model) + key := provider + ":" + canonicalModelLookupKey(model) s.mu.Lock() defer s.mu.Unlock() if s.lastPicked == nil { @@ -680,44 +1131,18 @@ func positiveWeightAuths(auths []*Auth) []*Auth { // Pick selects the next available auth using smooth weighted round-robin. func (s *WeightedRoundRobinSelector) Pick(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth) (*Auth, error) { - _ = opts - available, errAvailable := getSelectorAvailableAuths(ctx, positiveWeightAuths(auths), provider, model, time.Now()) - if errAvailable != nil { - return nil, errAvailable - } - available = preferCodexWebsocketAuths(ctx, provider, available) - stateModel := weightedSelectorStateModel(ctx, model) - key := provider + ":" + canonicalModelKey(stateModel) - - s.mu.Lock() - defer s.mu.Unlock() - if s.states == nil { - s.states = make(map[string]*smoothWeightedState) - } - limit := s.maxKeys - if limit <= 0 { - limit = 4096 - } - if _, ok := s.states[key]; !ok && len(s.states) >= limit { - s.states = make(map[string]*smoothWeightedState) - } - state := s.states[key] - if state == nil { - state = &smoothWeightedState{} - s.states[key] = state - } - weights := authWeightVector(available) - state.prepare(weights) - picked := pickSmoothWeightedAuth(available, state.current) - if picked == nil { - return nil, &Error{Code: "auth_unavailable", Message: "no auth available with positive weight"} + picked, reservation, errPick := s.reserveForRequest(ctx, provider, model, opts, auths, nil) + if errPick != nil { + return nil, errPick } + reservation.finish(true) return picked, nil } -// maxSmoothWeightedStateEntries bounds a single accumulator map so credentials that are -// removed permanently cannot leak entries. Real pools stay far below this bound, so the -// transient subsets produced by retry exclusions and cooldowns are never pruned. +// maxSmoothWeightedStateEntries is the floor bound on a single accumulator map so +// permanently removed credentials cannot leak entries on small pools. Larger pools scale +// their prune bound with the historical peak size (2*peak) so transient retry exclusions +// and cooldowns never wipe accumulated credits. const maxSmoothWeightedStateEntries = 1024 // prepare syncs the configured weights into the state without discarding accumulated @@ -726,6 +1151,9 @@ const maxSmoothWeightedStateEntries = 1024 // affinity), because discarding credits there would collapse selection onto the first // candidate in slice order. func (s *smoothWeightedState) prepare(weights map[string]int64) { + if len(weights) > s.peak { + s.peak = len(weights) + } if s.current == nil || weightsConfigChanged(s.weights, weights) { s.current = make(map[string]int64, len(weights)) } @@ -738,10 +1166,18 @@ func (s *smoothWeightedState) prepare(weights map[string]int64) { s.pruneStale(weights) } +func (s *smoothWeightedState) pruneLimit() int { + if scaled := 2 * s.peak; scaled > maxSmoothWeightedStateEntries { + return scaled + } + return maxSmoothWeightedStateEntries +} + // pruneStale drops entries for credentials outside the current candidate set, but only -// once a map exceeds the safety bound, so ordinary transient exclusions keep their credits. +// once a map exceeds the scaled safety bound, so transient exclusions keep their credits. func (s *smoothWeightedState) pruneStale(weights map[string]int64) { - if len(s.current) <= maxSmoothWeightedStateEntries && len(s.weights) <= maxSmoothWeightedStateEntries { + limit := s.pruneLimit() + if len(s.current) <= limit && len(s.weights) <= limit { return } for authID := range s.current { @@ -784,29 +1220,6 @@ func authWeightVector(auths []*Auth) map[string]int64 { return weights } -func pickSmoothWeightedAuth(auths []*Auth, current map[string]int64) *Auth { - var picked *Auth - var pickedCurrent int64 - var totalWeight int64 - for _, auth := range auths { - weight := authWeight(auth) - if auth == nil || weight <= 0 { - continue - } - current[auth.ID] = saturatingAddInt64(current[auth.ID], weight) - totalWeight = saturatingAddInt64(totalWeight, weight) - if picked == nil || current[auth.ID] > pickedCurrent { - picked = auth - pickedCurrent = current[auth.ID] - } - } - if picked == nil { - return nil - } - current[picked.ID] = saturatingAddInt64(current[picked.ID], -totalWeight) - return picked -} - func saturatingAddInt64(value, delta int64) int64 { if delta > 0 && value > math.MaxInt64-delta { return math.MaxInt64 @@ -855,19 +1268,76 @@ func isAuthBlockedForModelForRequest(ctx context.Context, auth *Auth, model stri if exp, ok := auth.AccessTokenExpirationTimeForRequest(ctx, clientHeaders...); ok && !exp.IsZero() && !exp.After(now) { return true, blockReasonOther, time.Time{} } + if authForce := effectiveAuthForceUntil(auth); authForce.After(now) && auth.NextRetryAfter.After(now) { + next := authForce + if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(next) { + next = auth.Quota.NextRecoverAt + } + if model != "" && len(auth.ModelStates) > 0 { + modelKey := canonicalModelLookupKey(model) + for stateModel, state := range auth.ModelStates { + if state == nil || canonicalModelLookupKey(stateModel) != modelKey { + continue + } + if state.Status == StatusDisabled { + return true, blockReasonDisabled, time.Time{} + } + stateBlocked, _, stateNext := availabilityBlock(state.Unavailable, state.Quota.Exceeded, state.NextRetryAfter, state.Quota.NextRecoverAt, now) + if stateBlocked && stateNext.After(next) { + next = stateNext + } + } + } + return true, blockReasonCooldown, next + } if auth.Quota.Exceeded && auth.Quota.Reason == "credential_quota" && auth.Quota.NextRecoverAt.After(now) { - return true, blockReasonCooldown, auth.Quota.NextRecoverAt + credNext := auth.Quota.NextRecoverAt + if model != "" && len(auth.ModelStates) > 0 { + modelKey := canonicalModelLookupKey(model) + for stateModel, state := range auth.ModelStates { + if state == nil || canonicalModelLookupKey(stateModel) != modelKey { + continue + } + if state.Status == StatusDisabled { + return true, blockReasonDisabled, time.Time{} + } + stateBlocked, _, next := availabilityBlock(state.Unavailable, state.Quota.Exceeded, state.NextRetryAfter, state.Quota.NextRecoverAt, now) + if stateBlocked && next.After(credNext) { + credNext = next + } + } + } + return true, blockReasonCooldown, credNext + } + if !auth.credentialRetryAfter.IsZero() && auth.credentialRetryAfter.After(now) { + credNext := auth.credentialRetryAfter + if model != "" && len(auth.ModelStates) > 0 { + modelKey := canonicalModelLookupKey(model) + for stateModel, state := range auth.ModelStates { + if state == nil || canonicalModelLookupKey(stateModel) != modelKey { + continue + } + if state.Status == StatusDisabled { + return true, blockReasonDisabled, time.Time{} + } + stateBlocked, _, next := availabilityBlock(state.Unavailable, state.Quota.Exceeded, state.NextRetryAfter, state.Quota.NextRecoverAt, now) + if stateBlocked && next.After(credNext) { + credNext = next + } + } + } + return true, blockReasonOther, credNext } unavailable := codexRefreshUnavailableForRequest(ctx, auth, now, clientHeaders...) if model != "" { if len(auth.ModelStates) > 0 { - modelKey := canonicalModelKey(model) + modelKey := canonicalModelLookupKey(model) matched := false blocked := false blockedReason := blockReasonNone nextRetry := time.Time{} for stateModel, state := range auth.ModelStates { - if state == nil || canonicalModelKey(stateModel) != modelKey { + if state == nil || canonicalModelLookupKey(stateModel) != modelKey { continue } matched = true @@ -938,6 +1408,7 @@ type SessionAffinitySelector struct { matcher *cliproxysession.MerklePrefixMatcher subagentAffinity bool rebindOnQuotaOnly bool + rebindOnNever bool } const ( @@ -946,12 +1417,17 @@ const ( // SessionAffinityRebindOnQuota preserves the existing session binding across transient failures // and only rebinds on quota, auth, model-support, or permanent unavailability. SessionAffinityRebindOnQuota = "quota" + // SessionAffinityRebindOnNever preserves the existing session binding across all failures + // and refuses to fail over a bound session to another credential. + SessionAffinityRebindOnNever = "never" ) func normalizeSessionAffinityRebindOn(value string) string { switch strings.ToLower(strings.TrimSpace(value)) { case SessionAffinityRebindOnQuota: return SessionAffinityRebindOnQuota + case SessionAffinityRebindOnNever: + return SessionAffinityRebindOnNever default: return SessionAffinityRebindOnAny } @@ -1016,9 +1492,9 @@ func isAuthBlockedByQuotaOrAuthForModelForRequest(ctx context.Context, auth *Aut return true } if model != "" && len(auth.ModelStates) > 0 { - modelKey := canonicalModelKey(model) + modelKey := canonicalModelLookupKey(model) for stateModel, state := range auth.ModelStates { - if state == nil || canonicalModelKey(stateModel) != modelKey { + if state == nil || canonicalModelLookupKey(stateModel) != modelKey { continue } if state.Status == StatusDisabled { @@ -1053,7 +1529,7 @@ func isStateBlockedByQuotaOrAuth(unavailable bool, quota QuotaState, nextRetryAf } func (s *SessionAffinitySelector) shouldPreserveBindingWhenUnavailable(ctx context.Context, candidates []*Auth, model, authID string, now time.Time) bool { - if s == nil || !s.rebindOnQuotaOnly || authID == "" { + if s == nil || (!s.rebindOnQuotaOnly && !s.rebindOnNever) || authID == "" { return false } if ctx != nil { @@ -1071,6 +1547,23 @@ func (s *SessionAffinitySelector) shouldPreserveBindingWhenUnavailable(ctx conte return false } +func (s *SessionAffinitySelector) unavailableBoundAuthError(ctx context.Context, candidates []*Auth, model, authID string, now time.Time) *Error { + if s.shouldPreserveBindingWhenUnavailable(ctx, candidates, model, authID, now) { + return &Error{ + Code: "session_auth_retry", + Message: "bound session credential is transiently unavailable", + Retryable: true, + HTTPStatus: http.StatusServiceUnavailable, + } + } + return &Error{ + Code: "session_auth_unavailable", + Message: "bound session credential is unavailable", + Retryable: false, + HTTPStatus: http.StatusTooManyRequests, + } +} + // SessionAffinityConfig configures the session affinity selector. type SessionAffinityConfig struct { Fallback Selector @@ -1099,13 +1592,14 @@ func NewSessionAffinitySelectorWithConfig(cfg SessionAffinityConfig) *SessionAff if cfg.SubagentAffinity != nil { subagentAffinity = *cfg.SubagentAffinity } - rebindOnQuotaOnly := normalizeSessionAffinityRebindOn(cfg.RebindOn) == SessionAffinityRebindOnQuota + rebindMode := normalizeSessionAffinityRebindOn(cfg.RebindOn) return &SessionAffinitySelector{ fallback: cfg.Fallback, cache: NewSessionCache(cfg.TTL), matcher: cliproxysession.NewMerklePrefixMatcher(cfg.TTL), subagentAffinity: subagentAffinity, - rebindOnQuotaOnly: rebindOnQuotaOnly, + rebindOnQuotaOnly: rebindMode == SessionAffinityRebindOnQuota, + rebindOnNever: rebindMode == SessionAffinityRebindOnNever, } } @@ -1128,7 +1622,16 @@ func (s *SessionAffinitySelector) Trees() *cliproxysession.InMemorySessionTreeSt // Note: The cache key includes provider, session ID, and model to handle cases where // a session uses multiple models (e.g., gemini-2.5-pro and gemini-3-flash-preview) // that may be supported by different auth credentials, and to avoid cross-provider conflicts. -func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth) (*Auth, error) { +func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth) (selected *Auth, errPick error) { + if ctx == nil { + ctx = context.Background() + } + if errContext := ctx.Err(); errContext != nil { + return nil, errContext + } + var reservation *weightedReservation + // Local bindings complete inside Pick; failed selections release speculative credit. + defer func() { reservation.finish(selected != nil && errPick == nil) }() entry := selectorLogEntry(ctx) if opts.Metadata == nil { opts.Metadata = make(map[string]any) @@ -1140,7 +1643,7 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri // consulted when no header, body, or execution-session identity is present. explicitID, explicitFallbackID := extractExplicitSessionIDs(opts.Headers, opts.OriginalRequest, opts.Metadata) if explicitID == "" { - if auth, handled, errLCP := s.pickLCP(ctx, provider, model, opts, auths, entry); handled || errLCP != nil { + if auth, handled, errLCP := s.pickLCP(ctx, provider, model, opts, auths, entry, &reservation); handled || errLCP != nil { return auth, errLCP } } else if opts.Metadata != nil { @@ -1182,13 +1685,13 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri return nil, errAvailable } entry.Debugf("session-affinity: no session ID extracted, falling back to default selector | provider=%s model=%s", provider, model) - return s.fallback.Pick(ctx, provider, model, opts, fallbackAuths) + return s.pickWithAffinityReservation(ctx, provider, model, opts, fallbackAuths, nil, &reservation) } // A single availability pass serves both lookups: the bound credential is validated against // every priority tier, while the fallback selector keeps seeing only the highest tier. available, err := getSelectorAvailableAuthsAcrossPriorities(ctx, availabilityCandidates, provider, model, now) - if err != nil { + if err != nil && !s.rebindOnNever { return nil, err } fallbackAuths := highestPriorityAuths(available) @@ -1232,11 +1735,20 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri if auth.ID == cachedAuthID { bind(auth.ID, true) entry.Infof("session-affinity: cache hit | session=%s auth=%s provider=%s model=%s", truncateSessionID(primaryID), auth.ID, provider, model) - return auth, nil + return s.pickWithAffinityReservation(ctx, provider, model, opts, available, auth, &reservation) } } + if s.rebindOnNever { + bind(cachedAuthID, false) + errBound := s.unavailableBoundAuthError(ctx, availabilityCandidates, model, cachedAuthID, now) + entry.Infof("session-affinity: cache hit but bound auth unavailable, refusing failover | session=%s bound_auth=%s code=%s provider=%s model=%s", truncateSessionID(primaryID), cachedAuthID, errBound.Code, provider, model) + return nil, errBound + } + if err != nil { + return nil, err + } // Cached auth not available, reselect via fallback selector for even distribution - auth, err := s.fallback.Pick(ctx, provider, model, opts, fallbackAuths) + auth, err := s.pickWithAffinityReservation(ctx, provider, model, opts, fallbackAuths, nil, &reservation) if err != nil { return nil, err } @@ -1270,7 +1782,7 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri if auth.ID == parentAuthID { bind(auth.ID, true) entry.Infof("session-affinity: guardian inherited parent binding | session=%s parent=%s auth=%s provider=%s model=%s", truncateSessionID(primaryID), truncateSessionID(fallbackID), auth.ID, provider, model) - return auth, nil + return s.pickWithAffinityReservation(ctx, provider, model, opts, available, auth, &reservation) } } } @@ -1287,12 +1799,18 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri } else { entry.Infof("session-affinity: fallback cache hit | session=%s fallback=%s auth=%s provider=%s model=%s", truncateSessionID(primaryID), truncateSessionID(fallbackID), auth.ID, provider, model) } - return auth, nil + return s.pickWithAffinityReservation(ctx, provider, model, opts, available, auth, &reservation) } } } + if !isSubagent && !isFork && s.rebindOnNever { + bind(cachedAuthID, false) + errBound := s.unavailableBoundAuthError(ctx, availabilityCandidates, model, cachedAuthID, now) + entry.Infof("session-affinity: fallback cache hit but bound auth unavailable, refusing failover | session=%s fallback=%s bound_auth=%s code=%s provider=%s model=%s", truncateSessionID(primaryID), truncateSessionID(fallbackID), cachedAuthID, errBound.Code, provider, model) + return nil, errBound + } if !isSubagent && !isFork && s.shouldPreserveBindingWhenUnavailable(ctx, availabilityCandidates, model, cachedAuthID, now) { - auth, err := s.fallback.Pick(ctx, provider, model, opts, fallbackAuths) + auth, err := s.pickWithAffinityReservation(ctx, provider, model, opts, fallbackAuths, nil, &reservation) if err != nil { return nil, err } @@ -1306,7 +1824,10 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri } } - auth, err := s.fallback.Pick(ctx, provider, model, opts, fallbackAuths) + if err != nil { + return nil, err + } + auth, err := s.pickWithAffinityReservation(ctx, provider, model, opts, fallbackAuths, nil, &reservation) if err != nil { return nil, err } @@ -1322,7 +1843,7 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri return auth, nil } -func (s *SessionAffinitySelector) pickLCP(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth, entry *log.Entry) (*Auth, bool, error) { +func (s *SessionAffinitySelector) pickLCP(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth, entry *log.Entry, reservation **weightedReservation) (*Auth, bool, error) { if s == nil || s.matcher == nil { return nil, false, nil } @@ -1351,7 +1872,7 @@ func (s *SessionAffinitySelector) pickLCP(ctx context.Context, provider, model s } now := time.Now() available, errAvailable := getSelectorAvailableAuthsAcrossPriorities(ctx, availabilityCandidates, provider, model, now) - if errAvailable != nil { + if errAvailable != nil && !s.rebindOnNever { return nil, true, errAvailable } @@ -1395,15 +1916,47 @@ func (s *SessionAffinitySelector) pickLCP(ctx context.Context, provider, model s } entry.Infof("session-affinity: LCP cache hit | session=%s prefix=%d auth=%s provider=%s model=%s", truncateSessionID(match.SessionID), match.PrefixLength, auth.ID, provider, model) } - return auth, true, nil + picked, errPick := s.pickWithAffinityReservation(ctx, provider, model, opts, available, auth, reservation) + return picked, true, errPick + } + if !match.IsFork && s.rebindOnNever { + if bindRes := s.matcher.BindFingerprintsWithContext(namespace, fingerprints, tailFingerprints, envDigest, minPrefixLength, match.AuthID); bindRes.SessionID != "" { + opts.Metadata[cliproxyexecutor.LCPAffinitySessionIDMetadataKey] = bindRes.SessionID + opts.Metadata[cliproxyexecutor.CanonicalSessionIDMetadataKey] = bindRes.SessionID + if bindRes.ParentSessionID != "" { + opts.Metadata[cliproxyexecutor.ParentSessionIDMetadataKey] = bindRes.ParentSessionID + } else if opts.Metadata != nil { + delete(opts.Metadata, cliproxyexecutor.ParentSessionIDMetadataKey) + } + if bindRes.AccessNumber > 0 && opts.Metadata != nil { + opts.Metadata[cliproxyexecutor.LCPAccessGenerationMetadataKey] = bindRes.AccessNumber + } + if bindRes.IsCompaction { + if opts.Metadata != nil { + opts.Metadata[cliproxyexecutor.IsCompactionMetadataKey] = true + delete(opts.Metadata, cliproxyexecutor.IsForkMetadataKey) + opts.Metadata[cliproxyexecutor.NodeKindMetadataKey] = "compaction" + } + } else if opts.Metadata != nil { + delete(opts.Metadata, cliproxyexecutor.IsForkMetadataKey) + delete(opts.Metadata, cliproxyexecutor.IsCompactionMetadataKey) + delete(opts.Metadata, cliproxyexecutor.NodeKindMetadataKey) + } + } + errBound := s.unavailableBoundAuthError(ctx, availabilityCandidates, model, match.AuthID, now) + entry.Infof("session-affinity: LCP cache hit but bound auth unavailable, refusing failover | session=%s bound_auth=%s code=%s provider=%s model=%s", truncateSessionID(match.SessionID), match.AuthID, errBound.Code, provider, model) + return nil, true, errBound } if !match.IsFork && s.shouldPreserveBindingWhenUnavailable(ctx, availabilityCandidates, model, match.AuthID, now) { preservedAuthID = match.AuthID } } + if errAvailable != nil { + return nil, true, errAvailable + } fallbackAuths := highestPriorityAuths(available) - auth, errPick := s.fallback.Pick(ctx, provider, model, opts, fallbackAuths) + auth, errPick := s.pickWithAffinityReservation(ctx, provider, model, opts, fallbackAuths, nil, reservation) if errPick != nil { return nil, true, errPick } @@ -1587,6 +2140,30 @@ func (s *SessionAffinitySelector) InvalidateAuth(authID string) { } } +// ForgetAuth forwards permanent credential removal to the fallback selector so +// weighted round-robin accounting can prune deregistered credentials without +// disturbing credits of transiently excluded credentials. +func (s *SessionAffinitySelector) ForgetAuth(authID string) { + s.ForgetAuthUpTo(authID, ^uint64(0), ^uint64(0)) +} + +// ForgetAuthUpTo forwards epoch-gated permanent credential removal to the fallback selector +// so delayed removals never evict a newly re-registered credential with the same ID. +func (s *SessionAffinitySelector) ForgetAuthUpTo(authID string, maxEpoch, maxGen uint64) { + if s == nil || authID == "" { + return + } + if epochForgetter, ok := s.fallback.(interface { + ForgetAuthUpTo(string, uint64, uint64) + }); ok && epochForgetter != nil { + epochForgetter.ForgetAuthUpTo(authID, maxEpoch, maxGen) + return + } + if forgetter, ok := s.fallback.(interface{ ForgetAuth(string) }); ok && forgetter != nil { + forgetter.ForgetAuth(authID) + } +} + // LookupAffinity observes the current session affinity binding without side effects. // It never selects a credential, creates a binding, rebinds, or refreshes TTL. // Optional authFilters allow callers (such as Manager) to exclude credentials that do not match the requested provider. @@ -1714,9 +2291,9 @@ func (s *SessionAffinitySelector) OnResult(res Result) { // selected credential is unhealthy, so preserve both explicit and LCP bindings. return } - if !res.Success && s.rebindOnQuotaOnly && !shouldRebindSessionAffinityOnError(res.Error) { - // Under session-affinity-rebind-on: quota, transient failures fail over for - // the current request without unbinding the session from its bound credential. + if !res.Success && (s.rebindOnNever || (s.rebindOnQuotaOnly && !shouldRebindSessionAffinityOnError(res.Error))) { + // Under session-affinity-rebind-on: never (or quota on transient failures), + // keep the session bound to its original credential. return } @@ -1796,6 +2373,75 @@ func (s *SessionAffinitySelector) OnResult(res Result) { } } +func (s *SessionAffinitySelector) boundAuthForRequest(providers []string, model string, opts cliproxyexecutor.Options) (string, bool) { + if s == nil { + return "", false + } + modelKey := canonicalModelKey(model) + candidateProviders := make([]string, 0, len(providers)+1) + candidateProviders = append(candidateProviders, "mixed") + for _, p := range providers { + p = strings.TrimSpace(p) + if p != "" && p != "mixed" { + candidateProviders = append(candidateProviders, p) + } + } + + explicitID, explicitFallbackID := extractExplicitSessionIDs(opts.Headers, opts.OriginalRequest, opts.Metadata) + if explicitID == "" && s.matcher != nil { + turns := cliproxysession.ExtractCanonicalTurns(opts.SourceFormat, opts.OriginalRequest) + if len(turns) > 0 { + fingerprints, minPrefixLength, tailFingerprints, envDigest := s.matcher.PrepareExt(turns) + if len(fingerprints) > 0 && minPrefixLength > 0 && minPrefixLength <= len(fingerprints) { + for _, candProvider := range candidateProviders { + if namespace := lcpAffinityNamespace(candProvider, model, opts.Metadata); namespace != "" { + if match, ok := s.matcher.MatchFingerprintsWithContext(namespace, fingerprints, tailFingerprints, envDigest, minPrefixLength); ok && !match.IsFork && match.AuthID != "" { + return match.AuthID, true + } + } + } + } + } + } + + if s.cache == nil { + return "", false + } + primaryID, fallbackID := explicitID, explicitFallbackID + if primaryID == "" { + primaryID, fallbackID = extractSessionIDs(opts.Headers, opts.OriginalRequest, opts.Metadata) + } + if primaryID != "" { + primaryID = cliproxysession.BoundSessionIdentity(primaryID) + } + if fallbackID != "" { + fallbackID = cliproxysession.BoundSessionIdentity(fallbackID) + } + isFork := false + if opts.Metadata != nil { + if forkFlag, ok := opts.Metadata[cliproxyexecutor.IsForkMetadataKey].(bool); ok && forkFlag { + isFork = true + } + } + isSubagent := !isFork && isSubagentSession(primaryID, fallbackID) + + if primaryID != "" { + for _, candProvider := range candidateProviders { + if authID, ok := s.cache.Get(candProvider + "::" + primaryID + "::" + modelKey); ok && authID != "" { + return authID, true + } + } + } + if fallbackID != "" && fallbackID != primaryID && !isSubagent && !isFork { + for _, candProvider := range candidateProviders { + if authID, ok := s.cache.Get(candProvider + "::" + fallbackID + "::" + modelKey); ok && authID != "" { + return authID, true + } + } + } + return "", false +} + // isGuardianRequest deliberately matches the header, not the configurable review model. func isGuardianRequest(headers http.Header) bool { for key, values := range headers { diff --git a/sdk/cliproxy/auth/selector_test.go b/sdk/cliproxy/auth/selector_test.go index 18ed81f30f4..37678684b25 100644 --- a/sdk/cliproxy/auth/selector_test.go +++ b/sdk/cliproxy/auth/selector_test.go @@ -205,16 +205,14 @@ func TestAuthWeight_InvalidAndOverflowValuesAreExcluded(t *testing.T) { } } -func TestPickSmoothWeightedAuth_SaturatesCorruptState(t *testing.T) { +func TestSmoothWeightedStateCharge_SaturatesAndClampsCorruptState(t *testing.T) { t.Parallel() - current := map[string]int64{"a": math.MaxInt64, "b": math.MinInt64} - picked := pickSmoothWeightedAuth([]*Auth{{ID: "a"}, {ID: "b"}}, current) - if picked == nil { - t.Fatal("pickSmoothWeightedAuth() returned nil") - } - if current["a"] != math.MaxInt64-2 || current["b"] != math.MinInt64+1 { - t.Fatalf("current state = %#v, want saturated arithmetic", current) + state := weightedPoolForTest("route", map[string]int64{"a": 1, "b": 1}, map[string]int64{"a": math.MaxInt64, "b": math.MinInt64}) + state.charge(0, false) + limit := maxSmoothWeightedCreditRounds * 2 + if state.currentForTest()["a"] != limit || state.currentForTest()["b"] != -limit { + t.Fatalf("current state = %#v, want saturated and clamped arithmetic", state.currentForTest()) } } diff --git a/sdk/cliproxy/auth/selector_weighted.go b/sdk/cliproxy/auth/selector_weighted.go new file mode 100644 index 00000000000..c048c3b0d2c --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted.go @@ -0,0 +1,922 @@ +package auth + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "math" + "sort" + "strconv" + "time" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +// weightedAccountingPoolKey carries the manager-validated pre-pin pool. It affects +// accounting only; the selector still receives pin-filtered selection candidates. +type weightedAccountingPoolKey struct{} + +// weightedTransportProviderKey preserves single-provider transport preference on +// the mixed entrypoint without changing its weighted accounting namespace. +type weightedTransportProviderKey struct{} + +// weightedReservation separates speculative credit from committed, clamped credit. +// Releasing one request must never undo accounting committed by another request. +type weightedReservation struct { + selector *WeightedRoundRobinSelector + state *weightedPoolState + generation uint64 + member int + selectedID string + selectedEpoch uint64 + candidateIDs []string + candidateEpochs []uint64 + total int64 + bound bool + finished bool +} + +// pickWithAffinityReservation normalizes weighted candidates and defers accounting +// until the local binding completes. Other fallback selectors keep their behavior. +func (s *SessionAffinitySelector) pickWithAffinityReservation(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth, bound *Auth, reservation **weightedReservation) (*Auth, error) { + weighted, ok := s.fallback.(*WeightedRoundRobinSelector) + if !ok { + if bound != nil { + return bound, nil + } + return s.fallback.Pick(ctx, provider, model, opts, auths) + } + picked, pending, errPick := weighted.reserveForRequest(ctx, provider, model, opts, auths, bound) + *reservation = pending + return picked, errPick +} + +// reserveForRequest shares candidate normalization and pinned accounting between +// bare weighted routing and session affinity, which owns deferred confirmation. +func (s *WeightedRoundRobinSelector) reserveForRequest(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth, bound *Auth) (*Auth, *weightedReservation, error) { + if ctx == nil { + ctx = context.Background() + } + if errContext := ctx.Err(); errContext != nil { + return nil, nil, errContext + } + if accountingAuths, ok := ctx.Value(weightedAccountingPoolKey{}).([]*Auth); ok { + pinnedID := pinnedAuthIDFromMetadata(opts.Metadata) + if bound == nil { + for _, auth := range auths { + if auth != nil && auth.ID == pinnedID { + bound = auth + break + } + } + } + if bound == nil || bound.ID != pinnedID || authWeight(bound) <= 0 { + return nil, nil, &Error{Code: "auth_unavailable", Message: "pinned auth is not available for weighted accounting"} + } + auths = positiveWeightAuths(accountingAuths) + } + transportProvider := provider + if singleProvider, ok := ctx.Value(weightedTransportProviderKey{}).(string); ok { + transportProvider = singleProvider + } + if providerPrefersWebsocketTransport(transportProvider) { + // Reuse the transport filter for every provider preferred by the scheduler. + transportProvider = "codex" + } + var available []*Auth + authID := "" + transportClass := "" + if bound == nil { + var errAvailable error + available, errAvailable = getSelectorAvailableAuths(ctx, positiveWeightAuths(auths), provider, model, time.Now()) + if errAvailable != nil { + return nil, nil, errAvailable + } + available = preferCodexWebsocketAuths(ctx, transportProvider, available) + if cliproxyexecutor.DownstreamWebsocket(ctx) && transportProvider == "codex" && len(available) > 0 { + if authWebsocketsEnabled(available[0]) { + transportClass = "ws" + } else { + transportClass = "http" + } + } + } else { + authID = bound.ID + // A binding may bypass priority or transport preference, but its traffic + // must only charge peers that compete with it, never another priority tier. + priority := authPriority(bound) + for _, auth := range auths { + if authPriority(auth) == priority { + available = append(available, auth) + } + } + preferred := preferCodexWebsocketAuths(ctx, transportProvider, available) + if len(preferred) < len(available) && !authWebsocketsEnabled(bound) { + // Keep an HTTP-bound session outside the preferred WebSocket pool. + nonWebsocket := available[:0] + for _, auth := range available { + if !authWebsocketsEnabled(auth) { + nonWebsocket = append(nonWebsocket, auth) + } + } + available = nonWebsocket + transportClass = "http" + } else { + available = preferred + if cliproxyexecutor.DownstreamWebsocket(ctx) && transportProvider == "codex" && len(available) > 0 { + if authWebsocketsEnabled(available[0]) { + transportClass = "ws" + } else { + transportClass = "http" + } + } + } + } + priority := inferredWeightedPoolPriority(available) + key := provider + ":" + canonicalModelLookupKey(weightedSelectorStateModel(ctx, model)) + picked, pending := s.reserveScoped(key, priority, transportClass, available, authID) + if picked == nil { + return nil, nil, &Error{Code: "auth_unavailable", Message: "no auth available with positive weight"} + } + return picked, pending, nil +} + +// weightedPoolMember stores each ID once, with parallel accounting values in a +// single allocation. Members are sorted by ID; reservations retain only an index. +type weightedPoolMember struct { + id string + weight int64 + current int64 + pending int64 + epoch uint64 + regEpoch uint64 + regGen uint64 + inFlight uint32 +} + +type weightedAuthVersion struct { + regEpoch uint64 + regGen uint64 +} + +func extractWeightedAuthVersions(available []*Auth, ids []string) []weightedAuthVersion { + versions := make([]weightedAuthVersion, len(ids)) + if len(available) == len(ids) { + sortedMatch := true + for i, auth := range available { + if auth == nil || auth.ID != ids[i] { + sortedMatch = false + break + } + versions[i] = weightedAuthVersion{regEpoch: auth.RegistrationEpoch, regGen: auth.Generation} + } + if sortedMatch { + return versions + } + clear(versions) + } + for _, auth := range available { + if auth == nil { + continue + } + idx := sort.SearchStrings(ids, auth.ID) + if idx < len(ids) && ids[idx] == auth.ID { + v := weightedAuthVersion{regEpoch: auth.RegistrationEpoch, regGen: auth.Generation} + if v.regEpoch > versions[idx].regEpoch || (v.regEpoch == versions[idx].regEpoch && v.regGen > versions[idx].regGen) { + versions[idx] = v + } + } + } + return versions +} + +func memberOlderOrEqual(member weightedPoolMember, maxEpoch, maxGen uint64) bool { + if member.regEpoch != maxEpoch { + return member.regEpoch < maxEpoch + } + return member.regGen <= maxGen +} + +// weightedPoolState is separate from the scheduler's transient-subset accumulator: +// each selector pool has fixed membership and shares its weights across reservations. +type weightedPoolState struct { + route string + members []weightedPoolMember + inFlight uint64 + generation uint64 + next *weightedPoolState // Exact-identity collision chain for the digest key. + dynamic bool // Shared bucket-scoped accumulator for pools > maxExactWeightedPoolMembers. + peak int // Largest candidate count observed on a dynamic pool. + nextMemberEpoch uint64 // Monotonic member identity counter isolating removed/re-added IDs. + lastActiveIDs []string // Most recent active candidate IDs for post-drain compaction. +} + +// maxExactWeightedPoolMembers is the candidate-set size above which exact-membership +// pools switch to a shared bucket-scoped dynamic accumulator so transient retry +// exclusions and cooldowns cannot collapse smooth WRR onto the lowest Auth.IDs. +const maxExactWeightedPoolMembers = maxSmoothWeightedStateEntries + +func inferredWeightedPoolPriority(available []*Auth) int { + for _, auth := range available { + if auth != nil { + return authPriority(auth) + } + } + return 0 +} + +func dynamicWeightedPoolKey(route string, priority int, transportClass string) string { + if priority == 0 && transportClass == "" { + return route + } + return route + "\x00p=" + strconv.Itoa(priority) + "\x00t=" + transportClass +} + +func sortedWeightedIDs(weights map[string]int64) []string { + ids := make([]string, 0, len(weights)) + for id := range weights { + ids = append(ids, id) + } + sort.Strings(ids) + return ids +} + +// weightedPoolStateKey isolates competing sets without retaining concatenated IDs. +// Weights stay out of the key so configuration changes invalidate reservations. +func weightedPoolStateKey(route string, weights map[string]int64) [32]byte { + return weightedPoolDigest(route, sortedWeightedIDs(weights)) +} + +func weightedPoolDigest(route string, ids []string) [32]byte { + size := 8 + len(route) + for _, id := range ids { + size += 8 + len(id) + } + identity := make([]byte, 0, size) + identity = binary.LittleEndian.AppendUint64(identity, uint64(len(route))) + identity = append(identity, route...) + for _, id := range ids { + identity = binary.LittleEndian.AppendUint64(identity, uint64(len(id))) + identity = append(identity, id...) + } + return sha256.Sum256(identity) +} + +// matches verifies the full identity even on a digest hit. Hash collisions must +// never combine the quota or configured weights of unrelated candidate pools. +func (s *weightedPoolState) matches(route string, ids []string) bool { + if s.route != route || len(s.members) != len(ids) { + return false + } + for i, id := range ids { + if s.members[i].id != id { + return false + } + } + return true +} + +func (s *weightedPoolState) prepareWithVersions(weights []int64, versions []weightedAuthVersion) { + weightChanged := false + epochReplaced := false + for i, member := range s.members { + if member.weight != weights[i] { + weightChanged = true + break + } + if member.regEpoch > 0 && versions[i].regEpoch > member.regEpoch { + epochReplaced = true + } + } + if weightChanged { + s.generation++ + s.inFlight = 0 + for i := range s.members { + s.members[i].weight = weights[i] + s.members[i].current = 0 + s.members[i].pending = 0 + s.members[i].regEpoch = versions[i].regEpoch + s.members[i].regGen = versions[i].regGen + } + return + } + if epochReplaced { + s.generation++ + s.inFlight = 0 + var totalWeight int64 + for i := range s.members { + s.members[i].pending = 0 + if s.members[i].regEpoch > 0 && versions[i].regEpoch > s.members[i].regEpoch { + s.members[i].current = 0 + } + if versions[i].regEpoch > s.members[i].regEpoch || + (versions[i].regEpoch == s.members[i].regEpoch && versions[i].regGen > s.members[i].regGen) { + s.members[i].regEpoch = versions[i].regEpoch + s.members[i].regGen = versions[i].regGen + } + totalWeight = saturatingAddInt64(totalWeight, s.members[i].weight) + } + if totalWeight > 0 { + s.boundCredits(totalWeight) + } + return + } + for i := range s.members { + if versions[i].regEpoch > s.members[i].regEpoch || + (versions[i].regEpoch == s.members[i].regEpoch && versions[i].regGen > s.members[i].regGen) { + s.members[i].regEpoch = versions[i].regEpoch + s.members[i].regGen = versions[i].regGen + } + } +} + +// reserve selects and reserves credit atomically. A non-empty authID preserves a +// sticky binding; otherwise committed and pending credits both guide selection. +func (s *WeightedRoundRobinSelector) reserve(route string, available []*Auth, authID string) (*Auth, *weightedReservation) { + return s.reserveScoped(route, inferredWeightedPoolPriority(available), "", available, authID) +} + +func (s *WeightedRoundRobinSelector) reserveScoped(route string, priority int, transportClass string, available []*Auth, authID string) (*Auth, *weightedReservation) { + weightVector := authWeightVector(available) + ids := sortedWeightedIDs(weightVector) + weights := make([]int64, len(ids)) + for i, id := range ids { + weights[i] = weightVector[id] + } + return s.reservePoolScoped(route, priority, transportClass, available, weights, ids, authID) +} + +// reservePool consumes a normalized pool. Scheduler ready views already supply +// ID-sorted candidates and cached weights, avoiding sorting and cloning auths. +// ids must be sorted, with one positive weight per ID in the parallel slice. +func (s *WeightedRoundRobinSelector) reservePool(route string, available []*Auth, weights []int64, ids []string, authID string) (*Auth, *weightedReservation) { + return s.reservePoolScoped(route, inferredWeightedPoolPriority(available), "", available, weights, ids, authID) +} + +func (s *WeightedRoundRobinSelector) reservePoolScoped(route string, priority int, transportClass string, available []*Auth, weights []int64, ids []string, authID string) (*Auth, *weightedReservation) { + dKey := dynamicWeightedPoolKey(route, priority, transportClass) + versions := extractWeightedAuthVersions(available, ids) + s.mu.Lock() + defer s.mu.Unlock() + if len(ids) > maxExactWeightedPoolMembers || s.largeStates[dKey] != nil { + return s.reserveDynamicPoolLocked(dKey, route, available, weights, ids, versions, authID) + } + key := weightedPoolDigest(route, ids) + if s.states == nil { + s.states = make(map[[32]byte]*weightedPoolState) + } + state := s.states[key] + for state != nil && !state.matches(route, ids) { + state = state.next + } + if state == nil { + limit := s.poolKeyLimit() + if s.stateCount+len(s.largeStates) >= limit { + if s.stateCount > 0 { + s.states = make(map[[32]byte]*weightedPoolState) + s.stateCount = 0 + } else { + s.evictOneLargePoolLocked() + } + } + state = &weightedPoolState{route: route, members: make([]weightedPoolMember, len(ids)), next: s.states[key]} + for i, id := range ids { + state.members[i] = weightedPoolMember{ + id: id, + weight: weights[i], + regEpoch: versions[i].regEpoch, + regGen: versions[i].regGen, + } + } + s.states[key] = state + s.stateCount++ + } else { + state.prepareWithVersions(weights, versions) + } + var picked *Auth + var pickedCurrent, total int64 + pickedMember := -1 + for _, auth := range available { + if auth == nil { + continue + } + index := sort.SearchStrings(ids, auth.ID) + if index == len(ids) || ids[index] != auth.ID || weights[index] <= 0 { + continue + } + total = saturatingAddInt64(total, weights[index]) + if authID != "" && auth.ID != authID { + continue + } + member := &state.members[index] + current := saturatingAddInt64(member.current, member.pending) + current = saturatingAddInt64(current, member.weight) + if picked == nil || current > pickedCurrent { + picked, pickedCurrent, pickedMember = auth, current, index + } + } + if picked == nil { + return nil, nil + } + // Bound traffic beyond the compensation window still keeps its credential, + // but must not create speculative credit that can starve concurrent picks. + if authID != "" && !state.boundChargeFits(pickedMember, total) { + return picked, nil + } + state.adjustPending(pickedMember, total, false) + state.inFlight++ + return picked, &weightedReservation{ + selector: s, state: state, generation: state.generation, + member: pickedMember, total: total, bound: authID != "", + } +} + +func (s *WeightedRoundRobinSelector) poolKeyLimit() int { + if s.maxKeys > 0 { + return s.maxKeys + } + return 4096 +} + +func (s *WeightedRoundRobinSelector) removeLargeOrderKeyLocked(target string) { + for i, key := range s.largeOrder { + if key == target { + s.largeOrder = append(s.largeOrder[:i], s.largeOrder[i+1:]...) + return + } + } +} + +func (s *WeightedRoundRobinSelector) evictOneLargePoolLocked() { + if len(s.largeOrder) == 0 { + for k := range s.largeStates { + delete(s.largeStates, k) + return + } + return + } + for i, key := range s.largeOrder { + st := s.largeStates[key] + if st == nil || st.inFlight == 0 { + delete(s.largeStates, key) + s.largeOrder = append(s.largeOrder[:i], s.largeOrder[i+1:]...) + return + } + } + oldest := s.largeOrder[0] + s.largeOrder = s.largeOrder[1:] + delete(s.largeStates, oldest) +} + +func (s *WeightedRoundRobinSelector) reserveDynamicPoolLocked(dKey, route string, available []*Auth, weights []int64, ids []string, versions []weightedAuthVersion, authID string) (*Auth, *weightedReservation) { + if s.largeStates == nil { + s.largeStates = make(map[string]*weightedPoolState) + } + state := s.largeStates[dKey] + if state == nil { + limit := s.poolKeyLimit() + for len(s.largeStates)+s.stateCount >= limit { + if s.stateCount > 0 { + s.states = make(map[[32]byte]*weightedPoolState) + s.stateCount = 0 + if len(s.largeStates) < limit { + break + } + } + if len(s.largeStates) == 0 { + break + } + s.evictOneLargePoolLocked() + } + state = &weightedPoolState{route: route, dynamic: true} + s.largeStates[dKey] = state + s.largeOrder = append(s.largeOrder, dKey) + } + state.syncDynamicMembers(ids, weights, versions) + + var picked *Auth + var pickedEpoch uint64 + var pickedCurrent, total int64 + for _, auth := range available { + if auth == nil { + continue + } + idIndex := sort.SearchStrings(ids, auth.ID) + if idIndex == len(ids) || ids[idIndex] != auth.ID || weights[idIndex] <= 0 { + continue + } + memberIndex, okMember := state.findMember(auth.ID) + if !okMember { + continue + } + weight := weights[idIndex] + total = saturatingAddInt64(total, weight) + if authID != "" && auth.ID != authID { + continue + } + member := &state.members[memberIndex] + current := saturatingAddInt64(member.current, member.pending) + current = saturatingAddInt64(current, weight) + if picked == nil || current > pickedCurrent { + picked, pickedEpoch, pickedCurrent = auth, member.epoch, current + } + } + if picked == nil { + return nil, nil + } + candidateIDs := append([]string(nil), ids...) + state.lastActiveIDs = candidateIDs + candidateEpochs := make([]uint64, len(ids)) + for i, id := range ids { + if memberIndex, okMember := state.findMember(id); okMember { + candidateEpochs[i] = state.members[memberIndex].epoch + } + } + fullTotalWeight := max(total, state.totalMemberWeight()) + if authID != "" && !state.dynamicBoundChargeFits(candidateIDs, candidateEpochs, picked.ID, pickedEpoch, total, fullTotalWeight) { + return picked, nil + } + state.adjustDynamicPending(candidateIDs, candidateEpochs, picked.ID, pickedEpoch, total, false) + state.inFlight++ + return picked, &weightedReservation{ + selector: s, + state: state, + generation: state.generation, + selectedID: picked.ID, + selectedEpoch: pickedEpoch, + candidateIDs: candidateIDs, + candidateEpochs: candidateEpochs, + total: total, + bound: authID != "", + } +} + +func (s *weightedPoolState) findMember(id string) (int, bool) { + index := sort.Search(len(s.members), func(i int) bool { return s.members[i].id >= id }) + if index < len(s.members) && s.members[index].id == id { + return index, true + } + return index, false +} + +func (s *weightedPoolState) findMemberWithEpoch(id string, epoch uint64) (int, bool) { + index, ok := s.findMember(id) + if !ok || s.members[index].epoch != epoch { + return index, false + } + return index, true +} + +func (s *weightedPoolState) totalMemberWeight() int64 { + var total int64 + for _, member := range s.members { + total = saturatingAddInt64(total, member.weight) + } + return total +} + +func (s *weightedPoolState) syncDynamicMembers(ids []string, weights []int64, versions []weightedAuthVersion) { + if len(ids) > s.peak { + s.peak = len(ids) + } + changed := false + for i, id := range ids { + if index, ok := s.findMember(id); ok && s.members[index].weight != weights[i] { + changed = true + break + } + } + if changed { + s.generation++ + s.inFlight = 0 + for i := range s.members { + s.members[i].current = 0 + s.members[i].pending = 0 + s.members[i].inFlight = 0 + } + } + for i, id := range ids { + ver := versions[i] + index, ok := s.findMember(id) + if ok { + if s.members[index].regEpoch > 0 && ver.regEpoch > s.members[index].regEpoch { + s.nextMemberEpoch++ + s.members[index] = weightedPoolMember{ + id: id, + weight: weights[i], + epoch: s.nextMemberEpoch, + regEpoch: ver.regEpoch, + regGen: ver.regGen, + } + continue + } + s.members[index].weight = weights[i] + if ver.regEpoch > s.members[index].regEpoch || + (ver.regEpoch == s.members[index].regEpoch && ver.regGen > s.members[index].regGen) { + s.members[index].regEpoch = ver.regEpoch + s.members[index].regGen = ver.regGen + } + continue + } + s.nextMemberEpoch++ + s.members = append(s.members, weightedPoolMember{}) + copy(s.members[index+1:], s.members[index:]) + s.members[index] = weightedPoolMember{ + id: id, + weight: weights[i], + epoch: s.nextMemberEpoch, + regEpoch: ver.regEpoch, + regGen: ver.regGen, + } + } + s.pruneDynamicMembers(ids) +} + +func (s *weightedPoolState) pruneDynamicMembers(presentIDs []string) { + pruneBound := max(maxSmoothWeightedStateEntries, 2*s.peak) + if len(s.members) <= pruneBound { + return + } + present := make(map[string]struct{}, len(presentIDs)) + for _, id := range presentIDs { + present[id] = struct{}{} + } + keepCount := 0 + for _, member := range s.members { + if member.inFlight > 0 { + keepCount++ + continue + } + if _, ok := present[member.id]; ok { + keepCount++ + } + } + if keepCount == len(s.members) { + return + } + kept := make([]weightedPoolMember, 0, keepCount) + for _, member := range s.members { + if member.inFlight > 0 { + kept = append(kept, member) + continue + } + if _, ok := present[member.id]; ok { + kept = append(kept, member) + } + } + s.members = kept +} + +func (s *weightedPoolState) adjustDynamicPending(ids []string, epochs []uint64, selectedID string, selectedEpoch uint64, subsetTotal int64, release bool) { + for i, id := range ids { + index, ok := s.findMemberWithEpoch(id, epochs[i]) + if !ok { + continue + } + member := &s.members[index] + delta := member.weight + if id == selectedID && epochs[i] == selectedEpoch { + delta -= subsetTotal + } + if release { + delta = -delta + if member.inFlight > 0 { + member.inFlight-- + } + } else { + member.inFlight++ + } + member.pending = saturatingAddInt64(member.pending, delta) + } +} + +func (s *weightedPoolState) dynamicBoundChargeFits(ids []string, epochs []uint64, selectedID string, selectedEpoch uint64, subsetTotal, fullTotalWeight int64) bool { + limit := int64(math.MaxInt64) + if fullTotalWeight <= math.MaxInt64/maxSmoothWeightedCreditRounds { + limit = fullTotalWeight * maxSmoothWeightedCreditRounds + } + for i, id := range ids { + index, ok := s.findMemberWithEpoch(id, epochs[i]) + if !ok { + continue + } + member := &s.members[index] + delta := member.weight + if id == selectedID && epochs[i] == selectedEpoch { + delta -= subsetTotal + } + current := saturatingAddInt64(member.current, member.pending) + next := saturatingAddInt64(current, delta) + if next < -limit || next > limit { + return false + } + } + return true +} + +func (s *weightedPoolState) chargeDynamic(ids []string, epochs []uint64, selectedID string, selectedEpoch uint64, subsetTotal int64, bound bool) { + fullTotalWeight := max(subsetTotal, s.totalMemberWeight()) + if !bound || s.dynamicBoundChargeFits(ids, epochs, selectedID, selectedEpoch, subsetTotal, fullTotalWeight) { + for i, id := range ids { + if index, ok := s.findMemberWithEpoch(id, epochs[i]); ok { + member := &s.members[index] + member.current = saturatingAddInt64(member.current, member.weight) + } + } + if index, ok := s.findMemberWithEpoch(selectedID, selectedEpoch); ok { + s.members[index].current = saturatingAddInt64(s.members[index].current, -subsetTotal) + } + } + if s.inFlight == 0 { + s.boundCredits(fullTotalWeight) + } +} + +// ForgetAuth removes permanently deregistered credentials from weighted pool state. +// Transient exclusions (retry tried sets and cooldowns) must never call ForgetAuth. +func (s *WeightedRoundRobinSelector) ForgetAuth(authID string) { + s.ForgetAuthUpTo(authID, ^uint64(0), ^uint64(0)) +} + +// ForgetAuthUpTo removes weighted pool entries for authID whose observed +// (RegistrationEpoch, Generation) is no newer than (maxEpoch, maxGen), so a delayed +// removal or disablement cannot evict a newly re-registered or re-enabled credential. +func (s *WeightedRoundRobinSelector) ForgetAuthUpTo(authID string, maxEpoch, maxGen uint64) { + if s == nil || authID == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + for dKey, state := range s.largeStates { + if index, ok := state.findMember(authID); ok && memberOlderOrEqual(state.members[index], maxEpoch, maxGen) { + last := len(state.members) - 1 + copy(state.members[index:], state.members[index+1:]) + state.members[last] = weightedPoolMember{} + state.members = state.members[:last] + if state.peak > len(state.members) { + state.peak = len(state.members) + } + if len(state.members) > 0 && cap(state.members) > 2*max(maxSmoothWeightedStateEntries, len(state.members)) { + compacted := make([]weightedPoolMember, len(state.members)) + copy(compacted, state.members) + state.members = compacted + } + state.lastActiveIDs = nil + } + if len(state.members) == 0 || (state.inFlight == 0 && state.peak <= maxExactWeightedPoolMembers && len(state.members) <= maxExactWeightedPoolMembers) { + delete(s.largeStates, dKey) + s.removeLargeOrderKeyLocked(dKey) + } + } + for key, head := range s.states { + var previous *weightedPoolState + for state := head; state != nil; { + next := state.next + if index, ok := state.findMember(authID); ok && memberOlderOrEqual(state.members[index], maxEpoch, maxGen) { + if previous == nil { + if next == nil { + delete(s.states, key) + } else { + s.states[key] = next + } + } else { + previous.next = next + } + s.stateCount-- + } else { + previous = state + } + state = next + } + } +} + +// finish confirms or releases a reservation exactly once under the selector lock. +func (r *weightedReservation) finish(committed bool) { + if r == nil { + return + } + r.selector.mu.Lock() + defer r.selector.mu.Unlock() + if r.finished { + return + } + r.finished = true + if r.state.generation != r.generation { + return + } + if r.state.dynamic { + r.state.adjustDynamicPending(r.candidateIDs, r.candidateEpochs, r.selectedID, r.selectedEpoch, r.total, true) + r.state.inFlight-- + if committed { + r.state.chargeDynamic(r.candidateIDs, r.candidateEpochs, r.selectedID, r.selectedEpoch, r.total, r.bound) + } else if r.state.inFlight == 0 { + r.state.boundCredits(max(r.total, r.state.totalMemberWeight())) + } + if r.state.inFlight == 0 { + r.state.pruneDynamicMembers(r.state.lastActiveIDs) + } + return + } + r.state.adjustPending(r.member, r.total, true) + r.state.inFlight-- + if committed { + r.state.charge(r.member, r.bound) + } else if r.state.inFlight == 0 { + // A final rollback can remove the offset to already committed credit. + r.state.boundCredits(r.total) + } +} + +// adjustPending must be called with the selector mutex held. Pending deltas are +// not clamped, so releasing them cannot lose credit at the compensation bound. +func (s *weightedPoolState) adjustPending(selected int, total int64, release bool) { + for i := range s.members { + member := &s.members[i] + delta := member.weight + if i == selected { + delta -= total + } + if release { + delta = -delta + } + member.pending = saturatingAddInt64(member.pending, delta) + } +} + +// maxSmoothWeightedCreditRounds bounds compensation after a long sticky session. +const maxSmoothWeightedCreditRounds int64 = 32 + +// boundChargeFits admits the whole sticky delta or none. Both reservation and +// commit include outstanding deltas: committed credit alone can transiently +// exceed the cap while successful reservations settle in a different order. +func (s *weightedPoolState) boundChargeFits(selected int, totalWeight int64) bool { + limit := int64(math.MaxInt64) + if totalWeight <= math.MaxInt64/maxSmoothWeightedCreditRounds { + limit = totalWeight * maxSmoothWeightedCreditRounds + } + for i, member := range s.members { + delta := member.weight + if i == selected { + delta -= totalWeight + } + current := saturatingAddInt64(member.current, member.pending) + next := saturatingAddInt64(current, delta) + if next < -limit || next > limit { + return false + } + } + return true +} + +func (s *weightedPoolState) charge(selected int, bound bool) { + var totalWeight int64 + for _, member := range s.members { + totalWeight = saturatingAddInt64(totalWeight, member.weight) + } + if !bound || s.boundChargeFits(selected, totalWeight) { + // At the cap, forced traffic cannot erase a small peer's earnings. + // Pending repayments still count until they actually roll back. + for i := range s.members { + member := &s.members[i] + member.current = saturatingAddInt64(member.current, member.weight) + } + member := &s.members[selected] + member.current = saturatingAddInt64(member.current, -totalWeight) + } + if s.inFlight == 0 { + s.boundCredits(totalWeight) + } +} + +// boundCredits runs only once the pool settles. Net pending deltas can be zero +// even with live reservations, so the in-flight count, not len(pending), decides +// when clipping cannot irreversibly discard another reservation's offset. +func (s *weightedPoolState) boundCredits(totalWeight int64) { + limit := int64(math.MaxInt64) + if totalWeight <= math.MaxInt64/maxSmoothWeightedCreditRounds { + limit = totalWeight * maxSmoothWeightedCreditRounds + } + var minCredit, maxCredit int64 = math.MaxInt64, math.MinInt64 + for _, member := range s.members { + minCredit = min(minCredit, member.current) + maxCredit = max(maxCredit, member.current) + } + // A common offset keeps leading credits distinct at the compensation bound. + // Independent clamps can repeatedly tie the leaders and starve the later + // candidate in deterministic selection order. + minOffset := saturatingAddInt64(maxCredit, -limit) + maxOffset := saturatingAddInt64(minCredit, limit) + var offset int64 + if minOffset > 0 || minOffset > maxOffset { + offset = minOffset + } else if maxOffset < 0 { + offset = maxOffset + } + // If the full spread cannot fit, cap only the trailing debt after rebasing + // the leader to the upper bound. Do not flatten leading candidates' credits. + for i := range s.members { + member := &s.members[i] + member.current = max(-limit, saturatingAddInt64(member.current, -offset)) + } +} diff --git a/sdk/cliproxy/auth/selector_weighted_affinity_test.go b/sdk/cliproxy/auth/selector_weighted_affinity_test.go new file mode 100644 index 00000000000..5736e0c8210 --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted_affinity_test.go @@ -0,0 +1,436 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "net/http" + "sync" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + cliproxysession "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestWeightedSessionAffinityCompensatesStickyRequests(t *testing.T) { + for _, source := range []string{"sticky", "parent", "guardian", "fork"} { + t.Run(source, func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{ + {ID: "a", Provider: "codex", Attributes: map[string]string{AttributeWeight: "3"}}, + {ID: "b", Provider: "codex"}, + } + parent := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"busy"}}} + parentID := CanonicalSessionID(parent.Headers, nil, nil) + parentModel := "model" + if source == "guardian" { + parentModel = "parent-model" + } + key := "codex::" + parentID + "::" + parentModel + selector.cache.setSessionAliases("b", "codex", parentID, key) + for i := range 4 { + opts := parent + if source != "sticky" { + opts = cliproxyexecutor.Options{Headers: http.Header{ + "Session_id": {fmt.Sprintf("child-%d", i)}, "X-Codex-Parent-Thread-Id": {"busy"}, + }} + if source == "guardian" { + opts.Headers.Set("X-Openai-Subagent", "guardian") + } + if source == "fork" { + opts.OriginalRequest = []byte(`{"forked_from_thread_id":"busy"}`) + } + } + picked, errPick := selector.Pick(t.Context(), "codex", "model", opts, auths) + if errPick != nil || picked == nil || picked.ID != "b" { + t.Fatalf("sticky request %d: pick=%v err=%v", i, picked, errPick) + } + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + if state.currentForTest()["a"] != 12 || state.currentForTest()["b"] != -12 || len(state.pendingForTest()) != 0 { + t.Fatalf("sticky credits: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } + for i := range 12 { + // Requests without an identity and cold sessions share the same credits. + opts := cliproxyexecutor.Options{} + if i%2 == 0 { + opts.Headers = http.Header{"Session_id": {fmt.Sprintf("new-%d", i)}} + } + picked, errPick := selector.Pick(t.Context(), "codex", "model", opts, auths) + if errPick != nil || picked == nil || picked.ID != "a" { + t.Fatalf("compensation %d: pick=%v err=%v", i, picked, errPick) + } + } + if state.currentForTest()["a"] != 0 || state.currentForTest()["b"] != 0 || len(state.pendingForTest()) != 0 { + t.Fatalf("compensated credits: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } + if binding, ok := selector.cache.Get(key); !ok || binding != "b" { + t.Fatalf("balancing moved the parent binding: %q, found=%t", binding, ok) + } + }) + } +} + +func TestWeightedSessionAffinityChangingPoolsDoNotStarveEqualWeights(t *testing.T) { + for _, newSession := range []bool{false, true} { + t.Run(fmt.Sprintf("new-session=%t", newSession), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{ + {ID: "a", Attributes: map[string]string{"priority": "0"}}, + {ID: "b", Attributes: map[string]string{"priority": "1"}}, + {ID: "c", Attributes: map[string]string{"priority": "1"}}, + } + sticky := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"lower-priority"}}} + id := CanonicalSessionID(sticky.Headers, nil, nil) + key := "codex::" + id + "::model" + selector.cache.Set(key, "a") + counts := map[string]int{} + const warmup, requests = 100, 1000 + for i := range requests { + picked, errPick := selector.Pick(t.Context(), "codex", "model", sticky, auths) + if errPick != nil || picked == nil || picked.ID != "a" { + t.Fatalf("sticky request %d: pick=%v err=%v", i, picked, errPick) + } + opts := cliproxyexecutor.Options{} + if newSession { + opts.Headers = http.Header{"Session_id": {fmt.Sprintf("fresh-%d", i)}} + } + picked, errPick = selector.Pick(t.Context(), "codex", "model", opts, auths) + if errPick != nil || picked == nil || (picked.ID != "b" && picked.ID != "c") { + t.Fatalf("fresh request %d: pick=%v err=%v", i, picked, errPick) + } + if i >= warmup { + counts[picked.ID]++ + } + } + if counts["b"] != (requests-warmup)/2 || counts["c"] != (requests-warmup)/2 { + t.Fatalf("changing pools starved equal-weight candidates after warmup: %v, want b=450 c=450", counts) + } + if binding, ok := selector.cache.Get(key); !ok || binding != "a" { + t.Fatalf("balancing moved the sticky binding: %q, found=%t", binding, ok) + } + if state := weightedStateForTest(t, weighted, "codex:model", "b", "c"); len(state.pendingForTest()) != 0 { + t.Fatalf("pending credits leaked: %v", state.pendingForTest()) + } + }) + } +} + +func TestWeightedSessionAffinityColdSelectionsCountOnce(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + counts := map[string]int{} + for i := range 40 { + picked, errPick := selector.Pick(t.Context(), "codex", "model", cliproxyexecutor.Options{ + Headers: http.Header{"Session_id": {fmt.Sprintf("session-%d", i)}}, + }, auths) + if errPick != nil || picked == nil { + t.Fatalf("pick=%v err=%v", picked, errPick) + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + if i == 0 && (state.currentForTest()["a"] != -1 || state.currentForTest()["b"] != 1) { + t.Fatalf("first selection charged more than once: %v", state.currentForTest()) + } + counts[picked.ID]++ + } + if counts["a"] != 30 || counts["b"] != 10 { + t.Fatalf("cold distribution = %v, want 30:10", counts) + } +} + +func TestWeightedSessionAffinityBoundsCompensation(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"long"}}} + id := CanonicalSessionID(opts.Headers, nil, nil) + selector.cache.Set("codex::"+id+"::model", "b") + for range 1000 { + picked, errPick := selector.Pick(t.Context(), "codex", "model", opts, auths) + if errPick != nil || picked == nil || picked.ID != "b" { + t.Fatalf("long session: pick=%v err=%v", picked, errPick) + } + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + limit := maxSmoothWeightedCreditRounds * 4 + // A bound charge is admitted as a whole, stopping within one delta of the cap. + wantCredit := limit / 3 * 3 + if state.currentForTest()["a"] != wantCredit || state.currentForTest()["b"] != -wantCredit { + t.Fatalf("bounded credits = %v, want +/- %d", state.currentForTest(), wantCredit) + } + for range wantCredit { + if _, errPick := weighted.Pick(t.Context(), "codex", "model", cliproxyexecutor.Options{}, auths); errPick != nil { + t.Fatal(errPick) + } + } + if state.currentForTest()["a"] != 0 || state.currentForTest()["b"] != 0 { + t.Fatalf("compensation did not finish: %v", state.currentForTest()) + } +} + +func TestWeightedSessionAffinityLCPCredits(t *testing.T) { + for _, source := range []string{"hit", "fork", "compaction"} { + t.Run(source, func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + root := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + OriginalRequest: []byte(`{"messages":[{"role":"user","content":"step 1"},` + + `{"role":"assistant","content":"ack 1"},{"role":"user","content":"step 2"},` + + `{"role":"assistant","content":"ack 2"},{"role":"user","content":"step 3"}]}`), + Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "caller"}, + } + // Seed the matcher without consuming weighted credits. + turns := cliproxysession.ExtractCanonicalTurns(root.SourceFormat, root.OriginalRequest) + selector.matcher.Bind(lcpAffinityNamespace("openai", "model", root.Metadata), turns, "b") + opts := root + if source == "fork" { + opts.OriginalRequest = []byte(`{"messages":[{"role":"user","content":"step 1"},` + + `{"role":"assistant","content":"ack 1"},{"role":"user","content":"branch"}]}`) + } else if source == "compaction" { + opts.OriginalRequest = []byte(`{"messages":[{"role":"user","content":"Steps 1 and 2 completed"},` + + `{"role":"assistant","content":"ack 2"},{"role":"user","content":"step 3"},` + + `{"role":"user","content":"step 4"}]}`) + } + picked, errPick := selector.Pick(t.Context(), "openai", "model", opts, auths) + if errPick != nil || picked == nil || picked.ID != "b" { + t.Fatalf("LCP %s: pick=%v err=%v", source, picked, errPick) + } + if source == "fork" && opts.Metadata[cliproxyexecutor.IsForkMetadataKey] != true { + t.Fatal("expected LCP fork") + } + if source == "compaction" && opts.Metadata[cliproxyexecutor.IsCompactionMetadataKey] != true { + t.Fatal("expected LCP compaction") + } + state := weightedStateForTest(t, weighted, "openai:model", "a", "b") + if state.currentForTest()["a"] != 3 || state.currentForTest()["b"] != -3 || len(state.pendingForTest()) != 0 { + t.Fatalf("LCP credits: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } + }) + } +} + +func TestWeightedReservationRollbackPreservesConcurrentCharges(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + key := "codex:model" + for range 1000 { + _, reservation := weighted.reserve(key, auths, "b") + reservation.finish(true) + } + state := weightedStateForTest(t, weighted, key, "a", "b") + _, rejected := weighted.reserve(key, auths, "b") + _, accepted := weighted.reserve(key, auths, "a") + accepted.finish(true) + rejected.finish(false) + rejected.finish(true) + accepted.finish(false) + limit := maxSmoothWeightedCreditRounds * 4 / 3 * 3 + if state.currentForTest()["a"] != limit-1 || state.currentForTest()["b"] != -limit+1 || len(state.pendingForTest()) != 0 { + t.Fatalf("rollback lost another charge: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } +} + +func TestWeightedReservationResetInvalidatesOldGeneration(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + key := "codex:model" + _, old := weighted.reserve(key, auths, "") + auths[0].Attributes[AttributeWeight] = "1" + _, latest := weighted.reserve(key, auths, "") + old.finish(true) + state := weightedStateForTest(t, weighted, key, "a", "b") + if state.currentForTest()["a"] != 0 || state.currentForTest()["b"] != 0 || state.pendingForTest()["a"] != -1 || state.pendingForTest()["b"] != 1 { + t.Fatalf("stale reservation changed new generation: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } + latest.finish(true) + if state.currentForTest()["a"] != -1 || state.currentForTest()["b"] != 1 || len(state.pendingForTest()) != 0 { + t.Fatalf("new generation accounting: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } +} + +func TestWeightedReservationConcurrentSelectionsSeePendingCredits(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + const requests = 40 + selected := make(chan *Auth, requests) + reservations := make(chan *weightedReservation, requests) + var ready sync.WaitGroup + ready.Add(requests) + for range requests { + go func() { + defer ready.Done() + picked, reservation := weighted.reserve("codex:model", auths, "") + selected <- picked + reservations <- reservation + }() + } + ready.Wait() + close(selected) + close(reservations) + counts := map[string]int{} + for auth := range selected { + if auth == nil { + t.Fatal("concurrent reservation returned no auth") + } + counts[auth.ID]++ + } + if counts["a"] != 30 || counts["b"] != 10 { + t.Fatalf("pending allocations ignored: %v", counts) + } + for reservation := range reservations { + reservation.finish(true) + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + if state.currentForTest()["a"] != 0 || state.currentForTest()["b"] != 0 || len(state.pendingForTest()) != 0 { + t.Fatalf("concurrent accounting: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } +} + +func TestWeightedSessionAffinityFailureDoesNotCharge(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{ + Fallback: weighted, RebindOn: SessionAffinityRebindOnNever, + }) + t.Cleanup(selector.Stop) + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"bound"}}} + id := CanonicalSessionID(opts.Headers, nil, nil) + selector.cache.Set("codex::"+id+"::model", "missing") + if auth, errPick := selector.Pick(t.Context(), "codex", "model", opts, []*Auth{{ID: "a"}, {ID: "b"}}); errPick == nil || auth != nil { + t.Fatalf("expected unavailable binding: auth=%v err=%v", auth, errPick) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if auth, errPick := selector.Pick(ctx, "codex", "model", opts, []*Auth{{ID: "a"}, {ID: "b"}}); !errors.Is(errPick, context.Canceled) || auth != nil { + t.Fatalf("expected cancellation: auth=%v err=%v", auth, errPick) + } + if len(weighted.states) != 0 { + t.Fatalf("failed selection changed weighted state: %v", weighted.states) + } +} + +func TestWeightedSessionAffinityEligiblePoolAndModelIsolation(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{ + {ID: "a", Attributes: map[string]string{AttributeWeight: "3", "priority": "1"}}, + {ID: "b", Attributes: map[string]string{"priority": "1"}}, + {ID: "lower", Attributes: map[string]string{AttributeWeight: "100"}}, + {ID: "zero", Attributes: map[string]string{AttributeWeight: "0", "priority": "2"}}, + {ID: "cooldown", Attributes: map[string]string{"priority": "2"}, ModelStates: map[string]*ModelState{ + "upstream": {Unavailable: true, NextRetryAfter: time.Now().Add(time.Hour)}, + }}, + } + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"alias"}}} + id := CanonicalSessionID(opts.Headers, nil, nil) + selector.cache.Set("codex::"+id+"::upstream", "b") + ctx := withWeightedSelectorStateModel(t.Context(), weighted, "requested(high)") + picked, errPick := selector.Pick(ctx, "codex", "upstream", opts, auths) + if errPick != nil || picked == nil || picked.ID != "b" { + t.Fatalf("sticky pick=%v err=%v", picked, errPick) + } + state := weightedStateForTest(t, weighted, "codex:requested", "a", "b") + if state == nil || len(weighted.states) != 1 || len(state.currentForTest()) != 2 || state.currentForTest()["a"] != 3 || state.currentForTest()["b"] != -3 { + t.Fatalf("wrong model key or eligible pool: %v", weighted.states) + } + picked, errPick = weighted.Pick(ctx, "codex", "", cliproxyexecutor.Options{}, auths[:2]) + if errPick != nil || picked == nil || picked.ID != "a" || state.currentForTest()["a"] != 2 || state.currentForTest()["b"] != -2 { + t.Fatalf("fallback did not share credits: pick=%v err=%v credits=%v", picked, errPick, state.currentForTest()) + } + for _, pair := range [][2]string{{"codex", "other-model"}, {"other-provider", "requested"}} { + if _, errOther := selector.Pick(t.Context(), pair[0], pair[1], cliproxyexecutor.Options{}, auths[:2]); errOther != nil { + t.Fatal(errOther) + } + } + if state.currentForTest()["a"] != 2 || state.currentForTest()["b"] != -2 { + t.Fatal("another provider or model changed credits") + } +} + +func TestWeightedSessionAffinityReselectionCountsOnce(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"reselect"}}} + id := CanonicalSessionID(opts.Headers, nil, nil) + key := "codex::" + id + "::model" + selector.cache.Set(key, "removed") + picked, errPick := selector.Pick(t.Context(), "codex", "model", opts, + []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}}) + if errPick != nil || picked == nil || picked.ID != "a" { + t.Fatalf("reselection: pick=%v err=%v", picked, errPick) + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + if state.currentForTest()["a"] != -1 || state.currentForTest()["b"] != 1 || len(state.pendingForTest()) != 0 { + t.Fatalf("reselection counted incorrectly: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } + if binding, ok := selector.cache.Get(key); !ok || binding != "a" { + t.Fatalf("reselection did not bind: %q, found=%t", binding, ok) + } +} + +func TestManagerWeightedSessionAffinityCompensation(t *testing.T) { + for _, mixed := range []bool{false, true} { + t.Run(fmt.Sprintf("mixed=%t", mixed), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + manager := NewManager(nil, selector, nil) + provider, model := "weighted-affinity", "weighted-model" + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + aID, bID := t.Name()+"-a", t.Name()+"-b" + for _, auth := range []*Auth{ + {ID: aID, Provider: provider, Status: StatusActive, Attributes: map[string]string{AttributeWeight: "3"}}, + {ID: bID, Provider: provider, Status: StatusActive}, + } { + if _, errRegister := manager.Register(WithSkipPersist(t.Context()), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + } + namespace := provider + if mixed { + namespace = "mixed" + } + parentHeaders := http.Header{"Session_id": {"manager-sticky"}} + id := CanonicalSessionID(parentHeaders, nil, nil) + selector.cache.Set(namespace+"::"+id+"::"+model, bID) + for i := range 16 { + opts := cliproxyexecutor.Options{Headers: parentHeaders} + want := bID + if i >= 4 { + opts.Headers = http.Header{"Session_id": {fmt.Sprintf("new-%d", i)}} + want = aID + } + var auth *Auth + var errPick error + if mixed { + auth, _, _, errPick = manager.pickNextMixed(t.Context(), []string{provider}, model, opts, nil) + } else { + auth, _, errPick = manager.pickNext(t.Context(), provider, model, opts, nil) + } + if errPick != nil || auth == nil || auth.ID != want { + t.Fatalf("request %d: auth=%v err=%v, want %q", i, auth, errPick, want) + } + } + state := weightedStateForTest(t, weighted, namespace+":"+model, aID, bID) + if state == nil || state.currentForTest()[aID] != 0 || state.currentForTest()[bID] != 0 || len(state.pendingForTest()) != 0 { + t.Fatalf("manager credits did not balance: %#v", state) + } + }) + } +} diff --git a/sdk/cliproxy/auth/selector_weighted_commit_order_test.go b/sdk/cliproxy/auth/selector_weighted_commit_order_test.go new file mode 100644 index 00000000000..58d18499a9d --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted_commit_order_test.go @@ -0,0 +1,199 @@ +package auth + +import ( + "fmt" + "maps" + "testing" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +func TestWeightedReservationFinalRollbackBoundsSettledCredits(t *testing.T) { + for _, rollbackFirst := range []bool{false, true} { + t.Run(fmt.Sprintf("rollback-first=%t", rollbackFirst), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a"}, {ID: "b"}} + reservations := map[string][]*weightedReservation{} + t.Cleanup(func() { + for _, group := range reservations { + for _, reservation := range group { + reservation.finish(false) + } + } + }) + for range 256 { + picked, reservation := weighted.reserve("codex:model", auths, "") + if picked == nil || reservation == nil { + t.Fatal("missing cold reservation") + } + reservations[picked.ID] = append(reservations[picked.ID], reservation) + } + ids := []string{"a", "b"} + if rollbackFirst { + ids = []string{"b", "a"} + } + for _, id := range ids { + for _, reservation := range reservations[id] { + reservation.finish(id == "a") + // Repeated finishing must not decrement the counter again. + reservation.finish(false) + } + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + limit := maxSmoothWeightedCreditRounds * 2 + if state.inFlight != 0 || len(state.pendingForTest()) != 0 || !maps.Equal(state.currentForTest(), map[string]int64{"a": -limit, "b": limit}) { + t.Fatalf("settled credit did not reach its bound: current=%v pending=%v in-flight=%d", state.currentForTest(), state.pendingForTest(), state.inFlight) + } + }) + } +} + +func TestWeightedReservationUnequalWeightsOutOfOrderCommits(t *testing.T) { + for _, first := range []string{"a", "b"} { + t.Run(first, func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + reservations := map[string][]*weightedReservation{} + t.Cleanup(func() { + for _, group := range reservations { + for _, reservation := range group { + reservation.finish(false) + } + } + }) + for range 512 { + picked, reservation := weighted.reserve("codex:model", auths, "") + if picked == nil || reservation == nil { + t.Fatal("missing cold reservation") + } + reservations[picked.ID] = append(reservations[picked.ID], reservation) + } + if len(reservations["a"]) != 384 || len(reservations["b"]) != 128 { + t.Fatalf("reservations did not follow 3:1: a=%d b=%d", len(reservations["a"]), len(reservations["b"])) + } + last := "b" + if first == "b" { + last = "a" + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + for _, reservation := range reservations[first] { + reservation.finish(true) + } + // New arrivals must see the remaining offsets before the batch settles. + for _, phase := range []string{"pending", "settled"} { + if phase == "settled" { + for _, reservation := range reservations[last] { + reservation.finish(true) + } + } + counts := map[string]int{} + for range 64 { + picked, errPick := weighted.Pick(t.Context(), "codex", "model", cliproxyexecutor.Options{}, auths) + if errPick != nil || picked == nil { + t.Fatalf("Pick failed: auth=%v err=%v", picked, errPick) + } + counts[picked.ID]++ + } + if counts["a"] != 48 || counts["b"] != 16 { + t.Fatalf("%s distribution = %v, want 48:16", phase, counts) + } + } + if state.inFlight != 0 || len(state.pendingForTest()) != 0 || !maps.Equal(state.currentForTest(), map[string]int64{"a": 0, "b": 0}) { + t.Fatalf("settled 3:1 batch drifted: %#v", state) + } + }) + } +} + +func TestWeightedReservationResetDoesNotReleaseNewGeneration(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a"}, {ID: "b"}} + var old []*weightedReservation + t.Cleanup(func() { + for _, reservation := range old { + reservation.finish(false) + } + }) + for range 256 { + _, reservation := weighted.reserve("codex:model", auths, "") + old = append(old, reservation) + } + auths[0].Attributes = map[string]string{AttributeWeight: "3"} + _, latest := weighted.reserve("codex:model", auths, "") + if latest == nil { + t.Fatal("missing new-generation reservation") + } + t.Cleanup(func() { latest.finish(false) }) + for _, reservation := range old { + reservation.finish(true) + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + if state.inFlight != 1 || state.hasCurrentForTest() || !maps.Equal(state.pendingForTest(), map[string]int64{"a": -1, "b": 1}) { + t.Fatalf("old generation altered new accounting: %#v", state) + } + latest.finish(true) + if state.inFlight != 0 || len(state.pendingForTest()) != 0 || !maps.Equal(state.currentForTest(), map[string]int64{"a": -1, "b": 1}) { + t.Fatalf("new generation failed to settle: %#v", state) + } +} + +func TestWeightedReservationOutOfOrderBalancedCommits(t *testing.T) { + for _, bound := range []bool{false, true} { + for _, first := range []string{"a", "b"} { + t.Run(fmt.Sprintf("bound=%t/first=%s", bound, first), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a"}, {ID: "b"}} + reservations := map[string][]*weightedReservation{} + t.Cleanup(func() { + for _, group := range reservations { + for _, reservation := range group { + reservation.finish(false) + } + } + }) + for i := range 256 { + boundID := "" + if bound { + boundID = auths[i%2].ID + } + picked, reservation := weighted.reserve("codex:model", auths, boundID) + if picked == nil || reservation == nil { + t.Fatalf("reserve %d returned pick=%v reservation=%v", i, picked, reservation) + } + reservations[picked.ID] = append(reservations[picked.ID], reservation) + } + if len(reservations["a"]) != 128 || len(reservations["b"]) != 128 { + t.Fatalf("unbalanced reservations: a=%d b=%d", len(reservations["a"]), len(reservations["b"])) + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + // A zero net pending vector does not mean all reservations settled. + if state.inFlight != 256 || len(state.pendingForTest()) != 0 { + t.Fatalf("in-flight=%d pending=%v, want 256 live balanced reservations", state.inFlight, state.pendingForTest()) + } + last := "b" + if first == "b" { + last = "a" + } + for _, id := range []string{first, last} { + for _, reservation := range reservations[id] { + reservation.finish(true) + } + } + if !maps.Equal(state.currentForTest(), map[string]int64{"a": 0, "b": 0}) || len(state.pendingForTest()) != 0 || state.inFlight != 0 { + t.Errorf("commit order distorted balanced credit: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } + counts := map[string]int{} + for range 64 { + picked, errPick := weighted.Pick(t.Context(), "codex", "model", cliproxyexecutor.Options{}, auths) + if errPick != nil || picked == nil { + t.Fatalf("Pick: auth=%v err=%v", picked, errPick) + } + counts[picked.ID]++ + } + if counts["a"] != 32 || counts["b"] != 32 { + t.Fatalf("post-commit distribution = %v, want a=32 b=32", counts) + } + }) + } + } +} diff --git a/sdk/cliproxy/auth/selector_weighted_memory_test.go b/sdk/cliproxy/auth/selector_weighted_memory_test.go new file mode 100644 index 00000000000..eec967e2883 --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted_memory_test.go @@ -0,0 +1,71 @@ +package auth + +import ( + "fmt" + "runtime" + "testing" +) + +func BenchmarkWeightedPoolReserve1000(b *testing.B) { + for _, bound := range []bool{false, true} { + b.Run(fmt.Sprintf("bound=%t", bound), func(b *testing.B) { + auths := make([]*Auth, 1000) + for i := range auths { + auths[i] = &Auth{ID: fmt.Sprintf("%036d", i)} + } + selector := &WeightedRoundRobinSelector{} + _, warmup := selector.reserve("codex:model", auths, "") + warmup.finish(true) + b.ReportAllocs() + b.ResetTimer() + for i := range b.N { + boundID := "" + if bound { + boundID = auths[i%len(auths)].ID + } + _, reservation := selector.reserve("codex:model", auths, boundID) + reservation.finish(true) + } + }) + } +} + +// BenchmarkWeightedPoolRetainedMemory measures live cache growth separately from +// total heap and allocation churn. Each retry subset omits a different credential. +func BenchmarkWeightedPoolRetainedMemory(b *testing.B) { + const members = 1000 + auths := make([]*Auth, members) + for i := range auths { + auths[i] = &Auth{ID: fmt.Sprintf("%036d", i)} + } + subset := make([]*Auth, 0, members-1) + var retained, heap, allocated int64 + b.ResetTimer() + for range b.N { + selector := &WeightedRoundRobinSelector{} + _, warmup := selector.reserve("codex:model", auths, "") + warmup.finish(true) + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + for excluded := range auths { + subset = append(subset[:0], auths[:excluded]...) + subset = append(subset, auths[excluded+1:]...) + _, reservation := selector.reserve("codex:model", subset, "") + reservation.finish(true) + } + runtime.GC() + runtime.ReadMemStats(&after) + if len(selector.states) != members+1 { + b.Fatalf("cached pools = %d, want %d", len(selector.states), members+1) + } + runtime.KeepAlive(selector) + runtime.KeepAlive(auths) + retained += int64(after.HeapAlloc) - int64(before.HeapAlloc) + heap += int64(after.HeapAlloc) + allocated += int64(after.TotalAlloc - before.TotalAlloc) + } + b.ReportMetric(float64(retained)/float64(b.N), "retained-B/op") + b.ReportMetric(float64(heap)/float64(b.N), "heap-total-B/op") + b.ReportMetric(float64(allocated)/float64(b.N), "alloc-total-B/op") +} diff --git a/sdk/cliproxy/auth/selector_weighted_model_key_test.go b/sdk/cliproxy/auth/selector_weighted_model_key_test.go new file mode 100644 index 00000000000..2f988316bad --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted_model_key_test.go @@ -0,0 +1,39 @@ +package auth + +import ( + "fmt" + "testing" + + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +func TestWeightedSelectorsShareEquivalentModelKeys(t *testing.T) { + for _, firstAffinity := range []bool{false, true} { + for _, secondAffinity := range []bool{false, true} { + for _, routeOverride := range []bool{false, true} { + t.Run(fmt.Sprintf("affinity=%t/%t/route=%t", firstAffinity, secondAffinity, routeOverride), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + affinity := NewSessionAffinitySelector(weighted) + t.Cleanup(affinity.Stop) + auths := []*Auth{{ID: "a"}, {ID: "b"}} + for i, useAffinity := range []bool{firstAffinity, secondAffinity} { + ctx := t.Context() + model := []string{" Model(high) ", "model(low)"}[i] + if routeOverride { + ctx = withWeightedSelectorStateModel(ctx, weighted, model) + model = []string{"upstream-a", "upstream-b"}[i] + } + var selector Selector = weighted + if useAffinity { + selector = affinity + } + picked, errPick := selector.Pick(ctx, "codex", model, cliproxyexecutor.Options{}, auths) + if errPick != nil || picked == nil || picked.ID != auths[i].ID { + t.Fatalf("request %d: pick=%v err=%v, want auth %s", i, picked, errPick, auths[i].ID) + } + } + }) + } + } + } +} diff --git a/sdk/cliproxy/auth/selector_weighted_overload_test.go b/sdk/cliproxy/auth/selector_weighted_overload_test.go new file mode 100644 index 00000000000..f7639a53689 --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted_overload_test.go @@ -0,0 +1,455 @@ +package auth + +import ( + "fmt" + "maps" + "net/http" + "strconv" + "sync" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +func TestWeightedOverloadExactCompensation(t *testing.T) { + for _, weights := range [][]int{{1, 1}, {3, 1}, {1, 3}, {1, 5, 1}, {2, 3, 5}, {1, 2, 3, 4}} { + for boundIndex := range weights { + t.Run(fmt.Sprintf("weights=%v/bound=%d", weights, boundIndex), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := make([]*Auth, len(weights)) + total := 0 + for i, weight := range weights { + auths[i] = &Auth{ID: fmt.Sprintf("auth-%d", i), Attributes: map[string]string{AttributeWeight: strconv.Itoa(weight)}} + total += weight + } + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"sticky"}}} + key := "codex::" + CanonicalSessionID(opts.Headers, nil, nil) + "::model" + selector.cache.Set(key, auths[boundIndex].ID) + counts := map[string]int{} + for i := range total * 4 { + request := opts + sticky := i < weights[boundIndex]*4 + if !sticky { + request = cliproxyexecutor.Options{Headers: http.Header{"Session_id": {fmt.Sprintf("fresh-%d", i)}}} + } + picked, errPick := selector.Pick(t.Context(), "codex", "model", request, auths) + if errPick != nil || picked == nil { + t.Fatalf("selection failed: pick=%v err=%v", picked, errPick) + } + if sticky && picked.ID != auths[boundIndex].ID { + t.Fatal("balancing moved an existing binding") + } + counts[picked.ID]++ + } + for i, weight := range weights { + if counts[auths[i].ID] != weight*4 { + t.Errorf("total allocation = %v, want weight vector %v times 4", counts, weights) + } + } + for _, state := range weighted.states { + for id, credit := range state.currentForTest() { + if credit != 0 { + t.Errorf("exact compensation left %q credit=%d", id, credit) + } + } + if len(state.pendingForTest()) != 0 { + t.Errorf("pending credit leaked: %v", state.pendingForTest()) + } + } + }) + } + } +} + +func TestWeightedOverloadSustainedStickyTrafficDoesNotStarveOthers(t *testing.T) { + for _, weights := range [][]int{{1, 1, 1}, {1, 3, 1}, {1, 5, 1}, {1, 1, 5}, {1, 9, 1}, {1, 1, 9}, {1, 5, 2, 1}} { + t.Run(fmt.Sprint(weights), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := make([]*Auth, len(weights)) + for i, weight := range weights { + auths[i] = &Auth{ID: fmt.Sprintf("auth-%d", i), Attributes: map[string]string{AttributeWeight: strconv.Itoa(weight)}} + } + sticky := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"busy"}}} + key := "codex::" + CanonicalSessionID(sticky.Headers, nil, nil) + "::model" + selector.cache.Set(key, auths[0].ID) + counts := map[string]int{} + for i := range 3000 { + picked, errPick := selector.Pick(t.Context(), "codex", "model", sticky, auths) + if errPick != nil || picked == nil || picked.ID != auths[0].ID { + t.Fatalf("binding changed: pick=%v err=%v", picked, errPick) + } + fresh := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {fmt.Sprintf("fresh-%d", i)}}} + picked, errPick = selector.Pick(t.Context(), "codex", "model", fresh, auths) + if errPick != nil || picked == nil { + t.Fatalf("fresh selection failed: pick=%v err=%v", picked, errPick) + } + if i >= 1000 { + counts[picked.ID]++ + } + } + ids := make([]string, len(auths)) + for i, auth := range auths { + ids[i] = auth.ID + } + state := weightedStateForTest(t, weighted, "codex:model", ids...) + t.Logf("fresh distribution after warmup: %v; committed=%v", counts, state.currentForTest()) + // Forced traffic makes global ratios infeasible; the remaining capacity + // should be shared by unbound peers rather than monopolized by one. + peerWeight := 0 + for _, weight := range weights[1:] { + peerWeight += weight + } + for i, auth := range auths[1:] { + want := 2000 * weights[i+1] / peerWeight + if counts[auth.ID] < want-2 || counts[auth.ID] > want+2 { + t.Errorf("peer %q got %d fresh requests, want approximately %d; distribution=%v", auth.ID, counts[auth.ID], want, counts) + } + } + }) + } +} + +func TestWeightedOverloadFeasibleSustainedTraffic(t *testing.T) { + for _, weights := range [][]int{{3, 1}, {1, 5, 1}, {1, 9, 1}, {1, 5, 2, 1}} { + t.Run(fmt.Sprint(weights), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := make([]*Auth, len(weights)) + total := 0 + for i, weight := range weights { + auths[i] = &Auth{ID: fmt.Sprintf("auth-%d", i), Attributes: map[string]string{AttributeWeight: strconv.Itoa(weight)}} + total += weight + } + sticky := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"feasible"}}} + key := "codex::" + CanonicalSessionID(sticky.Headers, nil, nil) + "::model" + selector.cache.Set(key, auths[0].ID) + counts := map[string]int{} + // Forced traffic is below A's target share, so exact aggregate ratios + // remain feasible without moving established bindings. + for i := range total * 2000 { + opts := cliproxyexecutor.Options{} + bound := i%(total*2) == 0 + if bound { + opts = sticky + } + picked, errPick := selector.Pick(t.Context(), "codex", "model", opts, auths) + if errPick != nil || picked == nil || (bound && picked.ID != auths[0].ID) { + t.Fatalf("request %d: pick=%v err=%v", i, picked, errPick) + } + if i >= total*1000 { + counts[picked.ID]++ + } + } + for i, weight := range weights { + if counts[auths[i].ID] != weight*1000 { + t.Errorf("feasible distribution drifted: counts=%v weights=%v", counts, weights) + } + } + t.Logf("feasible distribution: %v", counts) + }) + } +} + +func TestWeightedOverloadRecoveryAfterStickyTrafficStops(t *testing.T) { + for _, weights := range [][]int{{1, 5, 1}, {1, 9, 1}, {1, 5, 2, 1}} { + t.Run(fmt.Sprint(weights), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := make([]*Auth, len(weights)) + total := 0 + for i, weight := range weights { + auths[i] = &Auth{ID: fmt.Sprintf("auth-%d", i), Attributes: map[string]string{AttributeWeight: strconv.Itoa(weight)}} + total += weight + } + sticky := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"busy"}}} + key := "codex::" + CanonicalSessionID(sticky.Headers, nil, nil) + "::model" + selector.cache.Set(key, auths[0].ID) + for range 3000 { + if picked, errPick := selector.Pick(t.Context(), "codex", "model", sticky, auths); errPick != nil || picked == nil || picked.ID != auths[0].ID { + t.Fatalf("sticky selection failed: pick=%v err=%v", picked, errPick) + } + if _, errPick := selector.Pick(t.Context(), "codex", "model", cliproxyexecutor.Options{}, auths); errPick != nil { + t.Fatal(errPick) + } + } + counts := map[string]int{} + for i := range 1000 + total*100 { + picked, errPick := selector.Pick(t.Context(), "codex", "model", cliproxyexecutor.Options{}, auths) + if errPick != nil || picked == nil { + t.Fatalf("recovery selection failed: pick=%v err=%v", picked, errPick) + } + if i >= 1000 { + counts[picked.ID]++ + } + } + for i, weight := range weights { + if counts[auths[i].ID] != weight*100 { + t.Errorf("allocation did not recover after sticky traffic stopped: counts=%v weights=%v", counts, weights) + } + } + t.Logf("recovered distribution: %v", counts) + }) + } +} + +func TestWeightedOverloadPendingStickyReservationsDoNotStarveOthers(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a"}, {ID: "b", Attributes: map[string]string{AttributeWeight: "5"}}, {ID: "c"}} + const key = "codex:model" + const inFlight = 200 + reservations := make([]*weightedReservation, inFlight) + t.Cleanup(func() { + for _, reservation := range reservations { + reservation.finish(false) + } + }) + for i := range reservations { + picked, reservation := weighted.reserve(key, auths, "a") + if picked == nil || picked.ID != "a" { + t.Fatal("pending sticky request lost its binding") + } + reservations[i] = reservation + } + counts := map[string]int{} + for i := range 3000 { + // Maintain a fixed backlog without sleeps or timing-dependent coordination. + reservations[i%inFlight].finish(true) + _, reservations[i%inFlight] = weighted.reserve(key, auths, "a") + picked, reservation := weighted.reserve(key, auths, "") + reservation.finish(true) + if i >= 1000 { + counts[picked.ID]++ + } + } + if counts["c"] == 0 { + t.Fatalf("speculative sticky traffic starved c: %v", counts) + } + for _, reservation := range reservations { + reservation.finish(true) + } + state := weightedStateForTest(t, weighted, key, "a", "b", "c") + if len(state.pendingForTest()) != 0 { + t.Fatalf("settled reservations leaked credit: %v", state.pendingForTest()) + } +} + +func TestWeightedOverloadCommitAfterSpeculativeRepaymentRollsBack(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + const key = "codex:model" + for range 1000 { + _, reservation := weighted.reserve(key, auths, "b") + reservation.finish(true) + } + state := weightedStateForTest(t, weighted, key, "a", "b") + before := maps.Clone(state.currentForTest()) + _, first := weighted.reserve(key, auths, "") + _, second := weighted.reserve(key, auths, "") + t.Cleanup(func() { first.finish(false); second.finish(false) }) + // Two pending cold selections make room for a bound delta, but neither + // repayment is real yet. Its later commit must recheck the committed cap. + picked, bound := weighted.reserve(key, auths, "b") + if picked == nil || picked.ID != "b" || bound == nil { + t.Fatal("expected bound reservation funded by pending repayments") + } + t.Cleanup(func() { bound.finish(false) }) + first.finish(false) + second.finish(false) + bound.finish(true) + bound.finish(true) + bound.finish(false) + if !maps.Equal(state.currentForTest(), before) || len(state.pendingForTest()) != 0 { + t.Fatalf("late commit crossed the cap or leaked pending credit: before=%v current=%v pending=%v", before, state.currentForTest(), state.pendingForTest()) + } + // An over-limit bound selection succeeds without reserving any credit. + picked, skipped := weighted.reserve(key, auths, "b") + if picked == nil || picked.ID != "b" || skipped != nil || !maps.Equal(state.currentForTest(), before) || len(state.pendingForTest()) != 0 { + t.Fatal("saturated bound selection should preserve binding and all credits") + } +} + +func TestWeightedOverloadMultipleBusyBindings(t *testing.T) { + for _, busyPerFresh := range []int{1, 3, 10} { + t.Run(fmt.Sprint(busyPerFresh), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{ + {ID: "a"}, {ID: "b", Attributes: map[string]string{AttributeWeight: "5"}}, {ID: "c"}, {ID: "d"}, + } + boundOpts := make([]cliproxyexecutor.Options, 2) + for i, id := range []string{"a", "d"} { + boundOpts[i].Headers = http.Header{"Session_id": {"busy-" + id}} + sessionID := CanonicalSessionID(boundOpts[i].Headers, nil, nil) + selector.cache.Set("codex::"+sessionID+"::model", id) + } + windowCounts := map[string]int{} + for i := range 1400 { + for j := range busyPerFresh { + index := (i + j) % len(boundOpts) + picked, errPick := selector.Pick(t.Context(), "codex", "model", boundOpts[index], auths) + if errPick != nil || picked == nil || picked.ID != []string{"a", "d"}[index] { + t.Fatalf("busy binding changed: auth=%v err=%v", picked, errPick) + } + } + picked, errPick := selector.Pick(t.Context(), "codex", "model", cliproxyexecutor.Options{}, auths) + if errPick != nil || picked == nil { + t.Fatalf("fresh pick failed: auth=%v err=%v", picked, errPick) + } + if i >= 1000 { + windowCounts[picked.ID]++ + if (i+1)%100 == 0 { + if windowCounts["b"] == 0 || windowCounts["c"] == 0 { + t.Fatalf("busy=%d unbound peer starved in a 100-request window: %v", busyPerFresh, windowCounts) + } + clear(windowCounts) + } + } + } + }) + } +} + +func TestWeightedOverloadSaturatedChargeLeavesPeersUnchanged(t *testing.T) { + for _, credit := range []map[string]int64{ + {"a": -222, "b": 111, "c": 111}, + {"a": -112, "b": 222, "c": -110}, + } { + state := weightedPoolForTest("route", map[string]int64{"a": 1, "b": 5, "c": 1}, credit) + state.charge(0, true) + if !maps.Equal(state.currentForTest(), credit) { + t.Fatalf("saturated sticky charge changed peers: got=%v want=%v", state.currentForTest(), credit) + } + } +} + +func TestManagerWeightedOverloadStickyAndPinnedSessions(t *testing.T) { + for _, mixed := range []bool{false, true} { + for _, pinned := range []bool{false, true} { + t.Run(fmt.Sprintf("mixed=%t/pinned=%t", mixed, pinned), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + manager := NewManager(nil, selector, nil) + const provider, model = "sticky-overload", "sticky-overload-model" + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + aID, bID, cID := t.Name()+"-a", t.Name()+"-b", t.Name()+"-c" + for _, auth := range []*Auth{ + {ID: aID, Provider: provider, Status: StatusActive}, + {ID: bID, Provider: provider, Status: StatusActive, Attributes: map[string]string{AttributeWeight: "5"}}, + {ID: cID, Provider: provider, Status: StatusActive}, + } { + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + if _, errRegister := manager.Register(WithSkipPersist(t.Context()), auth); errRegister != nil { + t.Fatal(errRegister) + } + } + namespace := provider + if mixed { + namespace = "mixed" + } + sticky := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"busy"}}, Metadata: map[string]any{}} + key := namespace + "::" + CanonicalSessionID(sticky.Headers, nil, nil) + "::" + model + selector.cache.Set(key, aID) + if pinned { + sticky.Metadata[cliproxyexecutor.PinnedAuthMetadataKey] = aID + } + counts := map[string]int{} + for i := range 1600 { + for _, bound := range []bool{true, false} { + opts := sticky + if !bound { + opts = cliproxyexecutor.Options{Headers: http.Header{"Session_id": {fmt.Sprintf("new-%d", i)}}} + } + var auth *Auth + var errPick error + if mixed { + auth, _, _, errPick = manager.pickNextMixedLegacy(t.Context(), []string{provider}, model, opts, nil) + } else { + auth, _, errPick = manager.pickNextLegacy(t.Context(), provider, model, opts, nil) + } + if errPick != nil || auth == nil || (bound && auth.ID != aID) { + t.Fatalf("request %d bound=%t: auth=%v err=%v", i, bound, auth, errPick) + } + if !bound && i >= 1000 { + counts[auth.ID]++ + } + } + } + if counts[bID] != 500 || counts[cID] != 100 { + t.Fatalf("manager overload allocation = %v, want b=500 c=100", counts) + } + if binding, ok := selector.cache.Get(key); !ok || binding != aID { + t.Fatalf("manager moved busy binding: %q, found=%t", binding, ok) + } + state := weightedStateForTest(t, weighted, namespace+":"+model, aID, bID, cID) + if len(state.pendingForTest()) != 0 { + t.Fatalf("manager left speculative credit: %v", state.pendingForTest()) + } + }) + } + } +} + +func TestWeightedOverloadConcurrentStickyAccounting(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}} + headers := http.Header{"Session_id": {"sticky-concurrent"}} + key := "codex::" + CanonicalSessionID(headers, nil, nil) + "::model" + selector.cache.Set(key, "b") + type selection struct { + id string + err error + sticky bool + } + results := make(chan selection, 64) + start := make(chan struct{}) + var done sync.WaitGroup + for i := range 64 { + done.Add(1) + go func() { + defer done.Done() + isSticky := i < 8 + opts := cliproxyexecutor.Options{Headers: headers} + if !isSticky { + opts.Headers = http.Header{"Session_id": {fmt.Sprintf("new-%d", i)}} + } + <-start + picked, errPick := selector.Pick(t.Context(), "codex", "model", opts, auths) + id := "" + if picked != nil { + id = picked.ID + } + results <- selection{id: id, err: errPick, sticky: isSticky} + }() + } + close(start) + done.Wait() + close(results) + counts := map[string]int{} + for result := range results { + if result.err != nil || result.id == "" || (result.sticky && result.id != "b") { + t.Fatalf("invalid concurrent result: %+v", result) + } + counts[result.id]++ + } + state := weightedStateForTest(t, weighted, "codex:model", "a", "b") + // All 64 calls share one pool. Accounting must match actual accepted picks, + // regardless of whether the final arrivals happened to be sticky requests. + if state.currentForTest()["a"] != int64(64*3-counts["a"]*4) || state.currentForTest()["b"] != int64(64-counts["b"]*4) || len(state.pendingForTest()) != 0 { + t.Fatalf("concurrent accounting drifted: counts=%v committed=%v pending=%v", counts, state.currentForTest(), state.pendingForTest()) + } + if bound, ok := selector.cache.Get(key); !ok || bound != "b" { + t.Fatalf("concurrency moved sticky binding: %q, found=%t", bound, ok) + } +} diff --git a/sdk/cliproxy/auth/selector_weighted_pool_test.go b/sdk/cliproxy/auth/selector_weighted_pool_test.go new file mode 100644 index 00000000000..5fb73ffa9ca --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted_pool_test.go @@ -0,0 +1,287 @@ +package auth + +import ( + "fmt" + "maps" + "math/rand/v2" + "net/http" + "strconv" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +// weightedStateForTest checks that the requested accounting pool was created. +func weightedStateForTest(t *testing.T, selector *WeightedRoundRobinSelector, route string, ids ...string) *weightedPoolState { + t.Helper() + weights := make(map[string]int64, len(ids)) + for _, id := range ids { + weights[id] = 1 + } + state := selector.states[weightedPoolStateKey(route, weights)] + ids = sortedWeightedIDs(weights) + for state != nil && !state.matches(route, ids) { + state = state.next + } + if state == nil { + t.Fatalf("missing weighted state for %q and %v", route, ids) + } + return state +} + +func TestWeightedPoolsResumeCreditsAndIsolatePendingReservations(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + auths := []*Auth{{ID: "a", Attributes: map[string]string{AttributeWeight: "3"}}, {ID: "b"}, {ID: "c"}} + key := "codex:model" + _, pendingFull := weighted.reserve(key, auths, "b") + t.Cleanup(func() { pendingFull.finish(false) }) + _, pendingSubset := weighted.reserve(key, auths[:2], "b") + t.Cleanup(func() { pendingSubset.finish(false) }) + pendingSubset.finish(true) + subset := weightedStateForTest(t, weighted, key, "a", "b") + full := weightedStateForTest(t, weighted, key, "a", "b", "c") + if !maps.Equal(subset.currentForTest(), map[string]int64{"a": 3, "b": -3}) || full.hasCurrentForTest() { + t.Fatalf("commit crossed pool boundary: subset=%v full=%v", subset.currentForTest(), full.currentForTest()) + } + if !maps.Equal(full.pendingForTest(), map[string]int64{"a": 3, "b": -4, "c": 1}) { + t.Fatalf("another pool consumed pending credit: %v", full.pendingForTest()) + } + pendingFull.finish(false) + for range 100 { + _, reservation := weighted.reserve(key, auths, "b") + reservation.finish(true) + } + // A returning pool resumes its debt, independent of full-pool traffic. + for range 3 { + picked, reservation := weighted.reserve(key, []*Auth{auths[1], auths[0]}, "") + if picked == nil || picked.ID != "a" { + t.Fatalf("returning subset lost credit: pick=%v credits=%v", picked, subset.currentForTest()) + } + reservation.finish(true) + } + if !maps.Equal(subset.currentForTest(), map[string]int64{"a": 0, "b": 0}) || len(subset.pendingForTest()) != 0 || len(full.pendingForTest()) != 0 { + t.Fatalf("returning subset failed to balance: %#v", subset) + } +} + +func TestWeightedPoolInterleavingMatchesIndependentSelectors(t *testing.T) { + shared := &WeightedRoundRobinSelector{} + auths := []*Auth{ + {ID: "a", Attributes: map[string]string{AttributeWeight: "1"}}, + {ID: "b", Attributes: map[string]string{AttributeWeight: "3"}}, + {ID: "c", Attributes: map[string]string{AttributeWeight: "2"}}, + {ID: "d", Attributes: map[string]string{AttributeWeight: "5"}}, + } + var independent [16]WeightedRoundRobinSelector + rng := rand.New(rand.NewPCG(17, 29)) + for step := range 5000 { + mask := 1 + rng.IntN(15) + var pool []*Auth + for i, auth := range auths { + if mask&(1< weighted.maxKeys || old.state == current.state { + t.Fatal("pool eviction failed to bound or replace state") + } + old.finish(true) + if current.state.hasCurrentForTest() || !maps.Equal(current.state.pendingForTest(), map[string]int64{"a": -1, "b": 1}) { + t.Fatal("finishing an evicted reservation affected the new pool") + } + current.finish(true) +} + +func TestManagerWeightedPriorityPoolIsolation(t *testing.T) { + for _, mixed := range []bool{false, true} { + for _, pinned := range []bool{false, true} { + t.Run(fmt.Sprintf("mixed=%t/pinned=%t", mixed, pinned), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + manager := NewManager(nil, selector, nil) + const provider, model = "pool-isolation", "pool-model" + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + auths := []*Auth{ + {ID: t.Name() + "-a", Attributes: map[string]string{"priority": "0"}}, + {ID: t.Name() + "-b", Attributes: map[string]string{"priority": "1", AttributeWeight: "3"}}, + {ID: t.Name() + "-c", Attributes: map[string]string{"priority": "1", AttributeWeight: "1"}}, + } + for _, auth := range auths { + auth.Provider, auth.Status = provider, StatusActive + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + if _, errRegister := manager.Register(WithSkipPersist(t.Context()), auth); errRegister != nil { + t.Fatal(errRegister) + } + } + namespace := provider + if mixed { + namespace = "mixed" + } + sticky := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"priority-bound"}}, Metadata: map[string]any{}} + id := CanonicalSessionID(sticky.Headers, nil, nil) + selector.cache.Set(namespace+"::"+id+"::"+model, auths[0].ID) + if pinned { + sticky.Metadata[cliproxyexecutor.PinnedAuthMetadataKey] = auths[0].ID + } + counts := map[string]int{} + for i := range 1200 { + for _, bound := range []bool{true, false} { + opts := sticky + if !bound { + opts = cliproxyexecutor.Options{Headers: http.Header{"Session_id": {fmt.Sprintf("fresh-%d", i)}}} + } + var auth *Auth + var errPick error + if mixed { + auth, _, _, errPick = manager.pickNextMixedLegacy(t.Context(), []string{provider}, model, opts, nil) + } else { + auth, _, errPick = manager.pickNextLegacy(t.Context(), provider, model, opts, nil) + } + if errPick != nil || auth == nil || (bound && auth.ID != auths[0].ID) || (!bound && auth.ID == auths[0].ID) { + t.Fatalf("request %d bound=%t: auth=%v err=%v", i, bound, auth, errPick) + } + if !bound && i >= 200 { + counts[auth.ID]++ + } + } + } + if counts[auths[1].ID] != 750 || counts[auths[2].ID] != 250 { + t.Fatalf("manager cross-priority distribution = %v, want 750:250", counts) + } + }) + } + } +} + +func TestWeightedSessionAffinityPoolIsolation(t *testing.T) { + for _, reason := range []string{"priority", "websocket", "retry-exclusion", "cooldown"} { + for _, weights := range [][2]int{{1, 1}, {3, 1}, {1, 3}, {5, 2}} { + t.Run(fmt.Sprintf("%s/%d:%d", reason, weights[0], weights[1]), func(t *testing.T) { + weighted := &WeightedRoundRobinSelector{} + selector := NewSessionAffinitySelector(weighted) + t.Cleanup(selector.Stop) + auths := []*Auth{ + {ID: "a", Attributes: map[string]string{"priority": "0"}}, + {ID: "b", Attributes: map[string]string{AttributeWeight: strconv.Itoa(weights[0])}}, + {ID: "c", Attributes: map[string]string{AttributeWeight: strconv.Itoa(weights[1])}}, + } + ctx := t.Context() + switch reason { + case "priority": + auths[1].Attributes["priority"] = "1" + auths[2].Attributes["priority"] = "1" + case "websocket": + ctx = cliproxyexecutor.WithDownstreamWebsocket(ctx) + auths[1].Attributes["websockets"] = "true" + auths[2].Attributes["websockets"] = "true" + } + sticky := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"bound-a"}}} + id := CanonicalSessionID(sticky.Headers, nil, nil) + key := "codex::" + id + "::model" + selector.cache.Set(key, "a") + const warmup, measured = 1000, 1400 + counts := map[string]int{} + for i := range warmup + measured { + picked, errPick := selector.Pick(ctx, "codex", "model", sticky, auths) + if errPick != nil || picked == nil || picked.ID != "a" { + t.Fatalf("sticky request %d: pick=%v err=%v", i, picked, errPick) + } + freshAuths := auths + if reason == "retry-exclusion" { + freshAuths = auths[1:] + } else if reason == "cooldown" { + auths[0].Unavailable = true + auths[0].NextRetryAfter = time.Now().Add(time.Hour) + } + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {fmt.Sprintf("fresh-%d", i)}}} + picked, errPick = selector.Pick(ctx, "codex", "model", opts, freshAuths) + if errPick != nil || picked == nil || (picked.ID != "b" && picked.ID != "c") { + t.Fatalf("fresh request %d: pick=%v err=%v", i, picked, errPick) + } + if i >= warmup { + counts[picked.ID]++ + } + auths[0].Unavailable = false + auths[0].NextRetryAfter = time.Time{} + } + wantB := measured * weights[0] / (weights[0] + weights[1]) + if counts["b"] != wantB || counts["c"] != measured-wantB { + t.Fatalf("cross-pool traffic distorted cold selections: %v, want b=%d c=%d", counts, wantB, measured-wantB) + } + if bound, ok := selector.cache.Get(key); !ok || bound != "a" { + t.Fatalf("binding moved: %q, found=%t", bound, ok) + } + for _, state := range weighted.states { + if len(state.pendingForTest()) != 0 { + t.Fatalf("pending credits leaked: %v", state.pendingForTest()) + } + } + }) + } + } +} diff --git a/sdk/cliproxy/auth/selector_weighted_storage_test.go b/sdk/cliproxy/auth/selector_weighted_storage_test.go new file mode 100644 index 00000000000..0d937b90381 --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted_storage_test.go @@ -0,0 +1,88 @@ +package auth + +import ( + "maps" + "testing" +) + +// These snapshots keep assertions independent of the compact production layout. +func (s *weightedPoolState) currentForTest() map[string]int64 { + current := make(map[string]int64, len(s.members)) + for _, member := range s.members { + current[member.id] = member.current + } + return current +} + +func (s *weightedPoolState) pendingForTest() map[string]int64 { + pending := make(map[string]int64) + for _, member := range s.members { + if member.pending != 0 { + pending[member.id] = member.pending + } + } + return pending +} + +func (s *weightedPoolState) hasCurrentForTest() bool { + for _, member := range s.members { + if member.current != 0 { + return true + } + } + return false +} + +// TestWeightedPoolDigestCollisionIsolation forces digest hits for different exact +// identities, including a matching state behind a collision-chain head. +func TestWeightedPoolDigestCollisionIsolation(t *testing.T) { + for _, unrelated := range []*weightedPoolState{ + weightedPoolForTest("other-route", map[string]int64{"a": 1, "b": 1}, map[string]int64{"a": 7, "b": -7}), + weightedPoolForTest("route", map[string]int64{"a": 1, "c": 1}, map[string]int64{"a": 7, "c": -7}), + weightedPoolForTest("route", map[string]int64{"a": 1}, map[string]int64{"a": 7}), + } { + t.Run(unrelated.route+"/"+unrelated.members[len(unrelated.members)-1].id, func(t *testing.T) { + weights := map[string]int64{"a": 1, "b": 1} + key := weightedPoolStateKey("route", weights) + selector := &WeightedRoundRobinSelector{ + states: map[[32]byte]*weightedPoolState{key: unrelated}, stateCount: 1, maxKeys: 2, + } + before := unrelated.currentForTest() + picked, first := selector.reserve("route", []*Auth{{ID: "b"}, {ID: "a"}}, "b") + if picked == nil || picked.ID != "b" || first == nil || first.state == unrelated { + t.Fatal("digest collision reused an unrelated pool") + } + t.Cleanup(func() { first.finish(false) }) + matching := first.state + // Put the nonmatching state first to exercise a full chain lookup. + matching.next, unrelated.next, selector.states[key] = nil, matching, unrelated + _, second := selector.reserve("route", []*Auth{{ID: "a"}, {ID: "b"}}, "a") + if second == nil || second.state != matching || selector.stateCount != 2 { + t.Fatal("collision lookup failed to reuse the matching pool") + } + t.Cleanup(func() { second.finish(false) }) + first.finish(true) + second.finish(true) + if !maps.Equal(before, unrelated.currentForTest()) || unrelated.inFlight != 0 || len(unrelated.pendingForTest()) != 0 { + t.Fatal("collision accounting changed the unrelated pool") + } + if matching.hasCurrentForTest() || matching.inFlight != 0 || len(matching.pendingForTest()) != 0 { + t.Fatal("matching pool did not balance") + } + // Capacity still counts pools, not just distinct digest buckets. + _, third := selector.reserve("third-route", []*Auth{{ID: "a"}}, "") + third.finish(true) + if selector.stateCount != 1 || len(selector.states) != 1 { + t.Fatal("colliding pools bypassed the existing capacity limit") + } + }) + } +} + +func weightedPoolForTest(route string, weights, current map[string]int64) *weightedPoolState { + state := &weightedPoolState{route: route} + for _, id := range sortedWeightedIDs(weights) { + state.members = append(state.members, weightedPoolMember{id: id, weight: weights[id], current: current[id]}) + } + return state +} diff --git a/sdk/cliproxy/auth/selector_weighted_test.go b/sdk/cliproxy/auth/selector_weighted_test.go new file mode 100644 index 00000000000..31352e30170 --- /dev/null +++ b/sdk/cliproxy/auth/selector_weighted_test.go @@ -0,0 +1,79 @@ +package auth + +import ( + "maps" + "sort" + "testing" +) + +func TestSmoothWeightedStateChargeRebasesBeforeBounding(t *testing.T) { + for _, tc := range []struct { + name string + current map[string]int64 + weights map[string]int64 + authID string + want map[string]int64 + }{ + { + name: "smaller pool preserves leading difference", + current: map[string]int64{"a": -96, "b": 96, "c": 95}, + weights: map[string]int64{"b": 1, "c": 1}, + authID: "b", + want: map[string]int64{"b": 63, "c": 64}, + }, + { + name: "negative credits shift together", + current: map[string]int64{"a": 96, "b": -64, "c": -63}, + weights: map[string]int64{"b": 1, "c": 1}, + authID: "b", + want: map[string]int64{"b": -64, "c": -61}, + }, + { + name: "excessive spread clips debt without tying leaders", + current: map[string]int64{"a": -96, "b": 96, "c": 95}, + weights: map[string]int64{"a": 1, "b": 1, "c": 1}, + authID: "a", + want: map[string]int64{"a": -96, "b": 96, "c": 95}, + }, + { + name: "bounded credits do not shift", + current: map[string]int64{"b": 0, "c": 0}, + weights: map[string]int64{"b": 1, "c": 1}, + authID: "b", + want: map[string]int64{"b": -1, "c": 1}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + state := weightedPoolForTest("route", tc.weights, tc.current) + state.charge(sort.Search(len(state.members), func(i int) bool { return state.members[i].id >= tc.authID }), false) + if !maps.Equal(state.currentForTest(), tc.want) { + t.Fatalf("rebased credits = %v, want %v", state.currentForTest(), tc.want) + } + }) + } +} + +func TestWeightedReservationRollbackPreservesConcurrentCredits(t *testing.T) { + key := "codex:model" + weights := map[string]int64{"a": 1, "b": 1, "c": 1} + state := weightedPoolForTest(key, weights, map[string]int64{"a": -94, "b": 94, "c": 93}) + weighted := &WeightedRoundRobinSelector{states: map[[32]byte]*weightedPoolState{weightedPoolStateKey(key, weights): state}, stateCount: 1} + auths := []*Auth{{ID: "a"}, {ID: "b"}, {ID: "c"}} + _, rejected := weighted.reserve(key, auths, "a") + t.Cleanup(func() { rejected.finish(false) }) + _, accepted := weighted.reserve(key, auths, "b") + t.Cleanup(func() { accepted.finish(false) }) + accepted.finish(true) + want := map[string]int64{"a": -93, "b": 92, "c": 94} + if !maps.Equal(state.currentForTest(), want) { + t.Fatalf("committed credits = %v, want %v", state.currentForTest(), want) + } + if !maps.Equal(state.pendingForTest(), map[string]int64{"a": -2, "b": 1, "c": 1}) { + t.Fatalf("commit changed another request's reservation: %v", state.pendingForTest()) + } + rejected.finish(false) + rejected.finish(true) + if !maps.Equal(state.currentForTest(), want) || len(state.pendingForTest()) != 0 { + t.Fatalf("rollback changed committed credits: current=%v pending=%v", state.currentForTest(), state.pendingForTest()) + } +} diff --git a/sdk/cliproxy/auth/session_affinity_priority_test.go b/sdk/cliproxy/auth/session_affinity_priority_test.go index c6cd1fb3358..649bd329562 100644 --- a/sdk/cliproxy/auth/session_affinity_priority_test.go +++ b/sdk/cliproxy/auth/session_affinity_priority_test.go @@ -2,10 +2,13 @@ package auth import ( "context" + "errors" "net/http" + "strings" "testing" "time" + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" @@ -768,3 +771,643 @@ func TestManagerExecuteAndStreamRebindOnQuotaEndToEnd(t *testing.T) { }) } } + +func TestManagerSessionAffinityRebindOnNeverRefusesFailoverAndPreservesBinding(t *testing.T) { + for _, testCase := range []struct { + name string + providerSuffix string + pick func(*Manager, context.Context, string, string, cliproxyexecutor.Options, map[string]struct{}) (*Auth, error) + }{ + { + name: "single provider", + providerSuffix: "single", + pick: func(manager *Manager, ctx context.Context, provider, model string, opts cliproxyexecutor.Options, tried map[string]struct{}) (*Auth, error) { + auth, _, errPick := manager.pickNext(ctx, provider, model, opts, tried) + return auth, errPick + }, + }, + { + name: "mixed provider", + providerSuffix: "mixed", + pick: func(manager *Manager, ctx context.Context, provider, model string, opts cliproxyexecutor.Options, tried map[string]struct{}) (*Auth, error) { + auth, _, _, errPick := manager.pickNextMixed(ctx, []string{provider}, model, opts, tried) + return auth, errPick + }, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + ctx := context.Background() + provider := "affinity-rebind-never-" + testCase.providerSuffix + model := "affinity-rebind-never-model" + highID := provider + "-high" + lowID := provider + "-low" + + manager := NewManager(nil, nil, nil) + affinity := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{ + Fallback: &RoundRobinSelector{}, + TTL: time.Hour, + RebindOn: SessionAffinityRebindOnNever, + }) + defer affinity.Stop() + manager.SetSelector(affinity) + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + + for _, auth := range []*Auth{ + {ID: highID, Provider: provider, Status: StatusActive, Attributes: map[string]string{"priority": "1"}}, + {ID: lowID, Provider: provider, Status: StatusActive, Attributes: map[string]string{"priority": "0"}}, + } { + if _, errRegister := manager.Register(WithSkipPersist(ctx), auth); errRegister != nil { + t.Fatalf("Register(%s): %v", auth.ID, errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + } + + opts := cliproxyexecutor.Options{Metadata: map[string]any{ + cliproxyexecutor.DerivedSessionIDMetadataKey: "never-session", + }} + otherOpts := cliproxyexecutor.Options{Metadata: map[string]any{ + cliproxyexecutor.DerivedSessionIDMetadataKey: "never-other-session", + }} + + got, errPick := testCase.pick(manager, ctx, provider, model, opts, nil) + if errPick != nil || got == nil || got.ID != highID { + t.Fatalf("cold binding = %v (err=%v), want %q", got, errPick, highID) + } + manager.MarkResult(ctx, Result{ + AuthID: highID, + Provider: provider, + Model: model, + Success: true, + Options: opts, + }) + + // Transient failure on highID must refuse failover with 503 session_auth_retry and keep binding. + manager.MarkResult(ctx, Result{ + AuthID: highID, + Provider: provider, + Model: model, + Success: false, + Error: &Error{HTTPStatus: http.StatusBadGateway, Message: "502 overloaded"}, + Options: opts, + }) + if got, errPick = testCase.pick(manager, ctx, provider, model, opts, nil); errPick == nil { + t.Fatalf("transient unavailable pick succeeded with %v, want 503 session_auth_retry error", got) + } else { + var authErr *Error + if !errors.As(errPick, &authErr) || authErr == nil || authErr.Code != "session_auth_retry" || authErr.HTTPStatus != http.StatusServiceUnavailable { + t.Fatalf("transient unavailable pick err = %v, want 503 session_auth_retry", errPick) + } + } + + // A new unbound session while highID is cooling down must still pick lowID. + gotOther, errOther := testCase.pick(manager, ctx, provider, model, otherOpts, nil) + if errOther != nil || gotOther == nil || gotOther.ID != lowID { + t.Fatalf("new session pick while highID unavailable = %v (err=%v), want %q", gotOther, errOther, lowID) + } + + expireSessionAffinityPriorityModelCooldown(t, manager, highID, model) + got, errPick = testCase.pick(manager, ctx, provider, model, opts, nil) + if errPick != nil || got == nil || got.ID != highID { + t.Fatalf("pick after transient recovery = %v (err=%v), want %q", got, errPick, highID) + } + manager.MarkResult(ctx, Result{ + AuthID: highID, + Provider: provider, + Model: model, + Success: true, + Options: opts, + }) + + // Quota/auth failures (429, 403) on highID must refuse failover with 429 session_auth_unavailable and keep binding. + for _, blockErr := range []*Error{ + {HTTPStatus: http.StatusTooManyRequests, Message: "usage limit reached"}, + {HTTPStatus: http.StatusForbidden, Message: "forbidden"}, + } { + manager.MarkResult(ctx, Result{ + AuthID: highID, + Provider: provider, + Model: model, + Success: false, + Error: blockErr, + Options: opts, + }) + if got, errPick = testCase.pick(manager, ctx, provider, model, opts, nil); errPick == nil { + t.Fatalf("blocked (%v) pick succeeded with %v, want 429 session_auth_unavailable error", blockErr, got) + } else { + var authErr *Error + if !errors.As(errPick, &authErr) || authErr == nil || authErr.Code != "session_auth_unavailable" || authErr.HTTPStatus != http.StatusTooManyRequests { + t.Fatalf("blocked (%v) pick err = %v, want 429 session_auth_unavailable", blockErr, errPick) + } + } + expireSessionAffinityPriorityModelCooldown(t, manager, highID, model) + got, errPick = testCase.pick(manager, ctx, provider, model, opts, nil) + if errPick != nil || got == nil || got.ID != highID { + t.Fatalf("pick after blocked (%v) recovery = %v (err=%v), want %q", blockErr, got, errPick, highID) + } + manager.MarkResult(ctx, Result{ + AuthID: highID, + Provider: provider, + Model: model, + Success: true, + Options: opts, + }) + } + }) + } +} + +func TestManagerSessionAffinityRebindOnNeverLCPAndFallbackKeyPreserveBinding(t *testing.T) { + ctx := context.Background() + provider := "openai" + model := "gpt-5-never" + highID := "openai-never-high" + lowID := "openai-never-low" + + manager := NewManager(nil, nil, nil) + affinity := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{ + Fallback: &RoundRobinSelector{}, + TTL: time.Hour, + RebindOn: SessionAffinityRebindOnNever, + }) + defer affinity.Stop() + manager.SetSelector(affinity) + manager.RegisterExecutor(schedulerTestExecutor{provider: provider}) + + for _, auth := range []*Auth{ + {ID: highID, Provider: provider, Status: StatusActive, Attributes: map[string]string{"priority": "1"}}, + {ID: lowID, Provider: provider, Status: StatusActive, Attributes: map[string]string{"priority": "0"}}, + } { + if _, errRegister := manager.Register(WithSkipPersist(ctx), auth); errRegister != nil { + t.Fatalf("Register(%s): %v", auth.ID, errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + } + + makeTurnOpts := func(payload string) cliproxyexecutor.Options { + return cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatOpenAI, + OriginalRequest: []byte(payload), + Metadata: map[string]any{ + cliproxyexecutor.CallerScopeMetadataKey: "caller-lcp-never", + }, + } + } + + // 1. LCP cold binding on highID. + turn1 := makeTurnOpts(`{"messages":[{"role":"user","content":"turn 1 hello"}]}`) + got1, _, errPick := manager.pickNext(ctx, provider, model, turn1, nil) + if errPick != nil || got1 == nil || got1.ID != highID { + t.Fatalf("turn 1 pick = %v (err=%v), want %q", got1, errPick, highID) + } + manager.MarkResult(ctx, Result{AuthID: highID, Provider: provider, Model: model, Success: true, Options: turn1}) + + // 2. LCP turn 2 fails on highID with 429 quota -> failover attempt must refuse with 429 session_auth_unavailable and preserve binding. + turn2 := makeTurnOpts(`{"messages":[{"role":"user","content":"turn 1 hello"},{"role":"assistant","content":"hi"},{"role":"user","content":"turn 2 question"}]}`) + got2, _, errPick := manager.pickNext(ctx, provider, model, turn2, nil) + if errPick != nil || got2 == nil || got2.ID != highID { + t.Fatalf("turn 2 pick = %v (err=%v), want %q", got2, errPick, highID) + } + manager.MarkResult(ctx, Result{ + AuthID: highID, + Provider: provider, + Model: model, + Success: false, + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Message: "quota"}, + Options: turn2, + }) + + turn2Retry := makeTurnOpts(`{"messages":[{"role":"user","content":"turn 1 hello"},{"role":"assistant","content":"hi"},{"role":"user","content":"turn 2 question"}]}`) + if gotFailover, _, errFailover := manager.pickNext(ctx, provider, model, turn2Retry, nil); errFailover == nil { + t.Fatalf("LCP quota unavailable pick succeeded with %v, want 429 session_auth_unavailable", gotFailover) + } else { + var authErr *Error + if !errors.As(errFailover, &authErr) || authErr == nil || authErr.Code != "session_auth_unavailable" || authErr.HTTPStatus != http.StatusTooManyRequests { + t.Fatalf("LCP quota unavailable pick err = %v, want 429 session_auth_unavailable", errFailover) + } + } + + expireSessionAffinityPriorityModelCooldown(t, manager, highID, model) + turn2Recovered := makeTurnOpts(`{"messages":[{"role":"user","content":"turn 1 hello"},{"role":"assistant","content":"hi"},{"role":"user","content":"turn 2 question"}]}`) + got2Rec, _, errPick := manager.pickNext(ctx, provider, model, turn2Recovered, nil) + if errPick != nil || got2Rec == nil || got2Rec.ID != highID { + t.Fatalf("LCP turn 2 after recovery = %v (err=%v), want %q", got2Rec, errPick, highID) + } + manager.MarkResult(ctx, Result{AuthID: highID, Provider: provider, Model: model, Success: true, Options: turn2Recovered}) + + // 3. Fallback-key path (non-subagent, non-fork: conversation -> prompt_cache_key + conversation) + // refuses failover when bound auth is transiently unavailable. + fallbackInitOpts := cliproxyexecutor.Options{ + OriginalRequest: []byte(`{"conversation":"conv-never-1"}`), + } + gotFB1, _, errPick := manager.pickNext(ctx, provider, model, fallbackInitOpts, nil) + if errPick != nil || gotFB1 == nil || gotFB1.ID != highID { + t.Fatalf("fallback init pick = %v (err=%v), want %q", gotFB1, errPick, highID) + } + manager.MarkResult(ctx, Result{AuthID: highID, Provider: provider, Model: model, Success: true, Options: fallbackInitOpts}) + + manager.MarkResult(ctx, Result{ + AuthID: highID, + Provider: provider, + Model: model, + Success: false, + Error: &Error{HTTPStatus: http.StatusBadGateway, Message: "502 overloaded"}, + Options: fallbackInitOpts, + }) + fallbackLookupOpts := cliproxyexecutor.Options{ + OriginalRequest: []byte(`{"prompt_cache_key":"pck-never-1","conversation":"conv-never-1"}`), + } + if gotFB2, _, errFB2 := manager.pickNext(ctx, provider, model, fallbackLookupOpts, nil); errFB2 == nil { + t.Fatalf("fallback key unavailable pick succeeded with %v, want 503 session_auth_retry", gotFB2) + } else { + var authErr *Error + if !errors.As(errFB2, &authErr) || authErr == nil || authErr.Code != "session_auth_retry" || authErr.HTTPStatus != http.StatusServiceUnavailable { + t.Fatalf("fallback key unavailable pick err = %v, want 503 session_auth_retry", errFB2) + } + } + expireSessionAffinityPriorityModelCooldown(t, manager, highID, model) + gotFBRec, _, errPick := manager.pickNext(ctx, provider, model, fallbackLookupOpts, nil) + if errPick != nil || gotFBRec == nil || gotFBRec.ID != highID { + t.Fatalf("fallback key pick after recovery = %v (err=%v), want %q", gotFBRec, errPick, highID) + } +} + +func TestManagerExecuteAndStreamRebindOnNeverEndToEnd(t *testing.T) { + ctx := context.Background() + provider := "exec-rebind-never" + model := "exec-rebind-never-model" + authAID := provider + "-a" + authBID := provider + "-b" + + var failAuthErr map[string]func(call int) error + calls := make(map[string]int) + manager := NewManager(nil, nil, nil) + manager.SetRetryConfig(2, 30*time.Second, 0) + affinity := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{ + Fallback: &RoundRobinSelector{}, + TTL: time.Hour, + RebindOn: SessionAffinityRebindOnNever, + }) + defer affinity.Stop() + manager.SetSelector(affinity) + manager.RegisterExecutor(scriptedFailoverExecutor{ + provider: provider, + execute: func(_ context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + calls[auth.ID]++ + if fn := failAuthErr[auth.ID]; fn != nil { + if errFail := fn(calls[auth.ID]); errFail != nil { + return cliproxyexecutor.Response{}, errFail + } + } + return cliproxyexecutor.Response{Payload: []byte(auth.ID)}, nil + }, + stream: func(_ context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + calls[auth.ID]++ + if fn := failAuthErr[auth.ID]; fn != nil { + if errFail := fn(calls[auth.ID]); errFail != nil { + return nil, errFail + } + } + ch := make(chan cliproxyexecutor.StreamChunk, 1) + ch <- cliproxyexecutor.StreamChunk{Payload: []byte(auth.ID)} + close(ch) + return &cliproxyexecutor.StreamResult{Chunks: ch}, nil + }, + }) + + for _, auth := range []*Auth{ + {ID: authAID, Provider: provider, Status: StatusActive, Attributes: map[string]string{"priority": "1"}}, + {ID: authBID, Provider: provider, Status: StatusActive, Attributes: map[string]string{"priority": "0"}}, + } { + if _, errRegister := manager.Register(WithSkipPersist(ctx), auth); errRegister != nil { + t.Fatalf("Register(%s): %v", auth.ID, errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + } + + req := cliproxyexecutor.Request{Model: model} + sessionAOpts := cliproxyexecutor.Options{ + Headers: http.Header{"Session-Id": []string{"never-e2e-session-a"}}, + } + sessionBOpts := cliproxyexecutor.Options{ + Headers: http.Header{"Session-Id": []string{"never-e2e-session-b"}}, + } + + // 1. Bind session A to authAID. + resp, errExec := manager.Execute(ctx, []string{provider}, req, sessionAOpts) + if errExec != nil || string(resp.Payload) != authAID { + t.Fatalf("cold Execute = %q (err=%v), want %q", string(resp.Payload), errExec, authAID) + } + if calls[authBID] != 0 { + t.Fatalf("authB calls = %d, want 0", calls[authBID]) + } + + // 2. Make authA return 429 usage limit reached -> returns 429 to client without calling authB or running extra retry rounds. + calls[authAID] = 0 + failAuthErr = map[string]func(int) error{ + authAID: func(_ int) error { + return &Error{HTTPStatus: http.StatusTooManyRequests, Message: "usage_limit_reached: quota exhausted"} + }, + } + _, errExec = manager.Execute(ctx, []string{provider}, req, sessionAOpts) + if errExec == nil || statusCodeFromError(errExec) != http.StatusTooManyRequests || !strings.Contains(errExec.Error(), "usage_limit_reached") { + t.Fatalf("Execute on 429 = %v, want 429 usage_limit_reached", errExec) + } + if calls[authAID] != 1 { + t.Fatalf("authA calls on 429 = %d, want 1 (no extra retry rounds on quota error)", calls[authAID]) + } + if calls[authBID] != 0 { + t.Fatalf("authB calls after authA 429 = %d, want 0", calls[authBID]) + } + + // 3. Next request on session A while authA is in 429 cooldown returns 429 session_auth_unavailable without calling authA or authB. + _, errExec = manager.Execute(ctx, []string{provider}, req, sessionAOpts) + if errExec == nil || statusCodeFromError(errExec) != http.StatusTooManyRequests { + t.Fatalf("subsequent Execute on cooled session A = %v, want 429", errExec) + } + if calls[authAID] != 1 || calls[authBID] != 0 { + t.Fatalf("calls after cooled session A = (A=%d, B=%d), want (1, 0)", calls[authAID], calls[authBID]) + } + + // 4. A request with a new session ID (session B) goes to authB. + respB, errExecB := manager.Execute(ctx, []string{provider}, req, sessionBOpts) + if errExecB != nil || string(respB.Payload) != authBID { + t.Fatalf("new session B Execute = %q (err=%v), want %q", string(respB.Payload), errExecB, authBID) + } + if calls[authBID] != 1 { + t.Fatalf("authB calls = %d, want 1", calls[authBID]) + } + + // 5. Expire authA cooldown -> session A still bound to authA. + failAuthErr = nil + expireSessionAffinityPriorityModelCooldown(t, manager, authAID, model) + resp, errExec = manager.Execute(ctx, []string{provider}, req, sessionAOpts) + if errExec != nil || string(resp.Payload) != authAID { + t.Fatalf("Execute after authA quota recovery = %q (err=%v), want %q", string(resp.Payload), errExec, authAID) + } + + // 6. Transient 502 error on authA (with transient cooldown disabled) is retried on authA through retry rounds and never sent to authB. + prevTransientSec := transientErrorCooldownSeconds.Load() + SetTransientErrorCooldownSeconds(-1) + defer SetTransientErrorCooldownSeconds(int(prevTransientSec)) + + calls[authAID] = 0 + calls[authBID] = 0 + failAuthErr = map[string]func(int) error{ + authAID: func(call int) error { + if call == 1 { + return &Error{HTTPStatus: http.StatusBadGateway, Message: "502 bad gateway"} + } + return nil + }, + } + resp, errExec = manager.Execute(ctx, []string{provider}, req, sessionAOpts) + if errExec != nil || string(resp.Payload) != authAID { + t.Fatalf("Execute 502 retry on authA = %q (err=%v), want %q", string(resp.Payload), errExec, authAID) + } + if calls[authAID] != 2 || calls[authBID] != 0 { + t.Fatalf("calls after 502 retry = (A=%d, B=%d), want (2, 0)", calls[authAID], calls[authBID]) + } + + // 7. When authA fails with 502 across all retry rounds (or cooldown exceeds maxWait), Execute returns 503 session_auth_retry and never calls authB. + SetTransientErrorCooldownSeconds(-1) + manager.SetRetryConfig(2, 30*time.Second, 0) + calls[authAID] = 0 + calls[authBID] = 0 + failAuthErr = map[string]func(int) error{ + authAID: func(_ int) error { + return &Error{HTTPStatus: http.StatusBadGateway, Message: "502 overloaded"} + }, + } + _, errExec = manager.Execute(ctx, []string{provider}, req, sessionAOpts) + if errExec == nil || statusCodeFromError(errExec) != http.StatusServiceUnavailable { + t.Fatalf("Execute exhausted 502 retry rounds = %v, want 503 session_auth_retry", errExec) + } + var exhaustedRetryErr *Error + if !errors.As(errExec, &exhaustedRetryErr) || exhaustedRetryErr == nil || exhaustedRetryErr.Code != "session_auth_retry" { + t.Fatalf("Execute exhausted 502 error = %v, want session_auth_retry", errExec) + } + if calls[authAID] != 3 || calls[authBID] != 0 { + t.Fatalf("calls after exhausted 502 retry rounds = (A=%d, B=%d), want (3, 0)", calls[authAID], calls[authBID]) + } + + // 8. When authA is in transient 502 cooldown exceeding maxWait, both initial and subsequent requests on session A return 503 session_auth_retry and never call authB. + SetTransientErrorCooldownSeconds(0) + manager.SetRetryConfig(2, 0, 0) + calls[authAID] = 0 + calls[authBID] = 0 + _, errExec = manager.Execute(ctx, []string{provider}, req, sessionAOpts) + if errExec == nil || statusCodeFromError(errExec) != http.StatusServiceUnavailable { + t.Fatalf("Execute initial 502 with cooldown = %v, want 503 session_auth_retry", errExec) + } + if calls[authAID] != 1 || calls[authBID] != 0 { + t.Fatalf("calls after initial 502 = (A=%d, B=%d), want (1, 0)", calls[authAID], calls[authBID]) + } + + _, errExec = manager.Execute(ctx, []string{provider}, req, sessionAOpts) + if errExec == nil || statusCodeFromError(errExec) != http.StatusServiceUnavailable { + t.Fatalf("subsequent Execute while authA in 502 cooldown = %v, want 503", errExec) + } + var retryAuthErr *Error + if !errors.As(errExec, &retryAuthErr) || retryAuthErr == nil || retryAuthErr.Code != "session_auth_retry" { + t.Fatalf("subsequent Execute error = %v, want session_auth_retry", errExec) + } + if calls[authAID] != 1 || calls[authBID] != 0 { + t.Fatalf("calls after cooled 502 session A = (A=%d, B=%d), want (1, 0)", calls[authAID], calls[authBID]) + } + + _, errStream := manager.ExecuteStream(ctx, []string{provider}, req, sessionAOpts) + if errStream == nil || statusCodeFromError(errStream) != http.StatusServiceUnavailable { + t.Fatalf("subsequent ExecuteStream while authA in 502 cooldown = %v, want 503", errStream) + } + if calls[authAID] != 1 || calls[authBID] != 0 { + t.Fatalf("calls after cooled 502 ExecuteStream = (A=%d, B=%d), want (1, 0)", calls[authAID], calls[authBID]) + } +} + +func TestManagerSessionAffinityRebindOnNeverBlocksAntigravityCreditsCrossAuthFallback(t *testing.T) { + ctx := context.Background() + provider := "antigravity" + model := "claude-sonnet-4-6" + authAID := "antigravity-never-a" + authBID := "antigravity-never-b" + + calls := make(map[string]int) + var failAuthA bool + manager := NewManager(nil, nil, nil) + manager.SetConfig(&internalconfig.Config{ + QuotaExceeded: internalconfig.QuotaExceeded{AntigravityCredits: true}, + }) + manager.SetRetryConfig(0, 0, 0) + affinity := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{ + Fallback: &RoundRobinSelector{}, + TTL: time.Hour, + RebindOn: SessionAffinityRebindOnNever, + }) + defer affinity.Stop() + manager.SetSelector(affinity) + manager.RegisterExecutor(scriptedFailoverExecutor{ + provider: provider, + execute: func(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + calls[auth.ID]++ + if auth.ID == authAID && failAuthA { + return cliproxyexecutor.Response{}, &Error{HTTPStatus: http.StatusTooManyRequests, Message: "quota exhausted"} + } + return cliproxyexecutor.Response{Payload: []byte(auth.ID)}, nil + }, + stream: func(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + calls[auth.ID]++ + if auth.ID == authAID && failAuthA { + return nil, &Error{HTTPStatus: http.StatusTooManyRequests, Message: "quota exhausted"} + } + ch := make(chan cliproxyexecutor.StreamChunk, 1) + ch <- cliproxyexecutor.StreamChunk{Payload: []byte(auth.ID)} + close(ch) + return &cliproxyexecutor.StreamResult{Chunks: ch}, nil + }, + }) + + for _, auth := range []*Auth{ + {ID: authAID, Provider: provider, Status: StatusActive, Attributes: map[string]string{"priority": "1"}}, + {ID: authBID, Provider: provider, Status: StatusActive, Attributes: map[string]string{"priority": "0"}}, + } { + if _, errRegister := manager.Register(WithSkipPersist(ctx), auth); errRegister != nil { + t.Fatalf("Register(%s): %v", auth.ID, errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + } + SetAntigravityCreditsHint(authAID, AntigravityCreditsHint{Known: true, Available: false, UpdatedAt: time.Now()}) + SetAntigravityCreditsHint(authBID, AntigravityCreditsHint{Known: true, Available: true, UpdatedAt: time.Now()}) + t.Cleanup(func() { + SetAntigravityCreditsHint(authAID, AntigravityCreditsHint{}) + SetAntigravityCreditsHint(authBID, AntigravityCreditsHint{}) + }) + + req := cliproxyexecutor.Request{Model: model} + opts := cliproxyexecutor.Options{ + Headers: http.Header{"Session-Id": []string{"antigravity-never-session"}}, + } + + // 1. Cold Execute binds session to authA. + resp, errExec := manager.Execute(ctx, []string{provider}, req, opts) + if errExec != nil || string(resp.Payload) != authAID { + t.Fatalf("cold Execute = %q (err=%v), want %q", string(resp.Payload), errExec, authAID) + } + + // 2. authA returns 429 and has no credits; authB has available credits, but rebind-on: never must block switching to authB. + failAuthA = true + calls[authAID] = 0 + calls[authBID] = 0 + if _, errExec = manager.Execute(ctx, []string{provider}, req, opts); errExec == nil || statusCodeFromError(errExec) != http.StatusTooManyRequests { + t.Fatalf("Execute on 429 = %v, want 429", errExec) + } + if calls[authBID] != 0 { + t.Fatalf("authB calls after Execute 429 = %d, want 0", calls[authBID]) + } + + if _, errStream := manager.ExecuteStream(ctx, []string{provider}, req, opts); errStream == nil || statusCodeFromError(errStream) != http.StatusTooManyRequests { + t.Fatalf("ExecuteStream on cooled authA = %v, want 429", errStream) + } + if calls[authBID] != 0 { + t.Fatalf("authB calls after ExecuteStream 429 = %d, want 0", calls[authBID]) + } + + // 3. Explicit PinnedAuthMetadataKey pointing to authB on the same session must also be rejected and never call authB via credits fallback. + pinnedBOpts := cliproxyexecutor.Options{ + Headers: http.Header{"Session-Id": []string{"antigravity-never-session"}}, + Metadata: map[string]any{ + cliproxyexecutor.PinnedAuthMetadataKey: authBID, + }, + } + if _, errExec = manager.Execute(ctx, []string{provider}, req, pinnedBOpts); errExec == nil || statusCodeFromError(errExec) != http.StatusTooManyRequests { + t.Fatalf("Execute with conflicting PinnedAuthMetadataKey = %v, want 429", errExec) + } + if calls[authBID] != 0 { + t.Fatalf("authB calls after conflicting pinned Execute = %d, want 0", calls[authBID]) + } + if _, errStream := manager.ExecuteStream(ctx, []string{provider}, req, pinnedBOpts); errStream == nil || statusCodeFromError(errStream) != http.StatusTooManyRequests { + t.Fatalf("ExecuteStream with conflicting PinnedAuthMetadataKey = %v, want 429", errStream) + } + if calls[authBID] != 0 { + t.Fatalf("authB calls after conflicting pinned ExecuteStream = %d, want 0", calls[authBID]) + } +} + +func TestManagerSessionAffinityRebindOnNeverSingleAuthDisabledOrModelRemovedReturns429(t *testing.T) { + ctx := context.Background() + provider := "single-never-empty-cand" + model := "single-never-model" + authID := provider + "-only" + + manager := NewManager(nil, nil, nil) + manager.SetRetryConfig(0, 0, 0) + affinity := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{ + Fallback: &RoundRobinSelector{}, + TTL: time.Hour, + RebindOn: SessionAffinityRebindOnNever, + }) + defer affinity.Stop() + manager.SetSelector(affinity) + manager.RegisterExecutor(scriptedFailoverExecutor{provider: provider}) + + auth := &Auth{ID: authID, Provider: provider, Status: StatusActive} + if _, errRegister := manager.Register(WithSkipPersist(ctx), auth); errRegister != nil { + t.Fatalf("Register(%s): %v", auth.ID, errRegister) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + + req := cliproxyexecutor.Request{Model: model} + opts := cliproxyexecutor.Options{ + Headers: http.Header{"Session-Id": []string{"single-never-session"}}, + } + + // 1. Bind session to authID. + resp, errExec := manager.Execute(ctx, []string{provider}, req, opts) + if errExec != nil || string(resp.Payload) != authID { + t.Fatalf("cold Execute = %q (err=%v), want %q", string(resp.Payload), errExec, authID) + } + + // 2. Disable the only credential -> candidate list is empty, bound session must return 429 session_auth_unavailable (not 503). + disabled := auth.Clone() + disabled.Disabled = true + disabled.Status = StatusDisabled + if _, errUpdate := manager.Update(WithSkipPersist(ctx), disabled); errUpdate != nil { + t.Fatalf("Update(disabled): %v", errUpdate) + } + _, errExec = manager.Execute(ctx, []string{provider}, req, opts) + if errExec == nil || statusCodeFromError(errExec) != http.StatusTooManyRequests { + t.Fatalf("Execute when only bound auth is disabled = %v, want 429 session_auth_unavailable", errExec) + } + var authErr *Error + if !errors.As(errExec, &authErr) || authErr == nil || authErr.Code != "session_auth_unavailable" { + t.Fatalf("Execute disabled bound auth error = %v, want session_auth_unavailable", errExec) + } + + // An unbound session when candidates is empty must still receive auth_not_found. + unboundOpts := cliproxyexecutor.Options{ + Headers: http.Header{"Session-Id": []string{"single-never-unbound-session"}}, + } + if _, errUnbound := manager.Execute(ctx, []string{provider}, req, unboundOpts); !isAuthNotFoundError(errUnbound) { + t.Fatalf("Execute unbound session with empty candidates = %v, want auth_not_found", errUnbound) + } + + // 3. Re-enable auth, but remove model support from registry -> bound session must also return 429 session_auth_unavailable. + enabled := auth.Clone() + enabled.Disabled = false + enabled.Status = StatusActive + if _, errUpdate := manager.Update(WithSkipPersist(ctx), enabled); errUpdate != nil { + t.Fatalf("Update(enabled): %v", errUpdate) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, provider, []*registry.ModelInfo{{ID: "other-model"}}) + _, errExec = manager.Execute(ctx, []string{provider}, req, opts) + if errExec == nil || statusCodeFromError(errExec) != http.StatusTooManyRequests { + t.Fatalf("Execute when bound auth loses model support = %v, want 429 session_auth_unavailable", errExec) + } + if !errors.As(errExec, &authErr) || authErr == nil || authErr.Code != "session_auth_unavailable" { + t.Fatalf("Execute model-removed bound auth error = %v, want session_auth_unavailable", errExec) + } +} diff --git a/sdk/cliproxy/auth/siwc_refresh_cancellation_test.go b/sdk/cliproxy/auth/siwc_refresh_cancellation_test.go new file mode 100644 index 00000000000..9fa0ce60f22 --- /dev/null +++ b/sdk/cliproxy/auth/siwc_refresh_cancellation_test.go @@ -0,0 +1,57 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" +) + +func TestSIWCWakeCancellationPreservesOuterRefreshFailure(t *testing.T) { + for _, terminalOuter := range []bool{false, true} { + t.Run(fmt.Sprintf("terminalOuter=%t", terminalOuter), func(t *testing.T) { + var outerErr error + if terminalOuter { + outerErr = errors.New(`token refresh failed with status 401: {"error":{"code":"refresh_token_reused"}}`) + } + deferred := codex.WrapSIWCRefreshError(fmt.Errorf("SIWC renewal deferred until interactive macOS wake: %w", codex.ErrSIWCRefreshDeferred)) + executor := &issue6819OuterOnlyRefreshExecutor{id: "codex", refreshErr: codex.NewPartitionRefreshError(outerErr, deferred)} + manager := NewManager(nil, nil, nil) + manager.RegisterExecutor(executor) + auth := &Auth{ID: "wake-cancellation", Provider: "codex", Metadata: map[string]any{ + "access_token": "outer-access", "refresh_token": "outer-refresh", "use_siwc": true, + "expired": time.Now().Add(time.Hour).Format(time.RFC3339), + "siwc": map[string]any{ + "access_token": "siwc-access", "refresh_token": "siwc-refresh", "client_id": "oaiapp_cancellation", + "expires_at": time.Now().Add(time.Hour).Format(time.RFC3339), + }, + }} + if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil { + t.Fatal(errRegister) + } + if _, errRefresh := manager.ForceRefreshAuth(context.Background(), auth.ID); errRefresh == nil { + t.Fatal("expected deferred refresh") + } + current, ok := manager.GetByID(auth.ID) + if !ok { + t.Fatal("credential disappeared") + } + if terminalOuter { + if !current.RequiresSignIn || current.RejectedRefreshToken != "outer-refresh" { + t.Fatal("SIWC cancellation hid the terminal outer refresh rejection") + } + } else if current.RequiresSignIn || current.RefreshError != nil || current.NextRefreshAfter.IsZero() { + t.Fatal("pure SIWC cancellation did not use the cancellation rescheduler") + } + if current.RejectedSIWCRefreshToken != "" { + t.Fatal("wake deferral marked the SIWC grant as rejected") + } + if current.CodexSIWCStatus(time.Now()) != SIWCStatusValid { + t.Fatal("outer refresh rejection invalidated the working SIWC access token") + } + }) + } +} diff --git a/sdk/cliproxy/auth/siwc_renewal_window_test.go b/sdk/cliproxy/auth/siwc_renewal_window_test.go new file mode 100644 index 00000000000..3f91d8701c6 --- /dev/null +++ b/sdk/cliproxy/auth/siwc_renewal_window_test.go @@ -0,0 +1,66 @@ +package auth + +import ( + "testing" + "time" +) + +func TestSIWCRenewalUsesRealExpiryAndServerWindow(t *testing.T) { + expiry := time.Date(2026, 10, 29, 13, 8, 9, 0, time.UTC) + for _, tc := range []struct { + name string + earliest any + wantDue string + }{ + {"real expiry without double margin", nil, "2026-10-29T13:03:09Z"}, + {"early server window", "2026-10-29T12:58:09Z", "2026-10-29T13:03:09Z"}, + {"server RFC3339 window", "2026-10-29T13:07:09Z", "2026-10-29T13:07:09Z"}, + {"server Unix window", int64(1793279229), "2026-10-29T13:07:09Z"}, + {"server JSON Unix window", float64(1793279229), "2026-10-29T13:07:09Z"}, + {"malformed optional window", "invalid", "2026-10-29T13:03:09Z"}, + } { + t.Run(tc.name, func(t *testing.T) { + siwc := map[string]any{ + "access_token": "access", "refresh_token": "refresh", "client_id": "oaiapp_test", + "last_refresh": "2026-10-29T12:08:09Z", "expired": "2026-10-29T13:05:09Z", + "expires_at": "2026-10-29T13:08:09Z", "earliest_refresh_at": tc.earliest, + } + auth := &Auth{Provider: "codex", Metadata: map[string]any{"siwc": siwc}} + wantDue, errParse := time.Parse(time.RFC3339, tc.wantDue) + if errParse != nil { + t.Fatal(errParse) + } + due, has, need := CodexSIWCNeedsRefresh(auth, expiry.Add(-8*time.Minute)) + if !has || need || !due.Equal(wantDue) { + t.Fatalf("due = %v, has = %v, need = %v; want %v, true, false", due, has, need, wantDue) + } + for _, now := range []time.Time{wantDue, expiry.Add(3 * time.Hour)} { + if _, has, need := CodexSIWCNeedsRefresh(auth, now); !has || !need { + t.Fatalf("at %v: has = %v, need = %v; want renewal", now, has, need) + } + } + }) + } +} + +func TestSIWCRenewalServerWindowWithoutUsableAccessToken(t *testing.T) { + now := time.Date(2026, 10, 29, 12, 0, 0, 0, time.UTC) + earliest := now.Add(time.Minute) + for _, accessToken := range []string{"", "rejected", "opaque-without-expiry"} { + t.Run(accessToken, func(t *testing.T) { + auth := &Auth{RejectedSIWCAccessToken: "rejected", Metadata: map[string]any{ + "siwc": map[string]any{ + "access_token": accessToken, "refresh_token": "refresh", "client_id": "oaiapp_window", + "earliest_refresh_at": "2026-10-29T12:01:00Z", + }, + }} + due, has, need := CodexSIWCNeedsRefresh(auth, now) + if !has || need || !due.Equal(earliest) { + t.Fatalf("due = %v, has = %v, need = %v; want %v, true, false", due, has, need, earliest) + } + if _, has, need := CodexSIWCNeedsRefresh(auth, earliest); !has || !need { + t.Fatal("renewal was not due at the server window") + } + }) + } +} diff --git a/sdk/cliproxy/auth/types.go b/sdk/cliproxy/auth/types.go index 1991bc605be..80dad528ade 100644 --- a/sdk/cliproxy/auth/types.go +++ b/sdk/cliproxy/auth/types.go @@ -151,7 +151,11 @@ type Auth struct { // stamped at or below it were dispatched before the cooldown existed and // must not clear it. Runtime only: zero after restart so restored // cooldowns can still be cleared by any success. - cooldownRecordedSeq uint64 `json:"-"` + cooldownRecordedSeq uint64 `json:"-"` + forceCooldownUntil time.Time `json:"-"` + credQuotaForceUntil time.Time `json:"-"` + credentialRetryAfter time.Time `json:"-"` + forceCooldownSeeded bool `json:"-"` recentRequests recentRequestRing `json:"-"` indexAssigned bool `json:"-"` @@ -355,6 +359,10 @@ type QuotaState struct { // Cooldown transitions must use applyCooldownFields so they cannot replace // this snapshot. Signals map[string]string `json:"signals,omitempty"` + // cooldownSignals retains rejected quota headers captured when the active + // cooldown was recorded so out-of-order completions cannot overwrite them. + cooldownSignals map[string]string + cooldownEvaluated bool } // Clone returns an independent copy of the quota state. @@ -366,6 +374,12 @@ func (q QuotaState) Clone() QuotaState { copyQuota.Signals[key] = value } } + if len(q.cooldownSignals) > 0 { + copyQuota.cooldownSignals = make(map[string]string, len(q.cooldownSignals)) + for key, value := range q.cooldownSignals { + copyQuota.cooldownSignals[key] = value + } + } return copyQuota } @@ -390,7 +404,9 @@ type ModelState struct { // stamped at or below it were dispatched before the cooldown existed and // must not clear it. Runtime only: zero after restart so restored // cooldowns can still be cleared by any success. - cooldownRecordedSeq uint64 `json:"-"` + cooldownRecordedSeq uint64 `json:"-"` + forceCooldownUntil time.Time `json:"-"` + forceCooldownSeeded bool `json:"-"` // credentialQuotaShadow holds this model's independent (own-failure) // cooldown layer while the outer fields present the auth-level // credential quota propagated over it, so quota restoration can drop @@ -481,12 +497,10 @@ func (a *Auth) Clone() *Auth { copyAuth := *a copyAuth.Quota = a.Quota.Clone() if a.LastError != nil { - copyErr := *a.LastError - copyAuth.LastError = ©Err + copyAuth.LastError = a.LastError.Clone() } if a.RefreshError != nil { - copyErr := *a.RefreshError - copyAuth.RefreshError = ©Err + copyAuth.RefreshError = a.RefreshError.Clone() } if a.Attributes != nil { copyAuth.Attributes = make(map[string]string, len(a.Attributes)) @@ -796,12 +810,7 @@ func (m *ModelState) Clone() *ModelState { copyState := *m copyState.Quota = m.Quota.Clone() if m.LastError != nil { - copyState.LastError = &Error{ - Code: m.LastError.Code, - Message: m.LastError.Message, - Retryable: m.LastError.Retryable, - HTTPStatus: m.LastError.HTTPStatus, - } + copyState.LastError = m.LastError.Clone() } if m.credentialQuotaShadow != nil { copyState.credentialQuotaShadow = m.credentialQuotaShadow.cloneShallow() @@ -818,12 +827,7 @@ func (m *ModelState) cloneShallow() *ModelState { copyState.Quota = m.Quota.Clone() copyState.credentialQuotaShadow = nil if m.LastError != nil { - copyState.LastError = &Error{ - Code: m.LastError.Code, - Message: m.LastError.Message, - Retryable: m.LastError.Retryable, - HTTPStatus: m.LastError.HTTPStatus, - } + copyState.LastError = m.LastError.Clone() } return ©State } @@ -1139,6 +1143,15 @@ const CodexOuterRefreshLead = 96 * time.Hour // a Sign in with ChatGPT (SIWC) token, matching pi's DEFAULT_OAUTH_MINIMUM_VALIDITY_MS (5 minutes). const CodexSIWCRefreshLead = 5 * time.Minute +// SIWCEarliestRefreshTime returns the server's lower bound for SIWC token renewal. +func (a *Auth) SIWCEarliestRefreshTime() (time.Time, bool) { + if a == nil || a.Metadata == nil { + return time.Time{}, false + } + siwc, _ := a.Metadata["siwc"].(map[string]any) + return lookupMetadataTime(siwc, "earliest_refresh_at") +} + // SIWCStatus represents the read-only validity state of a Codex SIWC credential. type SIWCStatus string @@ -1356,28 +1369,26 @@ func CodexSIWCNeedsRefresh(a *Auth, now time.Time) (dueAt time.Time, hasRefresh siwcToken, _ := siwcMap["access_token"].(string) siwcToken = strings.TrimSpace(siwcToken) - if siwcToken == "" { - return now, true, true - } - if a.isSIWCAccessTokenRejected(siwcToken) { - return now, true, true - } - expiry, hasExpiry := a.SIWCExpirationTime() - if hasExpiry && !expiry.IsZero() { - due := expiry.Add(-CodexSIWCRefreshLead) - if !due.After(now) { - return now, true, true + due := now + if siwcToken != "" && !a.isSIWCAccessTokenRejected(siwcToken) { + // The legacy expired field already includes a margin; prefer the real expiry. + expiry, hasExpiry := a.SIWCRealExpirationTime() + if !hasExpiry { + expiry, hasExpiry = a.SIWCExpirationTime() } - return due, true, false - } - if lastRefresh, okLast := lookupMetadataTime(siwcMap, "last_refresh", "lastRefresh"); okLast && !lastRefresh.IsZero() { - due := lastRefresh.Add(CodexSIWCRefreshLead) - if !due.After(now) { - return now, true, true + if hasExpiry && !expiry.IsZero() { + due = expiry.Add(-CodexSIWCRefreshLead) + } else if lastRefresh, okLast := lookupMetadataTime(siwcMap, "last_refresh", "lastRefresh"); okLast && !lastRefresh.IsZero() { + due = lastRefresh.Add(CodexSIWCRefreshLead) } - return due, true, false } - return now, true, true + if earliest, okEarliest := a.SIWCEarliestRefreshTime(); okEarliest && earliest.After(due) { + due = earliest + } + if !due.After(now) { + return now, true, true + } + return due, true, false } // OuterAccessTokenExpirationTime returns the expiration time of the outer access_token, diff --git a/sdk/cliproxy/builder.go b/sdk/cliproxy/builder.go index 75e587c16fe..5238835fb1a 100644 --- a/sdk/cliproxy/builder.go +++ b/sdk/cliproxy/builder.go @@ -13,6 +13,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher" sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" @@ -52,6 +53,11 @@ type Builder struct { // cooldownStateStore overrides runtime cooldown persistence. cooldownStateStore coreauth.CooldownStateStore + // pluginInterceptorHost optionally overrides the PluginInterceptorHost + // installed on request handlers. The internal pluginHost still owns management + // routes and plugin executor wiring. + pluginInterceptorHost handlers.PluginInterceptorHost + // pluginHost owns dynamic plugin lifecycle and adapters. pluginHost *pluginhost.Host @@ -75,6 +81,13 @@ type Hooks struct { // modifications or additional setup. OnBeforeStart func(*config.Config) + // OnConfigApplied is called once at the end of every successful runtime + // config apply, after executor re-registration and model sync. Embedders can + // use it to reinstall caller-owned state (executor wrappers, custom selector + // adjustments, interceptor context) that config apply would otherwise reset. + // The hook runs inside the service config runtime mutex; it must not block. + OnConfigApplied func(*Service, *config.Config) + // OnAfterStart is called after the service has started successfully, // providing access to the service instance for additional operations. OnAfterStart func(*Service) @@ -161,6 +174,16 @@ func (b *Builder) WithCooldownStateStore(store coreauth.CooldownStateStore) *Bui return b } +// WithPluginInterceptorHost sets a caller-provided plugin interceptor host for +// request handling. The server wraps it so plugin model routing, lifecycle +// callbacks, and websocket observers keep delegating to the internal plugin +// host; management routes and plugin executors are unaffected. When unset the +// internal plugin host remains the request interceptor host as before. +func (b *Builder) WithPluginInterceptorHost(host handlers.PluginInterceptorHost) *Builder { + b.pluginInterceptorHost = host + return b +} + // WithPluginHost overrides the dynamic plugin host used by the service. func (b *Builder) WithPluginHost(host *pluginhost.Host) *Builder { b.pluginHost = host @@ -280,26 +303,30 @@ func (b *Builder) Build() (*Service, error) { } service := &Service{ - cfg: b.cfg.CloneForRuntime(), - configPath: b.configPath, - tokenProvider: tokenProvider, - apiKeyProvider: apiKeyProvider, - watcherFactory: watcherFactory, - hooks: b.hooks, - authManager: authManager, - accessManager: accessManager, - coreManager: coreManager, - cooldownStateStore: cooldownStateStore, - pluginHost: pluginHost, - discoveryManager: newDiscoveryAdvertiserManager(), - appliedRoutingState: appliedRoutingState, - serverOptions: append([]api.ServerOption(nil), b.serverOptions...), + pluginInterceptorHost: b.pluginInterceptorHost, + cfg: b.cfg.CloneForRuntime(), + configPath: b.configPath, + tokenProvider: tokenProvider, + apiKeyProvider: apiKeyProvider, + watcherFactory: watcherFactory, + hooks: b.hooks, + authManager: authManager, + accessManager: accessManager, + coreManager: coreManager, + cooldownStateStore: cooldownStateStore, + pluginHost: pluginHost, + discoveryManager: newDiscoveryAdvertiserManager(), + appliedRoutingState: appliedRoutingState, + serverOptions: append([]api.ServerOption(nil), b.serverOptions...), } service.proxyPoolPublisher = helps.RegisterProxyPoolPublisher() helps.AdvanceProxyPoolGeneration(service.proxyPoolPublisher, service.cfg) if b.postAuthHook != nil { service.serverOptions = append(service.serverOptions, api.WithPostAuthHook(b.postAuthHook)) } + if b.pluginInterceptorHost != nil { + service.serverOptions = append(service.serverOptions, api.WithPluginInterceptorHost(b.pluginInterceptorHost)) + } service.serverOptions = append(service.serverOptions, api.WithPostAuthPersistHook(service.runtimeAuthSyncHook()), api.WithPluginHost(pluginHost), diff --git a/sdk/cliproxy/executor/context.go b/sdk/cliproxy/executor/context.go index 30cbebf544f..eca0abf837b 100644 --- a/sdk/cliproxy/executor/context.go +++ b/sdk/cliproxy/executor/context.go @@ -8,11 +8,16 @@ import ( type downstreamWebsocketContextKey struct{} type requireUpstreamWebsocketContextKey struct{} type upstreamAttemptTrackerContextKey struct{} +type localWebsocketTurnTrackerContextKey struct{} type upstreamAttemptTracker struct { attempted atomic.Bool } +type localWebsocketTurnTracker struct { + executed atomic.Bool +} + // WithDownstreamWebsocket marks the current request as coming from a downstream websocket connection. func WithDownstreamWebsocket(ctx context.Context) context.Context { if ctx == nil { @@ -77,3 +82,48 @@ func UpstreamAttempted(ctx context.Context) bool { tracker, ok := ctx.Value(upstreamAttemptTrackerContextKey{}).(*upstreamAttemptTracker) return ok && tracker != nil && tracker.attempted.Load() } + +// WithLocalWebsocketTurnTracker installs a tracker that records when a downstream +// websocket turn was fulfilled locally over HTTP rather than establishing or +// owning an upstream websocket response. +func WithLocalWebsocketTurnTracker(ctx context.Context) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, localWebsocketTurnTrackerContextKey{}, &localWebsocketTurnTracker{}) +} + +// MarkLocalWebsocketTurn records that the current downstream websocket turn was +// answered locally without creating an upstream websocket response. +func MarkLocalWebsocketTurn(ctx context.Context) { + if ctx == nil { + return + } + tracker, ok := ctx.Value(localWebsocketTurnTrackerContextKey{}).(*localWebsocketTurnTracker) + if !ok || tracker == nil { + return + } + tracker.executed.Store(true) +} + +// ResetLocalWebsocketTurn clears the local websocket turn marker before a new auth attempt. +func ResetLocalWebsocketTurn(ctx context.Context) { + if ctx == nil { + return + } + tracker, ok := ctx.Value(localWebsocketTurnTrackerContextKey{}).(*localWebsocketTurnTracker) + if !ok || tracker == nil { + return + } + tracker.executed.Store(false) +} + +// LocalWebsocketTurnExecuted reports whether the current downstream websocket turn +// was fulfilled locally rather than on an upstream websocket. +func LocalWebsocketTurnExecuted(ctx context.Context) bool { + if ctx == nil { + return false + } + tracker, ok := ctx.Value(localWebsocketTurnTrackerContextKey{}).(*localWebsocketTurnTracker) + return ok && tracker != nil && tracker.executed.Load() +} diff --git a/sdk/cliproxy/model_registration_issue7512_test.go b/sdk/cliproxy/model_registration_issue7512_test.go new file mode 100644 index 00000000000..a472eaf0556 --- /dev/null +++ b/sdk/cliproxy/model_registration_issue7512_test.go @@ -0,0 +1,182 @@ +package cliproxy + +import ( + "context" + "strings" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" +) + +type issue7512Plugin struct { + provider string + models []pluginapi.ModelInfo +} + +func (p issue7512Plugin) Identifier() string { return p.provider } + +func (p issue7512Plugin) ParseAuth(context.Context, pluginapi.AuthParseRequest) (pluginapi.AuthParseResponse, error) { + return pluginapi.AuthParseResponse{}, nil +} + +func (p issue7512Plugin) StartLogin(context.Context, pluginapi.AuthLoginStartRequest) (pluginapi.AuthLoginStartResponse, error) { + return pluginapi.AuthLoginStartResponse{}, nil +} + +func (p issue7512Plugin) PollLogin(context.Context, pluginapi.AuthLoginPollRequest) (pluginapi.AuthLoginPollResponse, error) { + return pluginapi.AuthLoginPollResponse{}, nil +} + +func (p issue7512Plugin) RefreshAuth(context.Context, pluginapi.AuthRefreshRequest) (pluginapi.AuthRefreshResponse, error) { + return pluginapi.AuthRefreshResponse{}, nil +} + +func (p issue7512Plugin) StaticModels(context.Context, pluginapi.StaticModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{Provider: p.provider, Models: p.models}, nil +} + +func (p issue7512Plugin) ModelsForAuth(context.Context, pluginapi.AuthModelRequest) (pluginapi.ModelResponse, error) { + return pluginapi.ModelResponse{Provider: p.provider, Models: p.models}, nil +} + +func (p issue7512Plugin) Execute(context.Context, pluginapi.ExecutorRequest) (pluginapi.ExecutorResponse, error) { + return pluginapi.ExecutorResponse{}, nil +} + +func (p issue7512Plugin) ExecuteStream(context.Context, pluginapi.ExecutorRequest) (pluginapi.ExecutorStreamResponse, error) { + return pluginapi.ExecutorStreamResponse{}, nil +} + +func (p issue7512Plugin) CountTokens(context.Context, pluginapi.ExecutorRequest) (pluginapi.ExecutorResponse, error) { + return pluginapi.ExecutorResponse{}, nil +} + +func (p issue7512Plugin) HttpRequest(context.Context, pluginapi.ExecutorHTTPRequest) (pluginapi.ExecutorHTTPResponse, error) { + return pluginapi.ExecutorHTTPResponse{}, nil +} + +func TestIssue7512_AuthPluginEnforcesExclusionsAliasesDisabledAndKeepsCatalog(t *testing.T) { + for _, tc := range []struct { + name string + scope pluginapi.ExecutorModelScope + }{ + {name: "unset scope with auth provider", scope: ""}, + {name: "explicit oauth scope", scope: pluginapi.ExecutorModelScopeOAuth}, + {name: "explicit both scope with auth provider", scope: pluginapi.ExecutorModelScopeBoth}, + } { + t.Run(tc.name, func(t *testing.T) { + provider := "demo-issue7512-" + strings.ReplaceAll(tc.name, " ", "-") + pluginID := provider + "-plugin" + reg := registry.GetGlobalRegistry() + staticClientID := "plugin:" + pluginID + ":" + provider + ":executor" + reg.UnregisterClient(staticClientID) + + plugin := issue7512Plugin{ + provider: provider, + models: []pluginapi.ModelInfo{ + {ID: "demo-a"}, + {ID: "demo-blocked"}, + {ID: "demo-per-auth-blocked"}, + }, + } + + host := pluginhost.New() + host.RegisterPluginForTest(pluginID, pluginapi.Plugin{ + Capabilities: pluginapi.Capabilities{ + AuthProvider: plugin, + ModelProvider: plugin, + Executor: plugin, + ExecutorModelScope: tc.scope, + }, + }) + + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + cfg := &config.Config{ + OAuthExcludedModels: map[string][]string{ + provider: {"demo-blocked"}, + }, + OAuthModelAlias: map[string][]config.OAuthModelAlias{ + provider: {{Name: "demo-a", Alias: "demo-a-high", Fork: false}}, + }, + } + service := &Service{cfg: cfg, coreManager: manager, pluginHost: host} + + host.RegisterModels(t.Context(), reg) + host.RegisterExecutors(manager, reg) + t.Cleanup(func() { + reg.UnregisterClient(staticClientID) + }) + + // Phase 1: zero credentials must publish no models in ModelRegistry, + // while still keeping static catalog definitions available for #6736. + if available := reg.GetAvailableModelsByProvider(provider); len(available) != 0 { + t.Fatalf("with zero credentials, GetAvailableModelsByProvider(%q) = %#v, want empty", provider, available) + } + if catalog := host.ModelsForProvider(provider); len(catalog) != 3 { + t.Fatalf("with zero credentials, ModelsForProvider(%q) = %#v, want 3 catalog models", provider, catalog) + } + + // Phase 2: an active credential must enforce oauth-excluded-models, + // per-credential excluded_models, and oauth-model-alias (fork=false). + authID := provider + "-auth-1" + auth := &coreauth.Auth{ + ID: authID, + Provider: provider, + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "auth_kind": "oauth", + "excluded_models": "demo-blocked,demo-per-auth-blocked", + }, + } + registered, errRegister := manager.Register(t.Context(), auth) + if errRegister != nil { + t.Fatal(errRegister) + } + t.Cleanup(func() { + reg.UnregisterClient(authID) + }) + + service.registerModelsForAuth(t.Context(), registered) + + availableIDs := make(map[string]bool) + for _, item := range reg.GetAvailableModelsByProvider(provider) { + if item != nil && item.ID != "" { + availableIDs[item.ID] = true + } + } + if availableIDs["demo-blocked"] { + t.Fatal("oauth-excluded model demo-blocked leaked into ModelRegistry") + } + if availableIDs["demo-per-auth-blocked"] { + t.Fatal("per-credential excluded model demo-per-auth-blocked leaked into ModelRegistry") + } + if availableIDs["demo-a"] { + t.Fatal("unaliased model demo-a leaked despite fork=false oauth-model-alias") + } + if !availableIDs["demo-a-high"] { + t.Fatalf("aliased model demo-a-high missing from ModelRegistry: %#v", availableIDs) + } + + // Phase 3: disabling the credential must remove all published models for the provider. + disabledAuth := registered.Clone() + disabledAuth.Disabled = true + disabledAuth.Status = coreauth.StatusDisabled + updated, errUpdate := manager.Update(t.Context(), disabledAuth) + if errUpdate != nil { + t.Fatal(errUpdate) + } + service.registerModelsForAuth(t.Context(), updated) + + if available := reg.GetAvailableModelsByProvider(provider); len(available) != 0 { + t.Fatalf("with disabled credential, GetAvailableModelsByProvider(%q) = %#v, want empty", provider, available) + } + if catalog := host.ModelsForProvider(provider); len(catalog) != 3 { + t.Fatalf("with disabled credential, ModelsForProvider(%q) = %#v, want 3 catalog models", provider, catalog) + } + }) + } +} diff --git a/sdk/cliproxy/service.go b/sdk/cliproxy/service.go index b91becd439a..44891979e0c 100644 --- a/sdk/cliproxy/service.go +++ b/sdk/cliproxy/service.go @@ -16,6 +16,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher" "github.com/router-for-me/CLIProxyAPI/v8/internal/wsrelay" sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executionregistry" @@ -113,6 +114,10 @@ type Service struct { // pluginHost owns dynamic plugin lifecycle and runtime capability adapters. pluginHost *pluginhost.Host + // pluginInterceptorHost optionally overrides the PluginInterceptorHost + // installed on request handlers. Nil means the internal pluginHost is used. + pluginInterceptorHost handlers.PluginInterceptorHost + // shutdownOnce ensures shutdown is called only once. shutdownOnce sync.Once diff --git a/sdk/cliproxy/service_claude_thread_test.go b/sdk/cliproxy/service_claude_thread_test.go new file mode 100644 index 00000000000..0d64ed04224 --- /dev/null +++ b/sdk/cliproxy/service_claude_thread_test.go @@ -0,0 +1,62 @@ +package cliproxy + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func TestClaudeThreadSurvivesExecutorRebinding(t *testing.T) { + for _, force := range []bool{false, true} { + t.Run(map[bool]string{false: "credential update", true: "config reload"}[force], func(t *testing.T) { + service := &Service{cfg: &config.Config{}, coreManager: coreauth.NewManager(nil, nil, nil)} + auth := &coreauth.Auth{ID: t.Name(), Provider: "claude", Attributes: map[string]string{"api_key": "key-service-thread"}} + service.registerExecutorForAuth(auth, false) + first, found := service.coreManager.Executor("claude") + if !found { + t.Fatal("Claude executor was not registered") + } + calls := 0 + transport := claudeThreadServiceRoundTripper(func(req *http.Request) (*http.Response, error) { + calls++ + if got := strings.Join(helps.HeaderValuesCaseInsensitive(req.Header, "Anthropic-Beta"), ","); got != "message-threads-2026-08-12,effort-2025-11-24" { + t.Errorf("wire beta = %q, want original Thread profile", got) + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"msg_service_thread","type":"message","role":"assistant","model":"claude-opus-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)), Request: req}, nil + }) + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, Headers: http.Header{"Anthropic-Beta": []string{"message-threads-2026-08-12,effort-2025-11-24"}}} + request := cliproxyexecutor.Request{Model: "claude-opus-5", Payload: []byte(`{"model":"claude-opus-5","thread":{"type":"create"},"messages":[{"role":"user","content":"first"}]}`)} + if _, errExecute := first.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatal(errExecute) + } + service.cfg = &config.Config{} + service.registerExecutorForAuth(&coreauth.Auth{ID: "unrelated-credential", Provider: "claude"}, force) + second, foundSecond := service.coreManager.Executor("claude") + if !foundSecond || second == first { + t.Fatal("test requires a freshly rebound executor") + } + request.Payload = []byte(`{"model":"claude-opus-5","thread":{"type":"continue","previous_message_id":"msg_service_thread"},"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"second"}]}`) + if _, errExecute := second.Execute(ctx, auth, request, opts); errExecute != nil { + t.Fatalf("active Thread lost after unrelated executor rebinding: %v", errExecute) + } + if calls != 2 { + t.Fatalf("upstream requests = %d, want 2", calls) + } + }) + } +} + +type claudeThreadServiceRoundTripper func(*http.Request) (*http.Response, error) + +func (f claudeThreadServiceRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} diff --git a/sdk/cliproxy/service_config.go b/sdk/cliproxy/service_config.go index cbda28e2716..880f2603579 100644 --- a/sdk/cliproxy/service_config.go +++ b/sdk/cliproxy/service_config.go @@ -92,17 +92,30 @@ func normalizedRoutingRuntimeState(cfg *config.Config) routingRuntimeState { if state.sessionAffinity && cfg.Routing.SessionAffinitySubagents != nil { state.sessionAffinitySubagents = *cfg.Routing.SessionAffinitySubagents } - if state.sessionAffinity && strings.EqualFold(strings.TrimSpace(cfg.Routing.SessionAffinityRebindOn), coreauth.SessionAffinityRebindOnQuota) { - state.sessionAffinityRebindOn = coreauth.SessionAffinityRebindOnQuota + if state.sessionAffinity { + switch strings.ToLower(strings.TrimSpace(cfg.Routing.SessionAffinityRebindOn)) { + case coreauth.SessionAffinityRebindOnQuota: + state.sessionAffinityRebindOn = coreauth.SessionAffinityRebindOnQuota + case coreauth.SessionAffinityRebindOnNever: + state.sessionAffinityRebindOn = coreauth.SessionAffinityRebindOnNever + } } return state } func newRoutingSelector(state routingRuntimeState) coreauth.Selector { + return newRoutingSelectorWithExisting(state, nil) +} + +func newRoutingSelectorWithExisting(state routingRuntimeState, existing coreauth.Selector) coreauth.Selector { var selector coreauth.Selector switch state.strategy { case "weighted-round-robin": - selector = &coreauth.WeightedRoundRobinSelector{} + if existingWeighted := coreauth.UnwrapWeightedRoundRobinSelector(existing); existingWeighted != nil { + selector = existingWeighted + } else { + selector = &coreauth.WeightedRoundRobinSelector{} + } case "fill-first": selector = &coreauth.FillFirstSelector{} default: @@ -250,6 +263,9 @@ func (s *Service) applyConfigRuntime(ctx context.Context, commit configCommit, s return false } s.syncPluginModelRuntime(registrationCtx) + if ctx.Err() == nil && s.hooks.OnConfigApplied != nil { + s.hooks.OnConfigApplied(s, cfg) + } return ctx.Err() == nil } @@ -265,7 +281,7 @@ func (s *Service) applyManagerConfig(ctx context.Context, commit configCommit) b } routingState := normalizedRoutingRuntimeState(commit.cfg) if s.appliedRoutingState == nil || *s.appliedRoutingState != routingState { - s.coreManager.SetSelector(newRoutingSelector(routingState)) + s.coreManager.SetSelector(newRoutingSelectorWithExisting(routingState, s.coreManager.Selector())) s.appliedRoutingState = &routingState } s.applyRetryConfig(commit.cfg) diff --git a/sdk/cliproxy/service_executionregistry_test.go b/sdk/cliproxy/service_executionregistry_test.go index fef6d3bada2..643099288df 100644 --- a/sdk/cliproxy/service_executionregistry_test.go +++ b/sdk/cliproxy/service_executionregistry_test.go @@ -2972,6 +2972,46 @@ func TestServiceApplyConfigRuntimeSessionAffinityRebindOnChangeRecreatesSelector if changedSelector == initialSelector { t.Fatal("changing SessionAffinityRebindOn should recreate selector") } + + neverCfg := service.commitConfigUpdate(&config.Config{Routing: internalconfig.RoutingConfig{ + Strategy: "round-robin", + SessionAffinity: true, + SessionAffinityTTL: "1h", + SessionAffinityRebindOn: "never", + }}) + if !service.applyConfigRuntime(context.Background(), neverCfg, false) { + t.Fatal("never config runtime apply failed") + } + neverSelector := manager.Selector() + if neverSelector == changedSelector { + t.Fatal("changing SessionAffinityRebindOn to never should recreate selector") + } + + sameNeverCfg := service.commitConfigUpdate(&config.Config{Routing: internalconfig.RoutingConfig{ + Strategy: "round-robin", + SessionAffinity: true, + SessionAffinityTTL: "1h", + SessionAffinityRebindOn: " NEVER ", + }}) + if !service.applyConfigRuntime(context.Background(), sameNeverCfg, false) { + t.Fatal("same never config runtime apply failed") + } + if manager.Selector() != neverSelector { + t.Fatal("equivalent never SessionAffinityRebindOn should preserve selector") + } + + backToAnyCfg := service.commitConfigUpdate(&config.Config{Routing: internalconfig.RoutingConfig{ + Strategy: "round-robin", + SessionAffinity: true, + SessionAffinityTTL: "1h", + SessionAffinityRebindOn: "any", + }}) + if !service.applyConfigRuntime(context.Background(), backToAnyCfg, false) { + t.Fatal("back to any config runtime apply failed") + } + if manager.Selector() == neverSelector { + t.Fatal("changing SessionAffinityRebindOn from never to any should recreate selector") + } } func TestServiceSerializesHomeAndWatcherConfigRuntimeApply(t *testing.T) { diff --git a/sdk/cliproxy/service_executors.go b/sdk/cliproxy/service_executors.go index c83c246c23d..0ad196e297b 100644 --- a/sdk/cliproxy/service_executors.go +++ b/sdk/cliproxy/service_executors.go @@ -309,6 +309,12 @@ func (s *Service) registerExecutorForAuth(a *coreauth.Auth, forceReplace bool) { case "antigravity": s.coreManager.RegisterExecutor(executor.NewAntigravityExecutor(cfg)) case "claude": + if existing, found := s.coreManager.Executor("claude"); found { + if previous, ok := existing.(*executor.ClaudeExecutor); ok { + s.coreManager.RegisterExecutor(previous.WithConfig(cfg)) + return + } + } s.coreManager.RegisterExecutor(executor.NewClaudeExecutor(cfg)) case "kimi", "kimi-ai", "kimi.ai", "kimi.com": s.coreManager.RegisterExecutor(executor.NewKimiExecutor(cfg)) @@ -502,7 +508,7 @@ func (s *Service) pluginModelsForProvider(providerKey string) []*ModelInfo { if s == nil || s.pluginHost == nil { return nil } - return s.pluginHost.ModelsForProvider(providerKey) + return s.pluginHost.StaticAppendModelsForProvider(providerKey) } // appendPluginModels appends the provider's plugin static models that are not excluded. diff --git a/sdk/cliproxy/service_issue7499_test.go b/sdk/cliproxy/service_issue7499_test.go new file mode 100644 index 00000000000..c8f76c74a25 --- /dev/null +++ b/sdk/cliproxy/service_issue7499_test.go @@ -0,0 +1,287 @@ +package cliproxy + +import ( + "context" + "errors" + "net/http" + "testing" + + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi" +) + +// recordingInterceptorHost7499 implements the public handlers.PluginInterceptorHost +// surface with the minimum behavior needed by issue 7499 regression tests. +type recordingInterceptorHost7499 struct{} + +func (h *recordingInterceptorHost7499) InterceptRequestBeforeAuth(context.Context, pluginapi.RequestInterceptRequest) pluginapi.RequestInterceptResponse { + return pluginapi.RequestInterceptResponse{} +} + +func (h *recordingInterceptorHost7499) InterceptRequestAfterAuth(context.Context, pluginapi.RequestInterceptRequest) pluginapi.RequestInterceptResponse { + return pluginapi.RequestInterceptResponse{} +} + +func (h *recordingInterceptorHost7499) InterceptResponse(context.Context, pluginapi.ResponseInterceptRequest) pluginapi.ResponseInterceptResponse { + return pluginapi.ResponseInterceptResponse{} +} + +func (h *recordingInterceptorHost7499) InterceptStreamChunk(context.Context, pluginapi.StreamChunkInterceptRequest) pluginapi.StreamChunkInterceptResponse { + return pluginapi.StreamChunkInterceptResponse{} +} + +var _ handlers.PluginInterceptorHost = (*recordingInterceptorHost7499)(nil) + +// stubProviderExecutor7499 is a minimal ProviderExecutor used to prove config +// apply preserves a caller-installed wrapper for a built-in provider. +type stubProviderExecutor7499 struct { + provider string +} + +func (e *stubProviderExecutor7499) Identifier() string { return e.provider } + +func (e *stubProviderExecutor7499) Execute(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, errors.New("stub executor") +} + +func (e *stubProviderExecutor7499) ExecuteStream(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return nil, errors.New("stub executor") +} + +func (e *stubProviderExecutor7499) Refresh(context.Context, *coreauth.Auth) (*coreauth.Auth, error) { + return nil, errors.New("stub executor") +} + +func (e *stubProviderExecutor7499) CountTokens(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, errors.New("stub executor") +} + +func (e *stubProviderExecutor7499) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, errors.New("stub executor") +} + +var _ coreauth.ProviderExecutor = (*stubProviderExecutor7499)(nil) + +// newIssue7499Service builds a Service whose runtime application is fully +// stubbed so config apply stays in memory without touching the network. +// seedAuths are pre-registered on the core manager so applyConfigRuntime's +// force-replace executor pass sees them the same way a real deployment would. +func newIssue7499Service(t *testing.T, cfg *config.Config, hooks Hooks, seedAuths ...*coreauth.Auth) *Service { + t.Helper() + manager := coreauth.NewManager(nil, nil, nil) + for _, auth := range seedAuths { + if auth != nil { + manager.Register(context.Background(), auth) + } + } + service := &Service{ + cfg: cfg, + coreManager: manager, + hooks: hooks, + updateServerClientsContextFn: func(context.Context, *config.Config) bool { + return true + }, + applyPprofConfigContextFn: func(context.Context, *config.Config) bool { + return true + }, + } + return service +} + +// claudeWrapperExecutor7499 wraps a ProviderExecutor and exposes the current +// inner executor so tests can assert the hook re-wraps the rebuilt built-in +// executor rather than keeping a stale wrapper. +type claudeWrapperExecutor7499 struct { + inner coreauth.ProviderExecutor +} + +func (w *claudeWrapperExecutor7499) Identifier() string { return "claude" } + +func (w *claudeWrapperExecutor7499) Execute(ctx context.Context, auth *coreauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return w.inner.Execute(ctx, auth, req, opts) +} + +func (w *claudeWrapperExecutor7499) ExecuteStream(ctx context.Context, auth *coreauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return w.inner.ExecuteStream(ctx, auth, req, opts) +} + +func (w *claudeWrapperExecutor7499) Refresh(ctx context.Context, auth *coreauth.Auth) (*coreauth.Auth, error) { + return w.inner.Refresh(ctx, auth) +} + +func (w *claudeWrapperExecutor7499) CountTokens(ctx context.Context, auth *coreauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return w.inner.CountTokens(ctx, auth, req, opts) +} + +func (w *claudeWrapperExecutor7499) HttpRequest(ctx context.Context, auth *coreauth.Auth, req *http.Request) (*http.Response, error) { + return w.inner.HttpRequest(ctx, auth, req) +} + +var _ coreauth.ProviderExecutor = (*claudeWrapperExecutor7499)(nil) + +// TestIssue7499OnConfigAppliedKeepsCustomExecutorWrapper installs a caller-owned +// wrapper for the built-in "claude" provider via OnConfigApplied and requires a +// subsequent watcher-style config apply to keep the wrapper in place instead of +// restoring the stock built-in executor. +func TestIssue7499OnConfigAppliedKeepsCustomExecutorWrapper(t *testing.T) { + installed := &stubProviderExecutor7499{provider: "claude"} + var appliedCfg *config.Config + hookCalls := 0 + service := newIssue7499Service(t, &config.Config{}, Hooks{ + OnConfigApplied: func(s *Service, cfg *config.Config) { + hookCalls++ + appliedCfg = cfg + s.coreManager.RegisterExecutor(installed) + }, + }) + + newCfg := &config.Config{RequestRetry: 3} + service.applyWatcherConfigUpdate(newCfg) + + if hookCalls != 1 { + t.Fatalf("OnConfigApplied calls = %d, want 1", hookCalls) + } + if appliedCfg != service.cfg { + t.Fatalf("OnConfigApplied config = %#v, want applied service config %#v", appliedCfg, service.cfg) + } + got, ok := service.coreManager.Executor("claude") + if !ok { + t.Fatal("claude executor missing after config apply") + } + if got != installed { + t.Fatalf("claude executor = %#v (%T), want caller-installed wrapper %#v", got, got, installed) + } +} + +// TestIssue7499OnConfigAppliedRewrapsRebuiltClaudeExecutor registers a real +// built-in Claude executor, applies two successive configs, and asserts the +// hook reinstalls a wrapper around the *rebuilt* executor each time so the +// embedder never retains a stale configuration snapshot. +func TestIssue7499OnConfigAppliedRewrapsRebuiltClaudeExecutor(t *testing.T) { + service := newIssue7499Service(t, &config.Config{}, Hooks{}, &coreauth.Auth{ID: "claude-1", Provider: "claude"}) + // Seed the built-in claude executor the same way the service does. + service.coreManager.RegisterExecutor(executor.NewClaudeExecutor(service.cfg)) + + var wrappers []*claudeWrapperExecutor7499 + service.hooks = Hooks{ + OnConfigApplied: func(s *Service, cfg *config.Config) { + current, ok := s.coreManager.Executor("claude") + if !ok { + return + } + // The force-replace registration may expose the previous wrapper + // instead of the rebuilt stock executor; unwrap it so the embedder + // always wraps the current built-in instance. + for { + if w, isWrapper := current.(*claudeWrapperExecutor7499); isWrapper { + current = w.inner + continue + } + break + } + wrapper := &claudeWrapperExecutor7499{inner: current} + wrappers = append(wrappers, wrapper) + s.coreManager.RegisterExecutor(wrapper) + }, + } + + service.applyWatcherConfigUpdate(&config.Config{RequestRetry: 1}) + firstInner := wrappers[0].inner + if _, isClaude := firstInner.(*executor.ClaudeExecutor); !isClaude { + t.Fatalf("first inner executor = %T, want *executor.ClaudeExecutor", firstInner) + } + + service.applyWatcherConfigUpdate(&config.Config{RequestRetry: 7}) + if len(wrappers) != 2 { + t.Fatalf("wrapper installs = %d, want 2 across two applies", len(wrappers)) + } + secondInner := wrappers[1].inner + // The second apply must wrap a rebuilt built-in executor, not the previous + // wrapper (which would hide the stock executor) and not the same instance + // (which would carry stale configuration). + if _, isClaude := secondInner.(*executor.ClaudeExecutor); !isClaude { + t.Fatalf("second inner executor = %T, want *executor.ClaudeExecutor", secondInner) + } + if firstInner == secondInner { + t.Fatal("hook re-wrapped the same executor instance; config rebuild was not applied") + } + if _, isWrapper := secondInner.(*claudeWrapperExecutor7499); isWrapper { + t.Fatal("hook wrapped the previous wrapper instead of the rebuilt built-in executor") + } + + got, ok := service.coreManager.Executor("claude") + if !ok || got != wrappers[1] { + t.Fatalf("claude executor = %#v, want second wrapper %#v", got, wrappers[1]) + } +} + +// TestIssue7499OnConfigAppliedFiresOnEverySuccessfulApply ensures the hook is +// invoked once per successful config commit, matching the existing lifecycle +// contract that runtime state may be rebuilt on every apply. +func TestIssue7499OnConfigAppliedFiresOnEverySuccessfulApply(t *testing.T) { + hookCalls := 0 + service := newIssue7499Service(t, &config.Config{}, Hooks{ + OnConfigApplied: func(*Service, *config.Config) { + hookCalls++ + }, + }) + + service.applyWatcherConfigUpdate(&config.Config{RequestRetry: 1}) + service.applyWatcherConfigUpdate(&config.Config{RequestRetry: 2}) + + if hookCalls != 2 { + t.Fatalf("OnConfigApplied calls = %d, want 2 across two successful applies", hookCalls) + } +} + +// TestIssue7499OnConfigAppliedNotCalledOnRejectedUpdate ensures the hook only +// fires after a successful runtime apply, not for rejected or aborted commits. +func TestIssue7499OnConfigAppliedNotCalledOnRejectedUpdate(t *testing.T) { + hookCalls := 0 + service := newIssue7499Service(t, &config.Config{}, Hooks{ + OnConfigApplied: func(*Service, *config.Config) { + hookCalls++ + }, + }) + + invalidWeight := internalconfig.MaxCredentialWeight + 1 + service.applyConfigUpdate(&internalconfig.Config{ + VertexCompatAPIKey: []internalconfig.VertexCompatKey{{ + APIKey: "vertex-key", + Weight: &invalidWeight, + }}, + }) + + if hookCalls != 0 { + t.Fatalf("OnConfigApplied calls = %d, want 0 for rejected config", hookCalls) + } +} + +// TestIssue7499WithPluginInterceptorHost verifies the builder accepts any +// handlers.PluginInterceptorHost implementation and records it so the API +// server forwards the embedder host instead of forcing the internal plugin host +// onto handlers across startup and reload. +func TestIssue7499WithPluginInterceptorHost(t *testing.T) { + tmpDir := t.TempDir() + host := &recordingInterceptorHost7499{} + + service, errBuild := NewBuilder(). + WithConfig(&config.Config{AuthDir: tmpDir}). + WithConfigPath(tmpDir + "/config.yaml"). + WithPluginInterceptorHost(host). + Build() + if errBuild != nil { + t.Fatalf("Build() error = %v", errBuild) + } + if service == nil { + t.Fatal("Build() returned nil service") + } + if service.pluginInterceptorHost != host { + t.Fatalf("service plugin interceptor host = %#v, want %#v", service.pluginInterceptorHost, host) + } +} diff --git a/sdk/cliproxy/service_issue_7431_test.go b/sdk/cliproxy/service_issue_7431_test.go new file mode 100644 index 00000000000..9b396819f24 --- /dev/null +++ b/sdk/cliproxy/service_issue_7431_test.go @@ -0,0 +1,146 @@ +package cliproxy + +import ( + "context" + "fmt" + "net/http" + "testing" + + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +type noopServiceIssue7431Executor struct { + provider string +} + +func (e noopServiceIssue7431Executor) Identifier() string { return e.provider } + +func (e noopServiceIssue7431Executor) Execute(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{Payload: []byte(`{"ok":true}`)}, nil +} + +func (e noopServiceIssue7431Executor) ExecuteStream(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return nil, nil +} + +func (e noopServiceIssue7431Executor) Refresh(_ context.Context, auth *coreauth.Auth) (*coreauth.Auth, error) { + return auth, nil +} + +func (e noopServiceIssue7431Executor) CountTokens(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, nil +} + +func (e noopServiceIssue7431Executor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, nil +} + +func TestIssue7431_ServiceApplyManagerConfigPreservesWeightedSelectorAcrossAffinityReload(t *testing.T) { + ctx := coreauth.WithSkipPersist(t.Context()) + const ( + provider = "issue-7431-svc-wrr" + model = "issue-7431-svc-model" + ) + manager := coreauth.NewManager(nil, nil, nil) + manager.RegisterExecutor(noopServiceIssue7431Executor{provider: provider}) + service := &Service{coreManager: manager} + + initialCfg := &internalconfig.Config{ + Routing: internalconfig.RoutingConfig{ + Strategy: "weighted-round-robin", + SessionAffinity: false, + }, + } + if !service.applyManagerConfig(ctx, configCommit{cfg: initialCfg, sequence: 1}) { + t.Fatal("initial applyManagerConfig failed") + } + + reg := registry.GetGlobalRegistry() + var auths []*coreauth.Auth + for i := 0; i < 4; i++ { + id := fmt.Sprintf("svc-wrr-auth-%02d", i) + a := &coreauth.Auth{ID: id, Provider: provider, Status: coreauth.StatusActive} + auths = append(auths, a) + reg.RegisterClient(id, provider, []*registry.ModelInfo{{ID: model}}) + if _, errReg := manager.Register(ctx, a); errReg != nil { + t.Fatalf("register %s: %v", id, errReg) + } + manager.RefreshSchedulerEntry(id) + } + t.Cleanup(func() { + for _, a := range auths { + reg.UnregisterClient(a.ID) + } + }) + + var lastPickedID string + manager.RegisterExecutor(&funcIssue7431Executor{ + provider: provider, + onExec: func(a *coreauth.Auth) { + lastPickedID = a.ID + }, + }) + + var pickedBefore []string + for i := 0; i < 2; i++ { + if _, errExec := manager.Execute(ctx, []string{provider}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}); errExec != nil { + t.Fatalf("execute %d failed: %v", i, errExec) + } + pickedBefore = append(pickedBefore, lastPickedID) + } + if pickedBefore[0] != auths[0].ID || pickedBefore[1] != auths[1].ID { + t.Fatalf("picks before reload = %v, want [%s %s]", pickedBefore, auths[0].ID, auths[1].ID) + } + + // Reload routing config changing session-affinity while keeping strategy: weighted-round-robin. + reloadedCfg := &internalconfig.Config{ + Routing: internalconfig.RoutingConfig{ + Strategy: "weighted-round-robin", + SessionAffinity: true, + SessionAffinityTTL: "30m", + }, + } + if !service.applyManagerConfig(ctx, configCommit{cfg: reloadedCfg, sequence: 2}) { + t.Fatal("reload applyManagerConfig failed") + } + + if _, errExec := manager.Execute(ctx, []string{provider}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}); errExec != nil { + t.Fatalf("execute after reload failed: %v", errExec) + } + if lastPickedID != auths[2].ID { + t.Fatalf("pick after affinity config reload reset WRR to %q, want %q", lastPickedID, auths[2].ID) + } +} + +type funcIssue7431Executor struct { + provider string + onExec func(*coreauth.Auth) +} + +func (e funcIssue7431Executor) Identifier() string { return e.provider } + +func (e funcIssue7431Executor) Execute(_ context.Context, auth *coreauth.Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + if e.onExec != nil { + e.onExec(auth) + } + return cliproxyexecutor.Response{Payload: []byte(`{"ok":true}`)}, nil +} + +func (e funcIssue7431Executor) ExecuteStream(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return nil, nil +} + +func (e funcIssue7431Executor) Refresh(_ context.Context, auth *coreauth.Auth) (*coreauth.Auth, error) { + return auth, nil +} + +func (e funcIssue7431Executor) CountTokens(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, nil +} + +func (e funcIssue7431Executor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) { + return nil, nil +} diff --git a/sdk/cliproxy/session/claude_thread.go b/sdk/cliproxy/session/claude_thread.go new file mode 100644 index 00000000000..06278aabbe4 --- /dev/null +++ b/sdk/cliproxy/session/claude_thread.go @@ -0,0 +1,107 @@ +package session + +import ( + "context" + "errors" + "strings" + "sync" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +// ClaudeThreadStateTTL bounds recoverable Thread routing and wire-profile state. +const ClaudeThreadStateTTL = 24 * time.Hour + +const claudeThreadAuthLimit = 1024 + +type claudeThreadAuthEntry struct { + authID string + expiresAt time.Time +} + +var claudeThreadAuthCache = struct { + sync.Mutex + entries map[string]claudeThreadAuthEntry + order []string +}{entries: make(map[string]claudeThreadAuthEntry)} + +// ClaudeThreadCallerScope uses the same authenticated caller namespace at the +// execution and routing boundaries, without depending on a conversation ID. +func ClaudeThreadCallerScope(apiKey string, metadataSets ...map[string]any) string { + for _, metadata := range metadataSets { + if scope := metadataString(metadata, cliproxyexecutor.CallerScopeMetadataKey); scope != "" { + return scope + } + } + if scope := CallerScope(apiKey); scope != "" { + return scope + } + return "cpa-claude-thread-default-caller" +} + +func claudeThreadAuthKey(callerScope, messageID string) string { + return "claude:thread-auth:v1:" + kvstore.HashKeyPart(callerScope) + ":" + kvstore.HashKeyPart(messageID) +} + +func cacheClaudeThreadAuth(key, authID string) { + now := time.Now() + claudeThreadAuthCache.Lock() + defer claudeThreadAuthCache.Unlock() + entry, exists := claudeThreadAuthCache.entries[key] + if exists && now.Before(entry.expiresAt) { + return + } + if !exists { + claudeThreadAuthCache.order = append(claudeThreadAuthCache.order, key) + } + claudeThreadAuthCache.entries[key] = claudeThreadAuthEntry{authID: strings.Clone(authID), expiresAt: now.Add(ClaudeThreadStateTTL)} + if len(claudeThreadAuthCache.order) > claudeThreadAuthLimit { + delete(claudeThreadAuthCache.entries, claudeThreadAuthCache.order[0]) + claudeThreadAuthCache.order = claudeThreadAuthCache.order[1:] + } +} + +// RememberClaudeThreadAuth publishes ownership only after upstream success. +// Existing generic KV persistence keeps the binding available after a restart. +func RememberClaudeThreadAuth(callerScope, messageID, authID string) { + if callerScope == "" || messageID == "" || authID == "" { + return + } + key := claudeThreadAuthKey(callerScope, messageID) + cacheClaudeThreadAuth(key, authID) + kvstore.KVSetNXBestEffort(context.Background(), key, []byte(authID), ClaudeThreadStateTTL) +} + +// ClaudeThreadAuth returns a caller-isolated routing hint, not an authorization +// grant. The normal selector still validates credential availability and models. +func ClaudeThreadAuth(ctx context.Context, callerScope, messageID string) (string, bool, error) { + if callerScope == "" || messageID == "" { + return "", false, nil + } + key := claudeThreadAuthKey(callerScope, messageID) + claudeThreadAuthCache.Lock() + entry, found := claudeThreadAuthCache.entries[key] + claudeThreadAuthCache.Unlock() + if found && time.Now().Before(entry.expiresAt) { + return entry.authID, true, nil + } + client, kvMode, errClient := kvstore.CurrentKVClient() + if !kvMode || errClient != nil || client == nil { + return "", false, errClient + } + if ctx == nil { + ctx = context.Background() + } + raw, foundKV, errGet := client.KVGet(ctx, key) + if errGet != nil || !foundKV { + return "", false, errGet + } + authID := strings.TrimSpace(string(raw)) + if authID == "" { + return "", false, errors.New("empty Claude Thread credential binding") + } + cacheClaudeThreadAuth(key, authID) + return authID, true, nil +} diff --git a/sdk/cliproxy/session/claude_thread_test.go b/sdk/cliproxy/session/claude_thread_test.go new file mode 100644 index 00000000000..f52d9b5e137 --- /dev/null +++ b/sdk/cliproxy/session/claude_thread_test.go @@ -0,0 +1,78 @@ +package session + +import ( + "context" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" +) + +func TestClaudeThreadAuthRecoversFromKVWithCallerIsolation(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + path := filepath.Join(t.TempDir(), "kv.db") + if errConfigure := kvstore.ConfigureLocal(true, path); errConfigure != nil { + t.Fatal(errConfigure) + } + t.Cleanup(func() { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Error(errShutdown) + } + }) + scope := t.Name() + RememberClaudeThreadAuth(scope, "message-a", "credential-a") + key := claudeThreadAuthKey(scope, "message-a") + claudeThreadAuthCache.Lock() + delete(claudeThreadAuthCache.entries, key) + claudeThreadAuthCache.Unlock() + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + if errConfigure := kvstore.ConfigureLocal(true, path); errConfigure != nil { + t.Fatal(errConfigure) + } + authID, found, errLookup := ClaudeThreadAuth(context.Background(), scope, "message-a") + if errLookup != nil || !found || authID != "credential-a" { + t.Fatalf("restored owner=%q, found=%v, error=%v", authID, found, errLookup) + } + if _, foreign, errForeign := ClaudeThreadAuth(context.Background(), scope+"-other", "message-a"); errForeign != nil || foreign { + t.Fatalf("owner crossed caller scopes: found=%v, error=%v", foreign, errForeign) + } +} + +func TestClaudeThreadAuthMemoryIsBounded(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + scope := t.Name() + for i := 0; i <= claudeThreadAuthLimit; i++ { + RememberClaudeThreadAuth(scope, "message-"+strconv.Itoa(i), "credential-a") + } + if _, found, errLookup := ClaudeThreadAuth(context.Background(), scope, "message-0"); errLookup != nil || found { + t.Fatalf("oldest owner was not evicted: found=%v, error=%v", found, errLookup) + } + if authID, found, errLookup := ClaudeThreadAuth(context.Background(), scope, "message-"+strconv.Itoa(claudeThreadAuthLimit)); errLookup != nil || !found || authID != "credential-a" { + t.Fatalf("newest owner was lost: auth=%q, found=%v, error=%v", authID, found, errLookup) + } +} + +func TestClaudeThreadAuthMemoryExpiration(t *testing.T) { + if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { + t.Fatal(errShutdown) + } + scope := t.Name() + RememberClaudeThreadAuth(scope, "message-a", "credential-a") + key := claudeThreadAuthKey(scope, "message-a") + claudeThreadAuthCache.Lock() + entry := claudeThreadAuthCache.entries[key] + entry.expiresAt = time.Unix(0, 0) + claudeThreadAuthCache.entries[key] = entry + claudeThreadAuthCache.Unlock() + if _, found, errLookup := ClaudeThreadAuth(context.Background(), scope, "message-a"); errLookup != nil || found { + t.Fatalf("expired owner remained routable: found=%v, error=%v", found, errLookup) + } +} diff --git a/sdk/cliproxy/usage/home_selection.go b/sdk/cliproxy/usage/home_selection.go new file mode 100644 index 00000000000..c197e51865c --- /dev/null +++ b/sdk/cliproxy/usage/home_selection.go @@ -0,0 +1,37 @@ +package usage + +import "context" + +// HomeSelection identifies executions associated with a Home dispatch. Dispatch +// charges the first execution; reused executions are charged by primary usage. +// Additional-model records are billing details, not extra scheduling requests. +// Model is the scheduling route, not the upstream model. +type HomeSelection struct { + Reused bool `json:"reused"` + Additional bool `json:"additional,omitempty"` + Model string `json:"model"` + CredentialPolicy string `json:"credential_policy,omitempty"` +} + +type homeSelectionContextKey struct{} + +// WithHomeSelection captures immutable, attempt-scoped Home accounting metadata. +func WithHomeSelection(ctx context.Context, selection HomeSelection) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, homeSelectionContextKey{}, selection) +} + +// HomeSelectionFromContext returns a copy so follow-up responses cannot change +// the accounting metadata retained by the first response's usage reporter. +func HomeSelectionFromContext(ctx context.Context) *HomeSelection { + if ctx == nil { + return nil + } + selection, ok := ctx.Value(homeSelectionContextKey{}).(HomeSelection) + if !ok { + return nil + } + return &selection +} diff --git a/sdk/cliproxy/usage/home_selection_test.go b/sdk/cliproxy/usage/home_selection_test.go new file mode 100644 index 00000000000..036030efaea --- /dev/null +++ b/sdk/cliproxy/usage/home_selection_test.go @@ -0,0 +1,22 @@ +package usage + +import "testing" + +func TestHomeSelectionContextAndPublishSnapshot(t *testing.T) { + ctx := WithHomeSelection(t.Context(), HomeSelection{Model: "route"}) + followup := HomeSelectionFromContext(ctx) + followup.Reused = true + if HomeSelectionFromContext(ctx).Reused { + t.Fatal("follow-up mutated the first turn") + } + mgr := NewManager(10) + t.Cleanup(mgr.Stop) + plugin := &captureUsagePlugin{records: make(chan Record, 2)} + mgr.Register(plugin) + mgr.Publish(ctx, Record{}) + mgr.Publish(ctx, Record{HomeSelection: followup}) + first, second := <-plugin.records, <-plugin.records + if first.HomeSelection == nil || first.HomeSelection.Reused || second.HomeSelection == nil || !second.HomeSelection.Reused { + t.Fatalf("lost attempt metadata: first=%+v second=%+v", first.HomeSelection, second.HomeSelection) + } +} diff --git a/sdk/cliproxy/usage/manager.go b/sdk/cliproxy/usage/manager.go index 9b38c25c007..dd1f84ec455 100644 --- a/sdk/cliproxy/usage/manager.go +++ b/sdk/cliproxy/usage/manager.go @@ -30,7 +30,9 @@ type Record struct { TraceID string // SelectionID identifies the scheduler selection decision that produced this usage record when available. SelectionID string - Provider string + // HomeSelection carries deferred accounting for reused Home dispatches. + HomeSelection *HomeSelection + Provider string // BaseURL stores the configured upstream base URL when available. BaseURL string // ExecutorType stores the concrete executor type that handled the request. @@ -88,6 +90,10 @@ const FailureStreamTruncatedCode = "stream_truncated" // the selected credential, including local capability validation failures. const FailureRequestScopedCode = "request_scoped" +// FailureForceCooldownCode marks failures matched by a request-scoped error rule +// configured with a cooldown action (stop-and-cooldown or continue-and-cooldown). +const FailureForceCooldownCode = "force_cooldown" + // Failure holds HTTP failure metadata for an upstream request attempt. type Failure struct { StatusCode int @@ -737,6 +743,9 @@ func (m *Manager) Publish(ctx context.Context, record Record) { record.TraceID = trID } } + if record.HomeSelection == nil { + record.HomeSelection = HomeSelectionFromContext(ctx) + } if strings.TrimSpace(record.SelectionID) == "" { if selID := SelectionIDFromContext(ctx); selID != "" { record.SelectionID = selID diff --git a/sdk/pluginabi/types.go b/sdk/pluginabi/types.go index 2d7b2654a5f..49a8c972a1d 100644 --- a/sdk/pluginabi/types.go +++ b/sdk/pluginabi/types.go @@ -1,6 +1,9 @@ package pluginabi -import "encoding/json" +import ( + "encoding/json" + "strings" +) const ( // ABIVersion tracks the native C ABI shape (native plugin exports). @@ -149,12 +152,65 @@ const ( MethodHostRoutingResetCooldown = "host.routing.reset_cooldown" ) +// ErrorCode constants define the machine-readable Error.Code values recognized +// by CPA's routing and cooldown pipeline. +const ( + // ErrorCodeCredentialQuota marks a 429 refusal as exhausting or limiting the + // entire credential across all of its models (sets Result.CredentialScope and + // records quota reason "credential_quota"). Plugins may also set + // Error.CredentialScoped = true while keeping a provider-specific Code. + ErrorCodeCredentialQuota = "credential_quota" + // ErrorCodeTransientRateLimit marks a 429 refusal as a transient per-model + // capacity/admission limit that cools only the reporting model until + // RetryAfterSeconds without recording quota exhaustion or advancing backoff. + ErrorCodeTransientRateLimit = "transient_rate_limit" + // ErrorCodeRequestScoped marks a failure as caused by the request itself: + // CPA skips credential/model cooldown and stops credential rotation. + ErrorCodeRequestScoped = "request_scoped" + // ErrorCodeForceCooldown forces cooldown scheduling even when cooling is + // disabled for the credential, falling back to the default transient cooldown + // when no status-specific deadline applies. + ErrorCodeForceCooldown = "force_cooldown" + // ErrorCodeStreamTruncated marks an accepted upstream stream that terminated + // without a completion frame: CPA skips credential cooldown and does not + // replay the request on another credential. + ErrorCodeStreamTruncated = "stream_truncated" + // ErrorCodeConnectionLifecycle marks a client disconnect or session-close + // failure that must skip credential cooldown. + ErrorCodeConnectionLifecycle = "connection_lifecycle" + // ErrorCodeTransientTransport marks a pre-HTTP dial/TLS/DNS/reset failure + // that skips credential cooldown and remains eligible for request retries. + ErrorCodeTransientTransport = "transient_transport" + // ErrorCodeModelNotFound marks the requested model as unavailable on the + // selected credential so CPA cools only that model for 12h (or RetryAfterSeconds). + ErrorCodeModelNotFound = "model_not_found" + // ErrorCodeNotImplemented marks an optional capability (such as count_tokens) + // as unsupported so CPA keeps the credential and model available. + ErrorCodeNotImplemented = "not_implemented" +) + type Envelope struct { OK bool `json:"ok"` Result json.RawMessage `json:"result,omitempty"` Error *Error `json:"error,omitempty"` } +// Error carries a structured plugin failure across RPC envelopes and stream +// error_detail callbacks (host.stream.emit and host.stream.close). +// +// Routing and cooldown behavior is controlled by HTTPStatus, RetryAfterSeconds, +// CredentialScoped, and the recognized ErrorCode* values in Code: +// - CredentialScoped: true (or Code: ErrorCodeCredentialQuota) on a 429 marks +// the entire credential as rate-limited across all of its models +// (reason "credential_quota") until RetryAfterSeconds or the quota backoff. +// - Code: ErrorCodeTransientRateLimit on a 429 cools only the reporting model +// until RetryAfterSeconds without marking quota exceeded. +// - Code: ErrorCodeRequestScoped, ErrorCodeStreamTruncated, +// ErrorCodeConnectionLifecycle, or ErrorCodeTransientTransport skips +// credential/model cooldown. +// - Code: ErrorCodeForceCooldown enforces cooldown even when cooling is disabled. +// - Code: ErrorCodeModelNotFound cools only the requested model as unsupported. +// - Code: ErrorCodeNotImplemented keeps count_tokens failures availability-neutral. type Error struct { Code string `json:"code"` Message string `json:"message"` @@ -168,6 +224,10 @@ type Error struct { // for correctness. The same pair is accepted as error_detail on host.stream.emit // and host.stream.close. RetryAfterSeconds int `json:"retry_after_seconds,omitempty"` + // CredentialScoped reports whether the failure applies to the whole credential + // across all models (for example, an account-wide 429 quota or spend limit) + // rather than only the requested model. + CredentialScoped bool `json:"credential_scoped,omitempty"` } // Error implements the error interface for Error. @@ -194,6 +254,38 @@ func (e *Error) StatusCode() int { return e.HTTPStatus } +// IsCredentialScoped reports whether the Error applies to the entire credential. +func (e *Error) IsCredentialScoped() bool { + if e == nil { + return false + } + return e.CredentialScoped || strings.EqualFold(strings.TrimSpace(e.Code), ErrorCodeCredentialQuota) +} + +// IsRequestScoped reports whether the Error is tied to the request rather than the credential. +func (e *Error) IsRequestScoped() bool { + if e == nil || e.IsCredentialScoped() { + return false + } + return strings.EqualFold(strings.TrimSpace(e.Code), ErrorCodeRequestScoped) +} + +// IsTransientRateLimit reports whether the Error is a transient per-model capacity 429. +func (e *Error) IsTransientRateLimit() bool { + if e == nil || e.IsCredentialScoped() { + return false + } + return strings.EqualFold(strings.TrimSpace(e.Code), ErrorCodeTransientRateLimit) +} + +// IsStreamTruncated reports whether the Error represents a truncated accepted upstream stream. +func (e *Error) IsStreamTruncated() bool { + if e == nil || e.IsCredentialScoped() { + return false + } + return strings.EqualFold(strings.TrimSpace(e.Code), ErrorCodeStreamTruncated) +} + // NewError creates an Error instance with an optional HTTP status code. func NewError(code, message string, httpStatus ...int) *Error { status := 0 diff --git a/sdk/pluginabi/types_test.go b/sdk/pluginabi/types_test.go index d79c4c04349..99ad87fb8fa 100644 --- a/sdk/pluginabi/types_test.go +++ b/sdk/pluginabi/types_test.go @@ -208,3 +208,87 @@ func TestErrorInterfaceAndConstructor(t *testing.T) { t.Fatalf("default envelope JSON unexpectedly contained http_status: %s", string(defaultEnvBytes)) } } + +func TestErrorCredentialScopedAndCodes(t *testing.T) { + var _ interface{ IsCredentialScoped() bool } = (*Error)(nil) + + var nilErr *Error + if nilErr.IsCredentialScoped() { + t.Fatal("nil Error reported IsCredentialScoped() = true") + } + + modelScoped := NewError("rate_limited", "per-model rate limit", 429) + if modelScoped.IsCredentialScoped() { + t.Fatal("model-scoped Error reported IsCredentialScoped() = true") + } + + flagScoped := &Error{ + Code: "rate_limited", + Message: "account limited, resets at 2026-01-01T00:00:00Z", + HTTPStatus: 429, + RetryAfterSeconds: 120, + CredentialScoped: true, + } + if !flagScoped.IsCredentialScoped() { + t.Fatal("Error with CredentialScoped=true reported IsCredentialScoped() = false") + } + + raw, errMarshal := json.Marshal(Envelope{OK: false, Error: flagScoped}) + if errMarshal != nil { + t.Fatalf("marshal credential-scoped envelope: %v", errMarshal) + } + if !strings.Contains(string(raw), `"credential_scoped":true`) { + t.Fatalf("marshaled envelope missing credential_scoped: %s", string(raw)) + } + var decoded Envelope + if errUnmarshal := json.Unmarshal(raw, &decoded); errUnmarshal != nil { + t.Fatalf("unmarshal credential-scoped envelope: %v", errUnmarshal) + } + if decoded.Error == nil || !decoded.Error.CredentialScoped || !decoded.Error.IsCredentialScoped() { + t.Fatalf("decoded error = %+v, want CredentialScoped=true", decoded.Error) + } + + codeScoped := NewError(ErrorCodeCredentialQuota, "daily quota spent", 429) + if !codeScoped.IsCredentialScoped() { + t.Fatal("Error with ErrorCodeCredentialQuota reported IsCredentialScoped() = false") + } + if codeScoped.IsRequestScoped() || codeScoped.IsTransientRateLimit() { + t.Fatal("credential-scoped Error reported request-scoped or transient-rate-limit") + } + + reqScoped := NewError(ErrorCodeRequestScoped, "invalid prompt", 400) + if !reqScoped.IsRequestScoped() { + t.Fatal("Error with ErrorCodeRequestScoped reported IsRequestScoped() = false") + } + + transientRL := NewError(ErrorCodeTransientRateLimit, "turn rate limit", 429) + if !transientRL.IsTransientRateLimit() { + t.Fatal("Error with ErrorCodeTransientRateLimit reported IsTransientRateLimit() = false") + } + + truncated := NewError(ErrorCodeStreamTruncated, "stream ended early", 502) + if !truncated.IsStreamTruncated() { + t.Fatal("Error with ErrorCodeStreamTruncated reported IsStreamTruncated() = false") + } + truncatedCredScoped := &Error{ + Code: ErrorCodeStreamTruncated, + Message: "stream ended early", + HTTPStatus: 429, + CredentialScoped: true, + } + if !truncatedCredScoped.IsCredentialScoped() || truncatedCredScoped.IsStreamTruncated() { + t.Fatal("credential-scoped Error with stream_truncated code must prioritize IsCredentialScoped()") + } + + if ErrorCodeCredentialQuota != "credential_quota" || + ErrorCodeTransientRateLimit != "transient_rate_limit" || + ErrorCodeRequestScoped != "request_scoped" || + ErrorCodeForceCooldown != "force_cooldown" || + ErrorCodeStreamTruncated != "stream_truncated" || + ErrorCodeConnectionLifecycle != "connection_lifecycle" || + ErrorCodeTransientTransport != "transient_transport" || + ErrorCodeModelNotFound != "model_not_found" || + ErrorCodeNotImplemented != "not_implemented" { + t.Fatal("unexpected routing/cooldown error code constant values") + } +} diff --git a/sdk/pluginapi/types.go b/sdk/pluginapi/types.go index 718961c7639..b69cb8b6c3a 100644 --- a/sdk/pluginapi/types.go +++ b/sdk/pluginapi/types.go @@ -105,7 +105,10 @@ type Capabilities struct { // Executor sends requests to an upstream provider or local backend. Executor ProviderExecutor // ExecutorModelScope declares whether Executor serves static models, OAuth auth models, or both. - // Empty defaults to ExecutorModelScopeBoth for backward compatibility. + // Empty defaults to ExecutorModelScopeOAuth when AuthProvider/AuthProviders is declared, + // and ExecutorModelScopeBoth otherwise for backward compatibility. + // When AuthProvider/AuthProviders is declared, only ExecutorModelScopeStatic registers an + // unauthenticated static model client in ModelRegistry. ExecutorModelScope ExecutorModelScope // ExecutorInputFormats lists request protocols accepted directly by Executor. Executors must declare at least one. ExecutorInputFormats []string @@ -169,7 +172,8 @@ type Capabilities struct { type ExecutorModelScope string const ( - // ExecutorModelScopeBoth means the executor supports static and OAuth auth-bound models. + // ExecutorModelScopeBoth means the executor supports static and OAuth auth-bound models + // when no AuthProvider/AuthProviders is declared, or OAuth auth-bound models when credential-bound. ExecutorModelScopeBoth ExecutorModelScope = "both" // ExecutorModelScopeStatic means the executor supports only non-OAuth static models. ExecutorModelScopeStatic ExecutorModelScope = "static" @@ -1732,6 +1736,29 @@ type UsageDetail struct { CacheCreationTokens int64 // TotalTokens is the total token count. TotalTokens int64 + + // TextInputTokens is the optional text input token count. + TextInputTokens *int64 + // ImageInputTokens is the optional image input token count. + ImageInputTokens *int64 + // AudioInputTokens is the optional audio input token count. + AudioInputTokens *int64 + // VideoInputTokens is the optional video input token count. + VideoInputTokens *int64 + // FileInputTokens is the optional file input token count. + FileInputTokens *int64 + // CachedTextTokens is the optional cached text token count. + CachedTextTokens *int64 + // CachedImageTokens is the optional cached image token count. + CachedImageTokens *int64 + // CachedAudioTokens is the optional cached audio token count. + CachedAudioTokens *int64 + // TextOutputTokens is the optional text output token count. + TextOutputTokens *int64 + // ImageOutputTokens is the optional image output token count. + ImageOutputTokens *int64 + // AudioOutputTokens is the optional audio output token count. + AudioOutputTokens *int64 } // QuotaProvider surfaces credential quota, balance, and billing information for management clients. diff --git a/sdk/pluginapi/types_test.go b/sdk/pluginapi/types_test.go index 3db66fa9c1a..e40fa445cc9 100644 --- a/sdk/pluginapi/types_test.go +++ b/sdk/pluginapi/types_test.go @@ -869,6 +869,78 @@ func TestUsageRecordRequestIDAndTraceID(t *testing.T) { } } +func TestUsageDetailModalityTokenCounters(t *testing.T) { + int64Ptr := func(v int64) *int64 { return &v } + record := UsageRecord{ + Provider: "openai", + Model: "gpt-image-2.5-flare", + Detail: UsageDetail{ + InputTokens: 80, + OutputTokens: 1056, + CachedTokens: 40, + CacheReadTokens: 40, + TotalTokens: 1136, + TextInputTokens: int64Ptr(30), + ImageInputTokens: int64Ptr(50), + AudioInputTokens: int64Ptr(0), + VideoInputTokens: nil, + FileInputTokens: int64Ptr(12), + CachedTextTokens: int64Ptr(25), + CachedImageTokens: int64Ptr(15), + CachedAudioTokens: int64Ptr(0), + TextOutputTokens: int64Ptr(0), + ImageOutputTokens: int64Ptr(1056), + AudioOutputTokens: nil, + }, + } + + raw, errMarshal := json.Marshal(record) + if errMarshal != nil { + t.Fatalf("Marshal(UsageRecord) error = %v", errMarshal) + } + var decoded UsageRecord + if errUnmarshal := json.Unmarshal(raw, &decoded); errUnmarshal != nil { + t.Fatalf("Unmarshal(UsageRecord) error = %v", errUnmarshal) + } + got := decoded.Detail + if got.InputTokens != 80 || got.OutputTokens != 1056 || got.TotalTokens != 1136 { + t.Fatalf("aggregate Detail = %+v", got) + } + if got.TextInputTokens == nil || *got.TextInputTokens != 30 { + t.Fatalf("TextInputTokens = %v, want 30", got.TextInputTokens) + } + if got.ImageInputTokens == nil || *got.ImageInputTokens != 50 { + t.Fatalf("ImageInputTokens = %v, want 50", got.ImageInputTokens) + } + if got.AudioInputTokens == nil || *got.AudioInputTokens != 0 { + t.Fatalf("AudioInputTokens = %v, want explicit 0", got.AudioInputTokens) + } + if got.VideoInputTokens != nil { + t.Fatalf("VideoInputTokens = %v, want nil", got.VideoInputTokens) + } + if got.FileInputTokens == nil || *got.FileInputTokens != 12 { + t.Fatalf("FileInputTokens = %v, want 12", got.FileInputTokens) + } + if got.CachedTextTokens == nil || *got.CachedTextTokens != 25 { + t.Fatalf("CachedTextTokens = %v, want 25", got.CachedTextTokens) + } + if got.CachedImageTokens == nil || *got.CachedImageTokens != 15 { + t.Fatalf("CachedImageTokens = %v, want 15", got.CachedImageTokens) + } + if got.CachedAudioTokens == nil || *got.CachedAudioTokens != 0 { + t.Fatalf("CachedAudioTokens = %v, want explicit 0", got.CachedAudioTokens) + } + if got.TextOutputTokens == nil || *got.TextOutputTokens != 0 { + t.Fatalf("TextOutputTokens = %v, want explicit 0", got.TextOutputTokens) + } + if got.ImageOutputTokens == nil || *got.ImageOutputTokens != 1056 { + t.Fatalf("ImageOutputTokens = %v, want 1056", got.ImageOutputTokens) + } + if got.AudioOutputTokens != nil { + t.Fatalf("AudioOutputTokens = %v, want nil", got.AudioOutputTokens) + } +} + func TestQuotaPayloadJSON(t *testing.T) { // Test camelCase input camelJSON := []byte(`{ diff --git a/test/codex_power_darwin_test.go b/test/codex_power_darwin_test.go new file mode 100644 index 00000000000..1fd97eaa0b6 --- /dev/null +++ b/test/codex_power_darwin_test.go @@ -0,0 +1,18 @@ +//go:build darwin + +package test + +import ( + "context" + "os" + "testing" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" +) + +func TestMain(m *testing.M) { + codex.ReadSIWCSystemState = func(context.Context) ([]byte, error) { + return []byte("Current System Capabilities are: CPU Graphics Audio Network\nCurrent Power State: 4\n"), nil + } + os.Exit(m.Run()) +} diff --git a/test/issue7513_http_failover_test.go b/test/issue7513_http_failover_test.go new file mode 100644 index 00000000000..62e02f7896f --- /dev/null +++ b/test/issue7513_http_failover_test.go @@ -0,0 +1,386 @@ +package test + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + runtimeexecutor "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + claudehandlers "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers/claude" + openaihandlers "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers/openai" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestIssue7513_ClaudeAndOpenAIEndpointsRotateAndExhaustTo502(t *testing.T) { + gin.SetMode(gin.TestMode) + + endpoints := []struct { + name string + path string + finishReason string + streamBody string + nonStream string + wantSubstr string + }{ + { + name: "claude_messages", + path: "/v1/messages", + finishReason: "MALFORMED_FUNCTION_CALL", + streamBody: `{"model":"MODEL","max_tokens":1024,"stream":true,"messages":[{"role":"user","content":"hi"}]}`, + nonStream: `{"model":"MODEL","max_tokens":1024,"messages":[{"role":"user","content":"hi"}]}`, + wantSubstr: "recovered via vertex", + }, + { + name: "openai_chat_completions", + path: "/v1/chat/completions", + finishReason: "UNEXPECTED_TOOL_CALL", + streamBody: `{"model":"MODEL","stream":true,"messages":[{"role":"user","content":"hi"}]}`, + nonStream: `{"model":"MODEL","messages":[{"role":"user","content":"hi"}]}`, + wantSubstr: "recovered via vertex", + }, + { + name: "openai_responses", + path: "/v1/responses", + finishReason: "MALFORMED_RESPONSE", + streamBody: `{"model":"MODEL","stream":true,"input":"hi"}`, + nonStream: `{"model":"MODEL","input":"hi"}`, + wantSubstr: "recovered via vertex", + }, + } + + for _, ep := range endpoints { + t.Run(ep.name, func(t *testing.T) { + var agCalls atomic.Int32 + agServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + agCalls.Add(1) + body := `{"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"` + ep.finishReason + `"}],"usageMetadata":{"promptTokenCount":50,"candidatesTokenCount":1,"totalTokenCount":51},"modelVersion":"gemini-4-hydrogen"}}` + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: "+body+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, body) + })) + defer agServer.Close() + + var vertexCalls atomic.Int32 + vertexServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + vertexCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"recovered via vertex"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":50,"candidatesTokenCount":4,"totalTokenCount":54},"modelVersion":"gemini-4-hydrogen"}`+"\n\n") + })) + defer vertexServer.Close() + + model := "gemini-4-hydrogen-7513-" + ep.name + cfg := &config.Config{} + + // Subcase 1: Antigravity zero-output rotates cleanly to healthy Vertex without committing HTTP 200 prematurely. + manager := coreauth.NewManager(nil, nil, nil) + affinity := coreauth.NewSessionAffinitySelectorWithConfig(coreauth.SessionAffinityConfig{ + Fallback: &coreauth.RoundRobinSelector{}, + TTL: time.Hour, + RebindOn: coreauth.SessionAffinityRebindOnQuota, + }) + defer affinity.Stop() + manager.SetSelector(affinity) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(cfg)) + manager.RegisterExecutor(runtimeexecutor.NewGeminiVertexExecutor(cfg)) + + agAuth := &coreauth.Auth{ + ID: "ag-fail-" + ep.name, + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-ag", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-ag", + }, + Attributes: map[string]string{ + "base_url": agServer.URL, + "priority": "10", + }, + } + vertexAuth := &coreauth.Auth{ + ID: "vertex-ok-" + ep.name, + Provider: "vertex", + Status: coreauth.StatusActive, + Attributes: map[string]string{ + "api_key": "vertex-key", + "base_url": vertexServer.URL, + "priority": "1", + }, + } + for _, a := range []*coreauth.Auth{agAuth, vertexAuth} { + if _, errReg := manager.Register(context.Background(), a); errReg != nil { + t.Fatalf("Register(%s) error = %v", a.ID, errReg) + } + registry.GetGlobalRegistry().RegisterClient(a.ID, a.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(a.ID) + }) + } + + base := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + claudeH := claudehandlers.NewClaudeCodeAPIHandler(base) + openaiH := openaihandlers.NewOpenAIAPIHandler(base) + responsesH := openaihandlers.NewOpenAIResponsesAPIHandler(base) + + router := gin.New() + router.POST("/v1/messages", claudeH.ClaudeMessages) + router.POST("/v1/chat/completions", openaiH.ChatCompletions) + router.POST("/v1/responses", responsesH.Responses) + + streamPayload := strings.ReplaceAll(ep.streamBody, "MODEL", model) + req := httptest.NewRequest(http.MethodPost, ep.path, strings.NewReader(streamPayload)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("failover status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), ep.wantSubstr) { + t.Fatalf("failover body missing %q: %s", ep.wantSubstr, rec.Body.String()) + } + if agCalls.Load() != 1 || vertexCalls.Load() != 1 { + t.Fatalf("calls = (ag=%d, vertex=%d), want (1, 1)", agCalls.Load(), vertexCalls.Load()) + } + + // Subcase 2: When all credentials return zero-output abnormal finish, both stream and non-stream return HTTP 502. + exhaustedStreamModel := model + "-exhausted-stream" + exhaustedNonStreamModel := model + "-exhausted-nonstream" + exhaustedManager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + exhaustedManager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(cfg)) + for _, suffix := range []string{"a", "b"} { + failAuth := &coreauth.Auth{ + ID: "ag-exhausted-" + ep.name + "-" + suffix, + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-ag-" + suffix, + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-ag", + }, + Attributes: map[string]string{"base_url": agServer.URL}, + } + if _, errReg := exhaustedManager.Register(context.Background(), failAuth); errReg != nil { + t.Fatalf("Register(%s) error = %v", failAuth.ID, errReg) + } + registry.GetGlobalRegistry().RegisterClient(failAuth.ID, failAuth.Provider, []*registry.ModelInfo{ + {ID: exhaustedStreamModel}, + {ID: exhaustedNonStreamModel}, + }) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(failAuth.ID) + }) + } + + exhaustedBase := handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, exhaustedManager) + exhaustedRouter := gin.New() + exhaustedRouter.POST("/v1/messages", claudehandlers.NewClaudeCodeAPIHandler(exhaustedBase).ClaudeMessages) + exhaustedRouter.POST("/v1/chat/completions", openaihandlers.NewOpenAIAPIHandler(exhaustedBase).ChatCompletions) + exhaustedRouter.POST("/v1/responses", openaihandlers.NewOpenAIResponsesAPIHandler(exhaustedBase).Responses) + + beforeAgCalls := agCalls.Load() + exStreamReq := httptest.NewRequest(http.MethodPost, ep.path, strings.NewReader(strings.ReplaceAll(ep.streamBody, "MODEL", exhaustedStreamModel))) + exStreamReq.Header.Set("Content-Type", "application/json") + exStreamRec := httptest.NewRecorder() + exhaustedRouter.ServeHTTP(exStreamRec, exStreamReq) + if exStreamRec.Code != http.StatusBadGateway { + t.Fatalf("exhausted stream status = %d, want 502; body=%s", exStreamRec.Code, exStreamRec.Body.String()) + } + if gotCalls := agCalls.Load() - beforeAgCalls; gotCalls != 2 { + t.Fatalf("expected exhausted stream to rotate across both credentials (2 calls), got %d", gotCalls) + } + + beforeNonStreamCalls := agCalls.Load() + exNonStreamReq := httptest.NewRequest(http.MethodPost, ep.path, strings.NewReader(strings.ReplaceAll(ep.nonStream, "MODEL", exhaustedNonStreamModel))) + exNonStreamReq.Header.Set("Content-Type", "application/json") + exNonStreamRec := httptest.NewRecorder() + exhaustedRouter.ServeHTTP(exNonStreamRec, exNonStreamReq) + if exNonStreamRec.Code != http.StatusBadGateway { + t.Fatalf("exhausted non-stream status = %d, want 502; body=%s", exNonStreamRec.Code, exNonStreamRec.Body.String()) + } + if gotCalls := agCalls.Load() - beforeNonStreamCalls; gotCalls != 2 { + t.Fatalf("expected exhausted non-stream to rotate across both credentials (2 calls), got %d", gotCalls) + } + }) + } +} + +func TestIssue7513_ApplyPatchAbnormalEOFWithoutUsageRotatesAndExhaustsTo502(t *testing.T) { + gin.SetMode(gin.TestMode) + + var agCalls atomic.Int32 + agServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + agCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + // Zero-output abnormal finish WITHOUT usageMetadata, immediately followed by EOF. + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"modelVersion":"gemini-4-hydrogen"}}`+"\n\n") + })) + defer agServer.Close() + + var vertexCalls atomic.Int32 + vertexServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + vertexCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"apply_patch fallback ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":3,"totalTokenCount":23},"modelVersion":"gemini-4-hydrogen"}`+"\n\n") + })) + defer vertexServer.Close() + + cfg := &config.Config{} + model := "gemini-4-hydrogen-7513-apply-patch" + patchReq := `{"model":"` + model + `","stream":true,"input":"patch","tools":[{"type":"custom","name":"apply_patch"}]}` + + // Subcase 1: Rotates from Antigravity to healthy Vertex without emitting response.failed HTTP 200. + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(cfg)) + manager.RegisterExecutor(runtimeexecutor.NewGeminiVertexExecutor(cfg)) + + agAuth := &coreauth.Auth{ + ID: "ag-patch-fail", + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-ag", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-ag", + }, + Attributes: map[string]string{"base_url": agServer.URL, "priority": "10"}, + } + vertexAuth := &coreauth.Auth{ + ID: "vertex-patch-ok", + Provider: "vertex", + Status: coreauth.StatusActive, + Attributes: map[string]string{"api_key": "vertex-key", "base_url": vertexServer.URL, "priority": "1"}, + } + for _, a := range []*coreauth.Auth{agAuth, vertexAuth} { + if _, errReg := manager.Register(context.Background(), a); errReg != nil { + t.Fatalf("Register(%s) error = %v", a.ID, errReg) + } + registry.GetGlobalRegistry().RegisterClient(a.ID, a.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(a.ID) + }) + } + + router := gin.New() + router.POST("/v1/responses", openaihandlers.NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager)).Responses) + + req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(patchReq)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "apply_patch fallback ok") { + t.Fatalf("apply_patch failover = (%d, %s), want 200 with fallback text", rec.Code, rec.Body.String()) + } + if agCalls.Load() != 1 || vertexCalls.Load() != 1 { + t.Fatalf("calls = (ag=%d, vertex=%d), want (1, 1)", agCalls.Load(), vertexCalls.Load()) + } + + // Subcase 2: Exhausted apply_patch stream returns HTTP 502 (not HTTP 200 response.failed). + exhaustedModel := model + "-exhausted" + exManager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + exManager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(cfg)) + exAuth := &coreauth.Auth{ + ID: "ag-patch-exhausted", + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-ag", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-ag", + "disable_cooling": true, + }, + Attributes: map[string]string{"base_url": agServer.URL}, + } + if _, errReg := exManager.Register(context.Background(), exAuth); errReg != nil { + t.Fatalf("Register error = %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(exAuth.ID, exAuth.Provider, []*registry.ModelInfo{{ID: exhaustedModel}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(exAuth.ID) + }) + + exRouter := gin.New() + exRouter.POST("/v1/responses", openaihandlers.NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, exManager)).Responses) + exReq := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(strings.ReplaceAll(patchReq, model, exhaustedModel))) + exReq.Header.Set("Content-Type", "application/json") + exRec := httptest.NewRecorder() + exRouter.ServeHTTP(exRec, exReq) + if exRec.Code != http.StatusBadGateway { + t.Fatalf("exhausted apply_patch status = %d, want 502; body=%s", exRec.Code, exRec.Body.String()) + } + if strings.Contains(exRec.Body.String(), "response.failed") { + t.Fatalf("exhausted apply_patch leaked response.failed instead of clean 502: %s", exRec.Body.String()) + } +} + +func TestIssue7513_PartialTextWithMalformedFunctionCallPreservedOverClaudeHTTP(t *testing.T) { + gin.SetMode(gin.TestMode) + + agServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "streamGenerateContent") { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]}}],"modelVersion":"gemini-4-hydrogen"}}`+"\n\n") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":3,"totalTokenCount":23},"modelVersion":"gemini-4-hydrogen"}}`+"\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"partial answer"}]},"finishReason":"MALFORMED_FUNCTION_CALL"}],"usageMetadata":{"promptTokenCount":20,"candidatesTokenCount":3,"totalTokenCount":23},"modelVersion":"gemini-4-hydrogen"}}`) + })) + defer agServer.Close() + + model := "gemini-4-hydrogen-7513-partial-http" + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(&config.Config{})) + auth := &coreauth.Auth{ + ID: "ag-partial-http", + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-ag", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-ag", + }, + Attributes: map[string]string{"base_url": agServer.URL}, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register error = %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, auth.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(auth.ID) + }) + + router := gin.New() + router.POST("/v1/messages", claudehandlers.NewClaudeCodeAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager)).ClaudeMessages) + + for _, stream := range []bool{false, true} { + body := `{"model":"` + model + `","max_tokens":1024,"messages":[{"role":"user","content":"hi"}]}` + if stream { + body = `{"model":"` + model + `","max_tokens":1024,"stream":true,"messages":[{"role":"user","content":"hi"}]}` + } + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "partial answer") { + t.Fatalf("stream=%v status=%d body=%s, want 200 preserving partial answer", stream, rec.Code, rec.Body.String()) + } + if strings.Contains(rec.Body.String(), "event: error\n") { + t.Fatalf("stream=%v unexpectedly emitted error event: %s", stream, rec.Body.String()) + } + } +} diff --git a/test/issue7536_http_failover_test.go b/test/issue7536_http_failover_test.go new file mode 100644 index 00000000000..77bacc7be6e --- /dev/null +++ b/test/issue7536_http_failover_test.go @@ -0,0 +1,154 @@ +package test + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + runtimeexecutor "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + openaihandlers "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers/openai" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestIssue7536_SignatureOnlyZeroOutputNoFinishReasonRotatesAndExhaustsTo502(t *testing.T) { + gin.SetMode(gin.TestMode) + + zeroOutputSSE := `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"opaque-sig-7536","text":""}]}}],"usageMetadata":{"promptTokenCount":378515,"cachedContentTokenCount":376466,"totalTokenCount":378515},"modelVersion":"gemini-4-hydrogen","responseId":"resp-7536"},"traceId":"trace-7536","metadata":{}}` + "\n\n" + + var badCalls atomic.Int32 + badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + badCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, zeroOutputSSE) + })) + defer badServer.Close() + + var okCalls atomic.Int32 + okServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + okCalls.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"recovered on second credential"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":378515,"candidatesTokenCount":5,"totalTokenCount":378520},"modelVersion":"gemini-4-hydrogen"}}`+"\n\n") + })) + defer okServer.Close() + + model := "gemini-4-hydrogen-7536" + cfg := &config.Config{} + + // 1. Credential 1 returns signature-only zero-output EOF -> rotates to Credential 2 and returns 200 with real output. + manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + manager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(cfg)) + + badAuth := &coreauth.Auth{ + ID: "ag-7536-bad", + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-bad", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-bad", + }, + Attributes: map[string]string{ + "base_url": badServer.URL, + "priority": "10", + }, + } + okAuth := &coreauth.Auth{ + ID: "ag-7536-ok", + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-ok", + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-ok", + }, + Attributes: map[string]string{ + "base_url": okServer.URL, + "priority": "1", + }, + } + for _, a := range []*coreauth.Auth{badAuth, okAuth} { + if _, errReg := manager.Register(context.Background(), a); errReg != nil { + t.Fatalf("Register(%s) error = %v", a.ID, errReg) + } + registry.GetGlobalRegistry().RegisterClient(a.ID, a.Provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(a.ID) + }) + } + + router := gin.New() + router.POST("/v1/chat/completions", openaihandlers.NewOpenAIAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager)).ChatCompletions) + + reqBody := `{"model":"` + model + `","stream":true,"messages":[{"role":"user","content":"hi"}]}` + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(reqBody)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("failover status = %d, want 200; body=%s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "recovered on second credential") { + t.Fatalf("expected failover response from second credential, got: %s", rec.Body.String()) + } + if badCalls.Load() != 1 || okCalls.Load() != 1 { + t.Fatalf("calls = (bad=%d, ok=%d), want (1, 1)", badCalls.Load(), okCalls.Load()) + } + + // 2. When all credentials return signature-only zero-output EOF, return HTTP 502 (never HTTP 200 + finish_reason:"stop"). + exhaustedModel := model + "-exhausted" + exhaustedManager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil) + exhaustedManager.RegisterExecutor(runtimeexecutor.NewAntigravityExecutor(cfg)) + for _, suffix := range []string{"a", "b"} { + a := &coreauth.Auth{ + ID: "ag-7536-exhausted-" + suffix, + Provider: "antigravity", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "access_token": "token-" + suffix, + "expired": time.Now().Add(24 * time.Hour).Format(time.RFC3339), + "project_id": "project-" + suffix, + }, + Attributes: map[string]string{"base_url": badServer.URL}, + } + if _, errReg := exhaustedManager.Register(context.Background(), a); errReg != nil { + t.Fatalf("Register(%s) error = %v", a.ID, errReg) + } + registry.GetGlobalRegistry().RegisterClient(a.ID, a.Provider, []*registry.ModelInfo{{ID: exhaustedModel}}) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(a.ID) + }) + } + + exhaustedRouter := gin.New() + exhaustedRouter.POST("/v1/chat/completions", openaihandlers.NewOpenAIAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{ + Streaming: sdkconfig.StreamingConfig{BootstrapRetries: 1}, + }, exhaustedManager)).ChatCompletions) + + beforeCalls := badCalls.Load() + exReq := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"model":"`+exhaustedModel+`","stream":true,"messages":[{"role":"user","content":"hi"}]}`)) + exReq.Header.Set("Content-Type", "application/json") + exRec := httptest.NewRecorder() + exhaustedRouter.ServeHTTP(exRec, exReq) + + if exRec.Code != http.StatusBadGateway { + t.Fatalf("exhausted status = %d, want 502; body=%s", exRec.Code, exRec.Body.String()) + } + if strings.Contains(exRec.Body.String(), `"finish_reason":"stop"`) { + t.Fatalf("exhausted response must not emit finish_reason:stop: %s", exRec.Body.String()) + } + if got := badCalls.Load() - beforeCalls; got < 2 { + t.Fatalf("expected credential rotation & bootstrap retry (>=2 calls), got %d", got) + } +}