Merge upstream main and retain upstream tool-schema allocation isolation

Keep upstream's subprocess isolation in the overlapping tool-schema test.
Preserve the capacity-shed retry-delay and WS passthrough fixes, together
with the remaining allocation-test isolation guards.

Add HTTP failover coverage: capacity-shed exhaustion omits Retry-After,
while the existing ordinary 429 test continues to preserve that header.

Validation on Go 1.27.4:
- GOMAXPROCS=4 go test -tags=unit -count=1 ./...:
  28,223 test cases including subtests passed; 40 skipped.
- golangci-lint 2.14.0: 0 issues.
- Independent review of the complete PR diff: no material findings.
This commit is contained in:
Weicheng Yu committed 2026-11-18 08:55:06 +08:00
commit 02dea61bdb
433 files changed
+25416 -1940

No files matched your search

+2 -2
View File
@@ -35,7 +35,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
go version | grep -q 'go1.27.3'
go version | grep -q 'go1.27.4'
- name: Unit tests
working-directory: backend
run: make test-unit
@@ -75,7 +75,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
go version | grep -q 'go1.27.3'
go version | grep -q 'go1.27.4'
- name: golangci-lint
uses: golangci/golangci-lint-action@v9
with:
+1 -1
View File
@@ -137,7 +137,7 @@ jobs:
check-latest: false
cache: false
- name: Verify Go version
run: go version | grep -q 'go1.27.3'
run: go version | grep -q 'go1.27.4'
- name: Restore target-specific Go cache
id: go-cache
uses: actions/cache/restore@v6
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
go version | grep -q 'go1.27.3'
go version | grep -q 'go1.27.4'
- name: Run govulncheck
working-directory: backend
run: |
+1
View File
@@ -141,6 +141,7 @@ docs/*
!docs/PAYMENT_CN.md
!docs/ADMIN_PAYMENT_INTEGRATION_API.md
!docs/ASYNC_IMAGE_TASKS.md
!docs/OPENAI_IMAGES_CODEX.md
!docs/BATCH_IMAGE_MVP.md
!docs/COMPOSITE_GROUPS.md
!docs/PLUGIN_DEVELOPMENT.md
+1 -1
View File
@@ -53,7 +53,7 @@ npm install -g pnpm
### CI 要求
- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
- Go 版本必须是 **1.27.4**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.4'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
- 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml`
### 本地测试命令
+1 -1
View File
@@ -8,7 +8,7 @@
# =============================================================================
ARG NODE_IMAGE=node:24-alpine
ARG GOLANG_IMAGE=golang:1.27.3-alpine
ARG GOLANG_IMAGE=golang:1.27.4-alpine
ARG ALPINE_IMAGE=alpine:3.21
ARG POSTGRES_IMAGE=postgres:18-alpine
ARG GOPROXY=https://goproxy.cn,direct
+1
View File
@@ -11,6 +11,7 @@ FRONTEND_CRITICAL_VITEST := \
src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \
src/constants/__tests__/platforms.spec.ts \
src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \
src/components/account/__tests__/CNProviderQuotaCell.spec.ts \
src/components/account/__tests__/CreateAccountModal.spec.ts \
src/components/account/__tests__/EditAccountModal.spec.ts \
src/components/account/__tests__/credentialsBuilder.spec.ts \
+6 -6
View File
@@ -117,11 +117,6 @@ Please read the following carefully before using this project:
<td>Thanks to FennoAI for sponsoring this project! FennoAI is a high-stability, high-performance API relay provider for enterprise R&D teams and developers, compatible with the OpenAI and Anthropic protocols and seamlessly integrating with mainstream AI coding tools such as Codex, Claude Code, and OpenCode. The platform delivers enterprise-grade stability, supporting call volumes of 100 billion tokens per day, and supports business-to-business settlement and invoicing for both domestic and overseas entities to meet enterprise R&D and procurement needs. As an exclusive benefit for Sub2API users, purchase a subscription via the <a href="https://api.fenno.ai/s/dC4k">exclusive link</a> to get $50 worth of Coding Plan credit for only $1.99. Referral rewards are also available: invite friends to purchase and earn up to 20% commission — the more you invite, the more you earn.</td>
</tr>
<tr>
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
<td>Thank you to LanoX AI for sponsoring this project! <a href="https://lanox.ai/?c=6">LanoX AI</a> provides stable, cost-effective global model access services for developers, teams, and enterprises. 🎁 New User Benefits — Claim millions of free tokens, plus 500+ free models for easier low-cost testing, validation, and deployment 🧠 Global Leading Models — GPT · Claude · Gemini · Qwen · Grok... 🎬 Multimodal Creation — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ Enterprise-Grade Reliability — High availability 💎 native capability output 💎 no intelligence degradation 💎 no model mixing 💎 transparent usage and billing 💎 💰 Lower API Costs — Top-tier models from as low as 10% of official pricing, with clear documentation, simple integration, invoicing support, and enterprise-scale batch usage 🏢 Enterprise Choice — Ideal for AI products, Agents, content platforms, and R&D teams with high-volume model usage</td>
</tr>
<tr>
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> is a data collection proxy solution built for developers, providing stable and reliable residential proxy services. With 90M+ global residential IPs and 200+ country coverage, intelligent rotation, and precise geo-targeting, it helps projects such as web scraping, AI data training, SEO monitoring, and e-commerce data analysis break through access restrictions and improve data collection efficiency. It supports mainstream automation frameworks such as Playwright, Selenium, and Puppeteer, with prices as low as $0.65/GB — <a href="https://www.rapidproxy.io/?ref=sub2api">start your free test now</a>.</td>
@@ -184,7 +179,12 @@ Please read the following carefully before using this project:
<tr>
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> supplies Claude API access at wholesale per-token prices to businesses and high-volume developers. It serves the standard Anthropic Messages API, so it works with Claude Code, Sub2API, LiteLLM and One API without code changes. Sign up with code SUB2API for 5% off every call.</td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> supplies Claude API access at wholesale per-token prices to businesses and high-volume developers. It serves the standard Anthropic Messages API, so it works with Claude Code, Sub2API, LiteLLM and One API without code changes. Sign up with code SUB2API for 5% off every call, then join our Telegram group @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>) and ask an admin for $10 in credits.</td>
</tr>
<tr>
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> is an all-in-one AI API platform for developers and businesses, offering unified access to leading models including OpenAI, Claude, and Gemini for AI coding and text, image, audio, and video generation. It supports popular AI coding tools such as Claude Code and Codex, with pay-as-you-go pricing, real-time usage and cost monitoring, and 24/7 technical support to simplify model integration and keep development costs under control. New users can sign up through <a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">this link</a> to claim usage credits. From coding to multimodal creation, start your AI journey in one place!</td>
</tr>
</table>
+6 -6
View File
@@ -120,11 +120,6 @@
<td>感谢 FennoAI 赞助本项目!FennoAI 是一家面向企业研发团队和开发者的高稳定、高性能 API 中转服务商,兼容 OpenAI 与 Anthropic 协议,可无缝接入 Codex、Claude Code、OpenCode 等主流 AI 编程工具。平台具备企业级稳定性,可支撑千亿 Token/日的调用规模,并支持境内外主体公对公结算及开票,满足企业级研发与采购需求。作为 Sub2API 用户专属福利,通过<a href="https://api.fenno.ai/s/dC4k">专属链接</a>购买订阅,仅需 1.99 美元即可获得价值 50 美元的 Coding Plan 额度。同时支持邀请奖励,邀请好友购买最高可获得 20% 返佣,邀请越多,奖励越高。</td>
</tr>
<tr>
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
<td>感谢 LanoX AI 对本项目的赞助!<a href="https://lanox.ai/?c=6">LanoX AI</a> 为开发者、团队与企业提供稳定、高性价比的全球模型接入服务。 🎁 新用户福利 — 免费领取 百万 Token ,更有500+ 免费模型 — 低成本测试、验证、部署更轻松 🧠 全球主流模型 — GPT · Claude · Gemini · Qwen · Grok... 🎬 多模态创作 — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ 企业级稳定服务 — 高可用💎原生能力输出💎不降智💎不混模💎调用与计费透明💎 💰 更低调用成本 — 顶级模型低至官方价 1 折起,文档清晰、接入简单、支持开票与企业批量调用 🏢 企业优选 — 适用于 AI 产品、Agent、内容平台、研发团队批量调用</td>
</tr>
<tr>
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> 是面向开发者的数据采集代理解决方案,提供稳定可靠的住宅代理服务。通过 9000 万+全球住宅 IP和 200+国家覆盖、智能轮换机制和精准地区定位能力,帮助爬虫、AI 数据训练、SEO 监控、电商数据分析等项目突破访问限制,提高数据采集效率。支持 Playwright、Selenium、Puppeteer 等主流自动化框架,价格低至 $0.65/GB,<a href="https://www.rapidproxy.io/?ref=sub2api">立即免费测试吧</a>。</td>
@@ -187,7 +182,12 @@
<tr>
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> 以批发价向企业和大用量开发者提供 Claude API。提供标准的 Anthropic Messages API,Claude Code、Sub2API、LiteLLM、One API 无需改代码即可接入。使用邀请码 SUB2API 注册,每次调用立减 5%。</td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> 以批发价向企业和大用量开发者提供 Claude API。提供标准的 Anthropic Messages API,Claude Code、Sub2API、LiteLLM、One API 无需改代码即可接入。使用邀请码 SUB2API 注册,每次调用立减 5%;注册后加入 Telegram 群 @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>),向管理员申请 $10 额度。</td>
</tr>
<tr>
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> 是面向开发者与企业的一站式 AI API 服务平台,通过统一接口接入 OpenAI、Claude、Gemini 等主流模型,覆盖 AI 编程及文本、图像、音频、视频生成。支持 Claude Code、Codex 等主流 AI 编程工具,提供按量付费、实时用量与成本监控,以及 7×24 小时技术支持,让模型接入更便捷、开发成本更可控。新用户通过<a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">此链接</a>注册,可领取使用额度,从代码开发到多模态创作,一站开启 AI 应用之旅!</td>
</tr>
</table>
+6 -6
View File
@@ -119,11 +119,6 @@
<td>FennoAI のご支援に感謝します!FennoAI は、企業の研究開発チームと開発者向けの高安定・高性能 API 中継サービスプロバイダーです。OpenAI と Anthropic のプロトコルに対応し、Codex、Claude Code、OpenCode などの主要 AI コーディングツールにシームレスに接続できます。エンタープライズ級の安定性を備え、1 日あたり千億規模の Token 呼び出しに対応。国内外法人間の企業間決済と請求書発行もサポートし、企業の研究開発・調達ニーズに応えます。Sub2API ユーザー限定特典として、<a href="https://api.fenno.ai/s/dC4k">専用リンク</a>からサブスクリプションを購入すると、わずか 1.99 ドルで 50 ドル相当の Coding Plan クレジットを獲得できます。さらに招待報酬にも対応しており、友達の購入で最大 20% の還元を獲得可能。招待が多いほど、報酬も増えます。</td>
</tr>
<tr>
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
<td>本プロジェクトをご支援いただいている <a href="https://lanox.ai/?c=6">LanoX AI</a> に感謝します!LanoX AI は、開発者、チーム、企業向けに、安定性とコストパフォーマンスに優れたグローバルモデル接続サービスを提供しています。 🎁 新規ユーザー特典 — 数百万 Token を無料で獲得可能。さらに 500+ の無料モデルで、低コストなテスト、検証、デプロイをより簡単に 🧠 世界の主要モデル — GPT · Claude · Gemini · Qwen · Grok... 🎬 マルチモーダル制作 — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ エンタープライズ級の安定性 — 高可用性 💎 ネイティブ能力の出力 💎 性能劣化なし 💎 モデル混在なし 💎 利用量と課金が透明 💎 💰 より低い利用コスト — トップモデルを公式価格の 1 割から利用可能。明確なドキュメント、簡単な接続、請求書発行、企業向け一括利用に対応 🏢 企業に最適 — AI プロダクト、Agent、コンテンツプラットフォーム、大量利用する開発チームに最適</td>
</tr>
<tr>
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> は開発者向けのデータ収集プロキシソリューションであり、安定して信頼できる住宅用プロキシサービスを提供します。9,000 万以上のグローバル住宅 IP と 200 以上の国・地域のカバー、インテリジェントなローテーション機構、精密な地域ターゲティング機能により、クローラー、AI データ学習、SEO モニタリング、EC データ分析などのプロジェクトがアクセス制限を突破し、データ収集の効率を高めます。Playwright、Selenium、Puppeteer などの主要な自動化フレームワークに対応し、料金は $0.65/GB から。<a href="https://www.rapidproxy.io/?ref=sub2api">今すぐ無料でお試しください</a>。</td>
@@ -181,7 +176,12 @@
<tr>
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> は、企業や大量に利用する開発者向けに、Claude API を token 単位の卸売価格で提供しています。標準の Anthropic Messages API を提供しているため、Claude Code、Sub2API、LiteLLM、One API とコードを変更せずに連携できます。招待コード SUB2API で登録すると、すべての呼び出しが 5% オフになります。</td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> は、企業や大量に利用する開発者向けに、Claude API を token 単位の卸売価格で提供しています。標準の Anthropic Messages API を提供しているため、Claude Code、Sub2API、LiteLLM、One API とコードを変更せずに連携できます。招待コード SUB2API で登録すると、すべての呼び出しが 5% オフになります。登録後は Telegram グループ @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>) に参加し、管理者に $10 分のクレジットをリクエストしてください。</td>
</tr>
<tr>
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> は、開発者と企業向けのワンストップ AI API プラットフォームです。統一 API を通じて OpenAI、Claude、Gemini などの主要モデルを利用でき、AI コーディングからテキスト・画像・音声・動画の生成まで幅広く対応しています。Claude Code や Codex などの主要な AI コーディングツールに対応し、従量課金、リアルタイムの利用状況・コスト監視、24時間365日のテクニカルサポートを提供。モデル連携をより手軽にし、開発コストを管理しやすくします。<a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">こちらのリンク</a>から新規登録すると、利用クレジットを受け取れます。コード開発からマルチモーダル制作まで、AI 活用をここから始めましょう!</td>
</tr>
</table>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.27.2-alpine
FROM golang:1.27.4-alpine
WORKDIR /app
+1 -1
View File
@@ -1 +1 @@
0.2.20
0.2.22
+5
View File
@@ -111,6 +111,7 @@ func provideCleanup(
emailQueue *service.EmailQueueService,
billingCache *service.BillingCacheService,
usageRecordWorkerPool *service.UsageRecordWorkerPool,
usageBillingLanes *service.UsageBillingLaneCombiner,
balanceNotify *service.BalanceNotifyService,
digestSessions *service.DigestSessionStore,
subscriptionService *service.SubscriptionService,
@@ -331,6 +332,10 @@ func provideCleanup(
}
return nil
}},
{"UsageBillingLaneCombiner", func() error {
usageBillingLanes.Stop()
return nil
}},
{"OAuthService", func() error {
oauth.Stop()
return nil
+9 -2
View File
@@ -105,7 +105,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
usageLogRepository := repository.NewUsageLogRepository(client, db)
usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator)
opsRepository := repository.NewOpsRepository(db)
usageBillingRepository := repository.NewUsageBillingRepository(client, db)
usageBillingBatchRepository := repository.NewUsageBillingRepository(client, db)
usageBillingLaneCombiner := service.NewUsageBillingLaneCombiner(usageBillingBatchRepository)
usageBillingRepository := service.ProvideUsageBillingRepository(usageBillingLaneCombiner)
gatewayCache := repository.NewGatewayCache(redisClient)
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig)
@@ -359,7 +361,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher)
channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService)
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, usageBillingLaneCombiner, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
application := &Application{
Server: httpServer,
PromptAudit: promptService,
@@ -426,6 +428,7 @@ func provideCleanup(
emailQueue *service.EmailQueueService,
billingCache *service.BillingCacheService,
usageRecordWorkerPool *service.UsageRecordWorkerPool,
usageBillingLanes *service.UsageBillingLaneCombiner,
balanceNotify *service.BalanceNotifyService,
digestSessions *service.DigestSessionStore,
subscriptionService *service.SubscriptionService,
@@ -645,6 +648,10 @@ func provideCleanup(
}
return nil
}},
{"UsageBillingLaneCombiner", func() error {
usageBillingLanes.Stop()
return nil
}},
{"OAuthService", func() error {
oauth.Stop()
return nil
+1
View File
@@ -81,6 +81,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
emailQueueSvc,
billingCacheSvc,
&service.UsageRecordWorkerPool{},
nil, // usageBillingLanes
service.ProvideBalanceNotifyService(nil, nil, nil, nil),
service.NewDigestSessionStore(),
&service.SubscriptionService{},
+12 -1
View File
@@ -128,6 +128,8 @@ type Group struct {
AllowLive bool `json:"allow_live,omitempty"`
// 是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority
ForceOpenaiFast bool `json:"force_openai_fast,omitempty"`
// 是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)
ForceOpenaiUltrafast bool `json:"force_openai_ultrafast,omitempty"`
// 是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费
FreeOpenaiFast bool `json:"free_openai_fast,omitempty"`
// 仅允许非 apikey 类型账号关联到此分组
@@ -264,7 +266,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
switch columns[i] {
case group.FieldI18n, group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings:
values[i] = new([]byte)
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageCountBilling, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageCountBilling, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldForceOpenaiUltrafast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
values[i] = new(sql.NullBool)
case group.FieldRateMultiplier, group.FieldPeakRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k, group.FieldBatchImageDiscountMultiplier, group.FieldBatchImageHoldMultiplier, group.FieldVideoRateMultiplier, group.FieldVideoPrice480p, group.FieldVideoPrice720p, group.FieldVideoPrice1080p, group.FieldWebSearchPricePerCall, group.FieldSearchPricePer1k, group.FieldAudioRealtimePricePerMin, group.FieldAudioTtsPricePerMillionChars, group.FieldAudioSttPricePerHour, group.FieldProfitMinMargin, group.FieldProfitSafetyBuffer:
values[i] = new(sql.NullFloat64)
@@ -648,6 +650,12 @@ func (_m *Group) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.ForceOpenaiFast = value.Bool
}
case group.FieldForceOpenaiUltrafast:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field force_openai_ultrafast", values[i])
} else if value.Valid {
_m.ForceOpenaiUltrafast = value.Bool
}
case group.FieldFreeOpenaiFast:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field free_openai_fast", values[i])
@@ -1016,6 +1024,9 @@ func (_m *Group) String() string {
builder.WriteString("force_openai_fast=")
builder.WriteString(fmt.Sprintf("%v", _m.ForceOpenaiFast))
builder.WriteString(", ")
builder.WriteString("force_openai_ultrafast=")
builder.WriteString(fmt.Sprintf("%v", _m.ForceOpenaiUltrafast))
builder.WriteString(", ")
builder.WriteString("free_openai_fast=")
builder.WriteString(fmt.Sprintf("%v", _m.FreeOpenaiFast))
builder.WriteString(", ")
+10
View File
@@ -124,6 +124,8 @@ const (
FieldAllowLive = "allow_live"
// FieldForceOpenaiFast holds the string denoting the force_openai_fast field in the database.
FieldForceOpenaiFast = "force_openai_fast"
// FieldForceOpenaiUltrafast holds the string denoting the force_openai_ultrafast field in the database.
FieldForceOpenaiUltrafast = "force_openai_ultrafast"
// FieldFreeOpenaiFast holds the string denoting the free_openai_fast field in the database.
FieldFreeOpenaiFast = "free_openai_fast"
// FieldRequireOauthOnly holds the string denoting the require_oauth_only field in the database.
@@ -281,6 +283,7 @@ var Columns = []string{
FieldAllowMessagesDispatch,
FieldAllowLive,
FieldForceOpenaiFast,
FieldForceOpenaiUltrafast,
FieldFreeOpenaiFast,
FieldRequireOauthOnly,
FieldRequirePrivacySet,
@@ -410,6 +413,8 @@ var (
DefaultAllowLive bool
// DefaultForceOpenaiFast holds the default value on creation for the "force_openai_fast" field.
DefaultForceOpenaiFast bool
// DefaultForceOpenaiUltrafast holds the default value on creation for the "force_openai_ultrafast" field.
DefaultForceOpenaiUltrafast bool
// DefaultFreeOpenaiFast holds the default value on creation for the "free_openai_fast" field.
DefaultFreeOpenaiFast bool
// DefaultRequireOauthOnly holds the default value on creation for the "require_oauth_only" field.
@@ -699,6 +704,11 @@ func ByForceOpenaiFast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldForceOpenaiFast, opts...).ToFunc()
}
// ByForceOpenaiUltrafast orders the results by the force_openai_ultrafast field.
func ByForceOpenaiUltrafast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldForceOpenaiUltrafast, opts...).ToFunc()
}
// ByFreeOpenaiFast orders the results by the free_openai_fast field.
func ByFreeOpenaiFast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFreeOpenaiFast, opts...).ToFunc()
+15
View File
@@ -300,6 +300,11 @@ func ForceOpenaiFast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiFast, v))
}
// ForceOpenaiUltrafast applies equality check predicate on the "force_openai_ultrafast" field. It's identical to ForceOpenaiUltrafastEQ.
func ForceOpenaiUltrafast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiUltrafast, v))
}
// FreeOpenaiFast applies equality check predicate on the "free_openai_fast" field. It's identical to FreeOpenaiFastEQ.
func FreeOpenaiFast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldFreeOpenaiFast, v))
@@ -2310,6 +2315,16 @@ func ForceOpenaiFastNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldForceOpenaiFast, v))
}
// ForceOpenaiUltrafastEQ applies the EQ predicate on the "force_openai_ultrafast" field.
func ForceOpenaiUltrafastEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiUltrafast, v))
}
// ForceOpenaiUltrafastNEQ applies the NEQ predicate on the "force_openai_ultrafast" field.
func ForceOpenaiUltrafastNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldForceOpenaiUltrafast, v))
}
// FreeOpenaiFastEQ applies the EQ predicate on the "free_openai_fast" field.
func FreeOpenaiFastEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldFreeOpenaiFast, v))
+65
View File
@@ -738,6 +738,20 @@ func (_c *GroupCreate) SetNillableForceOpenaiFast(v *bool) *GroupCreate {
return _c
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_c *GroupCreate) SetForceOpenaiUltrafast(v bool) *GroupCreate {
_c.mutation.SetForceOpenaiUltrafast(v)
return _c
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_c *GroupCreate) SetNillableForceOpenaiUltrafast(v *bool) *GroupCreate {
if v != nil {
_c.SetForceOpenaiUltrafast(*v)
}
return _c
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_c *GroupCreate) SetFreeOpenaiFast(v bool) *GroupCreate {
_c.mutation.SetFreeOpenaiFast(v)
@@ -1183,6 +1197,10 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultForceOpenaiFast
_c.mutation.SetForceOpenaiFast(v)
}
if _, ok := _c.mutation.ForceOpenaiUltrafast(); !ok {
v := group.DefaultForceOpenaiUltrafast
_c.mutation.SetForceOpenaiUltrafast(v)
}
if _, ok := _c.mutation.FreeOpenaiFast(); !ok {
v := group.DefaultFreeOpenaiFast
_c.mutation.SetFreeOpenaiFast(v)
@@ -1395,6 +1413,9 @@ func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.ForceOpenaiFast(); !ok {
return &ValidationError{Name: "force_openai_fast", err: errors.New(`ent: missing required field "Group.force_openai_fast"`)}
}
if _, ok := _c.mutation.ForceOpenaiUltrafast(); !ok {
return &ValidationError{Name: "force_openai_ultrafast", err: errors.New(`ent: missing required field "Group.force_openai_ultrafast"`)}
}
if _, ok := _c.mutation.FreeOpenaiFast(); !ok {
return &ValidationError{Name: "free_openai_fast", err: errors.New(`ent: missing required field "Group.free_openai_fast"`)}
}
@@ -1695,6 +1716,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
_node.ForceOpenaiFast = value
}
if value, ok := _c.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
_node.ForceOpenaiUltrafast = value
}
if value, ok := _c.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
_node.FreeOpenaiFast = value
@@ -2801,6 +2826,18 @@ func (u *GroupUpsert) UpdateForceOpenaiFast() *GroupUpsert {
return u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsert) SetForceOpenaiUltrafast(v bool) *GroupUpsert {
u.Set(group.FieldForceOpenaiUltrafast, v)
return u
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsert) UpdateForceOpenaiUltrafast() *GroupUpsert {
u.SetExcluded(group.FieldForceOpenaiUltrafast)
return u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsert) SetFreeOpenaiFast(v bool) *GroupUpsert {
u.Set(group.FieldFreeOpenaiFast, v)
@@ -4078,6 +4115,20 @@ func (u *GroupUpsertOne) UpdateForceOpenaiFast() *GroupUpsertOne {
})
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsertOne) SetForceOpenaiUltrafast(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetForceOpenaiUltrafast(v)
})
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdateForceOpenaiUltrafast() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdateForceOpenaiUltrafast()
})
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsertOne) SetFreeOpenaiFast(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
@@ -5552,6 +5603,20 @@ func (u *GroupUpsertBulk) UpdateForceOpenaiFast() *GroupUpsertBulk {
})
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsertBulk) SetForceOpenaiUltrafast(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetForceOpenaiUltrafast(v)
})
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdateForceOpenaiUltrafast() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdateForceOpenaiUltrafast()
})
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsertBulk) SetFreeOpenaiFast(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
+34
View File
@@ -1023,6 +1023,20 @@ func (_u *GroupUpdate) SetNillableForceOpenaiFast(v *bool) *GroupUpdate {
return _u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_u *GroupUpdate) SetForceOpenaiUltrafast(v bool) *GroupUpdate {
_u.mutation.SetForceOpenaiUltrafast(v)
return _u
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableForceOpenaiUltrafast(v *bool) *GroupUpdate {
if v != nil {
_u.SetForceOpenaiUltrafast(*v)
}
return _u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_u *GroupUpdate) SetFreeOpenaiFast(v bool) *GroupUpdate {
_u.mutation.SetFreeOpenaiFast(v)
@@ -1887,6 +1901,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.ForceOpenaiFast(); ok {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
}
if value, ok := _u.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
}
if value, ok := _u.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
}
@@ -3243,6 +3260,20 @@ func (_u *GroupUpdateOne) SetNillableForceOpenaiFast(v *bool) *GroupUpdateOne {
return _u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_u *GroupUpdateOne) SetForceOpenaiUltrafast(v bool) *GroupUpdateOne {
_u.mutation.SetForceOpenaiUltrafast(v)
return _u
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableForceOpenaiUltrafast(v *bool) *GroupUpdateOne {
if v != nil {
_u.SetForceOpenaiUltrafast(*v)
}
return _u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_u *GroupUpdateOne) SetFreeOpenaiFast(v bool) *GroupUpdateOne {
_u.mutation.SetFreeOpenaiFast(v)
@@ -4137,6 +4168,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if value, ok := _u.mutation.ForceOpenaiFast(); ok {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
}
if value, ok := _u.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
}
if value, ok := _u.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
}
+1
View File
@@ -957,6 +957,7 @@ var (
{Name: "allow_messages_dispatch", Type: field.TypeBool, Default: false},
{Name: "allow_live", Type: field.TypeBool, Default: false},
{Name: "force_openai_fast", Type: field.TypeBool, Default: false},
{Name: "force_openai_ultrafast", Type: field.TypeBool, Default: false},
{Name: "free_openai_fast", Type: field.TypeBool, Default: false},
{Name: "require_oauth_only", Type: field.TypeBool, Default: false},
{Name: "require_privacy_set", Type: field.TypeBool, Default: false},
+55 -1
View File
@@ -22161,6 +22161,7 @@ type GroupMutation struct {
allow_messages_dispatch *bool
allow_live *bool
force_openai_fast *bool
force_openai_ultrafast *bool
free_openai_fast *bool
require_oauth_only *bool
require_privacy_set *bool
@@ -25058,6 +25059,42 @@ func (m *GroupMutation) ResetForceOpenaiFast() {
m.force_openai_fast = nil
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (m *GroupMutation) SetForceOpenaiUltrafast(b bool) {
m.force_openai_ultrafast = &b
}
// ForceOpenaiUltrafast returns the value of the "force_openai_ultrafast" field in the mutation.
func (m *GroupMutation) ForceOpenaiUltrafast() (r bool, exists bool) {
v := m.force_openai_ultrafast
if v == nil {
return
}
return *v, true
}
// OldForceOpenaiUltrafast returns the old "force_openai_ultrafast" field's value of the Group entity.
// If the Group object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupMutation) OldForceOpenaiUltrafast(ctx context.Context) (v bool, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldForceOpenaiUltrafast is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldForceOpenaiUltrafast requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldForceOpenaiUltrafast: %w", err)
}
return oldValue.ForceOpenaiUltrafast, nil
}
// ResetForceOpenaiUltrafast resets all changes to the "force_openai_ultrafast" field.
func (m *GroupMutation) ResetForceOpenaiUltrafast() {
m.force_openai_ultrafast = nil
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (m *GroupMutation) SetFreeOpenaiFast(b bool) {
m.free_openai_fast = &b
@@ -25995,7 +26032,7 @@ func (m *GroupMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *GroupMutation) Fields() []string {
fields := make([]string, 0, 68)
fields := make([]string, 0, 69)
if m.created_at != nil {
fields = append(fields, group.FieldCreatedAt)
}
@@ -26158,6 +26195,9 @@ func (m *GroupMutation) Fields() []string {
if m.force_openai_fast != nil {
fields = append(fields, group.FieldForceOpenaiFast)
}
if m.force_openai_ultrafast != nil {
fields = append(fields, group.FieldForceOpenaiUltrafast)
}
if m.free_openai_fast != nil {
fields = append(fields, group.FieldFreeOpenaiFast)
}
@@ -26316,6 +26356,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
return m.AllowLive()
case group.FieldForceOpenaiFast:
return m.ForceOpenaiFast()
case group.FieldForceOpenaiUltrafast:
return m.ForceOpenaiUltrafast()
case group.FieldFreeOpenaiFast:
return m.FreeOpenaiFast()
case group.FieldRequireOauthOnly:
@@ -26461,6 +26503,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldAllowLive(ctx)
case group.FieldForceOpenaiFast:
return m.OldForceOpenaiFast(ctx)
case group.FieldForceOpenaiUltrafast:
return m.OldForceOpenaiUltrafast(ctx)
case group.FieldFreeOpenaiFast:
return m.OldFreeOpenaiFast(ctx)
case group.FieldRequireOauthOnly:
@@ -26876,6 +26920,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
}
m.SetForceOpenaiFast(v)
return nil
case group.FieldForceOpenaiUltrafast:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetForceOpenaiUltrafast(v)
return nil
case group.FieldFreeOpenaiFast:
v, ok := value.(bool)
if !ok {
@@ -27647,6 +27698,9 @@ func (m *GroupMutation) ResetField(name string) error {
case group.FieldForceOpenaiFast:
m.ResetForceOpenaiFast()
return nil
case group.FieldForceOpenaiUltrafast:
m.ResetForceOpenaiUltrafast()
return nil
case group.FieldFreeOpenaiFast:
m.ResetFreeOpenaiFast()
return nil
+18 -14
View File
@@ -1183,66 +1183,70 @@ func init() {
groupDescForceOpenaiFast := groupFields[50].Descriptor()
// group.DefaultForceOpenaiFast holds the default value on creation for the force_openai_fast field.
group.DefaultForceOpenaiFast = groupDescForceOpenaiFast.Default.(bool)
// groupDescForceOpenaiUltrafast is the schema descriptor for force_openai_ultrafast field.
groupDescForceOpenaiUltrafast := groupFields[51].Descriptor()
// group.DefaultForceOpenaiUltrafast holds the default value on creation for the force_openai_ultrafast field.
group.DefaultForceOpenaiUltrafast = groupDescForceOpenaiUltrafast.Default.(bool)
// groupDescFreeOpenaiFast is the schema descriptor for free_openai_fast field.
groupDescFreeOpenaiFast := groupFields[51].Descriptor()
groupDescFreeOpenaiFast := groupFields[52].Descriptor()
// group.DefaultFreeOpenaiFast holds the default value on creation for the free_openai_fast field.
group.DefaultFreeOpenaiFast = groupDescFreeOpenaiFast.Default.(bool)
// groupDescRequireOauthOnly is the schema descriptor for require_oauth_only field.
groupDescRequireOauthOnly := groupFields[52].Descriptor()
groupDescRequireOauthOnly := groupFields[53].Descriptor()
// group.DefaultRequireOauthOnly holds the default value on creation for the require_oauth_only field.
group.DefaultRequireOauthOnly = groupDescRequireOauthOnly.Default.(bool)
// groupDescRequirePrivacySet is the schema descriptor for require_privacy_set field.
groupDescRequirePrivacySet := groupFields[53].Descriptor()
groupDescRequirePrivacySet := groupFields[54].Descriptor()
// group.DefaultRequirePrivacySet holds the default value on creation for the require_privacy_set field.
group.DefaultRequirePrivacySet = groupDescRequirePrivacySet.Default.(bool)
// groupDescDefaultMappedModel is the schema descriptor for default_mapped_model field.
groupDescDefaultMappedModel := groupFields[54].Descriptor()
groupDescDefaultMappedModel := groupFields[55].Descriptor()
// group.DefaultDefaultMappedModel holds the default value on creation for the default_mapped_model field.
group.DefaultDefaultMappedModel = groupDescDefaultMappedModel.Default.(string)
// group.DefaultMappedModelValidator is a validator for the "default_mapped_model" field. It is called by the builders before save.
group.DefaultMappedModelValidator = groupDescDefaultMappedModel.Validators[0].(func(string) error)
// groupDescMessagesDispatchModelConfig is the schema descriptor for messages_dispatch_model_config field.
groupDescMessagesDispatchModelConfig := groupFields[55].Descriptor()
groupDescMessagesDispatchModelConfig := groupFields[56].Descriptor()
// group.DefaultMessagesDispatchModelConfig holds the default value on creation for the messages_dispatch_model_config field.
group.DefaultMessagesDispatchModelConfig = groupDescMessagesDispatchModelConfig.Default.(domain.OpenAIMessagesDispatchModelConfig)
// groupDescModelAllowlist is the schema descriptor for model_allowlist field.
groupDescModelAllowlist := groupFields[56].Descriptor()
groupDescModelAllowlist := groupFields[57].Descriptor()
// group.DefaultModelAllowlist holds the default value on creation for the model_allowlist field.
group.DefaultModelAllowlist = groupDescModelAllowlist.Default.(domain.GroupModelAllowlist)
// groupDescCodexModelsManifestConfig is the schema descriptor for codex_models_manifest_config field.
groupDescCodexModelsManifestConfig := groupFields[57].Descriptor()
groupDescCodexModelsManifestConfig := groupFields[58].Descriptor()
// group.DefaultCodexModelsManifestConfig holds the default value on creation for the codex_models_manifest_config field.
group.DefaultCodexModelsManifestConfig = groupDescCodexModelsManifestConfig.Default.(domain.GroupCodexModelsManifestConfig)
// groupDescRpmLimit is the schema descriptor for rpm_limit field.
groupDescRpmLimit := groupFields[58].Descriptor()
groupDescRpmLimit := groupFields[59].Descriptor()
// group.DefaultRpmLimit holds the default value on creation for the rpm_limit field.
group.DefaultRpmLimit = groupDescRpmLimit.Default.(int)
// groupDescMaxReasoningEffort is the schema descriptor for max_reasoning_effort field.
groupDescMaxReasoningEffort := groupFields[59].Descriptor()
groupDescMaxReasoningEffort := groupFields[60].Descriptor()
// group.DefaultMaxReasoningEffort holds the default value on creation for the max_reasoning_effort field.
group.DefaultMaxReasoningEffort = groupDescMaxReasoningEffort.Default.(string)
// group.MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save.
group.MaxReasoningEffortValidator = groupDescMaxReasoningEffort.Validators[0].(func(string) error)
// groupDescMaxReasoningEffortOverLimit is the schema descriptor for max_reasoning_effort_over_limit field.
groupDescMaxReasoningEffortOverLimit := groupFields[60].Descriptor()
groupDescMaxReasoningEffortOverLimit := groupFields[61].Descriptor()
// group.DefaultMaxReasoningEffortOverLimit holds the default value on creation for the max_reasoning_effort_over_limit field.
group.DefaultMaxReasoningEffortOverLimit = groupDescMaxReasoningEffortOverLimit.Default.(string)
// group.MaxReasoningEffortOverLimitValidator is a validator for the "max_reasoning_effort_over_limit" field. It is called by the builders before save.
group.MaxReasoningEffortOverLimitValidator = groupDescMaxReasoningEffortOverLimit.Validators[0].(func(string) error)
// groupDescReasoningEffortMappings is the schema descriptor for reasoning_effort_mappings field.
groupDescReasoningEffortMappings := groupFields[61].Descriptor()
groupDescReasoningEffortMappings := groupFields[62].Descriptor()
// group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field.
group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping)
// groupDescProfitControlEnabled is the schema descriptor for profit_control_enabled field.
groupDescProfitControlEnabled := groupFields[62].Descriptor()
groupDescProfitControlEnabled := groupFields[63].Descriptor()
// group.DefaultProfitControlEnabled holds the default value on creation for the profit_control_enabled field.
group.DefaultProfitControlEnabled = groupDescProfitControlEnabled.Default.(bool)
// groupDescProfitMinMargin is the schema descriptor for profit_min_margin field.
groupDescProfitMinMargin := groupFields[63].Descriptor()
groupDescProfitMinMargin := groupFields[64].Descriptor()
// group.DefaultProfitMinMargin holds the default value on creation for the profit_min_margin field.
group.DefaultProfitMinMargin = groupDescProfitMinMargin.Default.(float64)
// groupDescProfitSafetyBuffer is the schema descriptor for profit_safety_buffer field.
groupDescProfitSafetyBuffer := groupFields[64].Descriptor()
groupDescProfitSafetyBuffer := groupFields[65].Descriptor()
// group.DefaultProfitSafetyBuffer holds the default value on creation for the profit_safety_buffer field.
group.DefaultProfitSafetyBuffer = groupDescProfitSafetyBuffer.Default.(float64)
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
+3
View File
@@ -253,6 +253,9 @@ func (Group) Fields() []ent.Field {
field.Bool("force_openai_fast").
Default(false).
Comment("是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority"),
field.Bool("force_openai_ultrafast").
Default(false).
Comment("是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)"),
field.Bool("free_openai_fast").
Default(false).
Comment("是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费"),
+2 -2
View File
@@ -1,6 +1,6 @@
module github.com/Wei-Shaw/sub2api
go 1.27.3
go 1.27.4
require (
entgo.io/ent v0.14.5
@@ -23,6 +23,7 @@ require (
github.com/go-playground/validator/v10 v10.14.0
github.com/go-webauthn/webauthn v0.17.4
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/jsonschema-go v0.4.2
github.com/google/uuid v1.6.0
github.com/google/wire v0.7.0
github.com/gorilla/websocket v1.5.3
@@ -130,7 +131,6 @@ require (
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/go-tpm v0.9.8 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/hcl/v2 v2.18.1 // indirect
+3 -3
View File
@@ -1025,7 +1025,7 @@ type CircuitBreakerConfig struct {
}
type ConcurrencyConfig struct {
// PingInterval: 并发等待期间的 SSE ping 间隔(秒)
// PingInterval: 并发等待期间的 SSE ping 间隔(秒),0 禁用 ping
PingInterval int `mapstructure:"ping_interval"`
}
@@ -3887,8 +3887,8 @@ func (c *Config) Validate() error {
if c.Ops.Cleanup.Enabled && strings.TrimSpace(c.Ops.Cleanup.Schedule) == "" {
return fmt.Errorf("ops.cleanup.schedule is required when ops.cleanup.enabled=true")
}
if c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30 {
return fmt.Errorf("concurrency.ping_interval must be between 5-30 seconds")
if c.Concurrency.PingInterval != 0 && (c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30) {
return fmt.Errorf("concurrency.ping_interval must be 0 (disabled) or between 5-30 seconds")
}
if c.Gateway.Grok.FreeQuotaSoftGateEnabled {
if c.Gateway.Grok.FreeQuotaTokenLimit <= 0 {
+14 -12
View File
@@ -1577,18 +1577,20 @@ func TestValidateOpsCleanupScheduleRequired(t *testing.T) {
func TestValidateConcurrencyPingInterval(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
cfg.Concurrency.PingInterval = 3
err = cfg.Validate()
if err == nil {
t.Fatalf("Validate() expected error for concurrency.ping_interval")
}
if !strings.Contains(err.Error(), "concurrency.ping_interval") {
t.Fatalf("Validate() expected concurrency.ping_interval error, got: %v", err)
for _, interval := range []int{-1, 0, 1, 3, 4, 5, 10, 30, 31} {
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
cfg.Concurrency.PingInterval = interval
err = cfg.Validate()
valid := interval == 0 || (interval >= 5 && interval <= 30)
if valid && err != nil {
t.Errorf("Validate() interval %d: %v", interval, err)
}
if !valid && (err == nil || !strings.Contains(err.Error(), "concurrency.ping_interval")) {
t.Errorf("Validate() interval %d: expected concurrency.ping_interval error, got %v", interval, err)
}
}
}
+7 -3
View File
@@ -178,7 +178,9 @@ var DefaultAntigravityModelMapping = map[string]string{
"gemini-3.8-flash-low": "gemini-3.8-flash-low",
"gemini-3.8-flash-medium": "gemini-3.8-flash-medium",
"gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered",
// Gemini 4 Argon tiered models
// Gemini 4 models
// Carbon uses the published model ID; do not infer Argon-style tier aliases.
"gemini-4-carbon": "gemini-4-carbon",
"gemini-4-argon": "gemini-4-argon-high",
"gemini-4-argon-high": "gemini-4-argon-high",
"gemini-4-argon-low": "gemini-4-argon-low",
@@ -197,8 +199,10 @@ var DefaultAntigravityModelMapping = map[string]string{
// aws_region 自动调整为匹配的区域前缀(如 eu.、apac.、jp. 等)
var DefaultBedrockModelMapping = map[string]string{
// Claude Fable
"claude-fable-5-1": "anthropic.claude-fable-5-1",
"claude-fable-5": "anthropic.claude-fable-5",
"claude-fable-5-2": "anthropic.claude-fable-5-2",
"claude-mythos-5-2": "anthropic.claude-mythos-5-2",
"claude-fable-5-1": "anthropic.claude-fable-5-1",
"claude-fable-5": "anthropic.claude-fable-5",
// Claude Opus
"claude-opus-5": "us.anthropic.claude-opus-5-v1",
"claude-opus-4-8": "us.anthropic.claude-opus-4-8-v1",
@@ -107,6 +107,7 @@ func TestDefaultAntigravityModelMapping_Gemini38FlashModels(t *testing.T) {
func TestDefaultAntigravityModelMapping_Gemini4ArgonAndClaude55Models(t *testing.T) {
cases := map[string]string{
"gemini-4-carbon": "gemini-4-carbon",
"gemini-4-argon": "gemini-4-argon-high",
"gemini-4-argon-high": "gemini-4-argon-high",
"gemini-4-argon-low": "gemini-4-argon-low",
@@ -131,6 +132,8 @@ func TestDefaultBedrockModelMapping_ContainsNewClaudeModels(t *testing.T) {
t.Parallel()
cases := map[string]string{
"claude-fable-5-2": "anthropic.claude-fable-5-2",
"claude-mythos-5-2": "anthropic.claude-mythos-5-2",
"claude-fable-5-1": "anthropic.claude-fable-5-1",
"claude-fable-5": "anthropic.claude-fable-5",
"claude-opus-4-8": "us.anthropic.claude-opus-4-8-v1",
@@ -239,6 +239,7 @@ type CreateGroupRequest struct {
AllowMessagesDispatch bool `json:"allow_messages_dispatch"`
AllowLive bool `json:"allow_live"`
ForceOpenAIFast bool `json:"force_openai_fast"`
ForceOpenAIUltrafast bool `json:"force_openai_ultrafast"`
FreeOpenAIFast bool `json:"free_openai_fast"`
RequireOAuthOnly bool `json:"require_oauth_only"`
RequirePrivacySet bool `json:"require_privacy_set"`
@@ -316,6 +317,7 @@ type UpdateGroupRequest struct {
AllowMessagesDispatch *bool `json:"allow_messages_dispatch"`
AllowLive *bool `json:"allow_live"`
ForceOpenAIFast *bool `json:"force_openai_fast"`
ForceOpenAIUltrafast *bool `json:"force_openai_ultrafast"`
FreeOpenAIFast *bool `json:"free_openai_fast"`
RequireOAuthOnly *bool `json:"require_oauth_only"`
RequirePrivacySet *bool `json:"require_privacy_set"`
@@ -719,6 +721,7 @@ func (h *GroupHandler) Create(c *gin.Context) {
AllowMessagesDispatch: req.AllowMessagesDispatch,
AllowLive: req.AllowLive,
ForceOpenAIFast: req.ForceOpenAIFast,
ForceOpenAIUltrafast: req.ForceOpenAIUltrafast,
FreeOpenAIFast: req.FreeOpenAIFast,
RequireOAuthOnly: req.RequireOAuthOnly,
RequirePrivacySet: req.RequirePrivacySet,
@@ -867,6 +870,7 @@ func (h *GroupHandler) Update(c *gin.Context) {
AllowMessagesDispatch: req.AllowMessagesDispatch,
AllowLive: req.AllowLive,
ForceOpenAIFast: req.ForceOpenAIFast,
ForceOpenAIUltrafast: req.ForceOpenAIUltrafast,
FreeOpenAIFast: req.FreeOpenAIFast,
RequireOAuthOnly: req.RequireOAuthOnly,
RequirePrivacySet: req.RequirePrivacySet,
@@ -25,3 +25,21 @@ func TestGroupRequestsDecodeForceOpenAIFast(t *testing.T) {
require.Nil(t, omitted.ForceOpenAIFast)
require.Nil(t, omitted.FreeOpenAIFast)
}
func TestGroupRequestsDecodeForceOpenAIUltrafast(t *testing.T) {
var createReq CreateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{"name":"ultrafast","force_openai_ultrafast":true}`), &createReq))
require.True(t, createReq.ForceOpenAIUltrafast)
require.False(t, createReq.ForceOpenAIFast)
var updateReq UpdateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{"force_openai_fast":false,"force_openai_ultrafast":true}`), &updateReq))
require.NotNil(t, updateReq.ForceOpenAIUltrafast)
require.True(t, *updateReq.ForceOpenAIUltrafast)
require.NotNil(t, updateReq.ForceOpenAIFast)
require.False(t, *updateReq.ForceOpenAIFast)
var omitted UpdateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{}`), &omitted))
require.Nil(t, omitted.ForceOpenAIUltrafast)
}
@@ -2881,6 +2881,10 @@ func (s *oauthPendingFlowRefreshTokenCacheStub) DeleteTokenFamily(context.Contex
return nil
}
func (s *oauthPendingFlowRefreshTokenCacheStub) ConsumeRefreshToken(context.Context, string) (*service.RefreshTokenData, error) {
return nil, service.ErrRefreshTokenNotFound
}
func (s *oauthPendingFlowRefreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error {
return nil
}
@@ -1478,6 +1478,10 @@ func (s *wechatOAuthRefreshTokenCacheStub) DeleteTokenFamily(context.Context, st
return nil
}
func (s *wechatOAuthRefreshTokenCacheStub) ConsumeRefreshToken(context.Context, string) (*service.RefreshTokenData, error) {
return nil, service.ErrRefreshTokenNotFound
}
func (s *wechatOAuthRefreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error {
return nil
}
+11 -7
View File
@@ -163,16 +163,20 @@ func bindOpenAIReasoningEffortPolicyForMessagesRequest(c *gin.Context, apiKey *s
return
}
bindRequestedReasoningEffort(c, body, strings.TrimSpace(gjson.GetBytes(body, "model").String()))
// The Messages bridge synthesizes a default OpenAI effort when
// output_config.effort is omitted. Bind the group policy only for an
// explicit client value so the ceiling does not alter that default.
effort := gjson.GetBytes(body, "output_config.effort")
if !effort.Exists() || effort.Type != gjson.String || strings.TrimSpace(effort.String()) == "" {
return
isCNTarget := service.IsCNProvider(effectiveAPIKeyPlatform(c, apiKey))
if isCNTarget {
effort := gjson.GetBytes(body, "output_config.effort")
if effort.Type != gjson.String || strings.TrimSpace(effort.String()) == "" {
return
}
}
maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey)
if !ok {
return
}
c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicy(c.Request.Context(), maxEffort, mappings, overLimit))
if isCNTarget {
c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicy(c.Request.Context(), maxEffort, mappings, overLimit))
return
}
c.Request = c.Request.WithContext(service.WithOpenAIReasoningEffortPolicyForMessages(c.Request.Context(), body, maxEffort, mappings, overLimit))
}
@@ -133,14 +133,34 @@ func TestOpenAIReasoningEffortPolicyForCompositeTarget(t *testing.T) {
require.True(t, changed)
require.JSONEq(t, `{"reasoning":{"effort":"medium"}}`, string(bound))
omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder())
omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil)
omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI))
bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, apiKey, []byte(`{"model":"gpt-5"}`))
omitted, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), body)
require.NoError(t, err)
require.False(t, changed)
require.Equal(t, body, omitted)
synthesizedGroup := &service.Group{
Platform: service.PlatformComposite,
ReasoningEffortMappings: []service.ReasoningEffortMapping{
{From: "medium", To: "low"},
{From: "none", To: "low"},
},
}
synthesizedAPIKey := &service.APIKey{Group: synthesizedGroup}
for _, tc := range []struct {
name string
request string
response string
want string
}{
{name: "default medium", request: `{"model":"gpt-5"}`, response: `{"reasoning":{"effort":"medium"}}`, want: "medium"},
{name: "disabled thinking none", request: `{"model":"gpt-5","thinking":{"type":"disabled"}}`, response: `{"reasoning":{"effort":"none"}}`, want: "low"},
} {
t.Run(tc.name, func(t *testing.T) {
omittedCtx, _ := gin.CreateTestContext(httptest.NewRecorder())
omittedCtx.Request = httptest.NewRequest("POST", "/v1/messages", nil)
omittedCtx.Request = omittedCtx.Request.WithContext(service.WithResolvedTargetPlatform(omittedCtx.Request.Context(), service.PlatformOpenAI))
bindOpenAIReasoningEffortPolicyForMessagesRequest(omittedCtx, synthesizedAPIKey, []byte(tc.request))
got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(omittedCtx.Request.Context(), []byte(tc.response))
require.NoError(t, err)
require.Equal(t, tc.want != "medium", changed)
require.Equal(t, tc.want, gjson.GetBytes(got, "reasoning.effort").String())
})
}
denyGroup := *group
denyGroup.MaxReasoningEffortOverLimit = service.ReasoningEffortOverLimitDeny
@@ -23,3 +23,18 @@ func TestGroupMapperExposesForceOpenAIFastOnlyToAdmins(t *testing.T) {
require.Contains(t, string(adminJSON), `"force_openai_fast":true`)
require.Contains(t, string(adminJSON), `"free_openai_fast":true`)
}
func TestGroupMapperExposesForceOpenAIUltrafastOnlyToAdmins(t *testing.T) {
group := &service.Group{
ID: 7, Name: "ultrafast", Platform: service.PlatformOpenAI, Status: service.StatusActive, ForceOpenAIUltrafast: true,
}
userJSON, err := json.Marshal(GroupFromService(group))
require.NoError(t, err)
require.NotContains(t, string(userJSON), "force_openai_ultrafast")
adminJSON, err := json.Marshal(GroupFromServiceAdmin(group))
require.NoError(t, err)
require.Contains(t, string(adminJSON), `"force_openai_ultrafast":true`)
require.Contains(t, string(adminJSON), `"force_openai_fast":false`)
}
+1
View File
@@ -149,6 +149,7 @@ func GroupFromServiceAdmin(g *service.Group) *AdminGroup {
out := &AdminGroup{
Group: groupFromServiceBase(g),
ForceOpenAIFast: g.ForceOpenAIFast,
ForceOpenAIUltrafast: g.ForceOpenAIUltrafast,
FreeOpenAIFast: g.FreeOpenAIFast,
ProfitControlEnabled: g.ProfitControlEnabled,
ProfitMinMargin: g.ProfitMinMargin,
+2 -1
View File
@@ -172,7 +172,8 @@ type Group struct {
type AdminGroup struct {
Group
// ForceOpenAIFast 是管理端请求策略,用户侧分组 DTO 无需暴露。
ForceOpenAIFast bool `json:"force_openai_fast"`
ForceOpenAIFast bool `json:"force_openai_fast"`
ForceOpenAIUltrafast bool `json:"force_openai_ultrafast"`
// FreeOpenAIFast 是管理端计费策略,用户侧分组 DTO 无需暴露。
FreeOpenAIFast bool `json:"free_openai_fast"`
@@ -0,0 +1,163 @@
//go:build unit
package handler
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
type compatEffortPolicyUpstream struct {
service.HTTPUpstream
bodies [][]byte
}
func (u *compatEffortPolicyUpstream) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
u.bodies = append(u.bodies, body)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)),
}, nil
}
func TestGatewayCompatibilityHandlersReasoningEffortPolicy(t *testing.T) {
gin.SetMode(gin.TestMode)
const model = "claude-sonnet-4.5"
for _, endpoint := range []string{"chat/completions", "responses"} {
for _, platform := range []string{service.PlatformAnthropic, service.PlatformComposite} {
for _, stream := range []bool{false, true} {
for _, tc := range []struct {
name string
effort string
ceiling string
overLimit string
mappings []service.ReasoningEffortMapping
want string
denied bool
}{
{name: "ceiling", effort: "high", ceiling: "medium", want: "medium"},
{name: "mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low"}}, want: "low"},
{name: "mapping then ceiling", effort: "low", ceiling: "medium", mappings: []service.ReasoningEffortMapping{{From: "low", To: "high"}}, want: "medium"},
{name: "model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: model}}, want: "low"},
{name: "other model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: "other-model"}}, want: "high"},
{name: "deny ceiling", effort: "high", ceiling: "medium", overLimit: service.ReasoningEffortOverLimitDeny, denied: true},
{name: "deny mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "deny"}}, denied: true},
{name: "within ceiling", effort: "low", ceiling: "medium", want: "low"},
{name: "no policy", effort: "high", want: "high"},
{name: "omitted", ceiling: "medium"},
} {
t.Run(fmt.Sprintf("%s/%s/stream=%t/%s", endpoint, platform, stream, tc.name), func(t *testing.T) {
cfg := &config.Config{}
groupID := int64(9400)
group := &service.Group{
ID: groupID, Hydrated: true, Platform: platform, Status: service.StatusActive, RateMultiplier: 1,
MaxReasoningEffort: tc.ceiling, MaxReasoningEffortOverLimit: tc.overLimit, ReasoningEffortMappings: tc.mappings,
}
account := &service.Account{
ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
Credentials: map[string]any{"api_key": "test-key"},
AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}},
}
cache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
snapshot := service.NewSchedulerSnapshotService(cache, nil, nil, nil, nil)
upstream := &compatEffortPolicyUpstream{}
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
billingRepo := &compatStreamUsageBillingRepo{}
billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
gateway := service.NewGatewayService(
nil, &fakeGroupRepo{group: group}, usageRepo, billingRepo, nil, nil, nil, nil, cfg,
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
h := &GatewayHandler{
gatewayService: gateway, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
}
request := map[string]any{"model": model, "stream": stream}
if endpoint == "chat/completions" {
request["messages"] = []map[string]string{{"role": "user", "content": "hello"}}
if tc.effort != "" {
request["reasoning_effort"] = tc.effort
}
} else {
request["input"] = "hello"
if tc.effort != "" {
request["reasoning"] = map[string]string{"effort": tc.effort}
}
}
body, err := json.Marshal(request)
require.NoError(t, err)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewReader(body)).WithContext(ctx)
c.Request.Header.Set("Content-Type", "application/json")
apiKey := &service.APIKey{
ID: 9402, UserID: 9403, GroupID: &groupID, Group: group,
User: &service.User{ID: 9403, Balance: 100},
}
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
if endpoint == "chat/completions" {
h.ChatCompletions(c)
} else {
h.Responses(c)
}
if tc.denied {
require.Equal(t, http.StatusForbidden, recorder.Code, recorder.Body.String())
errorField := "error.type"
if endpoint == "responses" {
errorField = "error.code"
}
require.Equal(t, "permission_error", gjson.Get(recorder.Body.String(), errorField).String())
require.Empty(t, upstream.bodies)
require.Zero(t, cache.snapshotCalls.Load(), "local policy denial precedes account selection")
require.Empty(t, usageRepo.created)
require.Empty(t, billingRepo.commands)
return
}
// Check the final Anthropic request, beyond handler parsing and both protocol conversions.
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Len(t, upstream.bodies, 1)
require.Equal(t, tc.want, gjson.GetBytes(upstream.bodies[0], "output_config.effort").String())
require.Equal(t, model, gjson.GetBytes(upstream.bodies[0], "model").String())
require.Contains(t, recorder.Body.String(), "partial")
require.Len(t, usageRepo.created, 1)
usage := <-usageRepo.created
if tc.effort == "" {
require.Nil(t, usage.RequestedReasoningEffort)
} else {
require.Equal(t, &tc.effort, usage.RequestedReasoningEffort)
require.Equal(t, &tc.want, usage.ReasoningEffort)
}
})
}
}
}
}
}
+11 -3
View File
@@ -80,7 +80,7 @@ func NewGatewayHandler(
cfg *config.Config,
settingService *service.SettingService,
) *GatewayHandler {
pingInterval := time.Duration(0)
pingInterval := defaultPingInterval
maxAccountSwitches := 10
maxAccountSwitchesGemini := 3
if cfg != nil {
@@ -915,6 +915,10 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
if fs.ForceCacheBilling {
requestCtx = service.WithForceCacheBilling(requestCtx)
}
if channelMapping.Mapped {
// 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。
requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel)
}
// 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover
writerSizeBeforeForward := c.Writer.Size()
if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey {
@@ -1127,8 +1131,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// - 粘性账号因负载/RPM 被跳过、选中了其他账号:不覆盖原绑定,
// 下次请求粘性账号恢复后仍可命中
if sessionKey != "" && (sessionBoundAccountID == 0 || sessionBoundAccountID == account.ID) {
if err := h.gatewayService.BindStickySession(c.Request.Context(), currentAPIKey.GroupID, sessionKey, account.ID); err != nil {
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
// Forward has completed; finish the bounded write even if the client disconnects.
bindCtx, cancelBind := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 5*time.Second)
bindErr := h.gatewayService.BindStickySession(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID)
cancelBind()
if bindErr != nil {
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(bindErr))
}
}
@@ -85,6 +85,12 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) {
return
}
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
respondOpenAIReasoningEffortPolicyError(c, err, h.chatCompletionsErrorResponse)
return
} else if changed {
body = cappedBody
}
reqStream, ok := parseOpenAICompatibleStream(body)
if !ok {
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
@@ -390,6 +396,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
zap.Error(err),
)
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(c.Request.Context()), apiKey.GroupID, selectionSessionHash, account.ID, err)
if result != nil {
submitForwardUsage(result)
}
@@ -85,6 +85,12 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) {
return
}
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
respondOpenAIReasoningEffortPolicyError(c, err, h.responsesErrorResponse)
return
} else if changed {
body = cappedBody
}
reqStream, ok := parseOpenAICompatibleStream(body)
if !ok {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
@@ -373,6 +379,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
zap.Error(err),
)
// The response is already committed, so the client retries; send that
// retry through scheduling again instead of back to this account.
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(requestCtx), apiKey.GroupID, sessionHash, account.ID, err)
if result != nil {
submitForwardUsage(result)
}
+2 -2
View File
@@ -172,7 +172,7 @@ type ConcurrencyHelper struct {
// NewConcurrencyHelper creates a new ConcurrencyHelper
func NewConcurrencyHelper(concurrencyService *service.ConcurrencyService, pingFormat SSEPingFormat, pingInterval time.Duration) *ConcurrencyHelper {
if pingInterval <= 0 {
if pingInterval < 0 {
pingInterval = defaultPingInterval
}
return &ConcurrencyHelper{
@@ -380,7 +380,7 @@ func (h *ConcurrencyHelper) waitForSlotWithPingTimeout(c *gin.Context, slotType
}
// Determine if ping is needed (streaming + ping format defined)
needPing := isStream && h.pingFormat != ""
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
var flusher http.Flusher
if needPing {
@@ -0,0 +1,67 @@
package handler
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestConcurrencyWaitPingInterval(t *testing.T) {
for _, slotType := range []string{"user", "account"} {
for _, format := range []SSEPingFormat{SSEPingFormatClaude, SSEPingFormatComment} {
for _, interval := range []time.Duration{0, time.Millisecond} {
t.Run(slotType+"/"+string(format)+"/"+interval.String(), func(t *testing.T) {
cache := &helperConcurrencyCacheStub{}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), format, interval)
require.Equal(t, interval, helper.pingInterval)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
started := false
_, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, 150*time.Millisecond, true, &started, false)
var concurrencyErr *ConcurrencyError
require.ErrorAs(t, err, &concurrencyErr)
require.True(t, concurrencyErr.IsTimeout)
if interval == 0 {
require.False(t, started)
require.False(t, c.Writer.Written())
require.False(t, recorder.Flushed)
require.Empty(t, recorder.Body.String())
require.Empty(t, recorder.Header().Get("Content-Type"))
c.JSON(http.StatusTooManyRequests, gin.H{"error": "busy"})
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
} else {
require.True(t, started)
require.True(t, recorder.Flushed)
require.Contains(t, recorder.Body.String(), string(format))
}
})
}
}
}
}
func TestConcurrencyWaitWithoutPingAcquiresSlot(t *testing.T) {
for _, slotType := range []string{"user", "account"} {
t.Run(slotType, func(t *testing.T) {
cache := &helperConcurrencyCacheStub{userSeq: []bool{true}, accountSeq: []bool{true}}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatClaude, 0)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
started := false
release, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, time.Second, true, &started, false)
require.NoError(t, err)
require.NotNil(t, release)
release()
require.False(t, started)
require.False(t, c.Writer.Written())
require.Empty(t, recorder.Body.String())
})
}
}
@@ -0,0 +1,186 @@
//go:build unit
package handler
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type stickyWritebackContextKey struct{}
type stickyWritebackCall struct {
err error
groupID int64
account int64
session string
ttl time.Duration
value any
deadline time.Time
}
type stickyWritebackCache struct {
service.GatewayCache
accountID int64
finished bool
calls []stickyWritebackCall
}
func (s *stickyWritebackCache) GetSessionAccountID(context.Context, int64, string) (int64, error) {
return s.accountID, nil
}
func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration) error {
if s.finished {
deadline, _ := ctx.Deadline()
s.calls = append(s.calls, stickyWritebackCall{
err: ctx.Err(), groupID: groupID, account: account, session: session, ttl: ttl,
value: ctx.Value(stickyWritebackContextKey{}), deadline: deadline,
})
}
if err := ctx.Err(); err != nil {
return err
}
s.accountID = account
return nil
}
func (s *stickyWritebackCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error {
return nil
}
func (s *stickyWritebackCache) DeleteSessionAccountID(context.Context, int64, string) error {
s.accountID = 0
return nil
}
type stickyWritebackBody struct {
io.Reader
finish func()
}
func (b *stickyWritebackBody) Close() error {
b.finish()
return nil
}
func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, stream := range []bool{false, true} {
name := "buffered"
if stream {
name = "streaming"
}
for _, tt := range []struct {
name string
bound int64
cancel bool
fail bool
wantWrites int
}{
{name: "new binding", wantWrites: 1},
{name: "new binding after disconnect", cancel: true, wantWrites: 1},
{name: "refresh binding", bound: 9401, wantWrites: 1},
{name: "refresh after disconnect", bound: 9401, cancel: true, wantWrites: 1},
{name: "different binding", bound: 9499, cancel: true},
{name: "forward failed", cancel: true, fail: true},
} {
t.Run(name+"/"+tt.name, func(t *testing.T) {
groupID := int64(9400)
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1}
account := &service.Account{
ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
Credentials: map[string]any{"api_key": "test-key"},
Extra: map[string]any{"anthropic_passthrough": true},
AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}},
}
cache := &stickyWritebackCache{accountID: tt.bound}
ctx := context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value")
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
t.Cleanup(cancel)
responseBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`
contentType := "application/json"
if stream {
responseBody = compatStreamUsagePartialStream + compatStreamUsageCompletion
contentType = "text/event-stream"
}
status := http.StatusOK
if tt.fail {
status = http.StatusBadRequest
responseBody = `{"type":"error","error":{"type":"invalid_request_error","message":"invalid input"}}`
}
upstream := &compatStreamUsageUpstream{response: &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": []string{contentType}},
Body: &stickyWritebackBody{Reader: strings.NewReader(responseBody), finish: func() {
// Forward closes its upstream body on return. Cancel precisely
// after that work, before the handler's terminal sticky write.
cache.finished = true
if tt.cancel {
cancel()
}
}},
}}
cfg := &config.Config{RunMode: config.RunModeSimple}
other := *account
other.ID = 9499
other.Schedulable = false
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, &other}}, nil, nil, nil, nil)
gw := service.NewGatewayService(
nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, cache, cfg,
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
h := &GatewayHandler{
gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
}
requestBody := `{"model":"claude-sonnet-4.5","max_tokens":16,"stream":false,"messages":[{"role":"user","content":"sticky writeback test"}]}`
if stream {
requestBody = strings.Replace(requestBody, `"stream":false`, `"stream":true`, 1)
}
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)).WithContext(ctx)
c.Request.Header.Set("Content-Type", "application/json")
key := &service.APIKey{ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, User: &service.User{ID: 9403, Balance: 100}}
c.Set(string(middleware.ContextKeyAPIKey), key)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
h.Messages(c)
require.Equal(t, 1, upstream.calls)
require.True(t, cache.finished)
require.Equal(t, status, rec.Code)
if tt.cancel {
require.ErrorIs(t, ctx.Err(), context.Canceled)
}
require.Len(t, cache.calls, tt.wantWrites)
for _, call := range cache.calls {
require.NoError(t, call.err, "a completed upstream request must retain its terminal sticky write")
require.Equal(t, groupID, call.groupID)
require.Equal(t, account.ID, call.account)
require.NotEmpty(t, call.session)
require.Positive(t, call.ttl)
require.Equal(t, "request-scoped value", call.value)
require.False(t, call.deadline.IsZero(), "the detached cache write must have a deadline")
require.WithinDuration(t, time.Now(), call.deadline, 5*time.Second)
}
})
}
}
}
@@ -275,6 +275,7 @@ func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) {
Result: &service.ForwardResult{
Model: modelName, UpstreamModel: mappedModel,
Usage: service.ClaudeUsage{InputTokens: int(tokens)}, CacheStorageTokenHours: storageTokenHours,
UpstreamPriceMultiplier: service.VertexUpstreamPriceMultiplier(account, mappedModel, ""),
},
APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt, ChannelUsageFields: usageFields,
})
@@ -674,15 +675,17 @@ func (h *GatewayHandler) submitGeminiCachedContentUsage(
if inputTokens <= 0 && storageTokenHours <= 0 {
return
}
priceMultiplier := service.VertexUpstreamPriceMultiplier(account, upstreamModel, "")
if upstreamModel == model {
upstreamModel = ""
}
result := &service.ForwardResult{
RequestID: requestID,
Model: model,
UpstreamModel: upstreamModel,
Usage: service.ClaudeUsage{InputTokens: inputTokens},
CacheStorageTokenHours: storageTokenHours,
RequestID: requestID,
Model: model,
UpstreamModel: upstreamModel,
Usage: service.ClaudeUsage{InputTokens: inputTokens},
CacheStorageTokenHours: storageTokenHours,
UpstreamPriceMultiplier: priceMultiplier,
}
inboundEndpoint := GetInboundEndpoint(c)
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
@@ -13,7 +13,6 @@ import (
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/domain"
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
"github.com/Wei-Shaw/sub2api/internal/pkg/gemini"
"github.com/Wei-Shaw/sub2api/internal/pkg/googleapi"
@@ -468,16 +467,8 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
sessionHash = extractGeminiCLISessionHash(c, body)
}
if sessionHash == "" && cachedContentBinding == nil {
// Fallback: 使用通用的会话哈希生成逻辑(适用于其他客户端)
parsedReq, _ := service.ParseGatewayRequest(service.NewRequestBodyRef(body), domain.PlatformGemini)
if parsedReq != nil {
parsedReq.SessionContext = &service.SessionContext{
ClientIP: ip.GetClientIP(c),
UserAgent: c.GetHeader("User-Agent"),
APIKeyID: apiKey.ID,
}
}
sessionHash = h.gatewayService.GenerateSessionHash(parsedReq)
// 其他客户端:按 API Key + 模型 + tools + systemInstruction + 第一条 user contents 的 parts 生成内容哈希
sessionHash = service.GenerateGeminiContentSessionHash(apiKey.ID, reqModel, body)
}
sessionKey := sessionHash
if sessionHash != "" {
@@ -0,0 +1,87 @@
//go:build unit
package handler
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestGrokImagesPreservesUpstreamErrorOnSyncAndAsyncRoutes(t *testing.T) {
for _, oauth := range []bool{false, true} {
accountType := "api-key"
if oauth {
accountType = "oauth"
}
for _, async := range []bool{false, true} {
route := "sync"
if async {
route = "async"
}
t.Run(accountType+"/"+route, func(t *testing.T) {
h, slots, _, upstream := newGrokMediaSlotHandler(t, oauth, false)
h.grokMediaEligibilityProber = grokMediaSlotProber(func(context.Context, int64) (bool, string, error) {
return true, "test account is eligible", nil
})
upstream.call = func(req *http.Request, _ int64) (*http.Response, error) {
assert.Equal(t, "/v1/images/edits", req.URL.Path)
return &http.Response{
StatusCode: http.StatusBadRequest,
Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"code":"invalid_image","error":"Image could not be decoded: https://example.test/image?access_token=secret&size=1","debug":"private upstream diagnostic"}`)),
}, nil
}
c, recorder := grokMediaSlotContext(context.Background(), true)
path := "/v1/images/edits"
if async {
path += "/async"
}
c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"grok-imagine-image","prompt":"test","image":{"url":"https://example.test/input.png"}}`))
c.Request.Header.Set("Content-Type", "application/json")
var responseBody []byte
if async {
store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute)
asyncHandler := NewAsyncImageHandler(tasks, h)
asyncHandler.Submit(c)
require.Equal(t, http.StatusAccepted, recorder.Code, recorder.Body.String())
taskID := gjson.GetBytes(recorder.Body.Bytes(), "task_id").String()
owner := service.ImageTaskOwner{UserID: 10, APIKeyID: 20}
require.Eventually(t, func() bool {
task, err := tasks.Get(context.Background(), owner, taskID)
return err == nil && task.Status != service.ImageTaskStatusProcessing
}, time.Second, 10*time.Millisecond)
poll, pollRecorder := grokMediaSlotContext(context.Background(), false)
poll.Params[0].Key, poll.Params[0].Value = "task_id", taskID
asyncHandler.Get(poll)
require.Equal(t, http.StatusOK, pollRecorder.Code)
responseBody = pollRecorder.Body.Bytes()
require.Equal(t, service.ImageTaskStatusFailed, gjson.GetBytes(responseBody, "status").String())
require.Equal(t, int64(http.StatusBadRequest), gjson.GetBytes(responseBody, "http_status").Int())
} else {
h.GrokImages(c)
require.Equal(t, http.StatusBadRequest, recorder.Code, recorder.Body.String())
responseBody = recorder.Body.Bytes()
}
require.Equal(t, "Image could not be decoded: https://example.test/image?access_token=***&size=1", gjson.GetBytes(responseBody, "error.message").String())
require.Equal(t, "invalid_image", gjson.GetBytes(responseBody, "error.code").String())
require.Equal(t, "invalid_request_error", gjson.GetBytes(responseBody, "error.type").String())
require.NotContains(t, string(responseBody), "secret")
require.NotContains(t, string(responseBody), "private upstream diagnostic")
require.Equal(t, 1, upstream.calls, "deterministic image errors must not retry another account")
slots.assertReleased(t)
})
}
}
}
@@ -0,0 +1,106 @@
package handler
import (
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestMessagesEffortPolicyBinding(t *testing.T) {
for _, platform := range []string{service.PlatformOpenAI, service.PlatformComposite} {
for _, test := range []struct {
name string
preference string
effort string
mappings []service.ReasoningEffortMapping
ceiling string
overLimit string
want string
deny bool
}{
{name: "omitted unchanged", effort: "medium", want: "medium"},
{name: "omitted ignores medium mapping", effort: "medium", mappings: []service.ReasoningEffortMapping{{From: "medium", To: "low"}}, want: "medium"},
{name: "omitted ignores ceiling", effort: "medium", ceiling: "low", want: "medium"},
{name: "omitted ignores deny ceiling", effort: "medium", ceiling: "low", overLimit: service.ReasoningEffortOverLimitDeny, want: "medium"},
{name: "numeric effort is not explicit", preference: `,"output_config":{"effort":123}`, effort: "medium", ceiling: "low", mappings: []service.ReasoningEffortMapping{{From: "medium", To: "deny"}}, want: "medium"},
{name: "boolean effort is not explicit", preference: `,"output_config":{"effort":true}`, effort: "medium", ceiling: "low", want: "medium"},
{name: "object effort is not explicit", preference: `,"output_config":{"effort":{"value":"high"}}`, effort: "medium", ceiling: "low", want: "medium"},
{name: "blank effort is omitted", preference: `,"output_config":{"effort":" "}`, effort: "medium", ceiling: "low", want: "medium"},
{name: "omitted none mapping does not cap medium default", effort: "medium", ceiling: "low", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}}, want: "medium"},
{name: "disabled omitted applies none only once", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}, {From: "low", To: "high"}}, want: "low"},
{name: "disabled omitted mapping capped", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "xhigh"}}, ceiling: "low", want: "low"},
{name: "disabled omitted mapping denied", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "xhigh"}}, ceiling: "low", overLimit: service.ReasoningEffortOverLimitDeny, deny: true},
{name: "disabled unmapped none not capped", preference: `,"thinking":{"type":"disabled"}`, effort: "none", ceiling: "low", overLimit: service.ReasoningEffortOverLimitDeny, want: "none"},
{name: "disabled explicit applies none", preference: `,"output_config":{"effort":"max"},"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low"}}, want: "low"},
{name: "explicit adaptive retains policy", preference: `,"output_config":{"effort":"high"},"thinking":{"type":"adaptive"}`, effort: "high", ceiling: "medium", want: "medium"},
{name: "omitted retains model scope", preference: `,"thinking":{"type":"disabled"}`, effort: "none", mappings: []service.ReasoningEffortMapping{{From: "none", To: "low", Model: "gpt-6-sol", MatchType: "exact"}}, want: "none"},
} {
t.Run(platform+"/"+test.name, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("POST", "/v1/messages", nil)
apiKey := &service.APIKey{Group: &service.Group{Platform: platform, MaxReasoningEffort: test.ceiling, ReasoningEffortMappings: test.mappings, MaxReasoningEffortOverLimit: test.overLimit}}
body := []byte(`{"model":"gpt-6.1-sol"` + test.preference + `}`)
ensureCompositeTargetPlatform(c, apiKey, "gpt-6.1-sol")
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body)
converted := []byte(`{"model":"gpt-6.1-sol","reasoning":{"effort":"` + test.effort + `"}}`)
got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(c.Request.Context(), converted)
if test.deny {
var overLimit *service.ReasoningEffortOverLimitError
require.ErrorAs(t, err, &overLimit)
require.Equal(t, "xhigh", overLimit.Requested)
require.Equal(t, "low", overLimit.Max)
require.False(t, changed)
require.Equal(t, converted, got)
return
}
require.NoError(t, err)
require.Equal(t, test.want, gjson.GetBytes(got, "reasoning.effort").String())
require.Equal(t, test.effort != test.want, changed)
if !changed {
require.Equal(t, converted, got)
}
})
}
}
}
func TestMessagesEffortPolicyBindingCNTargetsOmitted(t *testing.T) {
for _, target := range []string{service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax} {
for _, platform := range []string{target, service.PlatformComposite, service.PlatformOpenAI} {
for _, preference := range []string{
``,
`,"thinking":{"type":"disabled"}`,
`,"thinking":{"type":"adaptive"}`,
`,"thinking":{"type":"disabled"},"output_config":{"effort":" "}`,
`,"thinking":{"type":"disabled"},"output_config":{"effort":123}`,
`,"thinking":{"type":"disabled"},"output_config":{"effort":true}`,
`,"thinking":{"type":"disabled"},"output_config":{"effort":null}`,
`,"thinking":{"type":"disabled"},"output_config":{"effort":{}}`,
} {
t.Run(target+"/"+platform+"/"+preference, func(t *testing.T) {
requestContext, _ := gin.CreateTestContext(httptest.NewRecorder())
requestContext.Request = httptest.NewRequest("POST", "/v1/messages", nil)
if platform != target {
requestContext.Request = requestContext.Request.WithContext(service.WithResolvedTargetPlatform(requestContext.Request.Context(), target))
}
apiKey := &service.APIKey{Group: &service.Group{
Platform: platform, MaxReasoningEffort: "low", MaxReasoningEffortOverLimit: service.ReasoningEffortOverLimitDeny,
ReasoningEffortMappings: []service.ReasoningEffortMapping{{From: "none", To: "deny"}, {From: "medium", To: "deny"}},
}}
bindOpenAIReasoningEffortPolicyForMessagesRequest(requestContext, apiKey, []byte(`{"model":"glm-5.2"`+preference+`}`))
for _, effort := range []string{"none", "medium", "high"} {
converted := []byte(`{"model":"glm-5.2","reasoning_effort":"` + effort + `"}`)
got, changed, err := service.ApplyOpenAIReasoningEffortPolicyFromContext(requestContext.Request.Context(), converted)
require.NoError(t, err)
require.False(t, changed)
require.Equal(t, converted, got)
}
})
}
}
}
}
@@ -0,0 +1,63 @@
//go:build unit
package handler
import (
"math/rand"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestCodexCallOutputGateSkipsDeclaredToolsWithoutCandidate(t *testing.T) {
body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"},{"type":"function","name":"create_thread"}],` +
`"input":[{"type":"function_call","call_id":"c1","name":"shell"},{"type":"function_call_output","call_id":"c1","output":"ok"}]}`)
require.False(t, mayContainCodexCallOutputCandidate(body, "automation_update"))
require.False(t, mayContainCodexCallOutputCandidate(body, "create_thread", "send_message_to_thread"))
for name, normalize := range map[string]func([]byte) ([]byte, bool){
"untrusted": normalizeCodexUntrustedContext,
"automation": normalizeCodexAutomationBootstrap,
"delegation": normalizeCodexDelegationBootstrap,
} {
t.Run(name, func(t *testing.T) {
allocs := testing.AllocsPerRun(10, func() {
got, changed := normalize(body)
if changed || &got[0] != &body[0] {
t.Fatal("non-candidate body must be returned unchanged")
}
})
require.Zero(t, allocs)
})
}
}
// Whenever the ungated bootstrap path rewrites a body, the gate must admit it.
func TestCodexCallOutputGateAdmitsEveryRewrite(t *testing.T) {
u := func(hex string) string { return `\` + "u" + hex }
output := mustJSON(t, codexAutomationBootstrap("wiki", "never", automationBootstrapPrompt))
items := []string{
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`,
`{"type":"function_call_output","namespace":"codex_app","name":"` + u("0061") + `utomation_update","output":` + output + `}`,
`{"` + u("0074") + `ype":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`,
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","name":"other","output":` + output + `}`,
`{"type":"function_call_output","call_id":"c","output":"ok"}`,
`{"type":"message","role":"user","content":"automation_update function_call_output caf` + u("00e9") + `"}`,
`{"type":"function_call","call_id":"c","name":"automation_update"}`,
}
rng := rand.New(rand.NewSource(11))
rewrites := 0
for i := 0; i < 3000; i++ {
var parts []string
for n := rng.Intn(3); n >= 0; n-- {
parts = append(parts, items[rng.Intn(len(items))])
}
body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"}],"input":[` + strings.Join(parts, ",") + `]}`)
_, rewritten := normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false)
if rewritten {
rewrites++
require.True(t, mayContainCodexCallOutputCandidate(body, "automation_update"), "%s", body)
}
}
require.Positive(t, rewrites)
}
@@ -261,6 +261,25 @@ func TestInferenceFailoverExhaustionRestoresRetryAfter(t *testing.T) {
require.Equal(t, "17", recorder.Header().Get("Retry-After"))
}
func TestCapacityShedFailoverExhaustionOmitsRetryAfter(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := &OpenAIGatewayHandler{}
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable,
ResponseHeaders: http.Header{"Retry-After": []string{"326"}},
RequestScopedTransient: true,
ResponseBody: []byte(`{"error":{"code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`),
ClientMessage: "Our servers are currently overloaded. Please try again later.",
}, false)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
require.Empty(t, recorder.Header().Get("Retry-After"))
require.Contains(t, recorder.Body.String(), "server_error")
}
func TestFailoverExhaustionRejectsSecretBearingRetryAfter(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
@@ -15,6 +15,7 @@ import (
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/domain"
@@ -363,7 +364,7 @@ func NewOpenAIGatewayHandler(
opsService *service.OpsService,
cfg *config.Config,
) *OpenAIGatewayHandler {
pingInterval := time.Duration(0)
pingInterval := defaultPingInterval
maxAccountSwitches := 3
if cfg != nil {
pingInterval = time.Duration(cfg.Concurrency.PingInterval) * time.Second
@@ -437,6 +438,13 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
return
}
// Reject invalid UTF-8 before JSON transformation so malformed bytes do not
// become retryable upstream errors.
if !utf8.Valid(body) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Request body must be valid UTF-8 JSON. Send UTF-8 encoded bytes.")
return
}
setOpsRequestContext(c, "", false)
sessionHashBody := body
body, ok = h.normalizeOpenAIResponsesCompactRequest(c, reqLog, body)
@@ -481,6 +489,12 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
} else if changed {
body = cappedBody
}
if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed {
body = normalizedBody
reqLog.Info("openai.codex_untrusted_context_normalized",
zap.String("normalization", "call_output_to_user_message"),
)
}
if normalizedBody, changed := normalizeCodexAutomationBootstrap(body); changed {
body = normalizedBody
reqLog.Info("openai.codex_automation_bootstrap_normalized",
@@ -1399,7 +1413,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
defaultMappedModel := strings.TrimSpace(effectiveMappedModel)
// 应用渠道模型映射到请求体
forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel)
writerSizeBeforeForward := c.Writer.Size()
writerSizeBeforeForward := service.OpenAICompactKeepaliveAdjustedWrittenSize(c)
result, err := func() (*service.OpenAIForwardResult, error) {
defer func() {
if accountReleaseFunc != nil {
@@ -1487,11 +1501,16 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
)
return
}
if c.Writer.Size() != writerSizeBeforeForward {
if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) {
h.gatewayService.ObserveOpenAIAccountHealthFailure(c.Request.Context(), account, err)
h.handleAnthropicFailoverExhausted(c, failoverErr, true)
return
}
// Only keepalive bytes were written, so failover may continue, but
// every later error must be written as an SSE event.
if c.Writer.Written() {
streamStarted = true
}
if failoverErr.ShouldReportAccountScheduleFailure() {
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, nil), false, nil, err)
}
@@ -1649,16 +1668,24 @@ func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context,
h.anthropicStreamingAwareError(c, status, "api_error", failoverErr.ClientMessage, streamStarted)
return
}
// A failed or error frame that triggered the failover no longer reaches the
// client in-band, so its error passthrough rule is applied here instead.
if status, errType, msg, ok := service.ApplyOpenAIStreamFailedFrameRule(c, failoverErr); ok {
h.anthropicStreamingAwareError(c, status, errType, msg, streamStarted)
return
}
status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode)
h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted)
}
// ensureAnthropicErrorResponse writes a fallback Anthropic error if no response was written.
func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, streamStarted bool) bool {
if c == nil || c.Writer == nil || c.Writer.Written() {
// Keepalive pings alone do not count as a written response, but they do
// commit the response as SSE, so the fallback must then be an SSE event.
if c == nil || c.Writer == nil || service.OpenAICompactKeepaliveAdjustedWrittenSize(c) >= 0 {
return false
}
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted)
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted || c.Writer.Written())
return true
}
@@ -1715,11 +1742,23 @@ func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) {
// mayContainCodexCallOutputCandidate is a necessary condition for a bootstrap
// candidate, checked before the full uniqueness scan and decode. Its type and
// tool name are JSON strings, which appear literally unless a \u escape spells
// their letters; without either, normalization cannot change the body.
// their letters; without either, normalization cannot change the body. Escapes
// that real clients emit (control characters, HTML-safe and non-ASCII runes)
// cannot spell those letters and must not force the full decode.
//
// Tool declarations carry the same names, so a literal hit is confirmed by a
// zero-copy scan for an input item of type function_call_output whose name
// starts with one of toolNames. The full path rejects bodies with duplicate
// members, and without duplicates the scan reads the same values as the
// decoder.
func mayContainCodexCallOutputCandidate(body []byte, toolNames ...string) bool {
if bytes.Contains(body, []byte(`\u`)) {
return true
if !service.JSONMayEscapePlainASCII(body) && !containsCodexCallOutputLiterals(body, toolNames) {
return false
}
return service.ResponsesInputHasFunctionCallOutputNamed(body, toolNames...)
}
func containsCodexCallOutputLiterals(body []byte, toolNames []string) bool {
if !bytes.Contains(body, []byte("function_call_output")) {
return false
}
@@ -2472,23 +2472,76 @@ func TestOpenAIResponses_APIKeyPassthroughSSERateLimitUsesConfiguredPoolRetry(t
}
func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeCtxPool} {
t.Run(mode, func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLimitCase(t, mode, nil, false)
})
}
}
func TestOpenAIResponsesWebSocket_NativeLaterTurnUsageLimitDoesNotReplayFirstMessage(t *testing.T) {
for _, continuation := range []struct {
name string
input string
handshakeLimit bool
}{
{name: "user message", input: `[{"role":"user","content":"continue the task"}]`},
{name: "tool result", input: `[{"type":"function_call_output","call_id":"call_inspect","output":"file contents"}]`},
{name: "handshake after disconnect", input: `[{"role":"user","content":"continue the task"}]`, handshakeLimit: true},
} {
t.Run(continuation.name, func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLimitCase(t, service.OpenAIWSIngressModeCtxPool, []string{
`{"type":"response.create","model":"gpt-5.1","instructions":"Inspect the project before editing it.","tools":[{"type":"function","name":"inspect","parameters":{"type":"object"}}],"input":[{"role":"user","content":"fix the project"}]}`,
fmt.Sprintf(`{"type":"response.create","model":"gpt-5.1","store":%t,"previous_response_id":"resp_ws_turn_2","input":%s}`, continuation.handshakeLimit, continuation.input),
}, continuation.handshakeLimit)
})
}
}
func runOpenAIResponsesWebSocketUsageLimitCase(t *testing.T, mode string, followups []string, handshakeLimit bool) {
t.Helper()
gin.SetMode(gin.TestMode)
firstHitCh := make(chan []byte, 1)
firstHitCh := make(chan []byte, len(followups)+1)
secondHitCh := make(chan []byte, 1)
var firstConnections atomic.Int32
var secondConnections atomic.Int32
firstUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if firstConnections.Add(1) > 1 && handshakeLimit {
w.WriteHeader(http.StatusTooManyRequests)
return
}
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
if err != nil {
return
}
defer func() { _ = conn.CloseNow() }()
readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second)
_, payload, readErr := conn.Read(readCtx)
cancelRead()
if readErr == nil {
for turn := 0; turn <= len(followups); turn++ {
readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second)
_, payload, readErr := conn.Read(readCtx)
cancelRead()
if readErr != nil {
return
}
firstHitCh <- payload
if turn < len(followups) {
output := `[]`
if turn > 0 {
output = `[{"type":"function_call","call_id":"call_inspect","name":"inspect","arguments":"{}"}]`
}
completed := fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_ws_turn_%d","model":"gpt-5.1","output":%s,"usage":{"input_tokens":1,"output_tokens":1}}}`, turn+1, output)
writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second)
writeErr := conn.Write(writeCtx, coderws.MessageText, []byte(completed))
cancelWrite()
if writeErr != nil {
return
}
if handshakeLimit && turn == len(followups)-1 {
return
}
}
}
writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second)
@@ -2498,6 +2551,7 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T
defer firstUpstream.Close()
secondUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secondConnections.Add(1)
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
if err != nil {
return
@@ -2535,7 +2589,7 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T
},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModePassthrough,
"openai_apikey_responses_websockets_v2_mode": mode,
},
},
{
@@ -2553,7 +2607,7 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T
},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModePassthrough,
"openai_apikey_responses_websockets_v2_mode": mode,
},
},
}
@@ -2575,6 +2629,7 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo,
nil,
@@ -2628,7 +2683,11 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
c.Next()
})
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
handlerDone := make(chan struct{})
router.GET("/openai/v1/responses", func(c *gin.Context) {
h.ResponsesWebSocket(c)
close(handlerDone)
})
handlerServer := httptest.NewServer(router)
defer handlerServer.Close()
@@ -2647,22 +2706,52 @@ func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T
cancelWrite()
require.NoError(t, err)
for _, followup := range followups {
readCtx, cancelRead := context.WithTimeout(context.Background(), 5*time.Second)
_, event, readErr := clientConn.Read(readCtx)
cancelRead()
require.NoError(t, readErr)
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
writeErr := clientConn.Write(writeCtx, coderws.MessageText, []byte(followup))
cancelWrite()
require.NoError(t, writeErr)
}
readCtx, cancelRead := context.WithTimeout(context.Background(), 5*time.Second)
_, event, err := clientConn.Read(readCtx)
cancelRead()
require.NoError(t, err)
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
require.Equal(t, "resp_ws_failover_ok", gjson.GetBytes(event, "response.id").String())
select {
case <-firstHitCh:
case <-time.After(3 * time.Second):
t.Fatal("等待第一个上游收到首帧超时")
if len(followups) > 0 {
require.Equal(t, coderws.StatusTryAgainLater, coderws.CloseStatus(err), "a later-turn limit must not turn into a successful replay: %s", event)
require.ErrorContains(t, err, "rate limit")
} else {
require.NoError(t, err)
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
require.Equal(t, "resp_ws_failover_ok", gjson.GetBytes(event, "response.id").String())
}
_ = clientConn.CloseNow()
select {
case <-secondHitCh:
case <-time.After(3 * time.Second):
t.Fatal("等待第二个上游收到重放首帧超时")
case <-handlerDone:
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for websocket handler")
}
expectedFrames := len(followups) + 1
if handshakeLimit {
expectedFrames--
require.Equal(t, int32(2), firstConnections.Load(), "the same account must reject the replacement handshake")
}
require.Len(t, firstHitCh, expectedFrames)
if len(followups) > 0 {
require.Zero(t, secondConnections.Load(), "the replacement account must not receive the original connection message")
require.Empty(t, secondHitCh)
} else {
select {
case <-secondHitCh:
case <-time.After(3 * time.Second):
t.Fatal("等待第二个上游收到重放首帧超时")
}
}
require.Equal(t, []int64{int64(9902)}, accountRepo.rateLimitedIDs)
}
@@ -0,0 +1,336 @@
//go:build unit
package handler
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/model"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"go.uber.org/zap"
)
const (
preContentHandlerCreated = `data: {"type":"response.created","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n"
preContentHandlerFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request."}}}` + "\n\n"
preContentHandlerSuccess = preContentHandlerCreated +
`data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","content":[]}}` + "\n\n" +
`data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"answer from second account"}` + "\n\n" +
`data: {"type":"response.completed","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":4,"total_tokens":7}}}` + "\n\n"
)
// preContentFailoverUpstream hands each upstream request to respond, which
// gets the 1-based call number.
type preContentFailoverUpstream struct {
service.HTTPUpstream
mu sync.Mutex
hits []int64
respond func(call int) (*http.Response, error)
}
func (u *preContentFailoverUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
if req.Body != nil {
_, _ = io.Copy(io.Discard, req.Body)
}
u.mu.Lock()
u.hits = append(u.hits, accountID)
call := len(u.hits)
u.mu.Unlock()
return u.respond(call)
}
func (u *preContentFailoverUpstream) calls() int {
u.mu.Lock()
defer u.mu.Unlock()
return len(u.hits)
}
func preContentSSEResponse(body io.ReadCloser) *http.Response {
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: body}
}
// preContentStallThenFail stalls past one keepalive tick after the first event
// and then fails with failed.
func preContentStallThenFail(failed string) *http.Response {
pr, pw := io.Pipe()
go func() {
_, _ = io.WriteString(pw, preContentHandlerCreated)
time.Sleep(1300 * time.Millisecond)
_, _ = io.WriteString(pw, failed)
_ = pw.Close()
}()
return preContentSSEResponse(pr)
}
type unexpectedEOFReader struct{}
func (unexpectedEOFReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
type preContentFailoverScenario struct {
accounts []service.Account
respond func(call int) (*http.Response, error)
passthrough *service.ErrorPassthroughService
requestBody string
}
func preContentAccounts(count int) []service.Account {
accounts := make([]service.Account, 0, count)
for i := 0; i < count; i++ {
accounts = append(accounts, service.Account{
ID: int64(9201 + i), Name: "openai-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: i + 1,
Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"},
})
}
return accounts
}
func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest.ResponseRecorder, *preContentFailoverUpstream) {
t.Helper()
return serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(accountCount),
respond: func(call int) (*http.Response, error) {
if call == 1 {
return preContentStallThenFail(preContentHandlerFailed), nil
}
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerSuccess))), nil
},
})
}
func serveMessagesScenario(t *testing.T, sc preContentFailoverScenario) (*httptest.ResponseRecorder, *preContentFailoverUpstream) {
t.Helper()
gin.SetMode(gin.TestMode)
groupID := int64(9101)
repo := &grokCredentialHandlerRepo{accounts: sc.accounts, missingOnGet: map[int64]bool{}}
upstream := &preContentFailoverUpstream{respond: sc.respond}
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Gateway.MaxAccountSwitches = 3
cfg.Gateway.StreamKeepaliveInterval = 1
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
gateway := service.NewOpenAIGatewayService(
repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
service.NewBillingService(cfg, nil), nil, billingCache, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
}
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, sc.passthrough, nil, nil, cfg)
apiKey := &service.APIKey{
ID: 9102, GroupID: &groupID,
User: &service.User{ID: 9103, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, AllowMessagesDispatch: true},
}
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
service.BindErrorPassthroughService(c, sc.passthrough)
c.Next()
})
router.POST("/v1/messages", h.Messages)
rec := httptest.NewRecorder()
requestBody := sc.requestBody
if requestBody == "" {
requestBody = `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`
}
req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewBufferString(requestBody))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
return rec, upstream
}
// requireEndsWithSSEError checks that a response already committed as SSE ends
// with an Anthropic error event and never carries a bare JSON line.
func requireEndsWithSSEError(t *testing.T, body string) {
t.Helper()
lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:]
require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent)
require.Contains(t, lastEvent, `"type":"error"`)
for _, line := range strings.Split(body, "\n") {
require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line)
}
}
func TestOpenAIMessagesFailsOverAfterKeepaliveOnlyWrite(t *testing.T) {
rec, upstream := servePreContentFailoverMessages(t, 2)
body := rec.Body.String()
require.Equal(t, 2, upstream.calls(), "body: %q", body)
require.Equal(t, 1, strings.Count(body, "event: message_start"), "body: %q", body)
require.Contains(t, body, "answer from second account")
}
func TestOpenAIMessagesKeepaliveThenFailoverExhaustedEndsWithSSEError(t *testing.T) {
rec, upstream := servePreContentFailoverMessages(t, 1)
body := rec.Body.String()
require.Equal(t, 1, upstream.calls(), "body: %q", body)
require.Contains(t, body, "event: ping")
requireEndsWithSSEError(t, body)
}
func TestOpenAIMessagesFailoverThenSecondAccountReadErrorEndsWithSSEError(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(2),
respond: func(call int) (*http.Response, error) {
if call == 1 {
return preContentStallThenFail(preContentHandlerFailed), nil
}
return preContentSSEResponse(io.NopCloser(unexpectedEOFReader{})), nil
},
})
body := rec.Body.String()
require.Equal(t, 2, upstream.calls(), "body: %q", body)
require.NotContains(t, body, "message_start")
requireEndsWithSSEError(t, body)
}
func TestOpenAIMessagesFailoverThenSecondAccountCredentialErrorEndsWithSSEError(t *testing.T) {
accounts := preContentAccounts(2)
accounts[1].Credentials = map[string]any{"base_url": "http://upstream.example"}
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: accounts,
respond: func(call int) (*http.Response, error) {
return preContentStallThenFail(preContentHandlerFailed), nil
},
})
body := rec.Body.String()
require.Equal(t, 1, upstream.calls(), "body: %q", body)
require.NotContains(t, body, "message_start")
requireEndsWithSSEError(t, body)
}
func TestOpenAIMessagesSlotAcquireFailureAfterKeepaliveIsSSE(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
c.Header("Content-Type", "text/event-stream")
_, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n")
require.NoError(t, err)
streamStarted := true
h := &OpenAIGatewayHandler{}
selection := &service.AccountSelectionResult{Account: &service.Account{ID: 9201}}
_, result := h.acquireResponsesAccountSlot(c, nil, "", selection, true, &streamStarted, zap.NewNop())
require.Equal(t, openAISlotAcquireFailed, result)
body := rec.Body.String()
lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:]
require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent)
}
func newFailedFrameCodeRule(code string) *service.ErrorPassthroughService {
status := http.StatusTeapot
rule := &model.ErrorPassthroughRule{
ID: 1, Name: "frame code rule", Enabled: true, Priority: 1,
Keywords: []string{code}, MatchMode: model.MatchModeAny,
Platforms: []string{model.PlatformOpenAI}, ResponseCode: &status, PassthroughBody: true,
}
return service.NewErrorPassthroughService(&errorPassthroughRepoStub{rules: []*model.ErrorPassthroughRule{rule}}, nil)
}
// A failed frame that triggers a failover is no longer written in-band, so its
// passthrough rule has to apply once the failover is exhausted. The rule is
// keyed on the frame's own code, which the generic failover envelope lacks.
func TestOpenAIMessagesFailoverExhaustedAppliesFailedFrameRule(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(1),
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
respond: func(call int) (*http.Response, error) {
failed := `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n"
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + failed))), nil
},
})
body := rec.Body.String()
t.Logf("status=%d body=%q", rec.Code, body)
require.Equal(t, 1, upstream.calls(), "body: %q", body)
require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body)
require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body)
require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body)
}
const preContentRateLimitFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n"
func requireFailedFrameRuleJSON(t *testing.T, rec *httptest.ResponseRecorder) {
t.Helper()
body := rec.Body.String()
t.Logf("status=%d content-type=%q body=%q", rec.Code, rec.Header().Get("Content-Type"), body)
require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body)
require.Contains(t, rec.Header().Get("Content-Type"), "application/json")
require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body)
require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body)
}
// The failed frame is the first event of the stream, so it triggers the
// failover before any output and used to reach the generic mapping unchecked.
func TestOpenAIMessagesFirstEventFailedFrameExhaustedAppliesRule(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(1),
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
respond: func(call int) (*http.Response, error) {
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentRateLimitFailed))), nil
},
})
require.Equal(t, 1, upstream.calls())
requireFailedFrameRuleJSON(t, rec)
}
func TestOpenAIMessagesNonStreamFailedFrameExhaustedAppliesRule(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(1),
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
requestBody: `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`,
respond: func(call int) (*http.Response, error) {
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + preContentRateLimitFailed))), nil
},
})
require.Equal(t, 1, upstream.calls())
requireFailedFrameRuleJSON(t, rec)
}
// A failover triggered by an HTTP status keeps the built-in exhaustion mapping:
// no passthrough rule is looked up for it.
func TestOpenAIMessagesHTTPStatusFailoverExhaustedIgnoresPassthroughRule(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(1),
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
respond: func(call int) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusBadGateway,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}`)),
}, nil
},
})
body := rec.Body.String()
t.Logf("status=%d body=%q", rec.Code, body)
require.Equal(t, 1, upstream.calls(), "body: %q", body)
require.NotEqual(t, http.StatusTeapot, rec.Code, "body: %q", body)
require.Equal(t, "Upstream service temporarily unavailable", gjson.Get(body, "error.message").String(), "body: %q", body)
}
@@ -0,0 +1,203 @@
//go:build unit
package handler
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// Run the real Images handler, scheduler, parser and forwarding service over
// HTTP with fixture authentication, an account repository and a local upstream.
type nativeImageRouteUpstream struct {
service.HTTPUpstream
target *url.URL
client *http.Client
}
func (u *nativeImageRouteUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
forwarded := req.Clone(req.Context())
forwarded.URL.Scheme = u.target.Scheme
forwarded.URL.Host = u.target.Host
return u.client.Do(forwarded)
}
func newNativeImageRoute(t *testing.T, delay time.Duration, status int) (*httptest.Server, *atomic.Int64) {
t.Helper()
gin.SetMode(gin.TestMode)
var calls atomic.Int64
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
require.Equal(t, http.MethodPost, r.Method)
switch r.URL.Path {
case "/v1/images/generations":
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
require.Equal(t, "gpt-image-1", gjson.GetBytes(body, "model").String())
case "/v1/images/edits":
require.NoError(t, r.ParseMultipartForm(1<<20))
defer func() {
if r.MultipartForm != nil {
_ = r.MultipartForm.RemoveAll()
}
}()
require.Equal(t, "gpt-image-1", r.FormValue("model"))
part, _, err := r.FormFile("image")
require.NoError(t, err)
_ = part.Close()
default:
t.Errorf("unexpected upstream path: %s", r.URL.Path)
}
time.Sleep(delay)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if status == http.StatusOK {
_, _ = io.WriteString(w, `{"created":1710000000,"data":[{"b64_json":"aW1hZ2U="}]}`)
} else {
_, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","code":"native_route_rejected","message":"delayed image rejection"}}`)
}
}))
t.Cleanup(upstream.Close)
target, err := url.Parse(upstream.URL)
require.NoError(t, err)
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Gateway.ImageNonstreamKeepaliveInterval = 1
repo := openAIImagesFailoverAccountRepo{accounts: []service.Account{{ID: 1, Name: "fixture", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{"api_key": "fixture-key", "base_url": "https://fixture.example/v1"}}}}
transport := &nativeImageRouteUpstream{target: target, client: upstream.Client()}
deferred := service.NewDeferredService(repo, nil, time.Minute)
gateway := service.NewOpenAIGatewayService(repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, service.NewBillingService(cfg, nil), nil, nil, transport, deferred, nil, nil, nil, nil, nil, nil, nil)
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
handler := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg)
router := gin.New()
router.Use(func(c *gin.Context) {
groupID := int64(1)
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, GroupID: &groupID, Group: &service.Group{ID: 1, AllowImageGeneration: true}, User: &service.User{ID: 1}})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1})
})
router.POST("/v1/images/generations", handler.Images)
router.POST("/v1/images/edits", handler.Images)
server := httptest.NewServer(router)
t.Cleanup(server.Close)
return server, &calls
}
func nativeImageRequest(t *testing.T, endpoint string, native bool) *http.Request {
t.Helper()
var body bytes.Buffer
contentType := "application/json"
if strings.HasSuffix(endpoint, "/edits") {
writer := multipart.NewWriter(&body)
require.NoError(t, writer.WriteField("model", "gpt-image-1"))
require.NoError(t, writer.WriteField("prompt", "edit fixture"))
part, err := writer.CreateFormFile("image", "input.png")
require.NoError(t, err)
_, err = part.Write([]byte("fixture-image"))
require.NoError(t, err)
require.NoError(t, writer.Close())
contentType = writer.FormDataContentType()
} else {
_, _ = body.WriteString(`{"model":"gpt-image-1","prompt":"fixture"}`)
}
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, endpoint, &body)
require.NoError(t, err)
req.Header.Set("Content-Type", contentType)
if native {
req.Header.Set("X-Codex-Image-Turn-Id", "fixture-turn")
}
return req
}
func TestNativeImagesRoutesDelayedResponse(t *testing.T) {
for _, path := range []string{"/v1/images/generations", "/v1/images/edits"} {
for _, status := range []int{http.StatusBadRequest, http.StatusOK} {
t.Run(fmt.Sprintf("%s/%d", path, status), func(t *testing.T) {
gateway, calls := newNativeImageRoute(t, 1200*time.Millisecond, status)
target, err := url.Parse(gateway.URL)
require.NoError(t, err)
proxy := httputil.NewSingleHostReverseProxy(target)
baseTransport, ok := http.DefaultTransport.(*http.Transport)
require.True(t, ok)
transport := baseTransport.Clone()
transport.ResponseHeaderTimeout = 3 * time.Second
defer transport.CloseIdleConnections()
proxy.Transport = transport
downstream := httptest.NewServer(proxy)
defer downstream.Close()
started := time.Now()
resp, err := downstream.Client().Do(nativeImageRequest(t, downstream.URL+path, true))
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
require.GreaterOrEqual(t, time.Since(started), 1200*time.Millisecond, "no heartbeat may commit early headers")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.Equal(t, status, resp.StatusCode, string(body))
require.EqualValues(t, 1, calls.Load())
require.True(t, gjson.ValidBytes(body), string(body))
require.NotContains(t, string(body), "event:")
if status == http.StatusOK {
require.EqualValues(t, 1710000000, gjson.GetBytes(body, "created").Int())
require.Equal(t, "aW1hZ2U=", gjson.GetBytes(body, "data.0.b64_json").String())
} else {
require.Equal(t, "native_route_rejected", gjson.GetBytes(body, "error.code").String())
require.Equal(t, "delayed image rejection", gjson.GetBytes(body, "error.message").String())
}
})
}
}
}
// This is a real HTTP proxy header deadline. Native clients intentionally get
// no heartbeat: a deadline below image latency fails, while a sufficiently long
// deadline is covered above. Ordinary clients retain their heartbeat behavior.
func TestNativeImagesRoutesProxyTimeout(t *testing.T) {
for _, path := range []string{"/v1/images/generations", "/v1/images/edits"} {
for _, native := range []bool{true, false} {
t.Run(fmt.Sprintf("%s/native=%t", path, native), func(t *testing.T) {
gateway, calls := newNativeImageRoute(t, 1600*time.Millisecond, http.StatusOK)
target, err := url.Parse(gateway.URL)
require.NoError(t, err)
proxy := httputil.NewSingleHostReverseProxy(target)
baseTransport, ok := http.DefaultTransport.(*http.Transport)
require.True(t, ok)
transport := baseTransport.Clone()
transport.ResponseHeaderTimeout = 1300 * time.Millisecond
defer transport.CloseIdleConnections()
proxy.Transport = transport
proxy.ErrorHandler = func(w http.ResponseWriter, _ *http.Request, _ error) { w.WriteHeader(http.StatusGatewayTimeout) }
downstream := httptest.NewServer(proxy)
defer downstream.Close()
resp, err := downstream.Client().Do(nativeImageRequest(t, downstream.URL+path, native))
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
if native {
require.Equal(t, http.StatusGatewayTimeout, resp.StatusCode)
} else {
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Equal(t, "aW1hZ2U=", gjson.GetBytes(body, "data.0.b64_json").String())
}
require.EqualValues(t, 1, calls.Load())
})
}
}
}
@@ -0,0 +1,143 @@
//go:build unit
package handler
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/iotest"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
type nativeEndpointUpstream struct {
service.HTTPUpstream
mode string
paths []string
}
func (u *nativeEndpointUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
u.paths = append(u.paths, req.URL.Path)
if u.mode == "transport error" {
return nil, errors.New("synthetic upstream transport failure")
}
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}}
switch u.mode {
case "HTTP error":
response.StatusCode = http.StatusBadRequest
response.Body = io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"synthetic rejection"}}`))
case "body read error":
response.Body = io.NopCloser(iotest.ErrReader(errors.New("synthetic body read failure")))
default:
if gjson.GetBytes(body, "stream").Bool() {
response.Header.Set("Content-Type", "text/event-stream")
response.Body = io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion))
} else {
response.Body = io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"k3","content":[{"type":"text","text":"partial"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`))
}
}
return response, nil
}
func (u *nativeEndpointUpstream) DoWithTLS(req *http.Request, proxy string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
return u.Do(req, proxy, accountID, concurrency)
}
func TestOpenAINativeAnthropicEndpointDiagnostics(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, route := range []struct {
name string
path string
protocol string
platform string
}{
{"messages", "/v1/messages", service.APIProtocolAnthropic, service.PlatformKimi},
{"chat", "/v1/chat/completions", service.APIProtocolAnthropic, service.PlatformKimi},
{"responses", "/v1/responses", service.APIProtocolAnthropic, service.PlatformKimi},
{"adaptive messages", "/v1/messages", service.APIProtocolAdaptive, service.PlatformZhipu},
} {
for _, stream := range []bool{false, true} {
for _, mode := range []string{"transport error", "HTTP error", "body read error", "success"} {
t.Run(fmt.Sprintf("%s/stream=%t/%s", route.name, stream, mode), func(t *testing.T) {
upstream := &nativeEndpointUpstream{mode: mode}
cfg := &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{AllowInsecureHTTP: true}}}
gateway := service.NewOpenAIGatewayService(
nil, nil, nil, nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil, upstream,
nil, nil, nil, nil, nil, nil, nil, nil,
)
account := &service.Account{
ID: 9501, Platform: route.platform, Type: service.AccountTypeAPIKey,
Credentials: map[string]any{
"api_key": "test-key", "api_protocol": route.protocol,
"base_url": "http://anthropic.example",
"api_base_urls": map[string]any{
service.APIProtocolAnthropic: "http://anthropic.example",
service.APIProtocolChatCompletions: "http://chat.example",
},
},
}
model := "k3"
if route.protocol == service.APIProtocolAdaptive {
require.False(t, account.SupportsNativeCNResponses())
model = "glm-5.3"
}
request := map[string]any{"model": model, "stream": stream}
if route.path == "/v1/responses" {
request["input"] = "hello"
} else {
request["messages"] = []map[string]string{{"role": "user", "content": "hello"}}
request["max_tokens"] = 32
}
body, err := json.Marshal(request)
require.NoError(t, err)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, route.path, strings.NewReader(string(body)))
// The same Gin context can retain an earlier attempt's protocol.
service.SetActualOpenAIUpstreamEndpoint(c, EndpointChatCompletions)
var result *service.OpenAIForwardResult
switch route.path {
case "/v1/messages":
result, err = gateway.ForwardAsAnthropic(context.Background(), c, account, body, "", "")
case "/v1/chat/completions":
result, err = gateway.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
default:
result, err = gateway.Forward(context.Background(), c, account, body)
}
if mode == "success" {
require.NoError(t, err)
require.NotNil(t, result)
require.Equal(t, EndpointMessages, result.UpstreamEndpoint)
require.Contains(t, recorder.Body.String(), "partial")
} else {
require.Error(t, err)
if mode != "body read error" {
require.Nil(t, result, "error diagnostics must work without a forward result")
}
}
require.Len(t, upstream.paths, 1)
require.True(t, strings.HasSuffix(upstream.paths[0], EndpointMessages), "the request actually used native Anthropic: %v", upstream.paths)
// This is the endpoint reader used when writing operations errors and result-less usage.
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, account.Platform))
require.Equal(t, EndpointMessages, service.GetActualOpenAIUpstreamEndpoint(c))
})
}
}
}
}
@@ -0,0 +1,136 @@
package handler
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
)
var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`)
// Codex injects external context as standalone outputs, without a model tool call.
// Use the legacy user-message representation for HTTP Responses interoperability.
func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", "browser_info", "goal_objective", "untrusted_context") || !hasUniqueJSONMembers(body) {
return body, false
}
var request map[string]json.RawMessage
if json.Unmarshal(body, &request) != nil {
return body, false
}
var input []json.RawMessage
if json.Unmarshal(request["input"], &input) != nil {
return body, false
}
changed := false
for i, raw := range input {
var item map[string]json.RawMessage
if json.Unmarshal(raw, &item) != nil {
continue
}
readString := func(key string) string {
var value string
_ = json.Unmarshal(item[key], &value)
return value
}
if readString("type") != "function_call_output" || readString("namespace") != "agent" {
continue
}
if callID, exists := item["call_id"]; exists {
var value string
if bytes.Equal(bytes.TrimSpace(callID), []byte("null")) || json.Unmarshal(callID, &value) != nil || strings.TrimSpace(value) != "" {
continue
}
}
name, output := readString("name"), readString("output")
if !validCodexUntrustedContext(name, output) {
continue
}
text := "<external_" + name + ">" + output + "</external_" + name + ">"
if validCodexPageContext(name, output) {
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
}
message := map[string]any{
"type": "message",
"role": "user",
"content": []map[string]string{{
"type": "input_text",
"text": text,
}},
}
encoded, err := json.Marshal(message)
if err != nil {
return body, false
}
input[i] = encoded
changed = true
}
if !changed {
return body, false
}
encodedInput, err := json.Marshal(input)
if err != nil {
return body, false
}
request["input"] = encodedInput
encoded, err := json.Marshal(request)
if err != nil {
return body, false
}
return encoded, true
}
func validCodexUntrustedContext(name, output string) bool {
switch name {
case "browser_info", "goal_objective", "untrusted_context":
return strings.TrimSpace(output) != ""
default:
return validCodexPageContext(name, output)
}
}
func validCodexPageContext(name, output string) bool {
if name == "codex_apps_open_page" {
return validCodexPageSnapshot(output)
}
parts := codexSelectedPageName.FindStringSubmatch(name)
if len(parts) != 3 {
return false
}
part, err := strconv.Atoi(parts[1])
if err != nil {
return false
}
total, err := strconv.Atoi(parts[2])
if err != nil || part > total {
return false
}
header, snapshot, ok := strings.Cut(output, "\n")
if !ok || strings.TrimSuffix(header, "\r") != fmt.Sprintf("Companion Page snapshot part %d of %d:", part, total) || strings.TrimSpace(snapshot) == "" {
return false
}
// A multi-part snapshot may split inside a JSON string; preserve each chunk verbatim.
return total > 1 || validCodexPageSnapshot(snapshot)
}
func validCodexPageSnapshot(text string) bool {
if !hasUniqueJSONMembers([]byte(text)) {
return false
}
var snapshot map[string]json.RawMessage
if json.Unmarshal([]byte(text), &snapshot) != nil {
return false
}
id, exists := snapshot["page_id"]
if !exists {
return false
}
if bytes.Equal(bytes.TrimSpace(id), []byte("null")) {
return true
}
var value string
return json.Unmarshal(id, &value) == nil && strings.TrimSpace(value) != ""
}
@@ -0,0 +1,251 @@
package handler
import (
"encoding/json"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"go.uber.org/zap"
)
func pageContextItem(name, output string) map[string]any {
return map[string]any{"type": "function_call_output", "id": "fco_page", "namespace": "agent", "name": name, "output": output}
}
func pageContextRequest(t *testing.T, items ...any) []byte {
t.Helper()
body, err := json.Marshal(map[string]any{"model": "gpt-5", "input": items})
require.NoError(t, err)
return body
}
func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
open := `{"page_id":null}`
selected := "Companion Page snapshot part 1 of 1:\n" + `{"page_id":null,"document_view":null}`
body := pageContextRequest(t, pageContextItem("codex_apps_open_page", open), pageContextItem("codex_apps_selected_page_part_1_of_1", selected), map[string]any{"role": "user", "content": "hello"})
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
require.Equal(t, 400, w.Code)
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.False(t, c.Writer.Written())
for i, original := range []string{open, selected} {
item := gjson.GetBytes(got, "input").Array()[i]
require.Equal(t, "message", item.Get("type").String())
require.Equal(t, "user", item.Get("role").String())
require.Contains(t, item.Get("content.0.text").String(), original)
require.False(t, item.Get("call_id").Exists())
require.False(t, item.Get("id").Exists())
}
require.Equal(t, "hello", gjson.GetBytes(got, "input.2.content").String())
again, changed := normalizeCodexUntrustedContext(got)
require.False(t, changed)
require.Equal(t, got, again)
}
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
// AdditionalContextToolOutput derives names from caller-provided context keys.
// Codex 0.169.0 enables this representation by default (openai/codex#60487).
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
t.Run(name, func(t *testing.T) {
output := "external context\nline two"
body := pageContextRequest(t, pageContextItem(name, output),
map[string]any{"role": "user", "content": "continue"})
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.False(t, c.Writer.Written())
item := gjson.GetBytes(got, "input.0")
require.Equal(t, "message", item.Get("type").String())
require.Equal(t, "user", item.Get("role").String())
require.Equal(t, "<external_"+name+">"+output+"</external_"+name+">", item.Get("content.0.text").String())
require.False(t, item.Get("call_id").Exists())
require.Equal(t, "continue", gjson.GetBytes(got, "input.1.content").String())
again, changed := normalizeCodexUntrustedContext(got)
require.False(t, changed)
require.Equal(t, got, again)
})
}
}
func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) {
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
for _, override := range []map[string]any{
{"call_id": "call_real"},
{"call_id": nil},
{"call_id": 42},
{"namespace": "other"},
{"namespace": nil},
{"namespace": 42},
{"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}},
{"output": " "},
{"output": nil},
} {
item := pageContextItem(name, "context")
for key, value := range override {
item[key] = value
}
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed, "name=%s override=%v", name, override)
require.Equal(t, body, got)
}
item := pageContextItem(name, "context")
delete(item, "namespace")
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
}
// Recognized external context cannot make an unrelated tool result valid.
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
pageContextItem("read_file", "result"))
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.Equal(t, 400, w.Code)
// Keep historical calls, prior response and exact numeric metadata intact.
body = []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"goal_objective","output":"finish"}]}`)
got, changed = normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
for _, index := range []string{"input.0", "input.1"} {
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
}
}
func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) {
names := []string{"browser_info", "goal_objective", "untrusted_context"}
for _, callID := range []string{"", " \t\n"} {
items := make([]any, 0, len(names))
for _, name := range names {
item := pageContextItem(name, "context for "+name)
item["call_id"] = callID
delete(item, "id")
items = append(items, item)
}
got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...))
require.True(t, changed)
require.Len(t, gjson.GetBytes(got, "input").Array(), len(names))
for i, item := range gjson.GetBytes(got, "input").Array() {
require.Equal(t, "user", item.Get("role").String())
require.Equal(t, "<external_"+names[i]+">context for "+names[i]+"</external_"+names[i]+">", item.Get("content.0.text").String())
}
}
}
func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) {
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
for _, body := range []string{
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`,
} {
got, changed := normalizeCodexUntrustedContext([]byte(body))
require.False(t, changed)
require.Equal(t, body, string(got))
}
}
}
func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) {
body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
for _, index := range []string{"input.0", "input.1"} {
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
}
badTool := pageContextItem("read_file", "result")
body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool)
got, changed = normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.True(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutputMissingCallID)
}
func TestNormalizeCodexPageContextMixedBootstrap(t *testing.T) {
for _, item := range []map[string]any{
{"type": "function_call_output", "namespace": "codex_app", "name": "create_thread", "output": delegationEnvelope},
{"type": "function_call_output", "namespace": "codex_app", "name": "automation_update", "output": "<heartbeat><automation_id>test</automation_id></heartbeat>"},
} {
body := pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), item)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
got, _ = normalizeCodexAutomationBootstrap(got)
got, _ = normalizeCodexDelegationBootstrap(got)
require.False(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutput)
}
}
func TestNormalizeCodexPageContextMultipart(t *testing.T) {
first := "Companion Page snapshot part 1 of 2:\n" + `{"page_id":"page1","document_view":"hello`
second := "Companion Page snapshot part 2 of 2:\n" + ` world"}`
body := pageContextRequest(t, pageContextItem("codex_apps_selected_page_part_1_of_2", first), pageContextItem("codex_apps_selected_page_part_2_of_2", second))
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Contains(t, gjson.GetBytes(got, "input.0.content.0.text").String(), first)
require.Contains(t, gjson.GetBytes(got, "input.1.content.0.text").String(), second)
}
func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T) {
for _, tc := range []struct {
name string
key string
value any
}{
{"real call", "call_id", "call_real"},
{"invalid call id", "call_id", 42},
{"null call id", "call_id", nil},
{"other namespace", "namespace", "codex_app"},
{"missing namespace", "namespace", ""},
{"other tool", "name", "read_file"},
{"other type", "type", "custom_tool_call_output"},
{"not JSON", "output", "some text"},
{"not snapshot", "output", `{"other":null}`},
{"wrong page id", "output", `{"page_id":1}`},
{"duplicate snapshot key", "output", `{"page_id":null,"page_id":"other"}`},
{"part without header", "name", "codex_apps_selected_page_part_1_of_1"},
{"part out of range", "name", "codex_apps_selected_page_part_2_of_1"},
} {
t.Run(tc.name, func(t *testing.T) {
item := pageContextItem("codex_apps_open_page", `{"page_id":null}`)
item[tc.key] = tc.value
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
})
}
for _, body := range []string{
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","call_id":"real","call_id":"","output":"{\"page_id\":null}"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":null}"}]} trailing`,
} {
got, changed := normalizeCodexUntrustedContext([]byte(body))
require.False(t, changed)
require.Equal(t, body, string(got))
}
}
@@ -0,0 +1,52 @@
package handler
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestOpenAIResponses_RejectsInvalidUTF8BeforeRouting(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, suffix := range []string{"", `,"stream":false`, `,"stream":true`} {
for _, invalid := range [][]byte{{0xbb, 0xd8, 0xb8, 0xb4}, {0xe4, 0xbd}, {0xff}} {
t.Run(fmt.Sprintf("%s/%x", suffix, invalid), func(t *testing.T) {
body := append([]byte(`{"input":"`), invalid...)
body = append(body, []byte(`"`+suffix+`}`)...)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
groupID := int64(2)
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 101, GroupID: &groupID, User: &service.User{ID: 1}})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1})
h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil)
h.Responses(c)
require.Equal(t, http.StatusBadRequest, w.Code)
require.Contains(t, w.Body.String(), "valid UTF-8 JSON")
require.Contains(t, w.Body.String(), "invalid_request_error")
})
}
}
}
func TestOpenAIResponses_ValidUnicodeReachesFieldValidation(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewBufferString(`{"input":"回复 ok 🌍"}`))
groupID := int64(2)
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 101, GroupID: &groupID, User: &service.User{ID: 1}})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1})
h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil)
h.Responses(c)
require.Equal(t, http.StatusBadRequest, w.Code)
require.Contains(t, w.Body.String(), "model is required")
require.NotContains(t, w.Body.String(), "UTF-8")
}
@@ -417,6 +417,9 @@ func (h *UsageHandler) Stats(c *gin.Context) {
return
}
stats.TotalAccountCost = nil
for i := range stats.Endpoints {
stats.Endpoints[i].AccountCost = 0
}
stats.UpstreamEndpoints = nil
stats.EndpointPaths = nil
@@ -440,6 +440,10 @@ func (s *userHandlerRefreshTokenCacheStub) DeleteTokenFamily(context.Context, st
return nil
}
func (s *userHandlerRefreshTokenCacheStub) ConsumeRefreshToken(context.Context, string) (*service.RefreshTokenData, error) {
return nil, service.ErrRefreshTokenNotFound
}
func (s *userHandlerRefreshTokenCacheStub) AddToUserTokenSet(context.Context, int64, string, time.Duration) error {
return nil
}
@@ -27,7 +27,7 @@ func NewUserMsgQueueHelper(
pingFormat SSEPingFormat,
pingInterval time.Duration,
) *UserMsgQueueHelper {
if pingInterval <= 0 {
if pingInterval < 0 {
pingInterval = defaultPingInterval
}
return &UserMsgQueueHelper{
@@ -86,7 +86,7 @@ func (h *UserMsgQueueHelper) waitForLockWithPing(
streamStarted *bool,
reqLog *zap.Logger,
) (func(), error) {
needPing := isStream && h.pingFormat != ""
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
var flusher http.Flusher
if needPing {
@@ -196,7 +196,7 @@ func (h *UserMsgQueueHelper) ThrottleWithPing(
)
// 延迟期间发送 SSE ping(复用 waitForLockWithPing 的 ping 逻辑)
needPing := isStream && h.pingFormat != ""
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
var flusher http.Flusher
if needPing {
flusher, _ = c.Writer.(http.Flusher)
+13 -1
View File
@@ -348,7 +348,7 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
return nil, err
}
outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano())
outRequestNo := fmt.Sprintf("%s%s%s", req.OrderID, alipayRefundRequestSep, alipayRefundRequestNoSuffix(req.Amount))
result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{
OutTradeNo: req.OrderID,
RefundAmount: req.Amount,
@@ -374,6 +374,18 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
}, nil
}
// alipayRefundRequestNoSuffix 生成跨重试稳定的 out_request_no 后缀。
// 支付宝把相同的 out_request_no 视为同一次退款请求;如果重试换号,
// "网关已受理但返回错误"后的重试会变成第二笔真实退款。
// 与 wxpayRefundID 一致,用金额区分同一订单的不同退款金额。
func alipayRefundRequestNoSuffix(amount string) string {
normalized := strings.NewReplacer(".", "", "-", "").Replace(strings.TrimSpace(amount))
if normalized == "" {
return "0"
}
return normalized
}
// QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS
// 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。
func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) {
@@ -480,6 +480,67 @@ func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) {
}
}
// out_request_no 必须跨重试稳定:支付宝把相同的 out_request_no 视为同一次退款请求。
// 如果重试生成新的请求号,一次"网关已受理但返回错误"的重试会退两次。
func TestAlipayRefundOutRequestNoIsStableAcrossRetries(t *testing.T) {
origRefund := alipayTradeRefund
t.Cleanup(func() { alipayTradeRefund = origRefund })
var outRequestNos []string
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
outRequestNos = append(outRequestNos, param.OutRequestNo)
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil
}
provider := &Alipay{client: &alipay.Client{}}
req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}
for i := 0; i < 2; i++ {
if _, err := provider.Refund(context.Background(), req); err != nil {
t.Fatalf("Refund() error = %v", err)
}
}
if len(outRequestNos) != 2 {
t.Fatalf("got %d refund calls, want 2", len(outRequestNos))
}
if outRequestNos[0] != "sub2_7-refund-1250" {
t.Fatalf("out_request_no = %q, want sub2_7-refund-1250", outRequestNos[0])
}
if outRequestNos[0] != outRequestNos[1] {
t.Fatalf("out_request_no changed across retries: %q != %q", outRequestNos[0], outRequestNos[1])
}
}
// 模拟支付宝的幂等语义:相同的 out_request_no 只产生一笔真实退款。
// 重试时如果请求号变了,钱会被退两次;稳定请求号下只退一次。
func TestAlipayRefundRetryDoesNotDoubleRefund(t *testing.T) {
origRefund := alipayTradeRefund
t.Cleanup(func() { alipayTradeRefund = origRefund })
const refundCents = 1250
refundedCents := 0
seen := make(map[string]struct{})
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
if _, ok := seen[param.OutRequestNo]; !ok {
seen[param.OutRequestNo] = struct{}{}
refundedCents += refundCents
}
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil
}
provider := &Alipay{client: &alipay.Client{}}
req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}
for i := 0; i < 2; i++ {
if _, err := provider.Refund(context.Background(), req); err != nil {
t.Fatalf("Refund() error = %v", err)
}
}
if refundedCents != refundCents {
t.Fatalf("retry refunded %d cents, want %d (one refund only)", refundedCents, refundCents)
}
}
func TestAlipayQueryRefundMapsStatus(t *testing.T) {
origQuery := alipayTradeFastPayRefundQuery
t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
+18 -8
View File
@@ -50,7 +50,8 @@ type easyPayCustomMethod struct {
}
// NewEasyPay creates a new EasyPay provider.
// config keys: pid, pkey, apiBase, notifyUrl, returnUrl, cid, cidAlipay, cidWxpay
// config keys: pid, pkey, apiBase, notifyUrl, returnUrl, cid, cidAlipay, cidWxpay,
// refundSuccessCode (0 or 1; defaults to 1).
func NewEasyPay(instanceID string, config map[string]string) (*EasyPay, error) {
for _, k := range []string{"pid", "pkey", "apiBase", "notifyUrl", "returnUrl"} {
if strings.TrimSpace(config[k]) == "" {
@@ -61,6 +62,9 @@ func NewEasyPay(instanceID string, config map[string]string) (*EasyPay, error) {
for k, v := range config {
cfg[k] = v
}
if code := strings.TrimSpace(cfg["refundSuccessCode"]); code != "" && code != "0" && code != "1" {
return nil, fmt.Errorf("easypay refundSuccessCode must be 0 or 1")
}
cfg["apiBase"] = normalizeEasyPayAPIBase(cfg["apiBase"])
return &EasyPay{
instanceID: instanceID,
@@ -371,7 +375,7 @@ func (e *EasyPay) queryOrder(ctx context.Context, outTradeNo string) (*easyPayQu
}
// An explicit failure code wins over any paid-looking status field that
// may accompany it.
if resp.Code != nil && !easyPayResponseCodeIsSuccess(resp.Code) {
if resp.Code != nil && !easyPayResponseCodeIsSuccess(resp.Code, easypayCodeSuccess) {
msg := strings.TrimSpace(resp.Msg)
if msg == "" {
msg = summarizeEasyPayResponse(body)
@@ -506,6 +510,12 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st
}
func (e *EasyPay) Refund(ctx context.Context, req payment.RefundRequest) (*payment.RefundResponse, error) {
// Compatible gateways disagree on refund codes. Keep the existing default
// unless this instance explicitly selects a zero-success refund protocol.
successCode := easypayCodeSuccess
if strings.TrimSpace(e.config["refundSuccessCode"]) == "0" {
successCode = 0
}
attempts := e.refundAttempts(req)
if len(attempts) == 0 {
return nil, fmt.Errorf("easypay refund missing order identifier")
@@ -516,7 +526,7 @@ func (e *EasyPay) Refund(ctx context.Context, req payment.RefundRequest) (*payme
if err != nil {
return nil, fmt.Errorf("easypay refund request: %w", err)
}
if err := parseEasyPayRefundResponse(status, body); err != nil {
if err := parseEasyPayRefundResponse(status, body, successCode); err != nil {
if firstErr == nil {
firstErr = err
}
@@ -573,7 +583,7 @@ func isEasyPayRefundOrderNotFound(err error) bool {
strings.Contains(lower, "not exist")
}
func parseEasyPayRefundResponse(status int, body []byte) error {
func parseEasyPayRefundResponse(status int, body []byte, successCode int) error {
summary := summarizeEasyPayResponse(body)
if status < http.StatusOK || status >= http.StatusMultipleChoices {
return fmt.Errorf("easypay refund HTTP %d: %s", status, summary)
@@ -597,7 +607,7 @@ func parseEasyPayRefundResponse(status int, body []byte) error {
if err := json.Unmarshal(body, &resp); err != nil {
return fmt.Errorf("easypay refund non-JSON response (HTTP %d): %s", status, summary)
}
if !easyPayResponseCodeIsSuccess(resp.Code) {
if !easyPayResponseCodeIsSuccess(resp.Code, successCode) {
msg := strings.TrimSpace(resp.Msg)
if msg == "" {
msg = summary
@@ -607,13 +617,13 @@ func parseEasyPayRefundResponse(status int, body []byte) error {
return nil
}
func easyPayResponseCodeIsSuccess(code any) bool {
func easyPayResponseCodeIsSuccess(code any, successCode int) bool {
switch v := code.(type) {
case float64:
return int(v) == easypayCodeSuccess
return v == float64(successCode)
case string:
n, err := strconv.Atoi(strings.TrimSpace(v))
return err == nil && n == easypayCodeSuccess
return err == nil && n == successCode
default:
return false
}
@@ -180,6 +180,60 @@ func TestEasyPayRefundResponseErrors(t *testing.T) {
}
}
func TestEasyPayRefundSuccessCode(t *testing.T) {
t.Parallel()
for _, successCode := range []string{"", "1", "0"} {
t.Run("configured="+successCode, func(t *testing.T) {
t.Parallel()
for _, code := range []string{`0`, `"0"`, `1`, `"1"`, `-1`, `1.5`, `0.5`, `null`, `false`, `""`} {
t.Run("response="+code, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"code":` + code + `,"msg":"gateway result"}`))
}))
defer server.Close()
provider, err := NewEasyPay("test-instance", map[string]string{
"pid": "1001", "pkey": "test-key", "apiBase": server.URL,
"notifyUrl": "https://site.example/notify", "returnUrl": "https://site.example/return",
"refundSuccessCode": successCode,
})
if err != nil {
t.Fatal(err)
}
resp, err := provider.Refund(context.Background(), payment.RefundRequest{OrderID: "out-456", Amount: "1.50"})
wantSuccess := code == `1` || code == `"1"`
if successCode == "0" {
wantSuccess = code == `0` || code == `"0"`
}
if wantSuccess {
if err != nil || resp == nil || resp.Status != payment.ProviderStatusSuccess {
t.Fatalf("Refund() = %+v, %v; want success", resp, err)
}
} else if err == nil || resp != nil {
t.Fatalf("Refund() = %+v, %v; want rejection", resp, err)
}
})
}
})
}
}
func TestNewEasyPayRejectsInvalidRefundSuccessCode(t *testing.T) {
t.Parallel()
for _, code := range []string{"-1", "2", "0.5", "0,1", "auto"} {
t.Run(code, func(t *testing.T) {
_, err := NewEasyPay("test-instance", map[string]string{
"pid": "1001", "pkey": "test-key", "apiBase": "https://pay.example",
"notifyUrl": "https://site.example/notify", "returnUrl": "https://site.example/return",
"refundSuccessCode": code,
})
if err == nil {
t.Fatal("NewEasyPay accepted an invalid refund success code")
}
})
}
}
func TestSummarizeEasyPayResponsePreservesUTF8(t *testing.T) {
t.Parallel()
@@ -0,0 +1,68 @@
package antigravity
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestCarbonGenerationThinkingLevels(t *testing.T) {
for _, tc := range []struct {
name, body, level string
thoughts bool
}{
{"default", `{}`, "", false},
{"low", `{"output_config":{"effort":"low"}}`, "low", false},
{"medium", `{"output_config":{"effort":"medium"}}`, "medium", false},
{"high", `{"output_config":{"effort":"high"}}`, "high", false},
{"disabled wins", `{"thinking":{"type":"disabled"},"output_config":{"effort":"high"}}`, "low", false},
{"low budget", `{"thinking":{"type":"enabled","budget_tokens":1024}}`, "low", true},
{"medium budget", `{"thinking":{"type":"enabled","budget_tokens":4096}}`, "medium", true},
{"high budget", `{"thinking":{"type":"enabled","budget_tokens":32768}}`, "high", true},
{"adaptive default", `{"thinking":{"type":"adaptive"}}`, "", true},
{"effort wins", `{"thinking":{"type":"enabled","budget_tokens":32768},"output_config":{"effort":"medium"}}`, "medium", true},
} {
t.Run(tc.name, func(t *testing.T) {
var req ClaudeRequest
require.NoError(t, json.Unmarshal([]byte(tc.body), &req))
req.Model = "gemini-4-carbon"
req.MaxTokens = 1000
config := buildGenerationConfig(&req)
data, err := json.Marshal(config)
require.NoError(t, err)
require.NotContains(t, string(data), "thinkingBudget")
require.Equal(t, 1000, config.MaxOutputTokens, "Carbon budgets must not raise output limits")
if tc.level == "" && !tc.thoughts {
require.Nil(t, config.ThinkingConfig)
return
}
require.NotNil(t, config.ThinkingConfig)
require.Equal(t, tc.level, config.ThinkingConfig.ThinkingLevel)
require.Equal(t, tc.thoughts, config.ThinkingConfig.IncludeThoughts)
})
}
}
func TestCarbonTierPreservesUpstreamSelection(t *testing.T) {
for _, tier := range []string{"low", "medium", "high"} {
cfg := buildGenerationConfig(&ClaudeRequest{Model: "gemini-4-carbon-" + tier, Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 32768}, OutputConfig: &ClaudeOutputConfig{Effort: "low"}})
require.NotNil(t, cfg.ThinkingConfig)
require.True(t, cfg.ThinkingConfig.IncludeThoughts)
require.Empty(t, cfg.ThinkingConfig.ThinkingLevel)
require.Zero(t, cfg.ThinkingConfig.ThinkingBudget)
}
// Other models retain the existing budget behavior.
cfg := buildGenerationConfig(&ClaudeRequest{Model: "claude-sonnet-4-6", Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 4096}})
require.Equal(t, 4096, cfg.ThinkingConfig.ThinkingBudget)
require.Empty(t, cfg.ThinkingConfig.ThinkingLevel)
}
func TestCarbonTransformUsesMappedModelForThinking(t *testing.T) {
req := &ClaudeRequest{Model: "client-alias", MaxTokens: 4096, Messages: []ClaudeMessage{{Role: "user", Content: json.RawMessage(`"hello"`)}}, Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 4096}}
data, err := TransformClaudeToGeminiWithOptions(req, "project", "gemini-4-carbon", TransformOptions{})
require.NoError(t, err)
require.Contains(t, string(data), `"thinkingLevel":"medium"`)
require.NotContains(t, string(data), `thinkingBudget`)
require.NotContains(t, string(data), `stopSequences`)
}
@@ -9,17 +9,23 @@ import (
// ClaudeRequest Claude Messages API 请求
type ClaudeRequest struct {
Model string `json:"model"`
Messages []ClaudeMessage `json:"messages"`
MaxTokens int `json:"max_tokens,omitempty"`
System json.RawMessage `json:"system,omitempty"` // string 或 []SystemBlock
Stream bool `json:"stream,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
Tools []ClaudeTool `json:"tools,omitempty"`
Thinking *ThinkingConfig `json:"thinking,omitempty"`
Metadata *ClaudeMetadata `json:"metadata,omitempty"`
Model string `json:"model"`
Messages []ClaudeMessage `json:"messages"`
MaxTokens int `json:"max_tokens,omitempty"`
System json.RawMessage `json:"system,omitempty"` // string 或 []SystemBlock
Stream bool `json:"stream,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
Tools []ClaudeTool `json:"tools,omitempty"`
Thinking *ThinkingConfig `json:"thinking,omitempty"`
Metadata *ClaudeMetadata `json:"metadata,omitempty"`
OutputConfig *ClaudeOutputConfig `json:"output_config,omitempty"`
}
// ClaudeOutputConfig carries the requested reasoning effort.
type ClaudeOutputConfig struct {
Effort string `json:"effort,omitempty"`
}
// ClaudeMessage Claude 消息
@@ -214,6 +220,7 @@ var geminiModels = []modelDef{
{ID: "gemini-3.8-flash-low", DisplayName: "Gemini 3.8 Flash Low", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
{ID: "gemini-3.8-flash-medium", DisplayName: "Gemini 3.8 Flash Medium", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
{ID: "gemini-3.8-flash-tiered", DisplayName: "Gemini 3.8 Flash", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
{ID: "gemini-4-carbon", DisplayName: "Gemini 4 Carbon", CreatedAt: "2026-11-10T00:00:00Z", IsReasoning: true},
{ID: "gemini-4-argon-high", DisplayName: "Gemini 4 Argon (High)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
{ID: "gemini-4-argon-low", DisplayName: "Gemini 4 Argon (Low)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
{ID: "gemini-4-argon-medium", DisplayName: "Gemini 4 Argon (Medium)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
@@ -15,6 +15,7 @@ func TestDefaultModels_ContainsNewAndLegacyImageModels(t *testing.T) {
}
requiredIDs := []string{
"gemini-4-carbon",
"claude-fable-5-1",
"claude-fable-5",
"claude-opus-4-8",
@@ -80,6 +81,9 @@ func TestClaudeContentItem_ThinkingAlwaysHasSignature(t *testing.T) {
func TestIsGeminiReasoningModel_IncludesProAgent(t *testing.T) {
t.Parallel()
if !IsGeminiReasoningModel("gemini-4-carbon") {
t.Fatal("expected Carbon to be recognized as a Gemini reasoning model")
}
if !IsGeminiReasoningModel("gemini-pro-agent") {
t.Fatal("expected gemini-pro-agent to be recognized as a Gemini reasoning model")
}
@@ -84,8 +84,9 @@ type GeminiImageConfig struct {
// GeminiThinkingConfig Gemini thinking 配置
type GeminiThinkingConfig struct {
IncludeThoughts bool `json:"includeThoughts"`
ThinkingBudget int `json:"thinkingBudget,omitempty"`
IncludeThoughts bool `json:"includeThoughts"`
ThinkingBudget int `json:"thinkingBudget,omitempty"`
ThinkingLevel string `json:"thinkingLevel,omitempty"`
}
// GeminiToolDeclaration Gemini 工具声明
@@ -504,6 +504,7 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu
return nil, false, fmt.Errorf("parse content blocks: %w", err)
}
var toolMediaParts []GeminiPart
for _, block := range blocks {
switch block.Type {
case "text":
@@ -591,14 +592,15 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu
for _, part := range media {
response.Parts = append(response.Parts, GeminiFunctionResponsePart{InlineData: part.InlineData})
}
} else {
toolMediaParts = append(toolMediaParts, media...)
}
parts = append(parts, GeminiPart{FunctionResponse: response})
if !multimodalToolResults {
parts = append(parts, media...)
}
}
}
parts = append(parts, toolMediaParts...)
return parts, strippedThinking, nil
}
@@ -694,6 +696,45 @@ func isAntigravityOpusHighTierModel(model string) bool {
strings.HasPrefix(lower, "claude-opus-4-8")
}
// carbonThinkingConfig preserves the upstream default when no effort is specified.
// https://aistudio.google.com/docs/whats-new-gemini-4-carbon
func carbonThinkingConfig(req *ClaudeRequest, bareModel bool) *GeminiThinkingConfig {
cfg := &GeminiThinkingConfig{}
if req.Thinking != nil {
cfg.IncludeThoughts = req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive"
}
if bareModel {
if req.OutputConfig != nil {
switch strings.ToLower(strings.TrimSpace(req.OutputConfig.Effort)) {
case "none", "minimal", "low":
cfg.ThinkingLevel = "low"
case "medium":
cfg.ThinkingLevel = "medium"
case "high", "xhigh", "max":
cfg.ThinkingLevel = "high"
}
}
if req.Thinking != nil {
if req.Thinking.Type == "disabled" {
cfg.ThinkingLevel = "low"
} else if cfg.ThinkingLevel == "" && req.Thinking.Type == "enabled" && req.Thinking.BudgetTokens > 0 {
switch {
case req.Thinking.BudgetTokens <= 1024:
cfg.ThinkingLevel = "low"
case req.Thinking.BudgetTokens <= 8192:
cfg.ThinkingLevel = "medium"
default:
cfg.ThinkingLevel = "high"
}
}
}
}
if !cfg.IncludeThoughts && cfg.ThinkingLevel == "" {
return nil
}
return cfg
}
func buildGenerationConfig(req *ClaudeRequest) *GeminiGenerationConfig {
maxLimit := maxOutputTokensLimit(req.Model)
config := &GeminiGenerationConfig{
@@ -710,8 +751,16 @@ func buildGenerationConfig(req *ClaudeRequest) *GeminiGenerationConfig {
config.MaxOutputTokens = req.MaxTokens
}
// Carbon accepts thinking levels rather than token budgets. Tiered IDs, when
// supplied by the account catalog, already select the level upstream.
carbonModel := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(req.Model)), "models/")
isCarbon := carbonModel == "gemini-4-carbon" || carbonModel == "gemini-4-carbon-low" || carbonModel == "gemini-4-carbon-medium" || carbonModel == "gemini-4-carbon-high"
if isCarbon {
config.ThinkingConfig = carbonThinkingConfig(req, carbonModel == "gemini-4-carbon")
}
// Thinking 配置
if req.Thinking != nil && (req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive") {
if !isCarbon && req.Thinking != nil && (req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive") {
config.ThinkingConfig = &GeminiThinkingConfig{
IncludeThoughts: true,
}
@@ -743,13 +743,13 @@ func TestTransformClaudeToGemini_ToolResultImagesReachUpstream(t *testing.T) {
require.Equal(t, "toolu_img_1", userParts[0].FunctionResponse.ID)
require.Equal(t, "loaded colors.png", userParts[0].FunctionResponse.Response["result"])
require.NotNil(t, userParts[1].InlineData)
require.Equal(t, "image/png", userParts[1].InlineData.MimeType)
require.Equal(t, "aGVsbG8=", userParts[1].InlineData.Data)
require.NotNil(t, userParts[1].FunctionResponse)
require.Equal(t, "read_image", userParts[1].FunctionResponse.Name)
require.Equal(t, "Command executed successfully.", userParts[1].FunctionResponse.Response["result"])
require.NotNil(t, userParts[2].FunctionResponse)
require.Equal(t, "read_image", userParts[2].FunctionResponse.Name)
require.Equal(t, "Command executed successfully.", userParts[2].FunctionResponse.Response["result"])
require.NotNil(t, userParts[2].InlineData)
require.Equal(t, "image/png", userParts[2].InlineData.MimeType)
require.Equal(t, "aGVsbG8=", userParts[2].InlineData.Data)
require.NotNil(t, userParts[3].InlineData)
require.Equal(t, "image/jpeg", userParts[3].InlineData.MimeType)
@@ -376,24 +376,15 @@ func cleanJSONSchemaRecursive(value any) any {
}
}
// 8. [SAFETY] 处理缺失 items 的 Array (Gemini 严苛要求 array 必须声明 items Schema)
// 8. Gemini 只允许 array 携带 items,且 items 必须是非空 Schema 对象。
if t, _ := schemaMap["type"].(string); t == "array" {
itemsVal, hasItems := schemaMap["items"]
needDefaultItems := false
if !hasItems || itemsVal == nil {
needDefaultItems = true
} else if itemsMap, ok := itemsVal.(map[string]any); ok {
if len(itemsMap) == 0 {
needDefaultItems = true
}
} else if _, isBool := itemsVal.(bool); isBool {
needDefaultItems = true
}
if needDefaultItems {
if items, ok := schemaMap["items"].(map[string]any); !ok || len(items) == 0 {
schemaMap["items"] = map[string]any{
"type": "string",
}
}
} else {
delete(schemaMap, "items")
}
// 9. [SAFETY] Required 字段对齐
@@ -101,3 +101,45 @@ func TestToolResultMediaPlacement(t *testing.T) {
})
}
}
func TestParallelToolResultsKeepFunctionResponsesContiguousBeforeMedia(t *testing.T) {
for _, model := range []string{"claude-opus-5-5-medium", "claude-sonnet-4-6", "gemini-2.5-flash"} {
t.Run(model, func(t *testing.T) {
raw := []byte(`{"model":"` + model + `","input":[
{"type":"function_call","call_id":"call_img_1","name":"view_image","arguments":"{\"path\":\"a.png\"}"},
{"type":"function_call","call_id":"call_img_2","name":"view_image","arguments":"{\"path\":\"b.jpg\"}"},
{"type":"function_call","call_id":"call_cmd_3","name":"exec_command","arguments":"{\"cmd\":\"ls\"}"},
{"type":"function_call_output","call_id":"call_img_1","output":[{"type":"input_image","image_url":"data:image/png;base64,AQID"}]},
{"type":"function_call_output","call_id":"call_img_2","output":[{"type":"input_text","text":"loaded b.jpg"},{"type":"input_image","image_url":"data:image/jpeg;base64,BAUG"}]},
{"type":"function_call_output","call_id":"call_cmd_3","output":"README.md"}
]}`)
var req apicompat.ResponsesRequest
require.NoError(t, json.Unmarshal(raw, &req))
anthropic, err := apicompat.ResponsesToAnthropicRequest(&req)
require.NoError(t, err)
body, err := json.Marshal(anthropic)
require.NoError(t, err)
var claude ClaudeRequest
require.NoError(t, json.Unmarshal(body, &claude))
wire, err := TransformClaudeToGeminiWithOptions(&claude, "test-project", model, TransformOptions{})
require.NoError(t, err)
parts := gjson.GetBytes(wire, "request.contents.1.parts").Array()
require.Len(t, parts, 5)
require.Equal(t, "call_img_1", parts[0].Get("functionResponse.id").String())
require.Equal(t, "view_image", parts[0].Get("functionResponse.name").String())
require.Equal(t, "call_img_2", parts[1].Get("functionResponse.id").String())
require.Equal(t, "view_image", parts[1].Get("functionResponse.name").String())
require.Equal(t, "loaded b.jpg", parts[1].Get("functionResponse.response.result").String())
require.Equal(t, "call_cmd_3", parts[2].Get("functionResponse.id").String())
require.Equal(t, "exec_command", parts[2].Get("functionResponse.name").String())
require.Equal(t, "README.md", parts[2].Get("functionResponse.response.result").String())
require.Equal(t, "image/png", parts[3].Get("inlineData.mimeType").String())
require.Equal(t, "AQID", parts[3].Get("inlineData.data").String())
require.Equal(t, "image/jpeg", parts[4].Get("inlineData.mimeType").String())
require.Equal(t, "BAUG", parts[4].Get("inlineData.data").String())
})
}
}
@@ -0,0 +1,35 @@
package apicompat
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestAnthropicToResponsesDeferredEffortValidation(t *testing.T) {
for _, effort := range []string{"", "low", "high", "max"} {
t.Run(effort, func(t *testing.T) {
req := &AnthropicRequest{
Model: "gpt-6.1-sol",
MaxTokens: 1,
Thinking: &AnthropicThinking{Type: "disabled"},
OutputConfig: &AnthropicOutputConfig{Effort: effort},
}
_, err := AnthropicToResponses(req)
require.Error(t, err)
_, err = AnthropicToResponsesWithMinOutputTokens(req, 32)
require.Error(t, err)
converted, err := AnthropicToResponsesWithOptions(req, AnthropicToResponsesOptions{
MinOutputTokens: 32,
DeferReasoningEffortValidation: true,
})
require.NoError(t, err)
require.Equal(t, "gpt-6.1-sol", converted.Model)
require.Equal(t, "none", converted.Reasoning.Effort)
require.Empty(t, converted.Reasoning.Summary)
require.Equal(t, 32, *converted.MaxOutputTokens)
require.Equal(t, "disabled", req.Thinking.Type)
require.Equal(t, effort, req.OutputConfig.Effort)
})
}
}
@@ -1,6 +1,7 @@
package apicompat
import (
"encoding/base64"
"encoding/json"
"testing"
@@ -197,6 +198,50 @@ func TestAnthropicToResponses_ThinkingSignatureBecomesReasoning(t *testing.T) {
assert.Equal(t, "function_call", items[3].Type)
}
func TestAnthropicToResponses_ForeignReasoningEnvelopePreservesToolHistory(t *testing.T) {
envelope := "ccswitch-openai-reasoning-v1:" + base64.RawURLEncoding.EncodeToString([]byte(
`{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"gAAAA-foreign"}`,
))
for _, tc := range []struct{ name, signature string }{
{"valid envelope", envelope},
{"surrounding whitespace", " \n" + envelope + "\t"},
{"malformed envelope", "ccswitch-openai-reasoning-v1:not-base64!"},
} {
t.Run(tc.name, func(t *testing.T) {
blocks, err := json.Marshal([]AnthropicContentBlock{
{Type: "thinking", Signature: tc.signature},
{Type: "thinking", Signature: "native-ciphertext"},
{Type: "text", Text: "Checking now."},
{Type: "tool_use", ID: "call_1", Name: "lookup", Input: json.RawMessage(`{"key":"value"}`)},
})
require.NoError(t, err)
resp, err := AnthropicToResponses(&AnthropicRequest{
Model: "gpt-6.1-sol", MaxTokens: 1024,
Messages: []AnthropicMessage{
{Role: "user", Content: json.RawMessage(`"Check this"`)},
{Role: "assistant", Content: blocks},
{Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"call_1","content":"found"}]`)},
},
})
require.NoError(t, err)
var items []ResponsesInputItem
require.NoError(t, json.Unmarshal(resp.Input, &items))
require.Len(t, items, 5)
require.Equal(t, "reasoning", items[1].Type)
require.Equal(t, "native-ciphertext", items[1].EncryptedContent)
require.Equal(t, "assistant", items[2].Role)
require.JSONEq(t, `[{"type":"output_text","text":"Checking now."}]`, string(items[2].Content))
require.Equal(t, "function_call", items[3].Type)
require.Equal(t, "call_1", items[3].CallID)
require.Equal(t, "lookup", items[3].Name)
require.JSONEq(t, `{"key":"value"}`, items[3].Arguments)
require.Equal(t, "function_call_output", items[4].Type)
require.Equal(t, "call_1", items[4].CallID)
require.Equal(t, "found", items[4].Output)
})
}
}
func TestAnthropicToResponses_MaxTokensFloor(t *testing.T) {
req := &AnthropicRequest{
Model: "gpt-5.2",
@@ -19,8 +19,22 @@ func AnthropicToResponses(req *AnthropicRequest) (*ResponsesRequest, error) {
// AnthropicToResponsesWithMinOutputTokens converts an Anthropic request using
// the supplied max_output_tokens floor.
func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTokens int) (*ResponsesRequest, error) {
if err := openai.ValidateGPT61ReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil {
return nil, err
return AnthropicToResponsesWithOptions(req, AnthropicToResponsesOptions{MinOutputTokens: minOutputTokens})
}
// AnthropicToResponsesOptions controls conversion and optional deferred effort
// validation. Callers deferring validation must validate raw selections before
// conversion and the final effort after applying their policy.
type AnthropicToResponsesOptions struct {
MinOutputTokens int
DeferReasoningEffortValidation bool
}
func AnthropicToResponsesWithOptions(req *AnthropicRequest, options AnthropicToResponsesOptions) (*ResponsesRequest, error) {
if !options.DeferReasoningEffortValidation {
if err := openai.ValidateGPT61ReasoningEffort(req.Model, anthropicReasoningEffort(req)); err != nil {
return nil, err
}
}
input, err := convertAnthropicToResponsesInput(req.System, req.Messages)
if err != nil {
@@ -56,8 +70,8 @@ func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTok
if req.MaxTokens > 0 {
v := req.MaxTokens
if v < minOutputTokens {
v = minOutputTokens
if v < options.MinOutputTokens {
v = options.MinOutputTokens
}
out.MaxOutputTokens = &v
}
@@ -192,6 +206,16 @@ func anthropicMsgToResponsesItems(m AnthropicMessage) ([]ResponsesInputItem, err
return anthropicUserToResponses(m.Content)
case "assistant":
return anthropicAssistantToResponses(m.Content)
case "system":
// Mid-conversation system turns (e.g. hook output) keep system-level
// authority: Responses uses developer for them, not user.
items, err := anthropicUserToResponses(m.Content)
for i := range items {
if items[i].Role == "user" {
items[i].Role = "developer"
}
}
return items, err
default:
return anthropicUserToResponses(m.Content)
}
@@ -302,6 +326,11 @@ func anthropicAssistantToResponses(raw json.RawMessage) ([]ResponsesInputItem, e
if sig == "" || strings.HasPrefix(sig, "gAAAA") {
continue
}
// CC Switch carries a JSON reasoning item in this versioned envelope,
// not provider ciphertext. Ignore the foreign state when resuming directly.
if strings.HasPrefix(sig, "ccswitch-openai-reasoning-v1:") {
continue
}
items = append(items, ResponsesInputItem{
Type: "reasoning",
EncryptedContent: sig,
@@ -53,7 +53,7 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse {
for _, block := range resp.Content {
switch block.Type {
case "thinking", "redacted_thinking":
if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model) || claude.IsHaiku55(resp.Model)) && (block.Signature != "" || block.Data != "") {
if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model) || claude.IsHaiku55(resp.Model) || claude.IsFable52(resp.Model) || claude.IsMythos52(resp.Model)) && (block.Signature != "" || block.Data != "") {
item := ResponsesOutput{Type: "reasoning", ID: generateItemID(), EncryptedContent: encodeAnthropicThinking(block)}
if block.Thinking != "" {
item.Summary = []ResponsesSummary{{Type: "summary_text", Text: block.Thinking}}
@@ -72,7 +72,7 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse {
})
}
case "text":
if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model) || claude.IsHaiku55(resp.Model)) && block.Text != "" {
if (claude.IsOpus55(resp.Model) || claude.IsSonnet55(resp.Model) || claude.IsHaiku55(resp.Model) || claude.IsFable52(resp.Model) || claude.IsMythos52(resp.Model)) && block.Text != "" {
outputs = append(outputs, ResponsesOutput{Type: "message", ID: generateItemID(), Role: "assistant", Status: "completed", Content: []ResponsesContentPart{{Type: "output_text", Text: block.Text}}})
continue
}
@@ -289,7 +289,7 @@ func ResponsesEventToSSE(evt ResponsesStreamEvent) (string, error) {
func anthToResHandleMessageStart(evt *AnthropicStreamEvent, state *AnthropicEventToResponsesState) []ResponsesStreamEvent {
if evt.Message != nil {
state.ResponseID = evt.Message.ID
state.PreserveThinkingSignatures = state.PreserveThinkingSignatures || claude.IsOpus55(evt.Message.Model) || claude.IsSonnet55(evt.Message.Model) || claude.IsHaiku55(evt.Message.Model)
state.PreserveThinkingSignatures = state.PreserveThinkingSignatures || claude.IsOpus55(evt.Message.Model) || claude.IsSonnet55(evt.Message.Model) || claude.IsHaiku55(evt.Message.Model) || claude.IsFable52(evt.Message.Model) || claude.IsMythos52(evt.Message.Model)
if state.Model == "" {
state.Model = evt.Message.Model
}
@@ -0,0 +1,32 @@
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// A system message in the middle of an Anthropic conversation (e.g. hook
// output) must reach Responses as a developer item, not as user input.
func TestAnthropicToResponses_MidConversationSystemBecomesDeveloper(t *testing.T) {
out, err := AnthropicToResponses(&AnthropicRequest{
Model: "gpt-5.2",
MaxTokens: 64,
Messages: []AnthropicMessage{
{Role: "user", Content: json.RawMessage(`"hi"`)},
{Role: "system", Content: json.RawMessage(`[{"type":"text","text":"hook output"}]`)},
{Role: "system", Content: json.RawMessage(`"extra context"`)},
},
})
require.NoError(t, err)
input := gjson.ParseBytes(out.Input).Array()
require.Len(t, input, 3)
require.Equal(t, "user", input[0].Get("role").String())
require.Equal(t, "developer", input[1].Get("role").String())
require.Equal(t, "hook output", input[1].Get("content.0.text").String())
require.Equal(t, "developer", input[2].Get("role").String())
require.Equal(t, "extra context", input[2].Get("content.0.text").String())
}
@@ -445,6 +445,38 @@ func TestChatCompletionsToResponses_ResponseFormatJsonSchema(t *testing.T) {
}`, string(resp.Text.Format))
}
func TestChatCompletionsToResponses_ResponseFormatJsonSchemaDefaultsStrictFalse(t *testing.T) {
req := &ChatCompletionsRequest{
Model: "gpt-4o",
Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Return structured JSON"`)}},
ResponseFormat: json.RawMessage(`{
"type":"json_schema",
"json_schema":{
"name":"answer",
"schema":{
"type":"object",
"properties":{"ok":{"type":"boolean"}},
"required":["ok"]
}
}
}`),
}
resp, err := ChatCompletionsToResponses(req)
require.NoError(t, err)
require.NotNil(t, resp.Text)
assert.JSONEq(t, `{
"type":"json_schema",
"name":"answer",
"schema":{
"type":"object",
"properties":{"ok":{"type":"boolean"}},
"required":["ok"]
},
"strict":false
}`, string(resp.Text.Format))
}
func TestChatCompletionsToResponses_ImageURL(t *testing.T) {
content := `[{"type":"text","text":"Describe this"},{"type":"image_url","image_url":{"url":"data:image/png;base64,abc123"}}]`
req := &ChatCompletionsRequest{
@@ -0,0 +1,144 @@
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestFableMythos52ResponsesAdaptiveThinking(t *testing.T) {
for _, model := range []string{"claude-fable-5-2", "claude-mythos-5-2"} {
t.Run(model, func(t *testing.T) {
for _, effort := range []string{"", "low", "medium", "high", "xhigh", "max", "none", "minimal", "invalid"} {
t.Run("effort="+effort, func(t *testing.T) {
out, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: model, Input: json.RawMessage(`"hello"`), Reasoning: &ResponsesReasoning{Effort: effort}})
if effort == "none" || effort == "minimal" || effort == "invalid" {
require.ErrorContains(t, err, "reasoning effort")
return
}
require.NoError(t, err)
require.NotNil(t, out.Thinking)
require.Equal(t, "adaptive", out.Thinking.Type)
require.Zero(t, out.Thinking.BudgetTokens)
want := effort
if want == "" {
want = "high"
}
require.Equal(t, want, out.OutputConfig.Effort)
})
}
out, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: model, Input: json.RawMessage(`"hello"`)})
require.NoError(t, err)
require.Equal(t, "adaptive", out.Thinking.Type)
require.Equal(t, "high", out.OutputConfig.Effort)
for _, choice := range []string{`"required"`, `{"type":"function","name":"lookup"}`, `"auto"`, `"none"`} {
_, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: model, Input: json.RawMessage(`"hello"`), ToolChoice: json.RawMessage(choice)})
if choice == `"auto"` || choice == `"none"` {
require.NoError(t, err)
} else {
require.ErrorContains(t, err, "forced tool_choice")
}
}
})
}
}
func TestFableMythos52SignedThinkingResponsesRoundTrip(t *testing.T) {
for _, model := range []string{"claude-fable-5-2", "claude-mythos-5-2"} {
for _, block := range []AnthropicContentBlock{
{Type: "thinking", Thinking: "", Signature: "upstream-signed-block"},
{Type: "redacted_thinking", Data: "upstream-redacted-block"},
} {
t.Run(model+"/"+block.Type, func(t *testing.T) {
response := AnthropicToResponsesResponse(&AnthropicResponse{Model: model, Content: []AnthropicContentBlock{block, {Type: "text", Text: "progress"}, {Type: "tool_use", ID: "toolu_1", Name: "lookup", Input: json.RawMessage(`{}`)}}})
require.Len(t, response.Output, 3)
raw, err := json.Marshal(response.Output)
require.NoError(t, err)
var items []ResponsesInputItem
require.NoError(t, json.Unmarshal(raw, &items))
items = append(items, ResponsesInputItem{Type: "function_call_output", CallID: response.Output[2].CallID, Output: "ok"})
raw, err = json.Marshal(items)
require.NoError(t, err)
converted, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: model, Input: raw})
require.NoError(t, err)
require.Len(t, converted.Messages, 2)
var blocks []AnthropicContentBlock
require.NoError(t, json.Unmarshal(converted.Messages[0].Content, &blocks))
require.Len(t, blocks, 3)
require.Equal(t, block, blocks[0])
require.Equal(t, "text", blocks[1].Type)
require.Equal(t, "tool_use", blocks[2].Type)
})
}
}
}
func TestFableMythos52ChatAdapter(t *testing.T) {
for _, model := range []string{"claude-fable-5-2", "claude-mythos-5-2"} {
t.Run(model, func(t *testing.T) {
for _, effort := range []string{"", "xhigh", "max", "none"} {
responses, err := ChatCompletionsToResponses(&ChatCompletionsRequest{Model: model, ReasoningEffort: effort, Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"hello"`)}}})
require.NoError(t, err)
out, err := ResponsesToAnthropicRequest(responses)
if effort == "none" {
require.ErrorContains(t, err, "reasoning effort")
continue
}
require.NoError(t, err)
require.Equal(t, "adaptive", out.Thinking.Type)
want := effort
if want == "" {
want = "high"
}
require.Equal(t, want, out.OutputConfig.Effort)
}
for _, choice := range []string{`"required"`, `{"type":"function","function":{"name":"lookup"}}`} {
responses, err := ChatCompletionsToResponses(&ChatCompletionsRequest{Model: model, ToolChoice: json.RawMessage(choice), Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"hello"`)}}})
require.NoError(t, err)
_, err = ResponsesToAnthropicRequest(responses)
require.ErrorContains(t, err, "forced tool_choice")
}
})
}
}
func TestFableMythos52DoesNotChangeOlderModelConversion(t *testing.T) {
for _, model := range []string{"claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"} {
out, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: model, Input: json.RawMessage(`"hello"`), Reasoning: &ResponsesReasoning{Effort: "xhigh"}, ToolChoice: json.RawMessage(`"required"`)})
require.NoError(t, err)
require.Equal(t, "max", out.OutputConfig.Effort)
require.Equal(t, "enabled", out.Thinking.Type)
require.Positive(t, out.Thinking.BudgetTokens)
}
}
func TestFableMythos52StreamPreservesThinking(t *testing.T) {
for _, model := range []string{"claude-fable-5-2", "claude-mythos-5-2"} {
state := NewAnthropicEventToResponsesState()
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_start", Message: &AnthropicResponse{Model: model}}, state)
require.True(t, state.PreserveThinkingSignatures)
index := 0
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_start", Index: &index, ContentBlock: &AnthropicContentBlock{Type: "thinking"}}, state)
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_delta", Index: &index, Delta: &AnthropicDelta{Type: "signature_delta", Signature: "signed-stream"}}, state)
events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_stop", Index: &index}, state)
found := false
for _, event := range events {
if event.Type == "response.output_item.done" && event.Item != nil {
require.Contains(t, event.Item.EncryptedContent, anthropicThinkingEnvelopePrefix)
found = true
}
}
require.True(t, found)
}
}
func TestFableMythos52SamplingValidation(t *testing.T) {
for _, model := range []string{"claude-fable-5-2", "claude-mythos-5-2"} {
temperature, topP := 0.5, 1.0
_, err := ResponsesToAnthropicRequest(&ResponsesRequest{Model: model, Input: json.RawMessage(`"hi"`), Temperature: &temperature})
require.ErrorContains(t, err, "temperature")
_, err = ResponsesToAnthropicRequest(&ResponsesRequest{Model: model, Input: json.RawMessage(`"hi"`), TopP: &topP})
require.ErrorContains(t, err, "top_p")
}
}
@@ -23,6 +23,11 @@ func chatResponseFormatToResponsesTextFormat(raw json.RawMessage) json.RawMessag
return raw
}
schema["type"] = rawJSONString("json_schema")
// Chat Completions defaults strict to false while Responses defaults to strict,
// so make the intended mode explicit to avoid the upstream rejecting the schema.
if _, ok := schema["strict"]; !ok {
schema["strict"] = json.RawMessage("false")
}
out, err := json.Marshal(schema)
if err != nil {
@@ -0,0 +1,24 @@
package apicompat
import "strings"
// IsServerSideSearchCall reports whether a Responses output item is a search
// that the xAI server runs itself, so the client has nothing to execute.
//
// xAI documents the Responses API form of X Search as a custom_tool_call whose
// call_id starts with xs_, and attachment search as one whose call_id starts
// with as_; both are "handled by the xAI server"
// (https://docs.x.ai/developers/tools/tool-usage-details, "Using Responses API"
// table; https://docs.x.ai/developers/tools/x-search, "How X Search Works").
// A custom_tool_call without these prefixes is a client tool call.
//
// This is the only place the prefix rule lives. Converters that turn
// custom_tool_call items into client tool calls skip items for which it
// returns true when the caller says the upstream is xAI, and Grok search
// counting includes them.
func IsServerSideSearchCall(itemType, callID string) bool {
if itemType != "custom_tool_call" {
return false
}
return strings.HasPrefix(callID, "xs_") || strings.HasPrefix(callID, "as_")
}
@@ -0,0 +1,189 @@
package apicompat
import (
"testing"
"github.com/stretchr/testify/require"
)
// serverSideSearchStream is the event sequence of one custom_tool_call item
// followed by a text answer, in the shape xAI documents for X Search.
func serverSideSearchStream(callID, name string) []*ResponsesStreamEvent {
item := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_1", CallID: callID, Name: name, Input: `{"query":"q"}`, Status: "completed"}
added := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_1", CallID: callID, Name: name}
message := ResponsesOutput{Type: "message", ID: "msg_1", Role: "assistant", Content: []ResponsesContentPart{{Type: "output_text", Text: "found it"}}}
return []*ResponsesStreamEvent{
{Type: "response.created", Response: &ResponsesResponse{ID: "resp_1"}},
{Type: "response.output_item.added", OutputIndex: 0, Item: &added},
{Type: "response.custom_tool_call_input.delta", OutputIndex: 0, ItemID: "ctc_1", Delta: `{"query":"q"}`},
{Type: "response.custom_tool_call_input.done", OutputIndex: 0, ItemID: "ctc_1", Input: `{"query":"q"}`},
{Type: "response.output_item.done", OutputIndex: 0, Item: &item},
{Type: "response.output_text.delta", OutputIndex: 1, Delta: "found it"},
{Type: "response.output_item.done", OutputIndex: 1, Item: &message},
{Type: "response.completed", Response: &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{item, message}}},
}
}
func anthropicEventsOf(events []*ResponsesStreamEvent, xai bool) []AnthropicStreamEvent {
state := NewResponsesEventToAnthropicState()
state.XAIServerSideSearch = xai
var out []AnthropicStreamEvent
for _, event := range events {
out = append(out, ResponsesEventToAnthropicEvents(event, state)...)
}
return out
}
func chatChunksOf(events []*ResponsesStreamEvent, xai bool) []ChatCompletionsChunk {
state := NewResponsesEventToChatState()
state.XAIServerSideSearch = xai
var out []ChatCompletionsChunk
for _, event := range events {
out = append(out, ResponsesEventToChatChunks(event, state)...)
}
return out
}
func anthropicToolUseStarts(events []AnthropicStreamEvent) int {
count := 0
for _, event := range events {
if event.Type == "content_block_start" && event.ContentBlock != nil && event.ContentBlock.Type == "tool_use" {
count++
}
}
return count
}
func anthropicStopReason(events []AnthropicStreamEvent) string {
for _, event := range events {
if event.Type == "message_delta" && event.Delta != nil {
return event.Delta.StopReason
}
}
return ""
}
func chatToolCallChunks(chunks []ChatCompletionsChunk) int {
count := 0
for _, chunk := range chunks {
for _, choice := range chunk.Choices {
count += len(choice.Delta.ToolCalls)
}
}
return count
}
func chatFinishReason(chunks []ChatCompletionsChunk) string {
for _, chunk := range chunks {
for _, choice := range chunk.Choices {
if choice.FinishReason != nil {
return *choice.FinishReason
}
}
}
return ""
}
func TestResponsesEventToAnthropicEvents_ServerSideSearchIsNotToolUse(t *testing.T) {
for _, tt := range []struct {
name, callID, toolName string
xai bool
wantToolUse int
wantStop string
}{
{"x search", "xs_123", "x_keyword_search", true, 0, "end_turn"},
{"attachment search", "as_456", "attachment_search", true, 0, "end_turn"},
{"client custom tool", "call_9", "exec", true, 1, "tool_use"},
{"x search call id on a non-xAI upstream", "xs_123", "x_keyword_search", false, 1, "tool_use"},
{"attachment search call id on a non-xAI upstream", "as_456", "attachment_search", false, 1, "tool_use"},
} {
t.Run(tt.name, func(t *testing.T) {
events := anthropicEventsOf(serverSideSearchStream(tt.callID, tt.toolName), tt.xai)
require.Equal(t, tt.wantToolUse, anthropicToolUseStarts(events))
require.Equal(t, tt.wantStop, anthropicStopReason(events))
})
}
}
func TestResponsesEventToAnthropicEvents_ServerSideSearchKeepsClientToolCall(t *testing.T) {
stream := serverSideSearchStream("xs_123", "x_keyword_search")
client := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_2", CallID: "call_9", Name: "exec", Input: "dir"}
clientAdded := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_2", CallID: "call_9", Name: "exec"}
mixed := append([]*ResponsesStreamEvent{}, stream[:len(stream)-1]...)
mixed = append(mixed,
&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: 2, Item: &clientAdded},
&ResponsesStreamEvent{Type: "response.custom_tool_call_input.delta", OutputIndex: 2, ItemID: "ctc_2", Delta: "dir"},
&ResponsesStreamEvent{Type: "response.output_item.done", OutputIndex: 2, Item: &client},
&ResponsesStreamEvent{Type: "response.completed", Response: &ResponsesResponse{ID: "resp_1", Status: "completed"}},
)
events := anthropicEventsOf(mixed, true)
require.Equal(t, 1, anthropicToolUseStarts(events))
require.Equal(t, "tool_use", anthropicStopReason(events))
}
func TestResponsesEventToChatChunks_ServerSideSearchIsNotToolCall(t *testing.T) {
for _, tt := range []struct {
name, callID, toolName string
xai bool
wantToolCalls int
wantFinish string
}{
{"x search", "xs_123", "x_keyword_search", true, 0, "stop"},
{"attachment search", "as_456", "attachment_search", true, 0, "stop"},
{"client custom tool", "call_9", "exec", true, 2, "tool_calls"},
{"x search call id on a non-xAI upstream", "xs_123", "x_keyword_search", false, 2, "tool_calls"},
{"attachment search call id on a non-xAI upstream", "as_456", "attachment_search", false, 2, "tool_calls"},
} {
t.Run(tt.name, func(t *testing.T) {
chunks := chatChunksOf(serverSideSearchStream(tt.callID, tt.toolName), tt.xai)
// A client call is announced once and then carries its input delta.
require.Equal(t, tt.wantToolCalls, chatToolCallChunks(chunks))
require.Equal(t, tt.wantFinish, chatFinishReason(chunks))
})
}
}
func TestBufferedResponseAccumulator_ServerSideSearchIsNotRebuiltAsFunctionCall(t *testing.T) {
rebuild := func(callID, name string, xai bool) []ResponsesOutput {
acc := NewBufferedResponseAccumulator()
acc.XAIServerSideSearch = xai
for _, event := range serverSideSearchStream(callID, name) {
if event.Type == "response.completed" {
continue
}
acc.ProcessEvent(event)
}
resp := &ResponsesResponse{ID: "resp_1", Status: "completed"}
acc.SupplementResponseOutput(resp)
return resp.Output
}
client := rebuild("call_9", "exec", true)
require.Equal(t, "function_call", client[len(client)-1].Type)
require.Equal(t, "call_9", client[len(client)-1].CallID)
for _, callID := range []string{"xs_123", "as_456"} {
notXAI := rebuild(callID, "x_keyword_search", false)
require.Equal(t, "function_call", notXAI[len(notXAI)-1].Type, "without the xAI switch the item is rebuilt as before")
output := rebuild(callID, "x_keyword_search", true)
for _, item := range output {
require.NotEqual(t, "function_call", item.Type, "a server-side search is not a client function call")
}
last := output[len(output)-1]
require.Equal(t, "custom_tool_call", last.Type)
require.Equal(t, callID, last.CallID)
require.Equal(t, `{"query":"q"}`, last.Input)
resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: output}
message := ResponsesToAnthropic(resp, "m")
require.Equal(t, "end_turn", *message.StopReason)
for _, block := range message.Content {
require.NotEqual(t, "tool_use", block.Type)
}
chat := ResponsesToChatCompletions(resp, "m")
require.Empty(t, chat.Choices[0].Message.ToolCalls)
require.Equal(t, "stop", chat.Choices[0].FinishReason)
}
}
@@ -0,0 +1,30 @@
package apicompat
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestIsServerSideSearchCall(t *testing.T) {
tests := []struct {
name string
itemType string
callID string
want bool
}{
{"x search", "custom_tool_call", "xs_123", true},
{"attachment search", "custom_tool_call", "as_456", true},
{"padded call id is not a prefix match", "custom_tool_call", " xs_123", false},
{"client custom tool", "custom_tool_call", "call_9", false},
{"prefix is not a substring", "custom_tool_call", "call_xs_9", false},
{"no call id", "custom_tool_call", "", false},
{"function call keeps its client meaning", "function_call", "xs_123", false},
{"other server-side item types are separate items", "x_search_call", "xs_123", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, IsServerSideSearchCall(tt.itemType, tt.callID))
})
}
}
@@ -190,6 +190,11 @@ type ResponsesEventToAnthropicState struct {
PendingThinkingSignature string
HasToolCall bool
// XAIServerSideSearch is set by callers whose upstream is xAI. A
// custom_tool_call that IsServerSideSearchCall then never becomes a tool_use
// block, because xAI runs it itself.
XAIServerSideSearch bool
// OutputIndexToBlockIdx maps Responses output_index → Anthropic content block index.
OutputIndexToBlockIdx map[int]int
@@ -349,6 +354,9 @@ func resToAnthHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE
// function_call 与 custom_tool_call(custom/freeform 工具,如新版 apply_patch)
// 同样映射为 Anthropic 的 tool_use 块。
case "function_call", "custom_tool_call":
if state.XAIServerSideSearch && IsServerSideSearchCall(evt.Item.Type, evt.Item.CallID) {
return nil
}
var events []AnthropicStreamEvent
events = append(events, closeCurrentBlock(state)...)
@@ -17,7 +17,9 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
isOpus55 := claude.IsOpus55(req.Model)
isSonnet55 := claude.IsSonnet55(req.Model)
isHaiku55 := claude.IsHaiku55(req.Model)
system, messages, err := convertResponsesInputToAnthropic(req.Instructions, req.Input, isOpus55 || isSonnet55 || isHaiku55)
isFableOrMythos52 := claude.IsFable52(req.Model) || claude.IsMythos52(req.Model)
isAdaptiveModel := isOpus55 || isSonnet55 || isHaiku55 || isFableOrMythos52
system, messages, err := convertResponsesInputToAnthropic(req.Instructions, req.Input, isAdaptiveModel)
if err != nil {
return nil, err
}
@@ -57,13 +59,14 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
out.ToolChoice = tc
}
// The 5.5 models reject manual thinking. Opus/Sonnet 5.5 additionally reject
// The 5.5 models and Fable/Mythos 5.2 reject manual thinking.
// Fable/Mythos 5.2 and Opus/Sonnet 5.5 additionally reject
// forced tool use; Haiku 5.5 accepts it (starts with the tool call, no thinking
// block). Sonnet 5.5 supports between_tools to disable up-front thinking;
// Haiku 5.5 uses disabled (at high effort or below) instead.
// Resolve the upstream model before conversion: client aliases need not
// identify a Claude model.
if isOpus55 || isSonnet55 || isHaiku55 {
if isAdaptiveModel {
var choice struct {
Type string `json:"type"`
}
@@ -76,8 +79,10 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
return nil, fmt.Errorf("%s does not support forced tool_choice; use auto or none", req.Model)
}
effort := "medium"
if isSonnet55 {
if isSonnet55 || isFableOrMythos52 {
effort = "high"
}
if isSonnet55 {
if req.Temperature != nil && *req.Temperature != 1 {
return nil, fmt.Errorf("claude-sonnet-5-5 does not support non-default temperature")
}
@@ -85,15 +90,15 @@ func ResponsesToAnthropicRequest(req *ResponsesRequest) (*AnthropicRequest, erro
return nil, fmt.Errorf("claude-sonnet-5-5 does not support non-default top_p")
}
}
if isHaiku55 {
if isHaiku55 || isFableOrMythos52 {
if req.Temperature != nil && *req.Temperature != 1 {
return nil, fmt.Errorf("claude-haiku-5-5 does not support non-default temperature")
return nil, fmt.Errorf("%s does not support non-default temperature", req.Model)
}
if req.TopP != nil && *req.TopP != 0.99 {
return nil, fmt.Errorf("claude-haiku-5-5 does not support non-default top_p")
return nil, fmt.Errorf("%s does not support non-default top_p", req.Model)
}
if req.Temperature != nil && req.TopP != nil {
return nil, fmt.Errorf("claude-haiku-5-5 does not allow temperature and top_p together; omit both")
return nil, fmt.Errorf("%s does not allow temperature and top_p together; omit both", req.Model)
}
}
if req.Reasoning != nil && req.Reasoning.Effort != "" {
@@ -131,6 +131,11 @@ type ResponsesEventToChatState struct {
argumentBuffers map[int]*strings.Builder
IncludeUsage bool
Usage *ChatUsage
// XAIServerSideSearch is set by callers whose upstream is xAI. A
// custom_tool_call that IsServerSideSearchCall then never becomes a tool
// call, because xAI runs it itself.
XAIServerSideSearch bool
}
// NewResponsesEventToChatState returns an initialised stream state.
@@ -266,6 +271,9 @@ func resToChatHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE
if evt.Item == nil || (evt.Item.Type != "function_call" && evt.Item.Type != "custom_tool_call") {
return nil
}
if state.XAIServerSideSearch && IsServerSideSearchCall(evt.Item.Type, evt.Item.CallID) {
return nil
}
state.SawToolCall = true
idx := state.NextToolCallIndex
@@ -498,10 +506,16 @@ func generateChatCmplID() string {
// ---------------------------------------------------------------------------
type bufferedFuncCall struct {
OutputIndex int
CallID string
Name string
Args strings.Builder
OutputIndex int
CallID string
Name string
Namespace string
EncryptedFunctionArgs json.RawMessage
EncryptedContent string
Args strings.Builder
// ServerSideSearch marks a custom_tool_call the xAI server ran itself; it
// is rebuilt as that item, never as a client function_call.
ServerSideSearch bool
}
// BufferedResponseAccumulator collects content from Responses SSE delta events
@@ -513,6 +527,11 @@ type BufferedResponseAccumulator struct {
reasoning strings.Builder
funcCalls []bufferedFuncCall
outputIndexToFuncIdx map[int]int
// XAIServerSideSearch is set by callers whose upstream is xAI. A
// custom_tool_call that IsServerSideSearchCall is then rebuilt as that item
// instead of as a client function_call.
XAIServerSideSearch bool
}
// NewBufferedResponseAccumulator returns an initialised accumulator.
@@ -540,9 +559,13 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent)
idx := len(a.funcCalls)
a.outputIndexToFuncIdx[event.OutputIndex] = idx
a.funcCalls = append(a.funcCalls, bufferedFuncCall{
OutputIndex: event.OutputIndex,
CallID: event.Item.CallID,
Name: event.Item.Name,
OutputIndex: event.OutputIndex,
CallID: event.Item.CallID,
Name: event.Item.Name,
Namespace: event.Item.Namespace,
EncryptedFunctionArgs: event.Item.EncryptedFunctionArgs,
EncryptedContent: event.Item.EncryptedContent,
ServerSideSearch: a.XAIServerSideSearch && IsServerSideSearchCall(event.Item.Type, event.Item.CallID),
})
}
case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta":
@@ -606,11 +629,23 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput {
}
for i := range a.funcCalls {
if a.funcCalls[i].ServerSideSearch {
out = append(out, ResponsesOutput{
Type: "custom_tool_call",
CallID: a.funcCalls[i].CallID,
Name: a.funcCalls[i].Name,
Input: a.funcCalls[i].Args.String(),
})
continue
}
out = append(out, ResponsesOutput{
Type: "function_call",
CallID: a.funcCalls[i].CallID,
Name: a.funcCalls[i].Name,
Arguments: a.funcCalls[i].Args.String(),
Type: "function_call",
CallID: a.funcCalls[i].CallID,
Name: a.funcCalls[i].Name,
Namespace: a.funcCalls[i].Namespace,
EncryptedFunctionArgs: a.funcCalls[i].EncryptedFunctionArgs,
EncryptedContent: a.funcCalls[i].EncryptedContent,
Arguments: a.funcCalls[i].Args.String(),
})
}
+3
View File
@@ -417,6 +417,9 @@ type ResponsesOutput struct {
Arguments string `json:"arguments,omitempty"`
// 来源为 namespace 子工具时的归属命名空间(codex 按 namespace+name 路由该调用)。
Namespace string `json:"namespace,omitempty"`
// Preserve the upstream encryption marker, including explicit null/[];
// omitting it can make sealed arguments appear to be plaintext.
EncryptedFunctionArgs json.RawMessage `json:"encrypted_function_args,omitempty"`
// type=custom_tool_call(custom/freeform 工具,input 为自由文本)
Input string `json:"input,omitempty"`
@@ -9,7 +9,7 @@ func TestIsSupportedCLIVersion(t *testing.T) {
want bool
}{
{"内置基线本身", CLICurrentVersion, true},
{"高于基线的补丁位", "2.1.259", true},
{"高于基线的补丁位", "2.1.322", true},
{"高于基线的次版本", "2.2.0", true},
{"高于基线的主版本", "3.0.0", true},
{"低于基线", "2.1.219", false},
@@ -41,8 +41,8 @@ func TestResolveCLIVersion(t *testing.T) {
}{
{"未配置时用内置基线", "", CLICurrentVersion},
{"只有空白等同未配置", " ", CLICurrentVersion},
{"合法覆盖生效", "2.1.259", "2.1.259"},
{"两侧空白被裁掉", " 2.1.259 ", "2.1.259"},
{"合法覆盖生效", "2.1.322", "2.1.322"},
{"两侧空白被裁掉", " 2.1.322 ", "2.1.322"},
{"非法值回落基线", "not-a-version", CLICurrentVersion},
{"向下覆盖被拒", "2.0.0", CLICurrentVersion},
{"预发布后缀被拒(会毒化账号指纹)", "2.2.0-local", CLICurrentVersion},
+15 -2
View File
@@ -31,6 +31,7 @@ const (
BetaContextManagement = "context-management-2025-06-27"
BetaThinkingBindingControls = "thinking-binding-controls-2026-08-01"
BetaMidConversationOutputConfig = "mid-conversation-output-config-2026-07-01"
BetaPerTurnControl = "per-turn-control-2026-07-01"
BetaExtendedCacheTTL = "extended-cache-ttl-2025-04-11"
// server-side refusal fallback beta 字段族(beta Messages API 专有)。
@@ -87,7 +88,7 @@ const DefaultCacheControlTTL = "5m"
//
// ⚠️ 读取实际生效的版本号请用 CLIVersion(),它会叠加 SUB2API_CLAUDE_CLI_VERSION 覆盖。
// 直接引用本常量只在"表达内置基线"时才正确(例如覆盖值的下限校验)。
const CLICurrentVersion = "2.1.258"
const CLICurrentVersion = "2.1.321"
// FullClaudeCodeMimicryBetas 返回最"像"真实 Claude Code CLI 的完整 beta 列表,
// 用于 OAuth 账号伪装成 Claude Code 时使用。
@@ -145,6 +146,18 @@ type Model struct {
// DefaultModels Claude Code 客户端支持的默认模型列表
var DefaultModels = []Model{
{
ID: "claude-fable-5-2",
Type: "model",
DisplayName: "Claude Fable 5.2",
CreatedAt: "2026-11-09T00:00:00Z",
},
{
ID: "claude-mythos-5-2",
Type: "model",
DisplayName: "Claude Mythos 5.2",
CreatedAt: "2026-11-09T00:00:00Z",
},
{
ID: "claude-fable-5-1",
Type: "model",
@@ -241,7 +254,7 @@ func DefaultModelIDs() []string {
}
// DefaultTestModel 测试时使用的默认模型
const DefaultTestModel = "claude-sonnet-4-5-20250929"
const DefaultTestModel = "claude-sonnet-4-6"
// ModelIDOverrides Claude OAuth 请求需要的模型 ID 映射
var ModelIDOverrides = map[string]string{
@@ -57,6 +57,16 @@ func IsHaiku55(model string) bool {
return normalizeEffortModelID(model) == "claude-haiku-5-5"
}
// IsFable52 identifies Fable 5.2 after provider/local suffix normalization.
func IsFable52(model string) bool {
return normalizeEffortModelID(model) == "claude-fable-5-2"
}
// IsMythos52 identifies Mythos 5.2 after provider/local suffix normalization.
func IsMythos52(model string) bool {
return normalizeEffortModelID(model) == "claude-mythos-5-2"
}
func normalizeEffortModelID(model string) string {
id := strings.ToLower(strings.TrimSpace(model))
id = strings.TrimPrefix(id, "models/")
@@ -0,0 +1,38 @@
package claude
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestClaude52CatalogAndCapabilities(t *testing.T) {
for _, family := range []string{"fable", "mythos"} {
id := "claude-" + family + "-5-2"
t.Run(id, func(t *testing.T) {
count := 0
for _, model := range DefaultModels {
if model.ID == id {
count++
require.Equal(t, "model", model.Type)
require.Equal(t, "2026-11-09T00:00:00Z", model.CreatedAt)
}
}
require.Equal(t, 1, count)
for _, variant := range []string{id, "anthropic/" + id, "global.anthropic." + id, id + "-thinking", id + "-20261109"} {
require.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, EffortLevelsForModel(variant))
require.Equal(t, family == "fable", IsFable52(variant))
require.Equal(t, family == "mythos", IsMythos52(variant))
}
})
}
for _, model := range []string{"claude-fable-5-1", "claude-fable-5-20", "claude-fable-5-2-preview", "claude-mythos-5-20", "claude-mythos-5-2-preview"} {
require.False(t, IsFable52(model))
require.False(t, IsMythos52(model))
}
}
func TestCLICurrentVersionSatisfiesFable52Gate(t *testing.T) {
// https://code.claude.com/docs/en/model-config
require.GreaterOrEqual(t, compareSemver(t, CLICurrentVersion, "2.1.321"), 0)
}
@@ -4,7 +4,7 @@ import "testing"
func TestSupportsMultimodalFunctionResponses(t *testing.T) {
for model, want := range map[string]bool{
"gemini-3-pro": true, "gemini-3.8-flash": true, "gemini-4-argon": true,
"gemini-3-pro": true, "gemini-3.8-flash": true, "gemini-4-argon": true, "gemini-4-carbon": true,
"models/gemini-3-flash-preview": true, "gemini-2.5-flash": false,
"claude-sonnet-4-6": false, "client-alias": false, "": false,
} {
+1
View File
@@ -35,6 +35,7 @@ func DefaultModels() []Model {
{Name: "models/gemini-3.7-flash", SupportedGenerationMethods: methods},
{Name: "models/gemini-3.8-flash", SupportedGenerationMethods: methods},
{Name: "models/gemini-4-argon", SupportedGenerationMethods: methods},
{Name: "models/gemini-4-carbon", SupportedGenerationMethods: methods},
}
}
@@ -12,6 +12,7 @@ func TestDefaultModels_ContainsFallbackCatalogModels(t *testing.T) {
}
required := []string{
"models/gemini-4-carbon",
"models/gemini-3-pro-image",
"models/gemini-3.1-pro-preview-customtools",
"models/gemini-3.1-flash-image",
@@ -41,3 +42,14 @@ func TestHasFallbackModel_RecognizesCustomtoolsModel(t *testing.T) {
t.Fatalf("did not expect unknown model to exist in fallback catalog")
}
}
func TestHasFallbackModel_Carbon(t *testing.T) {
for _, model := range []string{"gemini-4-carbon", "models/gemini-4-carbon"} {
if !HasFallbackModel(model) {
t.Fatalf("expected Carbon fallback: %s", model)
}
}
if HasFallbackModel("gemini-4-carbon-preview") {
t.Fatal("must not invent a preview alias")
}
}
+1
View File
@@ -28,6 +28,7 @@ var DefaultModels = []Model{
{ID: "gemini-3.7-flash", Type: "model", DisplayName: "Gemini 3.7 Flash", CreatedAt: ""},
{ID: "gemini-3.8-flash", Type: "model", DisplayName: "Gemini 3.8 Flash", CreatedAt: ""},
{ID: "gemini-4-argon", Type: "model", DisplayName: "Gemini 4 Argon", CreatedAt: ""},
{ID: "gemini-4-carbon", Type: "model", DisplayName: "Gemini 4 Carbon", CreatedAt: ""},
}
// GoogleOneModels is the conservative model set exposed for legacy Google One
@@ -11,6 +11,7 @@ func TestDefaultModels_ContainsImageModels(t *testing.T) {
}
required := []string{
"gemini-4-carbon",
"gemini-3.1-flash-image",
"gemini-3-pro-image",
DefaultTestModel,
@@ -32,7 +33,7 @@ func TestGoogleOneModels_ExcludeUnsupportedNewAndImageModels(t *testing.T) {
t.Fatalf("expected Google One model %q to map to itself", id)
}
}
for _, id := range []string{"gemini-2.5-flash-image", "gemini-3.1-flash-image", "gemini-3.5-flash"} {
for _, id := range []string{"gemini-2.5-flash-image", "gemini-3.1-flash-image", "gemini-3.5-flash", "gemini-4-carbon"} {
if _, ok := mapping[id]; ok {
t.Fatalf("did not expect unsupported Google One model %q", id)
}
Loaded 100 of 433 files, more files were not shown because too many files have changed in this diff. Show more