diff --git a/.github/SECURITY.md b/.github/SECURITY.md
new file mode 100644
index 000000000..7ef6e7583
--- /dev/null
+++ b/.github/SECURITY.md
@@ -0,0 +1,107 @@
+# Security Policy
+
+[English](#english) | [中文](#中文)
+
+## English
+
+### Reporting a Vulnerability
+
+**Please do not report security vulnerabilities through public GitHub issues, pull requests, or discussions.**
+
+Report them privately through GitHub's private vulnerability reporting:
+
+**[Report a vulnerability](https://github.com/Wei-Shaw/sub2api/security/advisories/new)**
+
+(Repository → **Security** tab → **Report a vulnerability**.) Only the maintainers can see the report, and the advisory becomes the place to discuss, fix, and eventually publish the issue.
+
+If you cannot use GitHub private vulnerability reporting, email **dev@sub2api.org** instead, with `[Security]` in the subject line.
+
+A useful report includes:
+
+- The affected component and version (release tag or commit)
+- Impact: what an attacker can do and which privileges they need
+- Minimal reproduction steps or a proof of concept
+- Any non-default configuration required to trigger the issue
+- A suggested fix, if you have one
+
+### Supported Versions
+
+Sub2API releases frequently, and fixes ship in a new release rather than being backported.
+
+| Version | Supported |
+| ------- | --------- |
+| Latest release | ✅ |
+| Older releases | ❌ |
+
+Please confirm that the issue reproduces on the latest release or on `main` before reporting.
+
+### Scope
+
+In scope: the Sub2API backend, frontend, official Docker images, and deployment files in this repository.
+
+Usually out of scope:
+
+- Issues that require already-compromised admin credentials or server access
+- Risks arising from explicitly weakening documented security settings (for example, disabling `security.url_allowlist`)
+- Vulnerabilities in upstream AI providers or third-party dependencies with no Sub2API-specific impact (please report those upstream)
+- Missing best-practice headers or scanner output without a demonstrated impact
+
+### Disclosure Process
+
+1. We acknowledge the report and assess its validity and severity.
+2. We develop a fix privately in the advisory and may ask you to verify it.
+3. We publish a release containing the fix, then publish the GitHub Security Advisory (with a CVE when applicable), crediting you unless you prefer to stay anonymous.
+
+Please keep details private until the advisory is published. This is a volunteer-maintained project, so response times are best effort.
+
+## 中文
+
+### 报告漏洞
+
+**请不要通过公开的 Issue、Pull Request 或 Discussion 报告安全漏洞。**
+
+请使用 GitHub 私密漏洞报告功能提交:
+
+**[提交漏洞报告](https://github.com/Wei-Shaw/sub2api/security/advisories/new)**
+
+(仓库 → **Security** 标签页 → **Report a vulnerability**。)报告仅维护者可见,后续的讨论、修复与公告发布都在该安全公告中进行。
+
+如果无法使用 GitHub 私密漏洞报告,也可以发送邮件至 **dev@sub2api.org**,邮件标题请注明 `[Security]`。
+
+报告中建议包含:
+
+- 受影响的组件与版本(Release tag 或 commit)
+- 影响:攻击者能做什么、需要什么权限
+- 最小复现步骤或 PoC
+- 触发问题所需的非默认配置
+- 修复建议(如有)
+
+### 支持的版本
+
+Sub2API 发版频繁,安全修复随新版本发布,不向旧版本回移。
+
+| 版本 | 是否支持 |
+| ---- | -------- |
+| 最新 Release | ✅ |
+| 更早的版本 | ❌ |
+
+报告前请先确认问题在最新 Release 或 `main` 上仍可复现。
+
+### 范围
+
+范围内:本仓库中的 Sub2API 后端、前端、官方 Docker 镜像与部署文件。
+
+通常不在范围内:
+
+- 需要事先已掌握管理员凭据或服务器权限才能利用的问题
+- 因主动关闭文档中的安全配置(如关闭 `security.url_allowlist`)而产生的风险
+- 上游 AI 服务商或第三方依赖自身的漏洞,且对 Sub2API 无特定影响(请向上游报告)
+- 仅缺少最佳实践响应头或扫描器输出,但未证明实际影响
+
+### 披露流程
+
+1. 我们确认收到报告,并评估其有效性与严重程度。
+2. 我们在安全公告中私下开发修复,可能请你协助验证。
+3. 我们先发布包含修复的版本,再公开 GitHub 安全公告(适用时申请 CVE),并致谢报告者(如你希望匿名则不署名)。
+
+在公告发布前请勿公开漏洞细节。本项目由志愿者维护,响应时间尽力而为。
diff --git a/.github/audit-exceptions.yml b/.github/audit-exceptions.yml
index 6243f0fa7..5881136f5 100644
--- a/.github/audit-exceptions.yml
+++ b/.github/audit-exceptions.yml
@@ -3,16 +3,16 @@ exceptions:
- package: xlsx
advisory: "GHSA-4r6h-8v6p-xvw6"
severity: high
- reason: "Admin export only; switched to dynamic import to reduce exposure (CVE-2023-30533)"
- mitigation: "Load only on export; restrict export permissions and data scope"
- expires_on: "2026-10-06"
+ reason: "Write-only: admin UsageView lazily imports xlsx solely for XLSX.write export; the advisory requires parsing a crafted file and no XLSX.read path exists (CVE-2023-30533)"
+ mitigation: "Never parse untrusted spreadsheets with xlsx; no patched version on npm, migrate to SheetJS CDN build or another writer before expiry"
+ expires_on: "2027-01-06"
owner: "security@your-domain"
- package: xlsx
advisory: "GHSA-5pgg-2g8v-p4x9"
severity: high
- reason: "Admin export only; switched to dynamic import to reduce exposure (CVE-2024-22363)"
- mitigation: "Load only on export; restrict export permissions and data scope"
- expires_on: "2026-10-06"
+ reason: "Write-only: admin UsageView lazily imports xlsx solely for XLSX.write export; the advisory requires parsing a crafted file and no XLSX.read path exists (CVE-2024-22363)"
+ mitigation: "Never parse untrusted spreadsheets with xlsx; no patched version on npm, migrate to SheetJS CDN build or another writer before expiry"
+ expires_on: "2027-01-06"
owner: "security@your-domain"
- package: lodash
advisory: "GHSA-r5fr-rjxr-66jc"
diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml
index 2bac7259a..276bd8b23 100644
--- a/.github/workflows/backend-ci.yml
+++ b/.github/workflows/backend-ci.yml
@@ -33,7 +33,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
- go version | grep -q 'go1.27.0'
+ go version | grep -q 'go1.27.2'
- name: Unit tests
working-directory: backend
run: make test-unit
@@ -73,10 +73,10 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
- go version | grep -q 'go1.27.0'
+ go version | grep -q 'go1.27.2'
- name: golangci-lint
uses: golangci/golangci-lint-action@v9
with:
- version: v2.13
+ version: v2.14.0
args: --timeout=30m
working-directory: backend
diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml
index 97357efde..8caec3ff4 100644
--- a/.github/workflows/security-scan.yml
+++ b/.github/workflows/security-scan.yml
@@ -23,7 +23,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
- go version | grep -q 'go1.27.0'
+ go version | grep -q 'go1.27.2'
- name: Run govulncheck
working-directory: backend
run: |
diff --git a/Dockerfile b/Dockerfile
index 484bb66bb..64e93d84e 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -8,7 +8,7 @@
# =============================================================================
ARG NODE_IMAGE=node:24-alpine
-ARG GOLANG_IMAGE=golang:1.27.0-alpine
+ARG GOLANG_IMAGE=golang:1.27.2-alpine
ARG ALPINE_IMAGE=alpine:3.21
ARG POSTGRES_IMAGE=postgres:18-alpine
ARG GOPROXY=https://goproxy.cn,direct
diff --git a/Makefile b/Makefile
index e205902e2..55d9b7353 100644
--- a/Makefile
+++ b/Makefile
@@ -8,6 +8,12 @@ FRONTEND_CRITICAL_VITEST := \
src/components/account/__tests__/OpenAIReferralCell.spec.ts \
src/components/account/__tests__/OpenAIReferralCell.transport.spec.ts \
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__/CreateAccountModal.spec.ts \
+ src/components/account/__tests__/EditAccountModal.spec.ts \
+ src/components/account/__tests__/credentialsBuilder.spec.ts \
+ src/components/account/__tests__/OpenCodeGoProtocolRulesEditor.spec.ts \
src/components/keys/__tests__/BulkEditKeysModal.spec.ts \
src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts \
src/views/user/__tests__/KeysView.spec.ts \
@@ -18,10 +24,12 @@ FRONTEND_CRITICAL_VITEST := \
src/views/user/__tests__/PaymentResultView.spec.ts \
src/views/user/__tests__/ChannelStatusView.mode.spec.ts \
src/components/user/profile/__tests__/ProfileInfoCard.spec.ts \
+ src/components/user/profile/__tests__/ProfileIdentityBindingsSection.spec.ts \
src/views/admin/__tests__/SettingsView.spec.ts \
src/features/channel-monitor-v2/__tests__/designSystem.structure.spec.ts \
src/features/channel-monitor-v2/__tests__/monitorFormat.spec.ts \
- src/features/channel-monitor-v2/__tests__/monitorZoom.spec.ts
+ src/features/channel-monitor-v2/__tests__/monitorZoom.spec.ts \
+ src/components/admin/channel/__tests__/PricingEntryCard.modelDefaultPrice.spec.ts
# 一键编译前后端
build: build-backend build-frontend
diff --git a/README_CN.md b/README_CN.md
index 46a7b2202..0c68b3620 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -380,8 +380,10 @@ JWT_SECRET=your_jwt_secret_here
TOTP_ENCRYPTION_KEY=your_totp_key_here
# 可选:管理员账号
-ADMIN_EMAIL=admin@example.com
-ADMIN_PASSWORD=your_admin_password
+# 留空则首次启动时自动生成随机邮箱(登录用户名)和密码,并输出到日志。
+# 请勿使用 admin@example.com 这类可被猜中的值,它们是暴力破解的目标。
+ADMIN_EMAIL=
+ADMIN_PASSWORD=
# 可选:自定义端口
SERVER_PORT=8080
@@ -442,9 +444,9 @@ docker compose -f docker-compose.local.yml logs -f sub2api
在浏览器中打开 `http://你的服务器IP:8080`
-如果管理员密码是自动生成的,在日志中查找:
+如果管理员邮箱(登录用户名)或密码是自动生成的,在日志中查找:
```bash
-docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
+docker compose -f docker-compose.local.yml logs sub2api | grep "Generated admin"
```
#### 升级
@@ -743,6 +745,31 @@ OAuth / Setup Token 图片请求使用 Responses 主控模型调用 `image_gener
---
+## TypeSafe / Jev 使用说明
+
+Sub2API 支持使用 TypeSafe API Key 账户,通过 Jev 原生、非流式的 System One 协议调用模型。
+
+- 平台:`typesafe`;账号类型:API Key
+- 默认上游:`https://api.typesafe.ai`
+- 对外端点:`POST /v1/systemone`
+- 模型:`jev-latest`,TypeSafe 分组的 `/v1/models` 也会返回该模型
+- 问题类型:`noul`、`choice`、`score`
+
+请求和成功响应保持 System One 原生 JSON 结构。该端点不兼容 Chat Completions、Responses、Anthropic Messages 或流式客户端。
+
+问题校验遵循 TypeSafe OpenAPI 的线上协议 schema(SDK v0.5.7 也使用该 schema)。所有问题的 `instructions` 都可以省略或为 `null`。Noul 的 `criteria` 可以省略或为 `null`,其中 `true`/`false` 的描述和 Choice 描述支持字符串、对象、数组或 `null`。Score 的 `criteria` 必须是至少包含一档描述的数组,每档支持字符串、对象或数组;单档也合法。SDK 的整数键 Score 映射会由 SDK 在发送前转换为数组。
+
+```bash
+curl https://your-sub2api.example.com/v1/systemone \
+ -H 'Authorization: Bearer sk-your-sub2api-key' \
+ -H 'Content-Type: application/json' \
+ --data '{"model":"jev-latest","state":"待评估文本","questions":{"safety":{"type":"noul","instructions":"评估文本是否不安全"}}}'
+```
+
+`jev-latest` 内置价格为输入 `$0.042/百万 tokens`、输出 `$0`,渠道定价可以覆盖。凭据、欠费、权限、限流、过载、服务端和网络错误(`401`、`402`、`403`、`429`、`529`、`5xx`、传输错误)沿用现有账号错误策略(含自定义错误码与临时不可调度规则)并切换账号;请求错误(`400`、`413`、`422`)不会切换账号重试,也不会改变账号状态。TypeSafe 分组(以及路由到 TypeSafe 的 Composite 请求)调用 Messages、Chat Completions、Responses、count_tokens 时返回 `404`。
+
+---
+
## Antigravity 使用说明
Sub2API 支持 [Antigravity](https://antigravity.so/) 账户,授权后可通过专用端点访问 Claude 和 Gemini 模型。
diff --git a/README_JA.md b/README_JA.md
index 0d18a658c..26b9d0944 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -355,8 +355,10 @@ JWT_SECRET=your_jwt_secret_here
TOTP_ENCRYPTION_KEY=your_totp_key_here
# オプション: 管理者アカウント
-ADMIN_EMAIL=admin@example.com
-ADMIN_PASSWORD=your_admin_password
+# 空欄の場合、初回起動時にランダムなメールアドレス(ログインユーザー名)とパスワードが自動生成され、ログに出力されます。
+# admin@example.com のような推測されやすい値は総当たり攻撃の標的になるため避けてください。
+ADMIN_EMAIL=
+ADMIN_PASSWORD=
# オプション: カスタムポート
SERVER_PORT=8080
@@ -405,9 +407,9 @@ docker compose -f docker-compose.local.yml logs -f sub2api
ブラウザで `http://YOUR_SERVER_IP:8080` を開いてください。
-管理者パスワードが自動生成された場合は、ログで確認できます:
+管理者メールアドレス(ログインユーザー名)またはパスワードが自動生成された場合は、ログで確認できます:
```bash
-docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
+docker compose -f docker-compose.local.yml logs sub2api | grep "Generated admin"
```
#### アップグレード
diff --git a/backend/.golangci.yml b/backend/.golangci.yml
index 08d1b61f4..0ddcf5797 100644
--- a/backend/.golangci.yml
+++ b/backend/.golangci.yml
@@ -123,6 +123,15 @@ linters:
exclusions:
rules:
+ # x/net v0.60 deprecated the HTTP/2 compatibility adapters. Keep their
+ # existing per-protocol idle timeout and PING configuration in this CI fix.
+ - path: 'internal/(repository/http_upstream(_http2_keepalive_test)?|server/http)\.go$'
+ linters: [ staticcheck ]
+ text: 'SA1019: (\(golang\.org/x/net/http2\.(Server|Transport)\)\.|golang\.org/x/net/http2\.(ConfigureServer|ConfigureTransports|Server|Transport)\b)'
+ # Upstream libraries can still return the legacy typed GOAWAY error.
+ - path: 'internal/service/openai_codex_models_service(_test)?\.go$'
+ linters: [ staticcheck ]
+ text: 'SA1019: golang\.org/x/net/http2\.GoAwayError\b'
# G703/G704 污点分析在测试文件中只会命中 httptest mock 与测试者自设的
# 环境变量路径,不构成攻击面;且该分析跨环境结果不稳定(本地/CI 报告的
# 位置集合不同),逐点 nolint 无法收敛,故按路径豁免。生产代码不豁免,
diff --git a/backend/Dockerfile b/backend/Dockerfile
index 398d9bdfc..40e228cd3 100644
--- a/backend/Dockerfile
+++ b/backend/Dockerfile
@@ -1,4 +1,4 @@
-FROM golang:1.27.0-alpine
+FROM golang:1.27.2-alpine
WORKDIR /app
diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION
index 18efdb9ae..5ed5faa5f 100644
--- a/backend/cmd/server/VERSION
+++ b/backend/cmd/server/VERSION
@@ -1 +1 @@
-1.1.8
+1.1.10
diff --git a/backend/ent/migrate/schema.go b/backend/ent/migrate/schema.go
index 22caddf4f..88292b633 100644
--- a/backend/ent/migrate/schema.go
+++ b/backend/ent/migrate/schema.go
@@ -1128,6 +1128,7 @@ var (
{Name: "amount", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "decimal(20,2)"}},
{Name: "pay_amount", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "decimal(20,2)"}},
{Name: "fee_rate", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
+ {Name: "bonus_amount", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,2)"}},
{Name: "recharge_code", Type: field.TypeString, Size: 64},
{Name: "out_trade_no", Type: field.TypeString, Size: 64, Default: ""},
{Name: "payment_type", Type: field.TypeString, Size: 30},
@@ -1170,7 +1171,7 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "payment_orders_users_payment_orders",
- Columns: []*schema.Column{PaymentOrdersColumns[39]},
+ Columns: []*schema.Column{PaymentOrdersColumns[40]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
@@ -1179,7 +1180,7 @@ var (
{
Name: "paymentorder_out_trade_no",
Unique: true,
- Columns: []*schema.Column{PaymentOrdersColumns[8]},
+ Columns: []*schema.Column{PaymentOrdersColumns[9]},
Annotation: &entsql.IndexAnnotation{
Where: "out_trade_no <> ''",
},
@@ -1187,37 +1188,37 @@ var (
{
Name: "paymentorder_user_id",
Unique: false,
- Columns: []*schema.Column{PaymentOrdersColumns[39]},
+ Columns: []*schema.Column{PaymentOrdersColumns[40]},
},
{
Name: "paymentorder_status",
Unique: false,
- Columns: []*schema.Column{PaymentOrdersColumns[21]},
+ Columns: []*schema.Column{PaymentOrdersColumns[22]},
},
{
Name: "paymentorder_expires_at",
Unique: false,
- Columns: []*schema.Column{PaymentOrdersColumns[29]},
+ Columns: []*schema.Column{PaymentOrdersColumns[30]},
},
{
Name: "paymentorder_created_at",
Unique: false,
- Columns: []*schema.Column{PaymentOrdersColumns[37]},
+ Columns: []*schema.Column{PaymentOrdersColumns[38]},
},
{
Name: "paymentorder_paid_at",
Unique: false,
- Columns: []*schema.Column{PaymentOrdersColumns[30]},
+ Columns: []*schema.Column{PaymentOrdersColumns[31]},
},
{
Name: "paymentorder_payment_type_paid_at",
Unique: false,
- Columns: []*schema.Column{PaymentOrdersColumns[9], PaymentOrdersColumns[30]},
+ Columns: []*schema.Column{PaymentOrdersColumns[10], PaymentOrdersColumns[31]},
},
{
Name: "paymentorder_order_type",
Unique: false,
- Columns: []*schema.Column{PaymentOrdersColumns[14]},
+ Columns: []*schema.Column{PaymentOrdersColumns[15]},
},
},
}
diff --git a/backend/ent/mutation.go b/backend/ent/mutation.go
index 8a533188b..affee9d37 100644
--- a/backend/ent/mutation.go
+++ b/backend/ent/mutation.go
@@ -30113,6 +30113,8 @@ type PaymentOrderMutation struct {
addpay_amount *float64
fee_rate *float64
addfee_rate *float64
+ bonus_amount *float64
+ addbonus_amount *float64
recharge_code *string
out_trade_no *string
payment_type *string
@@ -30580,6 +30582,62 @@ func (m *PaymentOrderMutation) ResetFeeRate() {
m.addfee_rate = nil
}
+// SetBonusAmount sets the "bonus_amount" field.
+func (m *PaymentOrderMutation) SetBonusAmount(f float64) {
+ m.bonus_amount = &f
+ m.addbonus_amount = nil
+}
+
+// BonusAmount returns the value of the "bonus_amount" field in the mutation.
+func (m *PaymentOrderMutation) BonusAmount() (r float64, exists bool) {
+ v := m.bonus_amount
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldBonusAmount returns the old "bonus_amount" field's value of the PaymentOrder entity.
+// If the PaymentOrder 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 *PaymentOrderMutation) OldBonusAmount(ctx context.Context) (v float64, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldBonusAmount is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldBonusAmount requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldBonusAmount: %w", err)
+ }
+ return oldValue.BonusAmount, nil
+}
+
+// AddBonusAmount adds f to the "bonus_amount" field.
+func (m *PaymentOrderMutation) AddBonusAmount(f float64) {
+ if m.addbonus_amount != nil {
+ *m.addbonus_amount += f
+ } else {
+ m.addbonus_amount = &f
+ }
+}
+
+// AddedBonusAmount returns the value that was added to the "bonus_amount" field in this mutation.
+func (m *PaymentOrderMutation) AddedBonusAmount() (r float64, exists bool) {
+ v := m.addbonus_amount
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// ResetBonusAmount resets all changes to the "bonus_amount" field.
+func (m *PaymentOrderMutation) ResetBonusAmount() {
+ m.bonus_amount = nil
+ m.addbonus_amount = nil
+}
+
// SetRechargeCode sets the "recharge_code" field.
func (m *PaymentOrderMutation) SetRechargeCode(s string) {
m.recharge_code = &s
@@ -32123,7 +32181,7 @@ func (m *PaymentOrderMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *PaymentOrderMutation) Fields() []string {
- fields := make([]string, 0, 39)
+ fields := make([]string, 0, 40)
if m.user != nil {
fields = append(fields, paymentorder.FieldUserID)
}
@@ -32145,6 +32203,9 @@ func (m *PaymentOrderMutation) Fields() []string {
if m.fee_rate != nil {
fields = append(fields, paymentorder.FieldFeeRate)
}
+ if m.bonus_amount != nil {
+ fields = append(fields, paymentorder.FieldBonusAmount)
+ }
if m.recharge_code != nil {
fields = append(fields, paymentorder.FieldRechargeCode)
}
@@ -32263,6 +32324,8 @@ func (m *PaymentOrderMutation) Field(name string) (ent.Value, bool) {
return m.PayAmount()
case paymentorder.FieldFeeRate:
return m.FeeRate()
+ case paymentorder.FieldBonusAmount:
+ return m.BonusAmount()
case paymentorder.FieldRechargeCode:
return m.RechargeCode()
case paymentorder.FieldOutTradeNo:
@@ -32350,6 +32413,8 @@ func (m *PaymentOrderMutation) OldField(ctx context.Context, name string) (ent.V
return m.OldPayAmount(ctx)
case paymentorder.FieldFeeRate:
return m.OldFeeRate(ctx)
+ case paymentorder.FieldBonusAmount:
+ return m.OldBonusAmount(ctx)
case paymentorder.FieldRechargeCode:
return m.OldRechargeCode(ctx)
case paymentorder.FieldOutTradeNo:
@@ -32472,6 +32537,13 @@ func (m *PaymentOrderMutation) SetField(name string, value ent.Value) error {
}
m.SetFeeRate(v)
return nil
+ case paymentorder.FieldBonusAmount:
+ v, ok := value.(float64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetBonusAmount(v)
+ return nil
case paymentorder.FieldRechargeCode:
v, ok := value.(string)
if !ok {
@@ -32713,6 +32785,9 @@ func (m *PaymentOrderMutation) AddedFields() []string {
if m.addfee_rate != nil {
fields = append(fields, paymentorder.FieldFeeRate)
}
+ if m.addbonus_amount != nil {
+ fields = append(fields, paymentorder.FieldBonusAmount)
+ }
if m.addplan_id != nil {
fields = append(fields, paymentorder.FieldPlanID)
}
@@ -32739,6 +32814,8 @@ func (m *PaymentOrderMutation) AddedField(name string) (ent.Value, bool) {
return m.AddedPayAmount()
case paymentorder.FieldFeeRate:
return m.AddedFeeRate()
+ case paymentorder.FieldBonusAmount:
+ return m.AddedBonusAmount()
case paymentorder.FieldPlanID:
return m.AddedPlanID()
case paymentorder.FieldSubscriptionGroupID:
@@ -32777,6 +32854,13 @@ func (m *PaymentOrderMutation) AddField(name string, value ent.Value) error {
}
m.AddFeeRate(v)
return nil
+ case paymentorder.FieldBonusAmount:
+ v, ok := value.(float64)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.AddBonusAmount(v)
+ return nil
case paymentorder.FieldPlanID:
v, ok := value.(int64)
if !ok {
@@ -32976,6 +33060,9 @@ func (m *PaymentOrderMutation) ResetField(name string) error {
case paymentorder.FieldFeeRate:
m.ResetFeeRate()
return nil
+ case paymentorder.FieldBonusAmount:
+ m.ResetBonusAmount()
+ return nil
case paymentorder.FieldRechargeCode:
m.ResetRechargeCode()
return nil
diff --git a/backend/ent/paymentorder.go b/backend/ent/paymentorder.go
index c59106588..e957807be 100644
--- a/backend/ent/paymentorder.go
+++ b/backend/ent/paymentorder.go
@@ -33,6 +33,8 @@ type PaymentOrder struct {
PayAmount float64 `json:"pay_amount,omitempty"`
// FeeRate holds the value of the "fee_rate" field.
FeeRate float64 `json:"fee_rate,omitempty"`
+ // BonusAmount holds the value of the "bonus_amount" field.
+ BonusAmount float64 `json:"bonus_amount,omitempty"`
// RechargeCode holds the value of the "recharge_code" field.
RechargeCode string `json:"recharge_code,omitempty"`
// OutTradeNo holds the value of the "out_trade_no" field.
@@ -132,7 +134,7 @@ func (*PaymentOrder) scanValues(columns []string) ([]any, error) {
values[i] = new([]byte)
case paymentorder.FieldForceRefund:
values[i] = new(sql.NullBool)
- case paymentorder.FieldAmount, paymentorder.FieldPayAmount, paymentorder.FieldFeeRate, paymentorder.FieldRefundAmount:
+ case paymentorder.FieldAmount, paymentorder.FieldPayAmount, paymentorder.FieldFeeRate, paymentorder.FieldBonusAmount, paymentorder.FieldRefundAmount:
values[i] = new(sql.NullFloat64)
case paymentorder.FieldID, paymentorder.FieldUserID, paymentorder.FieldPlanID, paymentorder.FieldSubscriptionGroupID, paymentorder.FieldSubscriptionDays:
values[i] = new(sql.NullInt64)
@@ -204,6 +206,12 @@ func (_m *PaymentOrder) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.FeeRate = value.Float64
}
+ case paymentorder.FieldBonusAmount:
+ if value, ok := values[i].(*sql.NullFloat64); !ok {
+ return fmt.Errorf("unexpected type %T for field bonus_amount", values[i])
+ } else if value.Valid {
+ _m.BonusAmount = value.Float64
+ }
case paymentorder.FieldRechargeCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field recharge_code", values[i])
@@ -480,6 +488,9 @@ func (_m *PaymentOrder) String() string {
builder.WriteString("fee_rate=")
builder.WriteString(fmt.Sprintf("%v", _m.FeeRate))
builder.WriteString(", ")
+ builder.WriteString("bonus_amount=")
+ builder.WriteString(fmt.Sprintf("%v", _m.BonusAmount))
+ builder.WriteString(", ")
builder.WriteString("recharge_code=")
builder.WriteString(_m.RechargeCode)
builder.WriteString(", ")
diff --git a/backend/ent/paymentorder/paymentorder.go b/backend/ent/paymentorder/paymentorder.go
index 628837943..391389b15 100644
--- a/backend/ent/paymentorder/paymentorder.go
+++ b/backend/ent/paymentorder/paymentorder.go
@@ -28,6 +28,8 @@ const (
FieldPayAmount = "pay_amount"
// FieldFeeRate holds the string denoting the fee_rate field in the database.
FieldFeeRate = "fee_rate"
+ // FieldBonusAmount holds the string denoting the bonus_amount field in the database.
+ FieldBonusAmount = "bonus_amount"
// FieldRechargeCode holds the string denoting the recharge_code field in the database.
FieldRechargeCode = "recharge_code"
// FieldOutTradeNo holds the string denoting the out_trade_no field in the database.
@@ -115,6 +117,7 @@ var Columns = []string{
FieldAmount,
FieldPayAmount,
FieldFeeRate,
+ FieldBonusAmount,
FieldRechargeCode,
FieldOutTradeNo,
FieldPaymentType,
@@ -166,6 +169,8 @@ var (
UserNameValidator func(string) error
// DefaultFeeRate holds the default value on creation for the "fee_rate" field.
DefaultFeeRate float64
+ // DefaultBonusAmount holds the default value on creation for the "bonus_amount" field.
+ DefaultBonusAmount float64
// RechargeCodeValidator is a validator for the "recharge_code" field. It is called by the builders before save.
RechargeCodeValidator func(string) error
// DefaultOutTradeNo holds the default value on creation for the "out_trade_no" field.
@@ -249,6 +254,11 @@ func ByFeeRate(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFeeRate, opts...).ToFunc()
}
+// ByBonusAmount orders the results by the bonus_amount field.
+func ByBonusAmount(opts ...sql.OrderTermOption) OrderOption {
+ return sql.OrderByField(FieldBonusAmount, opts...).ToFunc()
+}
+
// ByRechargeCode orders the results by the recharge_code field.
func ByRechargeCode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRechargeCode, opts...).ToFunc()
diff --git a/backend/ent/paymentorder/where.go b/backend/ent/paymentorder/where.go
index d6fe9efc0..fab99d1ef 100644
--- a/backend/ent/paymentorder/where.go
+++ b/backend/ent/paymentorder/where.go
@@ -90,6 +90,11 @@ func FeeRate(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldEQ(FieldFeeRate, v))
}
+// BonusAmount applies equality check predicate on the "bonus_amount" field. It's identical to BonusAmountEQ.
+func BonusAmount(v float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldEQ(FieldBonusAmount, v))
+}
+
// RechargeCode applies equality check predicate on the "recharge_code" field. It's identical to RechargeCodeEQ.
func RechargeCode(v string) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldEQ(FieldRechargeCode, v))
@@ -590,6 +595,46 @@ func FeeRateLTE(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldLTE(FieldFeeRate, v))
}
+// BonusAmountEQ applies the EQ predicate on the "bonus_amount" field.
+func BonusAmountEQ(v float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldEQ(FieldBonusAmount, v))
+}
+
+// BonusAmountNEQ applies the NEQ predicate on the "bonus_amount" field.
+func BonusAmountNEQ(v float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldNEQ(FieldBonusAmount, v))
+}
+
+// BonusAmountIn applies the In predicate on the "bonus_amount" field.
+func BonusAmountIn(vs ...float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldIn(FieldBonusAmount, vs...))
+}
+
+// BonusAmountNotIn applies the NotIn predicate on the "bonus_amount" field.
+func BonusAmountNotIn(vs ...float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldNotIn(FieldBonusAmount, vs...))
+}
+
+// BonusAmountGT applies the GT predicate on the "bonus_amount" field.
+func BonusAmountGT(v float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldGT(FieldBonusAmount, v))
+}
+
+// BonusAmountGTE applies the GTE predicate on the "bonus_amount" field.
+func BonusAmountGTE(v float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldGTE(FieldBonusAmount, v))
+}
+
+// BonusAmountLT applies the LT predicate on the "bonus_amount" field.
+func BonusAmountLT(v float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldLT(FieldBonusAmount, v))
+}
+
+// BonusAmountLTE applies the LTE predicate on the "bonus_amount" field.
+func BonusAmountLTE(v float64) predicate.PaymentOrder {
+ return predicate.PaymentOrder(sql.FieldLTE(FieldBonusAmount, v))
+}
+
// RechargeCodeEQ applies the EQ predicate on the "recharge_code" field.
func RechargeCodeEQ(v string) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldEQ(FieldRechargeCode, v))
diff --git a/backend/ent/paymentorder_create.go b/backend/ent/paymentorder_create.go
index a1e113b1a..813ad5137 100644
--- a/backend/ent/paymentorder_create.go
+++ b/backend/ent/paymentorder_create.go
@@ -81,6 +81,20 @@ func (_c *PaymentOrderCreate) SetNillableFeeRate(v *float64) *PaymentOrderCreate
return _c
}
+// SetBonusAmount sets the "bonus_amount" field.
+func (_c *PaymentOrderCreate) SetBonusAmount(v float64) *PaymentOrderCreate {
+ _c.mutation.SetBonusAmount(v)
+ return _c
+}
+
+// SetNillableBonusAmount sets the "bonus_amount" field if the given value is not nil.
+func (_c *PaymentOrderCreate) SetNillableBonusAmount(v *float64) *PaymentOrderCreate {
+ if v != nil {
+ _c.SetBonusAmount(*v)
+ }
+ return _c
+}
+
// SetRechargeCode sets the "recharge_code" field.
func (_c *PaymentOrderCreate) SetRechargeCode(v string) *PaymentOrderCreate {
_c.mutation.SetRechargeCode(v)
@@ -517,6 +531,10 @@ func (_c *PaymentOrderCreate) defaults() {
v := paymentorder.DefaultFeeRate
_c.mutation.SetFeeRate(v)
}
+ if _, ok := _c.mutation.BonusAmount(); !ok {
+ v := paymentorder.DefaultBonusAmount
+ _c.mutation.SetBonusAmount(v)
+ }
if _, ok := _c.mutation.OutTradeNo(); !ok {
v := paymentorder.DefaultOutTradeNo
_c.mutation.SetOutTradeNo(v)
@@ -577,6 +595,9 @@ func (_c *PaymentOrderCreate) check() error {
if _, ok := _c.mutation.FeeRate(); !ok {
return &ValidationError{Name: "fee_rate", err: errors.New(`ent: missing required field "PaymentOrder.fee_rate"`)}
}
+ if _, ok := _c.mutation.BonusAmount(); !ok {
+ return &ValidationError{Name: "bonus_amount", err: errors.New(`ent: missing required field "PaymentOrder.bonus_amount"`)}
+ }
if _, ok := _c.mutation.RechargeCode(); !ok {
return &ValidationError{Name: "recharge_code", err: errors.New(`ent: missing required field "PaymentOrder.recharge_code"`)}
}
@@ -725,6 +746,10 @@ func (_c *PaymentOrderCreate) createSpec() (*PaymentOrder, *sqlgraph.CreateSpec)
_spec.SetField(paymentorder.FieldFeeRate, field.TypeFloat64, value)
_node.FeeRate = value
}
+ if value, ok := _c.mutation.BonusAmount(); ok {
+ _spec.SetField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
+ _node.BonusAmount = value
+ }
if value, ok := _c.mutation.RechargeCode(); ok {
_spec.SetField(paymentorder.FieldRechargeCode, field.TypeString, value)
_node.RechargeCode = value
@@ -1030,6 +1055,24 @@ func (u *PaymentOrderUpsert) AddFeeRate(v float64) *PaymentOrderUpsert {
return u
}
+// SetBonusAmount sets the "bonus_amount" field.
+func (u *PaymentOrderUpsert) SetBonusAmount(v float64) *PaymentOrderUpsert {
+ u.Set(paymentorder.FieldBonusAmount, v)
+ return u
+}
+
+// UpdateBonusAmount sets the "bonus_amount" field to the value that was provided on create.
+func (u *PaymentOrderUpsert) UpdateBonusAmount() *PaymentOrderUpsert {
+ u.SetExcluded(paymentorder.FieldBonusAmount)
+ return u
+}
+
+// AddBonusAmount adds v to the "bonus_amount" field.
+func (u *PaymentOrderUpsert) AddBonusAmount(v float64) *PaymentOrderUpsert {
+ u.Add(paymentorder.FieldBonusAmount, v)
+ return u
+}
+
// SetRechargeCode sets the "recharge_code" field.
func (u *PaymentOrderUpsert) SetRechargeCode(v string) *PaymentOrderUpsert {
u.Set(paymentorder.FieldRechargeCode, v)
@@ -1711,6 +1754,27 @@ func (u *PaymentOrderUpsertOne) UpdateFeeRate() *PaymentOrderUpsertOne {
})
}
+// SetBonusAmount sets the "bonus_amount" field.
+func (u *PaymentOrderUpsertOne) SetBonusAmount(v float64) *PaymentOrderUpsertOne {
+ return u.Update(func(s *PaymentOrderUpsert) {
+ s.SetBonusAmount(v)
+ })
+}
+
+// AddBonusAmount adds v to the "bonus_amount" field.
+func (u *PaymentOrderUpsertOne) AddBonusAmount(v float64) *PaymentOrderUpsertOne {
+ return u.Update(func(s *PaymentOrderUpsert) {
+ s.AddBonusAmount(v)
+ })
+}
+
+// UpdateBonusAmount sets the "bonus_amount" field to the value that was provided on create.
+func (u *PaymentOrderUpsertOne) UpdateBonusAmount() *PaymentOrderUpsertOne {
+ return u.Update(func(s *PaymentOrderUpsert) {
+ s.UpdateBonusAmount()
+ })
+}
+
// SetRechargeCode sets the "recharge_code" field.
func (u *PaymentOrderUpsertOne) SetRechargeCode(v string) *PaymentOrderUpsertOne {
return u.Update(func(s *PaymentOrderUpsert) {
@@ -2643,6 +2707,27 @@ func (u *PaymentOrderUpsertBulk) UpdateFeeRate() *PaymentOrderUpsertBulk {
})
}
+// SetBonusAmount sets the "bonus_amount" field.
+func (u *PaymentOrderUpsertBulk) SetBonusAmount(v float64) *PaymentOrderUpsertBulk {
+ return u.Update(func(s *PaymentOrderUpsert) {
+ s.SetBonusAmount(v)
+ })
+}
+
+// AddBonusAmount adds v to the "bonus_amount" field.
+func (u *PaymentOrderUpsertBulk) AddBonusAmount(v float64) *PaymentOrderUpsertBulk {
+ return u.Update(func(s *PaymentOrderUpsert) {
+ s.AddBonusAmount(v)
+ })
+}
+
+// UpdateBonusAmount sets the "bonus_amount" field to the value that was provided on create.
+func (u *PaymentOrderUpsertBulk) UpdateBonusAmount() *PaymentOrderUpsertBulk {
+ return u.Update(func(s *PaymentOrderUpsert) {
+ s.UpdateBonusAmount()
+ })
+}
+
// SetRechargeCode sets the "recharge_code" field.
func (u *PaymentOrderUpsertBulk) SetRechargeCode(v string) *PaymentOrderUpsertBulk {
return u.Update(func(s *PaymentOrderUpsert) {
diff --git a/backend/ent/paymentorder_update.go b/backend/ent/paymentorder_update.go
index e93f859c3..f0dbec1d7 100644
--- a/backend/ent/paymentorder_update.go
+++ b/backend/ent/paymentorder_update.go
@@ -154,6 +154,27 @@ func (_u *PaymentOrderUpdate) AddFeeRate(v float64) *PaymentOrderUpdate {
return _u
}
+// SetBonusAmount sets the "bonus_amount" field.
+func (_u *PaymentOrderUpdate) SetBonusAmount(v float64) *PaymentOrderUpdate {
+ _u.mutation.ResetBonusAmount()
+ _u.mutation.SetBonusAmount(v)
+ return _u
+}
+
+// SetNillableBonusAmount sets the "bonus_amount" field if the given value is not nil.
+func (_u *PaymentOrderUpdate) SetNillableBonusAmount(v *float64) *PaymentOrderUpdate {
+ if v != nil {
+ _u.SetBonusAmount(*v)
+ }
+ return _u
+}
+
+// AddBonusAmount adds value to the "bonus_amount" field.
+func (_u *PaymentOrderUpdate) AddBonusAmount(v float64) *PaymentOrderUpdate {
+ _u.mutation.AddBonusAmount(v)
+ return _u
+}
+
// SetRechargeCode sets the "recharge_code" field.
func (_u *PaymentOrderUpdate) SetRechargeCode(v string) *PaymentOrderUpdate {
_u.mutation.SetRechargeCode(v)
@@ -881,6 +902,12 @@ func (_u *PaymentOrderUpdate) sqlSave(ctx context.Context) (_node int, err error
if value, ok := _u.mutation.AddedFeeRate(); ok {
_spec.AddField(paymentorder.FieldFeeRate, field.TypeFloat64, value)
}
+ if value, ok := _u.mutation.BonusAmount(); ok {
+ _spec.SetField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
+ }
+ if value, ok := _u.mutation.AddedBonusAmount(); ok {
+ _spec.AddField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
+ }
if value, ok := _u.mutation.RechargeCode(); ok {
_spec.SetField(paymentorder.FieldRechargeCode, field.TypeString, value)
}
@@ -1217,6 +1244,27 @@ func (_u *PaymentOrderUpdateOne) AddFeeRate(v float64) *PaymentOrderUpdateOne {
return _u
}
+// SetBonusAmount sets the "bonus_amount" field.
+func (_u *PaymentOrderUpdateOne) SetBonusAmount(v float64) *PaymentOrderUpdateOne {
+ _u.mutation.ResetBonusAmount()
+ _u.mutation.SetBonusAmount(v)
+ return _u
+}
+
+// SetNillableBonusAmount sets the "bonus_amount" field if the given value is not nil.
+func (_u *PaymentOrderUpdateOne) SetNillableBonusAmount(v *float64) *PaymentOrderUpdateOne {
+ if v != nil {
+ _u.SetBonusAmount(*v)
+ }
+ return _u
+}
+
+// AddBonusAmount adds value to the "bonus_amount" field.
+func (_u *PaymentOrderUpdateOne) AddBonusAmount(v float64) *PaymentOrderUpdateOne {
+ _u.mutation.AddBonusAmount(v)
+ return _u
+}
+
// SetRechargeCode sets the "recharge_code" field.
func (_u *PaymentOrderUpdateOne) SetRechargeCode(v string) *PaymentOrderUpdateOne {
_u.mutation.SetRechargeCode(v)
@@ -1974,6 +2022,12 @@ func (_u *PaymentOrderUpdateOne) sqlSave(ctx context.Context) (_node *PaymentOrd
if value, ok := _u.mutation.AddedFeeRate(); ok {
_spec.AddField(paymentorder.FieldFeeRate, field.TypeFloat64, value)
}
+ if value, ok := _u.mutation.BonusAmount(); ok {
+ _spec.SetField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
+ }
+ if value, ok := _u.mutation.AddedBonusAmount(); ok {
+ _spec.AddField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
+ }
if value, ok := _u.mutation.RechargeCode(); ok {
_spec.SetField(paymentorder.FieldRechargeCode, field.TypeString, value)
}
diff --git a/backend/ent/runtime/runtime.go b/backend/ent/runtime/runtime.go
index 21160470f..60de682b3 100644
--- a/backend/ent/runtime/runtime.go
+++ b/backend/ent/runtime/runtime.go
@@ -906,7 +906,21 @@ func init() {
// compositemodelroute.DefaultTargetPlatform holds the default value on creation for the target_platform field.
compositemodelroute.DefaultTargetPlatform = compositemodelrouteDescTargetPlatform.Default.(string)
// compositemodelroute.TargetPlatformValidator is a validator for the "target_platform" field. It is called by the builders before save.
- compositemodelroute.TargetPlatformValidator = compositemodelrouteDescTargetPlatform.Validators[0].(func(string) error)
+ compositemodelroute.TargetPlatformValidator = func() func(string) error {
+ validators := compositemodelrouteDescTargetPlatform.Validators
+ fns := [...]func(string) error{
+ validators[0].(func(string) error),
+ validators[1].(func(string) error),
+ }
+ return func(target_platform string) error {
+ for _, fn := range fns {
+ if err := fn(target_platform); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ }()
// compositemodelrouteDescUpstreamModel is the schema descriptor for upstream_model field.
compositemodelrouteDescUpstreamModel := compositemodelrouteFields[4].Descriptor()
// compositemodelroute.DefaultUpstreamModel holds the default value on creation for the upstream_model field.
@@ -1323,70 +1337,74 @@ func init() {
paymentorderDescFeeRate := paymentorderFields[6].Descriptor()
// paymentorder.DefaultFeeRate holds the default value on creation for the fee_rate field.
paymentorder.DefaultFeeRate = paymentorderDescFeeRate.Default.(float64)
+ // paymentorderDescBonusAmount is the schema descriptor for bonus_amount field.
+ paymentorderDescBonusAmount := paymentorderFields[7].Descriptor()
+ // paymentorder.DefaultBonusAmount holds the default value on creation for the bonus_amount field.
+ paymentorder.DefaultBonusAmount = paymentorderDescBonusAmount.Default.(float64)
// paymentorderDescRechargeCode is the schema descriptor for recharge_code field.
- paymentorderDescRechargeCode := paymentorderFields[7].Descriptor()
+ paymentorderDescRechargeCode := paymentorderFields[8].Descriptor()
// paymentorder.RechargeCodeValidator is a validator for the "recharge_code" field. It is called by the builders before save.
paymentorder.RechargeCodeValidator = paymentorderDescRechargeCode.Validators[0].(func(string) error)
// paymentorderDescOutTradeNo is the schema descriptor for out_trade_no field.
- paymentorderDescOutTradeNo := paymentorderFields[8].Descriptor()
+ paymentorderDescOutTradeNo := paymentorderFields[9].Descriptor()
// paymentorder.DefaultOutTradeNo holds the default value on creation for the out_trade_no field.
paymentorder.DefaultOutTradeNo = paymentorderDescOutTradeNo.Default.(string)
// paymentorder.OutTradeNoValidator is a validator for the "out_trade_no" field. It is called by the builders before save.
paymentorder.OutTradeNoValidator = paymentorderDescOutTradeNo.Validators[0].(func(string) error)
// paymentorderDescPaymentType is the schema descriptor for payment_type field.
- paymentorderDescPaymentType := paymentorderFields[9].Descriptor()
+ paymentorderDescPaymentType := paymentorderFields[10].Descriptor()
// paymentorder.PaymentTypeValidator is a validator for the "payment_type" field. It is called by the builders before save.
paymentorder.PaymentTypeValidator = paymentorderDescPaymentType.Validators[0].(func(string) error)
// paymentorderDescPaymentTradeNo is the schema descriptor for payment_trade_no field.
- paymentorderDescPaymentTradeNo := paymentorderFields[10].Descriptor()
+ paymentorderDescPaymentTradeNo := paymentorderFields[11].Descriptor()
// paymentorder.PaymentTradeNoValidator is a validator for the "payment_trade_no" field. It is called by the builders before save.
paymentorder.PaymentTradeNoValidator = paymentorderDescPaymentTradeNo.Validators[0].(func(string) error)
// paymentorderDescOrderType is the schema descriptor for order_type field.
- paymentorderDescOrderType := paymentorderFields[14].Descriptor()
+ paymentorderDescOrderType := paymentorderFields[15].Descriptor()
// paymentorder.DefaultOrderType holds the default value on creation for the order_type field.
paymentorder.DefaultOrderType = paymentorderDescOrderType.Default.(string)
// paymentorder.OrderTypeValidator is a validator for the "order_type" field. It is called by the builders before save.
paymentorder.OrderTypeValidator = paymentorderDescOrderType.Validators[0].(func(string) error)
// paymentorderDescProviderInstanceID is the schema descriptor for provider_instance_id field.
- paymentorderDescProviderInstanceID := paymentorderFields[18].Descriptor()
+ paymentorderDescProviderInstanceID := paymentorderFields[19].Descriptor()
// paymentorder.ProviderInstanceIDValidator is a validator for the "provider_instance_id" field. It is called by the builders before save.
paymentorder.ProviderInstanceIDValidator = paymentorderDescProviderInstanceID.Validators[0].(func(string) error)
// paymentorderDescProviderKey is the schema descriptor for provider_key field.
- paymentorderDescProviderKey := paymentorderFields[19].Descriptor()
+ paymentorderDescProviderKey := paymentorderFields[20].Descriptor()
// paymentorder.ProviderKeyValidator is a validator for the "provider_key" field. It is called by the builders before save.
paymentorder.ProviderKeyValidator = paymentorderDescProviderKey.Validators[0].(func(string) error)
// paymentorderDescStatus is the schema descriptor for status field.
- paymentorderDescStatus := paymentorderFields[21].Descriptor()
+ paymentorderDescStatus := paymentorderFields[22].Descriptor()
// paymentorder.DefaultStatus holds the default value on creation for the status field.
paymentorder.DefaultStatus = paymentorderDescStatus.Default.(string)
// paymentorder.StatusValidator is a validator for the "status" field. It is called by the builders before save.
paymentorder.StatusValidator = paymentorderDescStatus.Validators[0].(func(string) error)
// paymentorderDescRefundAmount is the schema descriptor for refund_amount field.
- paymentorderDescRefundAmount := paymentorderFields[22].Descriptor()
+ paymentorderDescRefundAmount := paymentorderFields[23].Descriptor()
// paymentorder.DefaultRefundAmount holds the default value on creation for the refund_amount field.
paymentorder.DefaultRefundAmount = paymentorderDescRefundAmount.Default.(float64)
// paymentorderDescForceRefund is the schema descriptor for force_refund field.
- paymentorderDescForceRefund := paymentorderFields[25].Descriptor()
+ paymentorderDescForceRefund := paymentorderFields[26].Descriptor()
// paymentorder.DefaultForceRefund holds the default value on creation for the force_refund field.
paymentorder.DefaultForceRefund = paymentorderDescForceRefund.Default.(bool)
// paymentorderDescRefundRequestedBy is the schema descriptor for refund_requested_by field.
- paymentorderDescRefundRequestedBy := paymentorderFields[28].Descriptor()
+ paymentorderDescRefundRequestedBy := paymentorderFields[29].Descriptor()
// paymentorder.RefundRequestedByValidator is a validator for the "refund_requested_by" field. It is called by the builders before save.
paymentorder.RefundRequestedByValidator = paymentorderDescRefundRequestedBy.Validators[0].(func(string) error)
// paymentorderDescClientIP is the schema descriptor for client_ip field.
- paymentorderDescClientIP := paymentorderFields[34].Descriptor()
+ paymentorderDescClientIP := paymentorderFields[35].Descriptor()
// paymentorder.ClientIPValidator is a validator for the "client_ip" field. It is called by the builders before save.
paymentorder.ClientIPValidator = paymentorderDescClientIP.Validators[0].(func(string) error)
// paymentorderDescSrcHost is the schema descriptor for src_host field.
- paymentorderDescSrcHost := paymentorderFields[35].Descriptor()
+ paymentorderDescSrcHost := paymentorderFields[36].Descriptor()
// paymentorder.SrcHostValidator is a validator for the "src_host" field. It is called by the builders before save.
paymentorder.SrcHostValidator = paymentorderDescSrcHost.Validators[0].(func(string) error)
// paymentorderDescCreatedAt is the schema descriptor for created_at field.
- paymentorderDescCreatedAt := paymentorderFields[37].Descriptor()
+ paymentorderDescCreatedAt := paymentorderFields[38].Descriptor()
// paymentorder.DefaultCreatedAt holds the default value on creation for the created_at field.
paymentorder.DefaultCreatedAt = paymentorderDescCreatedAt.Default.(func() time.Time)
// paymentorderDescUpdatedAt is the schema descriptor for updated_at field.
- paymentorderDescUpdatedAt := paymentorderFields[38].Descriptor()
+ paymentorderDescUpdatedAt := paymentorderFields[39].Descriptor()
// paymentorder.DefaultUpdatedAt holds the default value on creation for the updated_at field.
paymentorder.DefaultUpdatedAt = paymentorderDescUpdatedAt.Default.(func() time.Time)
// paymentorder.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
diff --git a/backend/ent/schema/composite_model_route.go b/backend/ent/schema/composite_model_route.go
index fef7203de..5b191c30c 100644
--- a/backend/ent/schema/composite_model_route.go
+++ b/backend/ent/schema/composite_model_route.go
@@ -1,6 +1,8 @@
package schema
import (
+ "fmt"
+
"github.com/MACOS-DO/sub4api/ent/schema/mixins"
"github.com/MACOS-DO/sub4api/internal/domain"
@@ -45,6 +47,13 @@ func (CompositeModelRoute) Fields() []ent.Field {
field.String("target_platform").
MaxLen(50).
Default(domain.PlatformOpenAI).
+ Validate(func(s string) error {
+ // 目标平台须为平台清单中的具体平台;数据库不再维护 CHECK 约束。
+ if !domain.IsConcretePlatform(s) {
+ return fmt.Errorf("target_platform %q is not a concrete platform", s)
+ }
+ return nil
+ }).
Comment("Concrete provider platform."),
field.String("upstream_model").
MaxLen(200).
diff --git a/backend/ent/schema/payment_order.go b/backend/ent/schema/payment_order.go
index d25d1e5e1..c8ce5f1ed 100644
--- a/backend/ent/schema/payment_order.go
+++ b/backend/ent/schema/payment_order.go
@@ -50,6 +50,10 @@ func (PaymentOrder) Fields() []ent.Field {
field.Float("fee_rate").
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
Default(0),
+ // 充值赠送额度(USD)。已计入 amount;单独记录用于订单展示与推广返利基数剔除。
+ field.Float("bonus_amount").
+ SchemaType(map[string]string{dialect.Postgres: "decimal(20,2)"}).
+ Default(0),
field.String("recharge_code").
MaxLen(64),
diff --git a/backend/ent/schema/user_platform_quota.go b/backend/ent/schema/user_platform_quota.go
index 9c30a8976..b0e94cdfe 100644
--- a/backend/ent/schema/user_platform_quota.go
+++ b/backend/ent/schema/user_platform_quota.go
@@ -11,6 +11,7 @@ import (
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"github.com/MACOS-DO/sub4api/ent/schema/mixins"
+ "github.com/MACOS-DO/sub4api/internal/domain"
)
// UserPlatformQuota holds the schema definition for per-user per-platform quota.
@@ -38,15 +39,12 @@ func (UserPlatformQuota) Fields() []ent.Field {
MaxLen(32).
NotEmpty().
Validate(func(s string) error {
- // 注意:平台列表的单一权威源为 service.AllowedQuotaPlatforms;
- // 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。
- switch s {
- case "anthropic", "openai", "gemini", "antigravity", "grok",
- "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "openai_bps":
- return nil
- default:
+ // 平台白名单为平台清单(domain/platforms.go)中的全部具体平台,
+ // 与 service.AllowedQuotaPlatforms 同源;数据库不再维护 CHECK 约束。
+ if !domain.IsConcretePlatform(s) {
return fmt.Errorf("platform %q is not allowed", s)
}
+ return nil
}),
// 日 / 周 / 月 USD 上限:
diff --git a/backend/go.mod b/backend/go.mod
index 11861909c..2b35d3e9b 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -1,6 +1,6 @@
module github.com/MACOS-DO/sub4api
-go 1.27.0
+go 1.27.2
require (
entgo.io/ent v0.14.5
@@ -19,6 +19,7 @@ require (
github.com/coder/websocket v1.8.14
github.com/dgraph-io/ristretto v0.2.0
github.com/gin-gonic/gin v1.9.1
+ 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/uuid v1.6.0
@@ -51,12 +52,12 @@ require (
github.com/wechatpay-apiv3/wechatpay-go v0.2.21
github.com/zeromicro/go-zero v1.9.4
go.uber.org/zap v1.24.0
- golang.org/x/crypto v0.55.0
+ golang.org/x/crypto v0.57.0
golang.org/x/image v0.41.0
- golang.org/x/mod v0.38.0
- golang.org/x/net v0.58.0
- golang.org/x/sync v0.22.0
- golang.org/x/term v0.45.0
+ golang.org/x/mod v0.41.0
+ golang.org/x/net v0.60.0
+ golang.org/x/sync v0.23.0
+ golang.org/x/term v0.46.0
google.golang.org/grpc v1.83.2
google.golang.org/protobuf v1.36.11
gopkg.in/natefinch/lumberjack.v2 v2.2.1
@@ -121,7 +122,6 @@ require (
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
- github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/go-webauthn/x v0.2.6 // indirect
github.com/goccy/go-json v0.10.2 // indirect
@@ -202,10 +202,10 @@ require (
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
- golang.org/x/sys v0.47.0 // indirect
- golang.org/x/text v0.41.0 // indirect
+ golang.org/x/sys v0.48.0 // indirect
+ golang.org/x/text v0.42.0 // indirect
golang.org/x/time v0.12.0 // indirect
- golang.org/x/tools v0.48.0 // indirect
+ golang.org/x/tools v0.50.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
modernc.org/libc v1.67.6 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 191db3cc5..298e6087f 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -566,6 +566,8 @@ golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
+golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
+golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
@@ -582,6 +584,8 @@ golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
+golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
+golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -605,6 +609,8 @@ golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
+golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
+golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -618,6 +624,8 @@ golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
+golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -651,6 +659,8 @@ golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
+golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@@ -665,6 +675,8 @@ golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
+golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
+golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@@ -677,6 +689,8 @@ golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
+golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
+golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -693,6 +707,10 @@ golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
+golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
+golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
+golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
+golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go
index 9ecd9e5ce..94f51a6d9 100644
--- a/backend/internal/domain/constants.go
+++ b/backend/internal/domain/constants.go
@@ -29,10 +29,17 @@ const (
PlatformZhipu = "zhipu" // 智谱 GLM (bigmodel)
PlatformDeepseek = "deepseek" // DeepSeek
PlatformMiniMax = "minimax" // MiniMax (M 系列)
+ PlatformTypeSafe = "typesafe" // TypeSafe AI System One (Jev)
// PlatformOpenCodeGo 是 OpenCode 平台(账号类型 Zen 按量 / Go 订阅)。
- // 值保持 opencode_go 以兼容已落库的分组、配额与 Composite 路由 CHECK。
+ // 值保持 opencode_go 以兼容已落库的账号、分组、配额与 Composite 路由。
PlatformOpenCodeGo = "opencode_go"
- PlatformComposite = "composite"
+ // PlatformCommandCode 是 Command Code Provider API(多模型聚合,积分计费,
+ // 订阅套餐另有 5 小时 / 每周滚动窗口)。
+ PlatformCommandCode = "command_code"
+ // PlatformCline 是 Cline API(多模型聚合,OpenAI 兼容 Chat Completions;按量积分计费,
+ // 另有 ClinePass 订阅)。
+ PlatformCline = "cline"
+ PlatformComposite = "composite"
)
// Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。
diff --git a/backend/internal/domain/platforms.go b/backend/internal/domain/platforms.go
new file mode 100644
index 000000000..7a84e3443
--- /dev/null
+++ b/backend/internal/domain/platforms.go
@@ -0,0 +1,150 @@
+package domain
+
+// 平台清单:平台的单一数据来源。"所有平台"类列表(分组平台、用户额度、组合
+// 路由目标、调度快照、定价匹配等)与"某网关族"类列表都从这里派生;新增平台
+// 登记一条即可在这些位置生效,无需逐处修改或新增数据库约束迁移。
+//
+// 依赖具体实现的能力(OAuth、渠道监控、余额 / Coding Plan 探测、用量窗口、
+// Codex 模型目录等)仍由各自的代码显式列出,不在此处声明。
+
+// PlatformGateway 标识平台请求由哪个网关服务处理。
+type PlatformGateway string
+
+const (
+ // PlatformGatewayAnthropic 由 GatewayService 处理(Claude Messages 协议,以及 TypeSafe 的 /v1/systemone)。
+ PlatformGatewayAnthropic PlatformGateway = "anthropic"
+ // PlatformGatewayOpenAI 由 OpenAIGatewayService 处理(OpenAI、Grok 与多协议 API Key 供应商)。
+ PlatformGatewayOpenAI PlatformGateway = "openai"
+ // PlatformGatewayGemini 由 Gemini 兼容网关处理。
+ PlatformGatewayGemini PlatformGateway = "gemini"
+ // PlatformGatewayAntigravity 由 Antigravity 网关处理。
+ PlatformGatewayAntigravity PlatformGateway = "antigravity"
+)
+
+// PlatformSpec 描述一个具体(非 composite)平台。
+type PlatformSpec struct {
+ ID string `json:"id"`
+ DisplayName string `json:"display_name"`
+ Gateway PlatformGateway `json:"gateway"`
+ // CNProvider 标识国产单一厂商(Kimi / 智谱 / DeepSeek / MiniMax),共享国产
+ // 供应商的余额 / Coding Plan 等能力。
+ CNProvider bool `json:"cn_provider"`
+ // LiteLLMProvider 是定价目录中的 provider 名;空表示不支持从定价目录同步模型。
+ LiteLLMProvider string `json:"litellm_provider,omitempty"`
+}
+
+// platformList 的顺序即平台的展示顺序。
+var platformList = []PlatformSpec{
+ {ID: PlatformAnthropic, DisplayName: "Anthropic", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "anthropic"},
+ {ID: PlatformOpenAI, DisplayName: "OpenAI", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "openai"},
+ {ID: PlatformOpenAIBPS, DisplayName: "OpenAI BPS", Gateway: PlatformGatewayOpenAI},
+ {ID: PlatformGemini, DisplayName: "Gemini", Gateway: PlatformGatewayGemini, LiteLLMProvider: "gemini"},
+ {ID: PlatformAntigravity, DisplayName: "Antigravity", Gateway: PlatformGatewayAntigravity, LiteLLMProvider: "anthropic"},
+ {ID: PlatformGrok, DisplayName: "Grok", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "xai"},
+ {ID: PlatformKimi, DisplayName: "Kimi", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "moonshot"},
+ {ID: PlatformZhipu, DisplayName: "Zhipu GLM", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "zhipu"},
+ {ID: PlatformDeepseek, DisplayName: "DeepSeek", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "deepseek"},
+ {ID: PlatformMiniMax, DisplayName: "MiniMax", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "minimax"},
+ {ID: PlatformOpenCodeGo, DisplayName: "OpenCode", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "opencode-go"},
+ {ID: PlatformTypeSafe, DisplayName: "TypeSafe / Jev", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "typesafe"},
+ {ID: PlatformCommandCode, DisplayName: "Command Code", Gateway: PlatformGatewayOpenAI},
+ {ID: PlatformCline, DisplayName: "Cline", Gateway: PlatformGatewayOpenAI},
+}
+
+var platformIndex = func() map[string]int {
+ index := make(map[string]int, len(platformList))
+ for i, spec := range platformList {
+ index[spec.ID] = i
+ }
+ return index
+}()
+
+// Platforms 返回全部具体平台(副本),按展示顺序。
+func Platforms() []PlatformSpec {
+ out := make([]PlatformSpec, len(platformList))
+ copy(out, platformList)
+ return out
+}
+
+// LookupPlatform 返回具体平台的登记信息;composite 与未知值返回 false。
+func LookupPlatform(id string) (PlatformSpec, bool) {
+ i, ok := platformIndex[id]
+ if !ok {
+ return PlatformSpec{}, false
+ }
+ return platformList[i], true
+}
+
+// IsConcretePlatform 报告 id 是否为已登记的具体平台(不含 composite)。
+func IsConcretePlatform(id string) bool {
+ _, ok := platformIndex[id]
+ return ok
+}
+
+// IsGroupPlatform 报告 id 是否可作为分组平台(具体平台或 composite)。
+func IsGroupPlatform(id string) bool {
+ return id == PlatformComposite || IsConcretePlatform(id)
+}
+
+// ConcretePlatformIDs 返回全部具体平台标识,按展示顺序。
+func ConcretePlatformIDs() []string {
+ return PlatformIDsWhere(func(PlatformSpec) bool { return true })
+}
+
+// PlatformIDsWhere 返回满足条件的具体平台标识,按展示顺序。
+func PlatformIDsWhere(match func(PlatformSpec) bool) []string {
+ out := make([]string, 0, len(platformList))
+ for _, spec := range platformList {
+ if match(spec) {
+ out = append(out, spec.ID)
+ }
+ }
+ return out
+}
+
+// compositePrecedenceHead 是组合分组查找顺序的固定前缀(历史顺序:Gemini 先于 OpenAI)。
+var compositePrecedenceHead = []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI}
+
+// compositePrecedenceTail 是组合分组查找顺序的固定后缀(Sub4API:OpenAI BPS 只经显式路由
+// 暴露,始终最后回退)。
+var compositePrecedenceTail = []string{PlatformOpenAIBPS}
+
+// CompositePrecedencePlatformIDs 返回按平台依次回退时的顺序:组合分组在请求目标
+// 解析前逐平台查找定价 / 模型映射(先命中者生效)、拼接默认模型列表,以及调度快照
+// 遍历。沿用历史顺序 anthropic、gemini、openai,其余按展示顺序,新登记的平台追加在末尾。
+func CompositePrecedencePlatformIDs() []string {
+ out := make([]string, 0, len(platformList))
+ seen := make(map[string]struct{}, len(platformList))
+ for _, id := range compositePrecedenceHead {
+ if IsConcretePlatform(id) {
+ out = append(out, id)
+ seen[id] = struct{}{}
+ }
+ }
+ for _, id := range compositePrecedenceTail {
+ seen[id] = struct{}{}
+ }
+ for _, spec := range platformList {
+ if _, ok := seen[spec.ID]; !ok {
+ out = append(out, spec.ID)
+ }
+ }
+ for _, id := range compositePrecedenceTail {
+ if IsConcretePlatform(id) {
+ out = append(out, id)
+ }
+ }
+ return out
+}
+
+// UsesOpenAIGateway 报告平台是否由 OpenAI 网关处理。
+func UsesOpenAIGateway(id string) bool {
+ spec, ok := LookupPlatform(id)
+ return ok && spec.Gateway == PlatformGatewayOpenAI
+}
+
+// IsCNProviderPlatform 报告平台是否为国产单一厂商。
+func IsCNProviderPlatform(id string) bool {
+ spec, ok := LookupPlatform(id)
+ return ok && spec.CNProvider
+}
diff --git a/backend/internal/domain/platforms_test.go b/backend/internal/domain/platforms_test.go
new file mode 100644
index 000000000..7936e2a31
--- /dev/null
+++ b/backend/internal/domain/platforms_test.go
@@ -0,0 +1,75 @@
+package domain
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// 重构前各处手写的平台列表,作为平台清单派生结果的等价基准;重构后新登记的平台
+// (Command Code、Cline)按同类平台(OpenCode)的位置补入。
+var (
+ legacyDisplayOrder = []string{
+ PlatformAnthropic, PlatformOpenAI, PlatformOpenAIBPS, PlatformGemini, PlatformAntigravity, PlatformGrok,
+ PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
+ PlatformCommandCode,
+ PlatformCline,
+ }
+ legacyCompositePrecedence = []string{
+ PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok,
+ PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
+ PlatformCommandCode,
+ PlatformCline,
+ PlatformOpenAIBPS,
+ }
+ legacyOpenAIGateway = []string{
+ PlatformOpenAI, PlatformOpenAIBPS, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
+ PlatformCommandCode,
+ PlatformCline,
+ }
+ legacyCNProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax}
+ legacyLiteLLMByPlatf = map[string]string{
+ PlatformAnthropic: "anthropic", PlatformOpenAI: "openai", PlatformGemini: "gemini",
+ PlatformAntigravity: "anthropic", PlatformGrok: "xai", PlatformKimi: "moonshot",
+ PlatformZhipu: "zhipu", PlatformDeepseek: "deepseek", PlatformMiniMax: "minimax",
+ PlatformOpenCodeGo: "opencode-go", PlatformTypeSafe: "typesafe", PlatformCommandCode: "", PlatformCline: "", PlatformOpenAIBPS: "",
+ }
+)
+
+func TestPlatformListMatchesLegacyLists(t *testing.T) {
+ require.Equal(t, legacyDisplayOrder, ConcretePlatformIDs())
+ require.Equal(t, legacyCompositePrecedence, CompositePrecedencePlatformIDs())
+ require.Equal(t, legacyOpenAIGateway, PlatformIDsWhere(func(spec PlatformSpec) bool {
+ return spec.Gateway == PlatformGatewayOpenAI
+ }))
+ require.Equal(t, legacyCNProviders, PlatformIDsWhere(func(spec PlatformSpec) bool { return spec.CNProvider }))
+ for platform, provider := range legacyLiteLLMByPlatf {
+ spec, ok := LookupPlatform(platform)
+ require.True(t, ok, platform)
+ require.Equal(t, provider, spec.LiteLLMProvider, platform)
+ }
+}
+
+func TestPlatformListPredicates(t *testing.T) {
+ for _, platform := range legacyDisplayOrder {
+ require.True(t, IsConcretePlatform(platform), platform)
+ require.True(t, IsGroupPlatform(platform), platform)
+ spec, ok := LookupPlatform(platform)
+ require.True(t, ok, platform)
+ require.NotEmpty(t, spec.DisplayName, platform)
+ require.NotEmpty(t, spec.Gateway, platform)
+ }
+ require.False(t, IsConcretePlatform(PlatformComposite))
+ require.True(t, IsGroupPlatform(PlatformComposite))
+ for _, invalid := range []string{"", "moonshot", "Kimi", "openai ", "glm", "bogus"} {
+ require.False(t, IsConcretePlatform(invalid), invalid)
+ require.False(t, IsGroupPlatform(invalid), invalid)
+ require.False(t, UsesOpenAIGateway(invalid), invalid)
+ }
+}
+
+func TestPlatformsReturnsCopy(t *testing.T) {
+ platforms := Platforms()
+ platforms[0].ID = "mutated"
+ require.Equal(t, PlatformAnthropic, Platforms()[0].ID)
+}
diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go
index a1e2d9d60..ddf63b133 100644
--- a/backend/internal/handler/admin/account_handler.go
+++ b/backend/internal/handler/admin/account_handler.go
@@ -27,6 +27,7 @@ import (
"github.com/MACOS-DO/sub4api/internal/pkg/openai"
"github.com/MACOS-DO/sub4api/internal/pkg/response"
"github.com/MACOS-DO/sub4api/internal/pkg/timezone"
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
"github.com/MACOS-DO/sub4api/internal/pkg/xai"
"github.com/MACOS-DO/sub4api/internal/service"
@@ -1276,7 +1277,7 @@ func (h *AccountHandler) Update(c *gin.Context) {
// 网关会按"现状即证据"默认走 Responses。
func (h *AccountHandler) scheduleOpenAIResponsesProbe(account *service.Account) {
if account == nil || account.Type != service.AccountTypeAPIKey ||
- (account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform)) {
+ (account.Platform != service.PlatformOpenAI && !account.RoutesProtocolByInbound()) {
return
}
if h.accountTestService == nil {
@@ -2967,10 +2968,9 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
return
}
- // Handle Antigravity accounts: return Claude + Gemini models
+ // Explicit account mappings expose their request-side names to connectivity tests.
if account.Platform == service.PlatformAntigravity {
- // 直接复用 antigravity.DefaultModels(),与 /v1/models 端点保持同步
- response.Success(c, antigravity.DefaultModels())
+ response.Success(c, antigravityAccountTestModels(account.Credentials["model_mapping"]))
return
}
@@ -3024,6 +3024,12 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
return
}
+ // TypeSafe accounts serve only the native System One model.
+ if account.IsTypeSafe() {
+ response.Success(c, []claude.Model{{ID: typesafe.JevLatestModel, Type: "model", DisplayName: typesafe.JevLatestModel}})
+ return
+ }
+
// Handle Claude/Anthropic accounts
// For OAuth and Setup-Token accounts: return default models
if account.IsOAuth() {
@@ -3065,6 +3071,48 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
response.Success(c, models)
}
+// antigravityAccountTestModels uses the stored mapping rather than GetModelMapping,
+// which supplies defaults and compatibility aliases that the administrator did not configure.
+func antigravityAccountTestModels(rawMapping any) []antigravity.ClaudeModel {
+ var mappedIDs []string
+ switch mapping := rawMapping.(type) {
+ case map[string]any:
+ for id := range mapping {
+ if strings.TrimSpace(id) != "" {
+ mappedIDs = append(mappedIDs, id)
+ }
+ }
+ case map[string]string:
+ for id := range mapping {
+ if strings.TrimSpace(id) != "" {
+ mappedIDs = append(mappedIDs, id)
+ }
+ }
+ }
+ if len(mappedIDs) == 0 {
+ return antigravity.DefaultModels()
+ }
+
+ sort.Strings(mappedIDs)
+ defaultByID := make(map[string]antigravity.ClaudeModel)
+ for _, model := range antigravity.DefaultModels() {
+ defaultByID[model.ID] = model
+ }
+ models := make([]antigravity.ClaudeModel, 0, len(mappedIDs))
+ for _, id := range mappedIDs {
+ if model, ok := defaultByID[id]; ok {
+ models = append(models, model)
+ continue
+ }
+ models = append(models, antigravity.ClaudeModel{
+ ID: id,
+ Type: "model",
+ DisplayName: id,
+ })
+ }
+ return models
+}
+
// SyncUpstreamModels handles syncing live supported models from an account's upstream.
// POST /api/v1/admin/accounts/:id/models/sync-upstream
func (h *AccountHandler) SyncUpstreamModels(c *gin.Context) {
diff --git a/backend/internal/handler/admin/account_handler_available_models_test.go b/backend/internal/handler/admin/account_handler_available_models_test.go
index 8ce8520cf..e08a73374 100644
--- a/backend/internal/handler/admin/account_handler_available_models_test.go
+++ b/backend/internal/handler/admin/account_handler_available_models_test.go
@@ -10,6 +10,7 @@ import (
"testing"
"github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/antigravity"
"github.com/MACOS-DO/sub4api/internal/pkg/tlsfingerprint"
"github.com/MACOS-DO/sub4api/internal/service"
"github.com/gin-gonic/gin"
@@ -330,6 +331,49 @@ func TestAccountHandlerGetAvailableModels_GeminiGoogleOneUsesConservativeCatalog
require.NotContains(t, ids, "gemini-2.5-flash-image")
}
+func TestAccountHandlerGetAvailableModels_Antigravity(t *testing.T) {
+ defaults := antigravity.DefaultModels()
+ known := defaults[0]
+ custom := antigravity.ClaudeModel{ID: "claude-custom-alias", Type: "model", DisplayName: "claude-custom-alias"}
+ cases := []struct {
+ name string
+ credentials map[string]any
+ want []antigravity.ClaudeModel
+ }{
+ {name: "nil credentials", want: defaults},
+ {name: "missing mapping", credentials: map[string]any{}, want: defaults},
+ {name: "empty JSON mapping", credentials: map[string]any{"model_mapping": map[string]any{}}, want: defaults},
+ {name: "empty string mapping", credentials: map[string]any{"model_mapping": map[string]string{}}, want: defaults},
+ {name: "blank key", credentials: map[string]any{"model_mapping": map[string]any{" ": "upstream-model"}}, want: defaults},
+ {name: "JSON mapping keys and metadata", credentials: map[string]any{"model_mapping": map[string]any{
+ known.ID: known.ID, custom.ID: "upstream-model",
+ }}, want: []antigravity.ClaudeModel{custom, known}},
+ {name: "string mapping keys and metadata", credentials: map[string]any{"model_mapping": map[string]string{
+ known.ID: known.ID, custom.ID: "upstream-model",
+ }}, want: []antigravity.ClaudeModel{custom, known}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ for _, accountType := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} {
+ t.Run(accountType, func(t *testing.T) {
+ svc := &availableModelsAdminService{
+ stubAdminService: newStubAdminService(),
+ account: service.Account{ID: 51, Platform: service.PlatformAntigravity, Type: accountType, Credentials: tc.credentials},
+ }
+ rec := httptest.NewRecorder()
+ setupAvailableModelsRouter(svc).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/51/models", nil))
+ require.Equal(t, http.StatusOK, rec.Code)
+ var resp struct {
+ Data []antigravity.ClaudeModel `json:"data"`
+ }
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
+ require.Equal(t, tc.want, resp.Data)
+ })
+ }
+ })
+ }
+}
+
func TestAccountHandlerSyncUpstreamModels_ConfigErrorReturnsBadRequest(t *testing.T) {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
@@ -526,3 +570,36 @@ func TestAccountHandlerSyncUpstreamModels_MetadataEnrichmentFailureReturnsWarnin
require.Len(t, resp.Data.Warnings, 1)
require.Equal(t, "upstream_model_metadata_incomplete", resp.Data.Warnings[0].Code)
}
+
+func TestAccountHandlerGetAvailableModels_TypeSafeOnlyReturnsJev(t *testing.T) {
+ for _, credentials := range []map[string]any{
+ {"api_key": "ts-secret"},
+ {"api_key": "ts-secret", "model_mapping": map[string]any{"jev-latest": "jev-latest"}},
+ } {
+ svc := &availableModelsAdminService{
+ stubAdminService: newStubAdminService(),
+ account: service.Account{
+ ID: 46,
+ Name: "typesafe",
+ Platform: service.PlatformTypeSafe,
+ Type: service.AccountTypeAPIKey,
+ Status: service.StatusActive,
+ Credentials: credentials,
+ },
+ }
+ router := setupAvailableModelsRouter(svc)
+
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/46/models", nil))
+ require.Equal(t, http.StatusOK, rec.Code)
+
+ var resp struct {
+ Data []struct {
+ ID string `json:"id"`
+ } `json:"data"`
+ }
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
+ require.Len(t, resp.Data, 1)
+ require.Equal(t, "jev-latest", resp.Data[0].ID)
+ }
+}
diff --git a/backend/internal/handler/admin/channel_handler.go b/backend/internal/handler/admin/channel_handler.go
index f8ffbfa42..1b872690a 100644
--- a/backend/internal/handler/admin/channel_handler.go
+++ b/backend/internal/handler/admin/channel_handler.go
@@ -5,6 +5,7 @@ import (
"strconv"
"strings"
+ "github.com/MACOS-DO/sub4api/internal/domain"
infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
"github.com/MACOS-DO/sub4api/internal/pkg/pagination"
"github.com/MACOS-DO/sub4api/internal/pkg/response"
@@ -631,19 +632,14 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
})
}
-// platformToLiteLLMProvider maps a channel platform name to the corresponding
-// LiteLLM provider string used as the key in the pricing catalog.
-var platformToLiteLLMProvider = map[string]string{
- service.PlatformAnthropic: "anthropic",
- service.PlatformOpenAI: "openai",
- service.PlatformGemini: "gemini",
- service.PlatformAntigravity: "anthropic",
- service.PlatformGrok: "xai",
- service.PlatformKimi: "moonshot",
- service.PlatformZhipu: "zhipu",
- service.PlatformDeepseek: "deepseek",
- service.PlatformMiniMax: "minimax",
- service.PlatformOpenCodeGo: "opencode-go",
+// platformLiteLLMProvider maps a channel platform name to the corresponding
+// LiteLLM provider string used as the key in the pricing catalog (platform list).
+func platformLiteLLMProvider(platform string) (string, bool) {
+ spec, ok := domain.LookupPlatform(platform)
+ if !ok || spec.LiteLLMProvider == "" {
+ return "", false
+ }
+ return spec.LiteLLMProvider, true
}
// SyncPricingModels 返回 LiteLLM 定价目录中指定平台的最新模型列表
@@ -656,7 +652,7 @@ func (h *ChannelHandler) SyncPricingModels(c *gin.Context) {
return
}
- provider, ok := platformToLiteLLMProvider[platform]
+ provider, ok := platformLiteLLMProvider(platform)
if !ok {
response.ErrorFrom(c, infraerrors.BadRequest("UNSUPPORTED_PLATFORM",
fmt.Sprintf("unsupported platform: %s", platform)).
diff --git a/backend/internal/handler/admin/channel_handler_test.go b/backend/internal/handler/admin/channel_handler_test.go
index 860d3f902..cdd42b9e8 100644
--- a/backend/internal/handler/admin/channel_handler_test.go
+++ b/backend/internal/handler/admin/channel_handler_test.go
@@ -565,7 +565,7 @@ func TestSyncPricingModels_ValidPlatform_EmptyService(t *testing.T) {
svc := service.NewPricingService(nil, nil)
router := setupSyncPricingModelsRouter(svc)
- for _, platform := range []string{"anthropic", "openai", "gemini", "antigravity", "grok", "kimi", "zhipu", "deepseek", "minimax"} {
+ for _, platform := range []string{"anthropic", "openai", "gemini", "antigravity", "grok", "kimi", "zhipu", "deepseek", "minimax", "typesafe"} {
req := httptest.NewRequest(http.MethodGet, "/channels/pricing/sync-models?platform="+platform, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
diff --git a/backend/internal/handler/admin/group_handler.go b/backend/internal/handler/admin/group_handler.go
index 2d0cffcd2..a5ccc87e3 100644
--- a/backend/internal/handler/admin/group_handler.go
+++ b/backend/internal/handler/admin/group_handler.go
@@ -184,7 +184,7 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) {
type CreateGroupRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
- Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go openai_bps composite"`
+ Platform string `json:"platform" binding:"omitempty,group_platform"`
RateMultiplier float64 `json:"rate_multiplier"`
IsExclusive bool `json:"is_exclusive"`
SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"`
@@ -258,7 +258,7 @@ type CreateGroupRequest struct {
type UpdateGroupRequest struct {
Name string `json:"name"`
Description *string `json:"description"`
- Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go openai_bps composite"`
+ Platform string `json:"platform" binding:"omitempty,group_platform"`
RateMultiplier *float64 `json:"rate_multiplier"`
IsExclusive *bool `json:"is_exclusive"`
Status string `json:"status" binding:"omitempty,oneof=active inactive"`
@@ -332,7 +332,7 @@ type UpdateGroupRequest struct {
type CompositeRouteRequest struct {
PublicModel string `json:"public_model" binding:"required"`
MatchType string `json:"match_type" binding:"omitempty,oneof=exact prefix"`
- TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go openai_bps"`
+ TargetPlatform string `json:"target_platform" binding:"required,concrete_platform"`
UpstreamModel string `json:"upstream_model"`
Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"`
Priority int `json:"priority"`
diff --git a/backend/internal/handler/admin/group_handler_platform_test.go b/backend/internal/handler/admin/group_handler_platform_test.go
index 0c820868b..ba4560598 100644
--- a/backend/internal/handler/admin/group_handler_platform_test.go
+++ b/backend/internal/handler/admin/group_handler_platform_test.go
@@ -28,6 +28,8 @@ func TestGroupPlatformBinding_AllowedPlatforms(t *testing.T) {
allowed := []string{
"anthropic", "openai", "gemini", "antigravity", "grok",
"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "composite",
+ "typesafe",
+ "command_code", "cline",
}
for _, platform := range allowed {
t.Run("create_"+platform, func(t *testing.T) {
@@ -71,8 +73,8 @@ func TestGroupPlatformBinding_RejectsInvalidPlatforms(t *testing.T) {
}
}
-func TestCompositeRouteTargetPlatform_AllowsCNProviders(t *testing.T) {
- for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go"} {
+func TestCompositeRouteTargetPlatform_AllowsConcreteProviders(t *testing.T) {
+ for _, platform := range []string{"kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "command_code", "cline"} {
var req CompositeRouteRequest
body := fmt.Sprintf(`{"public_model":"m","target_platform":%q}`, platform)
require.NoError(t, bindGroupPlatformJSON(t, &req, body))
diff --git a/backend/internal/handler/admin/payment_handler.go b/backend/internal/handler/admin/payment_handler.go
index ac95f8bb7..4ffbd0e8a 100644
--- a/backend/internal/handler/admin/payment_handler.go
+++ b/backend/internal/handler/admin/payment_handler.go
@@ -125,6 +125,7 @@ type AdminPaymentOrderResult struct {
Amount float64 `json:"amount"`
PayAmount float64 `json:"pay_amount"`
FeeRate float64 `json:"fee_rate"`
+ BonusAmount float64 `json:"bonus_amount"`
Currency string `json:"currency"`
RechargeCode string `json:"recharge_code,omitempty"`
OutTradeNo string `json:"out_trade_no"`
@@ -182,6 +183,7 @@ func sanitizeAdminPaymentOrderForResponse(order *dbent.PaymentOrder) *AdminPayme
Amount: order.Amount,
PayAmount: order.PayAmount,
FeeRate: order.FeeRate,
+ BonusAmount: order.BonusAmount,
Currency: service.PaymentOrderCurrency(order),
RechargeCode: order.RechargeCode,
OutTradeNo: order.OutTradeNo,
diff --git a/backend/internal/handler/admin/platform_validation.go b/backend/internal/handler/admin/platform_validation.go
new file mode 100644
index 000000000..114a3a528
--- /dev/null
+++ b/backend/internal/handler/admin/platform_validation.go
@@ -0,0 +1,30 @@
+package admin
+
+import (
+ "fmt"
+
+ "github.com/MACOS-DO/sub4api/internal/domain"
+ "github.com/gin-gonic/gin/binding"
+ "github.com/go-playground/validator/v10"
+)
+
+// 平台相关的请求绑定校验标签,由平台清单(domain/platforms.go)驱动,替代在
+// binding 标签里手写 oneof 白名单(新增平台时易漏加,导致分组无法创建):
+// - group_platform:已登记的具体平台或 composite;
+// - concrete_platform:已登记的具体平台。
+func init() {
+ engine, ok := binding.Validator.Engine().(*validator.Validate)
+ if !ok {
+ panic("platform validation requires a go-playground validator engine")
+ }
+ if err := engine.RegisterValidation("group_platform", func(fl validator.FieldLevel) bool {
+ return domain.IsGroupPlatform(fl.Field().String())
+ }); err != nil {
+ panic(fmt.Errorf("register group_platform validation: %w", err))
+ }
+ if err := engine.RegisterValidation("concrete_platform", func(fl validator.FieldLevel) bool {
+ return domain.IsConcretePlatform(fl.Field().String())
+ }); err != nil {
+ panic(fmt.Errorf("register concrete_platform validation: %w", err))
+ }
+}
diff --git a/backend/internal/handler/admin/setting_handler.go b/backend/internal/handler/admin/setting_handler.go
index 5f3610b20..855df94a6 100644
--- a/backend/internal/handler/admin/setting_handler.go
+++ b/backend/internal/handler/admin/setting_handler.go
@@ -368,6 +368,9 @@ func (h *SettingHandler) GetSettings(c *gin.Context) {
PaymentBalanceRechargeMultiplier: paymentCfg.BalanceRechargeMultiplier,
PaymentSubscriptionUSDToCNYRate: paymentCfg.SubscriptionUSDToCNYRate,
PaymentRechargeFeeRate: paymentCfg.RechargeFeeRate,
+ PaymentRechargeBonusTiers: rechargeBonusTiersToDTO(paymentCfg.RechargeBonusTiers),
+ PaymentRechargeBonusMode: rechargeBonusModeToDTO(paymentCfg.RechargeBonusMode),
+ PaymentRechargeBonusNotice: paymentCfg.RechargeBonusNotice,
PaymentLoadBalanceStrat: paymentCfg.LoadBalanceStrategy,
PaymentProductNamePrefix: paymentCfg.ProductNamePrefix,
PaymentProductNameSuffix: paymentCfg.ProductNameSuffix,
diff --git a/backend/internal/handler/admin/setting_handler_recharge_bonus.go b/backend/internal/handler/admin/setting_handler_recharge_bonus.go
new file mode 100644
index 000000000..7e8fe17a6
--- /dev/null
+++ b/backend/internal/handler/admin/setting_handler_recharge_bonus.go
@@ -0,0 +1,33 @@
+package admin
+
+import (
+ "github.com/MACOS-DO/sub4api/internal/handler/dto"
+ "github.com/MACOS-DO/sub4api/internal/service"
+)
+
+// rechargeBonusTiersFromDTO 请求 nil 表示未携带该字段(保持现值);空数组表示清空阶梯。
+func rechargeBonusTiersFromDTO(items *[]dto.RechargeBonusTier) *[]service.RechargeBonusTier {
+ if items == nil {
+ return nil
+ }
+ out := make([]service.RechargeBonusTier, 0, len(*items))
+ for _, item := range *items {
+ out = append(out, service.RechargeBonusTier{MinAmount: item.MinAmount, BonusPercent: item.BonusPercent})
+ }
+ return &out
+}
+
+// rechargeBonusModeToDTO 输出已归一化的模式(空/非法按 bonus)。
+func rechargeBonusModeToDTO(mode string) string {
+ normalized, _ := service.NormalizeRechargeBonusMode(mode)
+ return normalized
+}
+
+// rechargeBonusTiersToDTO 始终返回非 nil 切片,空配置输出 []。
+func rechargeBonusTiersToDTO(items []service.RechargeBonusTier) []dto.RechargeBonusTier {
+ out := make([]dto.RechargeBonusTier, 0, len(items))
+ for _, item := range items {
+ out = append(out, dto.RechargeBonusTier{MinAmount: item.MinAmount, BonusPercent: item.BonusPercent})
+ }
+ return out
+}
diff --git a/backend/internal/handler/admin/setting_handler_update.go b/backend/internal/handler/admin/setting_handler_update.go
index 6574e86b1..2b0b7763b 100644
--- a/backend/internal/handler/admin/setting_handler_update.go
+++ b/backend/internal/handler/admin/setting_handler_update.go
@@ -316,11 +316,15 @@ type UpdateSettingsRequest struct {
PaymentBalanceRechargeMultiplier *float64 `json:"payment_balance_recharge_multiplier"`
PaymentSubscriptionUSDToCNYRate *float64 `json:"payment_subscription_usd_to_cny_rate"`
PaymentRechargeFeeRate *float64 `json:"payment_recharge_fee_rate"`
- PaymentLoadBalanceStrat *string `json:"payment_load_balance_strategy"`
- PaymentProductNamePrefix *string `json:"payment_product_name_prefix"`
- PaymentProductNameSuffix *string `json:"payment_product_name_suffix"`
- PaymentHelpImageURL *string `json:"payment_help_image_url"`
- PaymentHelpText *string `json:"payment_help_text"`
+ // nil 表示不更新;空数组表示清空阶梯
+ PaymentRechargeBonusTiers *[]dto.RechargeBonusTier `json:"payment_recharge_bonus_tiers"`
+ PaymentRechargeBonusMode *string `json:"payment_recharge_bonus_mode"`
+ PaymentRechargeBonusNotice *string `json:"payment_recharge_bonus_notice"`
+ PaymentLoadBalanceStrat *string `json:"payment_load_balance_strategy"`
+ PaymentProductNamePrefix *string `json:"payment_product_name_prefix"`
+ PaymentProductNameSuffix *string `json:"payment_product_name_suffix"`
+ PaymentHelpImageURL *string `json:"payment_help_image_url"`
+ PaymentHelpText *string `json:"payment_help_text"`
// Cancel rate limit
PaymentCancelRateLimitEnabled *bool `json:"payment_cancel_rate_limit_enabled"`
@@ -2161,6 +2165,9 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) {
BalanceRechargeMultiplier: req.PaymentBalanceRechargeMultiplier,
SubscriptionUSDToCNYRate: req.PaymentSubscriptionUSDToCNYRate,
RechargeFeeRate: req.PaymentRechargeFeeRate,
+ RechargeBonusTiers: rechargeBonusTiersFromDTO(req.PaymentRechargeBonusTiers),
+ RechargeBonusMode: req.PaymentRechargeBonusMode,
+ RechargeBonusNotice: req.PaymentRechargeBonusNotice,
LoadBalanceStrategy: req.PaymentLoadBalanceStrat,
ProductNamePrefix: req.PaymentProductNamePrefix,
ProductNameSuffix: req.PaymentProductNameSuffix,
@@ -2446,6 +2453,9 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) {
PaymentBalanceRechargeMultiplier: updatedPaymentCfg.BalanceRechargeMultiplier,
PaymentSubscriptionUSDToCNYRate: updatedPaymentCfg.SubscriptionUSDToCNYRate,
PaymentRechargeFeeRate: updatedPaymentCfg.RechargeFeeRate,
+ PaymentRechargeBonusTiers: rechargeBonusTiersToDTO(updatedPaymentCfg.RechargeBonusTiers),
+ PaymentRechargeBonusMode: rechargeBonusModeToDTO(updatedPaymentCfg.RechargeBonusMode),
+ PaymentRechargeBonusNotice: updatedPaymentCfg.RechargeBonusNotice,
PaymentLoadBalanceStrat: updatedPaymentCfg.LoadBalanceStrategy,
PaymentProductNamePrefix: updatedPaymentCfg.ProductNamePrefix,
PaymentProductNameSuffix: updatedPaymentCfg.ProductNameSuffix,
@@ -2522,6 +2532,7 @@ func hasPaymentFields(req UpdateSettingsRequest) bool {
req.PaymentEnabledTypes != nil || req.PaymentBalanceDisabled != nil ||
req.PaymentBalanceRechargeMultiplier != nil || req.PaymentSubscriptionUSDToCNYRate != nil ||
req.PaymentRechargeFeeRate != nil ||
+ req.PaymentRechargeBonusTiers != nil || req.PaymentRechargeBonusMode != nil || req.PaymentRechargeBonusNotice != nil ||
req.PaymentLoadBalanceStrat != nil || req.PaymentProductNamePrefix != nil ||
req.PaymentProductNameSuffix != nil || req.PaymentHelpImageURL != nil ||
req.PaymentHelpText != nil || req.PaymentCancelRateLimitEnabled != nil ||
diff --git a/backend/internal/handler/auth_oauth_pending_flow_test.go b/backend/internal/handler/auth_oauth_pending_flow_test.go
index 08dedfcde..a7f0ad8c5 100644
--- a/backend/internal/handler/auth_oauth_pending_flow_test.go
+++ b/backend/internal/handler/auth_oauth_pending_flow_test.go
@@ -3593,3 +3593,20 @@ func (oauthPendingFlowTotpEncryptorStub) Encrypt(plaintext string) (string, erro
func (oauthPendingFlowTotpEncryptorStub) Decrypt(ciphertext string) (string, error) {
return ciphertext, nil
}
+
+func (s *oauthPendingFlowEmailCacheStub) IncrVerificationCodeAttempts(_ context.Context, email string) (int, error) {
+ data := s.verificationCodes[email]
+ if data == nil {
+ return 0, errors.New("verification code not found")
+ }
+ data.Attempts++
+ return data.Attempts, nil
+}
+
+func (s *oauthPendingFlowEmailCacheStub) IncrNotifyVerifyCodeAttempts(context.Context, string) (int, error) {
+ return 0, errors.New("notify verification code not found")
+}
+
+func (s *oauthPendingFlowEmailCacheStub) ConsumePasswordResetToken(context.Context, string, string) (bool, error) {
+ return false, nil
+}
diff --git a/backend/internal/handler/dto/recharge_bonus_tiers.go b/backend/internal/handler/dto/recharge_bonus_tiers.go
new file mode 100644
index 000000000..21731566a
--- /dev/null
+++ b/backend/internal/handler/dto/recharge_bonus_tiers.go
@@ -0,0 +1,7 @@
+package dto
+
+// RechargeBonusTier 充值赠送档位:余额充值支付金额 ≥ MinAmount 时,在到账基数上赠送 BonusPercent%。
+type RechargeBonusTier struct {
+ MinAmount float64 `json:"min_amount"`
+ BonusPercent float64 `json:"bonus_percent"`
+}
diff --git a/backend/internal/handler/dto/settings.go b/backend/internal/handler/dto/settings.go
index 7959e181f..d7aa663c6 100644
--- a/backend/internal/handler/dto/settings.go
+++ b/backend/internal/handler/dto/settings.go
@@ -285,11 +285,15 @@ type SystemSettings struct {
PaymentBalanceRechargeMultiplier float64 `json:"payment_balance_recharge_multiplier"`
PaymentSubscriptionUSDToCNYRate float64 `json:"payment_subscription_usd_to_cny_rate"`
PaymentRechargeFeeRate float64 `json:"payment_recharge_fee_rate"`
- PaymentLoadBalanceStrat string `json:"payment_load_balance_strategy"`
- PaymentProductNamePrefix string `json:"payment_product_name_prefix"`
- PaymentProductNameSuffix string `json:"payment_product_name_suffix"`
- PaymentHelpImageURL string `json:"payment_help_image_url"`
- PaymentHelpText string `json:"payment_help_text"`
+ // 充值赠送阶梯与活动文案
+ PaymentRechargeBonusTiers []RechargeBonusTier `json:"payment_recharge_bonus_tiers"`
+ PaymentRechargeBonusMode string `json:"payment_recharge_bonus_mode"`
+ PaymentRechargeBonusNotice string `json:"payment_recharge_bonus_notice"`
+ PaymentLoadBalanceStrat string `json:"payment_load_balance_strategy"`
+ PaymentProductNamePrefix string `json:"payment_product_name_prefix"`
+ PaymentProductNameSuffix string `json:"payment_product_name_suffix"`
+ PaymentHelpImageURL string `json:"payment_help_image_url"`
+ PaymentHelpText string `json:"payment_help_text"`
// Cancel rate limit
PaymentCancelRateLimitEnabled bool `json:"payment_cancel_rate_limit_enabled"`
diff --git a/backend/internal/handler/endpoint.go b/backend/internal/handler/endpoint.go
index 1a4fab02c..38ce98a51 100644
--- a/backend/internal/handler/endpoint.go
+++ b/backend/internal/handler/endpoint.go
@@ -16,6 +16,7 @@ import (
const (
EndpointMessages = "/v1/messages"
+ EndpointSystemOne = "/v1/systemone"
EndpointChatCompletions = "/v1/chat/completions"
EndpointEmbeddings = "/v1/embeddings"
EndpointAlphaSearch = "/v1/alpha/search"
@@ -94,6 +95,8 @@ func NormalizeInboundEndpoint(path string) string {
return EndpointChatCompletions
case strings.Contains(path, EndpointMessages):
return EndpointMessages
+ case strings.Contains(path, EndpointSystemOne):
+ return EndpointSystemOne
case strings.Contains(path, EndpointImagesGenerations) || strings.Contains(path, "/images/generations"):
return EndpointImagesGenerations
case strings.Contains(path, EndpointImagesEdits) || strings.Contains(path, "/images/edits"):
@@ -223,6 +226,9 @@ func DeriveUpstreamEndpoint(inbound, rawRequestPath, platform string) string {
case service.PlatformAnthropic:
return EndpointMessages
+ case service.PlatformTypeSafe:
+ return EndpointSystemOne
+
case service.PlatformGemini:
return EndpointGeminiModels
diff --git a/backend/internal/handler/endpoint_test.go b/backend/internal/handler/endpoint_test.go
index 376423643..6bef9dcce 100644
--- a/backend/internal/handler/endpoint_test.go
+++ b/backend/internal/handler/endpoint_test.go
@@ -23,6 +23,7 @@ func TestNormalizeInboundEndpoint(t *testing.T) {
}{
// Direct canonical paths.
{"/v1/messages", EndpointMessages},
+ {"/v1/systemone", EndpointSystemOne},
{"/v1/chat/completions", EndpointChatCompletions},
{"/v1/embeddings", EndpointEmbeddings},
{"/v1/alpha/search", EndpointAlphaSearch},
@@ -97,6 +98,7 @@ func TestDeriveUpstreamEndpoint(t *testing.T) {
}{
// Anthropic.
{"anthropic messages", EndpointMessages, "/v1/messages", service.PlatformAnthropic, EndpointMessages},
+ {"typesafe system one", EndpointSystemOne, "/v1/systemone", service.PlatformTypeSafe, EndpointSystemOne},
// Gemini.
{"gemini models", EndpointGeminiModels, "/v1beta/models/gemini:gen", service.PlatformGemini, EndpointGeminiModels},
diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go
index 74f7c7573..2f597e4e5 100644
--- a/backend/internal/handler/gateway_handler.go
+++ b/backend/internal/handler/gateway_handler.go
@@ -24,6 +24,7 @@ import (
"github.com/MACOS-DO/sub4api/internal/pkg/logger"
"github.com/MACOS-DO/sub4api/internal/pkg/openai"
"github.com/MACOS-DO/sub4api/internal/pkg/timezone"
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
"github.com/MACOS-DO/sub4api/internal/pkg/xai"
"github.com/MACOS-DO/sub4api/internal/securityaudit"
middleware2 "github.com/MACOS-DO/sub4api/internal/server/middleware"
@@ -222,6 +223,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups")
return
}
+ if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) {
+ return
+ }
if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolAnthropicMessages, reqModel, body); decision != nil && !decision.AllowNextStage {
h.anthropicSecurityAuditError(c, decision)
@@ -1162,7 +1166,7 @@ func (h *GatewayHandler) Models(c *gin.Context) {
}
if platform == service.PlatformComposite {
- availableModels, err := h.compositeAvailableModels(c.Request.Context(), groupID)
+ availableModels, err := h.compositeAvailableModels(c.Request.Context(), groupID, "", true)
if err != nil {
h.errorResponse(c, http.StatusInternalServerError, "api_error", "Failed to load composite model catalog")
return
@@ -1214,6 +1218,10 @@ func (h *GatewayHandler) Models(c *gin.Context) {
writeGrokModelsList(c, xai.DefaultModelIDs())
return
}
+ if platform == service.PlatformTypeSafe {
+ writeModelsList(c, platform, []string{typesafe.JevLatestModel})
+ return
+ }
writeModelsListResponse(c, claude.DefaultModels)
}
@@ -1269,22 +1277,23 @@ func (h *GatewayHandler) codexModelIDsForGroup(ctx context.Context, group *servi
platform = group.Platform
}
if platform == service.PlatformComposite {
- availableModels, err := h.compositeAvailableModels(ctx, groupID)
+ availableModels, err := h.compositeAvailableModels(ctx, groupID, service.CompositeRouteEndpointResponses, false)
if err != nil {
return nil, err
}
fallbackModels := defaultCodexModelIDsForPlatform(service.PlatformComposite)
+ // A non-nil empty catalog (BPS configured but nothing usable) disables the static fallback.
+ models := availableModels
+ if models == nil {
+ models = fallbackModels
+ }
if group.ModelAllowlistEnabled() {
- source := availableModels
- if source == nil {
- source = fallbackModels
- }
- return group.ModelAllowlist.FilterForListing(source), nil
+ models = group.ModelAllowlist.FilterForListing(models)
}
- if availableModels != nil {
- return availableModels, nil
+ if filtered, err := h.gatewayService.FilterCompositeCodexModels(ctx, group.ID, models); err == nil {
+ return filtered, nil
}
- return fallbackModels, nil
+ return models, nil
}
availableModels := h.gatewayService.GetAvailableModels(ctx, groupID, platform)
@@ -1298,14 +1307,24 @@ func (h *GatewayHandler) codexModelIDsForGroup(ctx context.Context, group *servi
return fallbackModels, nil
}
-func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *int64) ([]string, error) {
+// compositeAvailableModels lists the models the composite group can serve.
+// includeSystemOne adds TypeSafe models, which only work through /v1/systemone;
+// LLM client catalogs (Codex) must exclude them.
+func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *int64, endpoint string, includeSystemOne bool) ([]string, error) {
if h == nil || h.gatewayService == nil {
return nil, nil
}
seen := make(map[string]struct{})
models := make([]string, 0)
schedulablePlatforms := h.gatewayService.GetSchedulablePlatforms(ctx, groupID)
- for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo} {
+ for _, platform := range domain.CompositePrecedencePlatformIDs() {
+ if platform == service.PlatformTypeSafe && !includeSystemOne {
+ continue
+ }
+ // OpenAI BPS models are exposed only through explicit routes; see CompleteCompositeBPSModelCatalog.
+ if platform == service.PlatformOpenAIBPS {
+ continue
+ }
platformModels := h.gatewayService.GetAvailableModels(ctx, groupID, platform)
if len(platformModels) == 0 {
// CN 供应商没有静态默认模型列表(defaultModelIDsForPlatform 的
@@ -1326,6 +1345,16 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID *
models = append(models, model)
}
}
+ // A route can expose a public ID that no account model mapping contains.
+ // On lookup failure, retain the existing account-derived catalog only.
+ if routeModels, err := h.gatewayService.GetCompositeRouteModels(ctx, groupID, endpoint, includeSystemOne); err == nil {
+ for _, model := range routeModels {
+ if _, ok := seen[model]; !ok {
+ seen[model] = struct{}{}
+ models = append(models, model)
+ }
+ }
+ }
return h.gatewayService.CompleteCompositeBPSModelCatalog(ctx, groupID, models)
}
@@ -1491,10 +1520,18 @@ func defaultModelIDsForPlatform(platform string) []string {
return xai.DefaultModelIDs()
case service.PlatformOpenCodeGo:
return service.DefaultOpenCodeGoModelIDs()
+ case service.PlatformTypeSafe:
+ return []string{"jev-latest"}
case service.PlatformComposite:
ids := make([]string, 0)
seen := make(map[string]struct{})
- for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo} {
+ for _, concretePlatform := range domain.CompositePrecedencePlatformIDs() {
+ // TypeSafe is deliberately skipped: jev-latest only works through
+ // /v1/systemone, so the static fallback never advertises it to LLM
+ // clients. compositeAvailableModels lists it when the group can serve it.
+ if concretePlatform == service.PlatformTypeSafe {
+ continue
+ }
for _, id := range defaultModelIDsForPlatform(concretePlatform) {
if _, ok := seen[id]; ok {
continue
@@ -2179,6 +2216,9 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups")
return
}
+ if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) {
+ return
+ }
setOpsRequestContext(c, parsedReq.Model, parsedReq.Stream)
setOpsEndpointContext(c, "", int16(service.RequestTypeFromLegacy(parsedReq.Stream, false)))
diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go
index f04dacdab..51c5d9319 100644
--- a/backend/internal/handler/gateway_handler_chat_completions.go
+++ b/backend/internal/handler/gateway_handler_chat_completions.go
@@ -82,6 +82,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups")
return
}
+ if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) {
+ return
+ }
reqStream, ok := parseOpenAICompatibleStream(body)
if !ok {
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go
index f2e113905..161b6d4e0 100644
--- a/backend/internal/handler/gateway_handler_responses.go
+++ b/backend/internal/handler/gateway_handler_responses.go
@@ -82,6 +82,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups")
return
}
+ if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) {
+ return
+ }
reqStream, ok := parseOpenAICompatibleStream(body)
if !ok {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
diff --git a/backend/internal/handler/gateway_models_retrieve_test.go b/backend/internal/handler/gateway_models_retrieve_test.go
index b353ba5c1..3ba11cbf1 100644
--- a/backend/internal/handler/gateway_models_retrieve_test.go
+++ b/backend/internal/handler/gateway_models_retrieve_test.go
@@ -27,7 +27,7 @@ func requestModelForTest(h *GatewayHandler, group *service.Group, modelID, etag
func TestRetrieveModelMatchesVisibleCatalogue(t *testing.T) {
gin.SetMode(gin.TestMode)
- for _, platform := range []string{service.PlatformOpenAI, service.PlatformAnthropic, service.PlatformGemini, service.PlatformGrok, service.PlatformComposite} {
+ for _, platform := range []string{service.PlatformOpenAI, service.PlatformAnthropic, service.PlatformGemini, service.PlatformGrok, service.PlatformTypeSafe, service.PlatformComposite} {
for _, mapped := range []bool{false, true} {
name := platform + "/fallback"
if mapped {
diff --git a/backend/internal/handler/gateway_models_test.go b/backend/internal/handler/gateway_models_test.go
index 4b006eeac..6d975e000 100644
--- a/backend/internal/handler/gateway_models_test.go
+++ b/backend/internal/handler/gateway_models_test.go
@@ -3,6 +3,7 @@ package handler
import (
"context"
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
"strings"
@@ -22,6 +23,16 @@ type gatewayModelsAccountRepoStub struct {
byGroup map[int64][]service.Account
}
+type gatewayModelsRouteRepoStub struct {
+ service.CompositeModelRouteRepository
+ routes []service.CompositeModelRoute
+ err error
+}
+
+func (s *gatewayModelsRouteRepoStub) ListByGroup(_ context.Context, _ int64, _ bool) ([]service.CompositeModelRoute, error) {
+ return s.routes, s.err
+}
+
type gatewayModelsResponseForTest struct {
Object string `json:"object"`
Data []gatewayModelItemForTest `json:"data"`
@@ -81,16 +92,80 @@ func (s *gatewayModelsAccountRepoStub) ListModelAvailabilityCandidates(ctx conte
return s.ListSchedulableByGroupID(ctx, *groupID)
}
-func newGatewayModelsHandlerForTest(repo service.AccountRepository) *GatewayHandler {
+func newGatewayModelsHandlerForTest(repo service.AccountRepository, routeRepo ...service.CompositeModelRouteRepository) *GatewayHandler {
+ var resolver *service.CompositeRouteResolver
+ if len(routeRepo) > 0 {
+ resolver = service.NewCompositeRouteResolver(routeRepo[0])
+ }
return &GatewayHandler{
gatewayService: service.NewGatewayService(
repo,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
- nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
+ nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, resolver, nil, nil,
),
}
}
+func TestGatewayCompositeRouteModelsAppearInBothCatalogs(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ const groupID int64 = 7784
+ accounts := &gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{
+ groupID: {{ID: 1, Platform: service.PlatformOpenAI, Credentials: map[string]any{
+ "model_mapping": map[string]any{"mapped-model": "upstream"},
+ }}},
+ }}
+ routes := &gatewayModelsRouteRepoStub{routes: []service.CompositeModelRoute{
+ {PublicModel: "route-only", MatchType: service.CompositeRouteMatchExact, Enabled: true},
+ {PublicModel: "route-only", MatchType: service.CompositeRouteMatchExact, Enabled: true},
+ {PublicModel: "mapped-model", MatchType: service.CompositeRouteMatchExact, Enabled: true},
+ {PublicModel: "image-only", MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointImages, Enabled: true},
+ {PublicModel: "prefix-", MatchType: service.CompositeRouteMatchPrefix, Enabled: true},
+ {PublicModel: "disabled", MatchType: service.CompositeRouteMatchExact, Enabled: false},
+ }}
+ for _, tc := range []struct {
+ name string
+ repo service.CompositeModelRouteRepository
+ allowlist []string
+ want []string
+ }{
+ {"routes", routes, nil, []string{"mapped-model", "route-only", "image-only"}},
+ {"allowlist", routes, []string{"route-only", "disabled", "unknown"}, []string{"route-only"}},
+ {"lookup failure", &gatewayModelsRouteRepoStub{err: errors.New("unavailable")}, nil, []string{"mapped-model"}},
+ {"allowlisted lookup failure", &gatewayModelsRouteRepoStub{err: errors.New("unavailable")}, []string{"mapped-model", "unknown"}, []string{"mapped-model"}},
+ {"no route repo", nil, nil, []string{"mapped-model"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := newGatewayModelsHandlerForTest(accounts, tc.repo)
+ group := &service.Group{ID: groupID, Platform: service.PlatformComposite}
+ if tc.allowlist != nil {
+ group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: tc.allowlist}
+ }
+ for _, endpoint := range []string{"models", "codex"} {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
+ c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: group})
+ if endpoint == "models" {
+ h.Models(c)
+ var got gatewayModelsResponseForTest
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
+ require.Equal(t, tc.want, modelIDsForTest(got.Data))
+ } else {
+ h.CodexModels(c)
+ var got codexModelsResponseForTest
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
+ want := tc.want
+ if tc.name == "routes" {
+ want = []string{"mapped-model", "route-only"}
+ }
+ require.ElementsMatch(t, want, codexModelSlugsForTest(got.Models))
+ }
+ require.Equal(t, http.StatusOK, rec.Code)
+ }
+ })
+ }
+}
+
func TestDefaultModelIDsForCompositeIncludesAntigravityDefaults(t *testing.T) {
antigravityIDs := defaultModelIDsForPlatform(service.PlatformAntigravity)
require.NotEmpty(t, antigravityIDs)
@@ -932,6 +1007,10 @@ func TestDefaultCodexModelIDsForPlatform_DeepSeekUsesDeepSeekModels(t *testing.T
require.Equal(t, defaultModelIDsForPlatform(service.PlatformAnthropic), defaultCodexModelIDsForPlatform(service.PlatformAnthropic))
}
+func TestDefaultModelIDsForPlatform_TypeSafeUsesJev(t *testing.T) {
+ require.Equal(t, []string{"jev-latest"}, defaultModelIDsForPlatform(service.PlatformTypeSafe))
+}
+
func TestGatewayCodexModels_DeepSeekWithoutMappingUsesDeepSeekDefaults(t *testing.T) {
gin.SetMode(gin.TestMode)
const groupID int64 = 130
@@ -1522,3 +1601,232 @@ func TestGatewayModels_GPT6SolLunaDiscoveryRespectsGroupAndAccountRestrictions(t
})
}
}
+
+// Scenario: jev-latest only works through /v1/systemone, so Composite groups list
+// it in /v1/models only when they can serve it, and never in the Codex manifest.
+func TestGatewayModels_CompositeTypeSafeListingScope(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ groupID := int64(66)
+ h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{
+ byGroup: map[int64][]service.Account{
+ groupID: {{ID: 1, Platform: service.PlatformAnthropic}, {ID: 2, Platform: service.PlatformTypeSafe, Type: service.AccountTypeAPIKey}},
+ },
+ })
+ newContext := func(path string) (*gin.Context, *httptest.ResponseRecorder) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodGet, path, nil)
+ c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
+ Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
+ })
+ return c, rec
+ }
+
+ c, rec := newContext("/v1/models")
+ h.Models(c)
+ require.Equal(t, http.StatusOK, rec.Code)
+ var models gatewayModelsResponseForTest
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &models))
+ require.Contains(t, modelIDsForTest(models.Data), "jev-latest")
+ require.Contains(t, modelIDsForTest(models.Data), "claude-opus-4-6")
+
+ c, rec = newContext("/models?client_version=0.147.0")
+ h.CodexModels(c)
+ require.Equal(t, http.StatusOK, rec.Code)
+ var manifest codexModelsResponseForTest
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &manifest))
+ slugs := codexModelSlugsForTest(manifest.Models)
+ require.Contains(t, slugs, "claude-opus-4-6")
+ require.NotContains(t, slugs, "jev-latest")
+}
+
+func TestDefaultModelIDsForPlatform_CompositeFallbackExcludesTypeSafe(t *testing.T) {
+ require.NotContains(t, defaultModelIDsForPlatform(service.PlatformComposite), "jev-latest")
+ require.NotContains(t, defaultCodexModelIDsForPlatform(service.PlatformComposite), "jev-latest")
+}
+
+func TestGatewayModels_CompositeExactRoutesRespectTypeSafeIsolation(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ const groupID int64 = 7784
+ routes := &gatewayModelsRouteRepoStub{routes: []service.CompositeModelRoute{
+ {PublicModel: "systemone-any-alias", TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointAny, Enabled: true},
+ {PublicModel: "systemone-responses-alias", TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointResponses, Enabled: true},
+ {PublicModel: "systemone-legacy-alias", TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchExact, Enabled: true},
+ {PublicModel: "jev-latest", TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchExact, Enabled: true},
+ {PublicModel: "responses-alias", TargetPlatform: service.PlatformOpenAI, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointResponses, Enabled: true},
+ {PublicModel: "image-alias", TargetPlatform: service.PlatformOpenAI, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointImages, Enabled: true},
+ }}
+ h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{}, routes)
+ wantModels := make([]string, 0, len(routes.routes))
+ for _, route := range routes.routes {
+ wantModels = append(wantModels, route.PublicModel)
+ }
+ for _, allowlisted := range []bool{false, true} {
+ name := "unrestricted"
+ if allowlisted {
+ name = "allowlisted"
+ }
+ t.Run(name, func(t *testing.T) {
+ group := &service.Group{ID: groupID, Platform: service.PlatformComposite}
+ if allowlisted {
+ group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{
+ "systemone-any-alias", "systemone-responses-alias", "systemone-legacy-alias", "jev-latest", "responses-alias", "image-alias",
+ }}
+ }
+ for _, codex := range []bool{false, true} {
+ rec := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(rec)
+ ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
+ ctx.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: group})
+ if codex {
+ h.CodexModels(ctx)
+ var manifest codexModelsResponseForTest
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &manifest))
+ require.Equal(t, []string{"responses-alias"}, codexModelSlugsForTest(manifest.Models))
+ } else {
+ h.Models(ctx)
+ var models gatewayModelsResponseForTest
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &models))
+ require.ElementsMatch(t, wantModels, modelIDsForTest(models.Data))
+ }
+ require.Equal(t, http.StatusOK, rec.Code)
+ }
+ })
+ }
+}
+
+func TestGatewayModels_CompositeCodexFiltersEffectiveResponsesRoutes(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ const groupID int64 = 7793
+ defaultModel := defaultModelIDsForPlatform(service.PlatformOpenAI)[0]
+ for _, scenario := range []struct {
+ name string
+ model string
+ accounts []service.Account
+ routes []service.CompositeModelRoute
+ }{
+ {
+ name: "colliding exact routes",
+ model: "shared-alias",
+ routes: []service.CompositeModelRoute{
+ {PublicModel: "shared-alias", TargetPlatform: service.PlatformOpenAI, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointAny, Priority: 1, Enabled: true},
+ {PublicModel: "shared-alias", TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointResponses, Priority: 100, Enabled: true},
+ },
+ },
+ {
+ name: "account alias exact override",
+ model: "account-alias",
+ accounts: []service.Account{{ID: 1, Platform: service.PlatformOpenAI, Credentials: map[string]any{
+ "model_mapping": map[string]any{"account-alias": "gpt-5"},
+ }}},
+ routes: []service.CompositeModelRoute{
+ {PublicModel: "account-alias", TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointResponses, Enabled: true},
+ },
+ },
+ {
+ name: "account alias prefix override",
+ model: "account-alias",
+ accounts: []service.Account{{ID: 1, Platform: service.PlatformOpenAI, Credentials: map[string]any{
+ "model_mapping": map[string]any{"account-alias": "gpt-5"},
+ }}},
+ routes: []service.CompositeModelRoute{
+ {PublicModel: "account-", TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchPrefix, Endpoint: service.CompositeRouteEndpointResponses, Enabled: true},
+ },
+ },
+ {
+ name: "account default override",
+ model: defaultModel,
+ accounts: []service.Account{{ID: 1, Platform: service.PlatformOpenAI}},
+ routes: []service.CompositeModelRoute{
+ {PublicModel: defaultModel, TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointResponses, Enabled: true},
+ },
+ },
+ {
+ name: "fallback default override",
+ model: defaultModel,
+ routes: []service.CompositeModelRoute{
+ {PublicModel: defaultModel, TargetPlatform: service.PlatformTypeSafe, MatchType: service.CompositeRouteMatchPrefix, Endpoint: service.CompositeRouteEndpointResponses, Enabled: true},
+ },
+ },
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ for _, allowlisted := range []bool{false, true} {
+ name := "unrestricted"
+ if allowlisted {
+ name = "allowlisted"
+ }
+ t.Run(name, func(t *testing.T) {
+ routes := append([]service.CompositeModelRoute(nil), scenario.routes...)
+ if scenario.name != "fallback default override" {
+ routes = append(routes, service.CompositeModelRoute{
+ PublicModel: "responses-control", TargetPlatform: service.PlatformOpenAI, MatchType: service.CompositeRouteMatchExact, Endpoint: service.CompositeRouteEndpointResponses, Enabled: true,
+ })
+ }
+ h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{
+ byGroup: map[int64][]service.Account{groupID: scenario.accounts},
+ }, &gatewayModelsRouteRepoStub{routes: routes})
+ group := &service.Group{ID: groupID, Platform: service.PlatformComposite}
+ if allowlisted {
+ group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{scenario.model, "responses-control"}}
+ }
+ for _, codex := range []bool{false, true} {
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
+ ctx.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: group})
+ if codex {
+ h.CodexModels(ctx)
+ var manifest codexModelsResponseForTest
+ require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &manifest))
+ slugs := codexModelSlugsForTest(manifest.Models)
+ require.NotContains(t, slugs, scenario.model)
+ if scenario.name != "fallback default override" {
+ require.Contains(t, slugs, "responses-control")
+ } else if allowlisted {
+ require.Empty(t, slugs)
+ }
+ } else {
+ h.Models(ctx)
+ var models gatewayModelsResponseForTest
+ require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &models))
+ require.Contains(t, modelIDsForTest(models.Data), scenario.model)
+ }
+ require.Equal(t, http.StatusOK, recorder.Code)
+ }
+ })
+ }
+ })
+ }
+}
+
+func TestGatewayModels_CompositeCodexRouteLookupErrorKeepsFallback(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ const groupID int64 = 7793
+ model := defaultCodexModelIDsForPlatform(service.PlatformComposite)[0]
+ for _, allowlisted := range []bool{false, true} {
+ name := "unrestricted"
+ if allowlisted {
+ name = "allowlisted"
+ }
+ t.Run(name, func(t *testing.T) {
+ h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{}, &gatewayModelsRouteRepoStub{err: errors.New("unavailable")})
+ group := &service.Group{ID: groupID, Platform: service.PlatformComposite}
+ if allowlisted {
+ group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{model}}
+ }
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
+ ctx.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: group})
+ h.CodexModels(ctx)
+ require.Equal(t, http.StatusOK, recorder.Code)
+ var manifest codexModelsResponseForTest
+ require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &manifest))
+ require.Contains(t, codexModelSlugsForTest(manifest.Models), model)
+ if allowlisted {
+ require.Len(t, manifest.Models, 1)
+ }
+ })
+ }
+}
diff --git a/backend/internal/handler/gateway_systemone.go b/backend/internal/handler/gateway_systemone.go
new file mode 100644
index 000000000..fff015d4f
--- /dev/null
+++ b/backend/internal/handler/gateway_systemone.go
@@ -0,0 +1,287 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/ip"
+ "github.com/MACOS-DO/sub4api/internal/pkg/logger"
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
+ middleware2 "github.com/MACOS-DO/sub4api/internal/server/middleware"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/gin-gonic/gin"
+ "go.uber.org/zap"
+)
+
+const systemOneOnlyPlatformMessage = "TypeSafe models are only available through POST /v1/systemone"
+
+// rejectSystemOneOnlyPlatform stops TypeSafe traffic from entering a non System
+// One protocol chain. TypeSafe accounts only speak the native System One
+// protocol; letting them reach the Anthropic/OpenAI converters would send
+// foreign payloads (and the account key) to the wrong upstream path and feed
+// the resulting auth failures back into account state.
+func rejectSystemOneOnlyPlatform(c *gin.Context, apiKey *service.APIKey, writeError func(*gin.Context, int, string, string)) bool {
+ if _, forced := middleware2.GetForcePlatformFromContext(c); forced {
+ return false
+ }
+ if effectiveAPIKeyPlatform(c, apiKey) != service.PlatformTypeSafe {
+ return false
+ }
+ service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
+ writeError(c, http.StatusNotFound, "not_found_error", systemOneOnlyPlatformMessage)
+ return true
+}
+
+// SystemOne proxies TypeSafe's native, non-streaming System One protocol.
+func (h *GatewayHandler) SystemOne(c *gin.Context) {
+ requestStart := time.Now()
+ apiKey, ok := middleware2.GetAPIKeyFromContext(c)
+ if !ok || apiKey == nil || apiKey.Group == nil {
+ h.errorResponse(c, http.StatusUnauthorized, "authentication_error", "Invalid API key")
+ return
+ }
+ subject, ok := middleware2.GetAuthSubjectFromContext(c)
+ if !ok {
+ h.errorResponse(c, http.StatusInternalServerError, "api_error", "User context not found")
+ return
+ }
+ reqLog := requestLogger(c, "handler.gateway.systemone",
+ zap.Int64("user_id", subject.UserID),
+ zap.Int64("api_key_id", apiKey.ID),
+ zap.Any("group_id", apiKey.GroupID),
+ )
+
+ body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
+ if err != nil {
+ if maxErr, ok := extractMaxBytesError(err); ok {
+ h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
+ return
+ }
+ h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body")
+ return
+ }
+ model, err := typesafe.ValidateSystemOneRequest(body)
+ if err != nil {
+ h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error())
+ return
+ }
+ ensureCompositeTargetPlatform(c, apiKey, model)
+ if apiKey.Group.Platform != service.PlatformTypeSafe &&
+ (apiKey.Group.Platform != service.PlatformComposite || !compositeTargetPlatformAllowed(c, apiKey, model, service.PlatformTypeSafe)) {
+ h.errorResponse(c, http.StatusNotFound, "not_found_error", "System One is only available for TypeSafe and compatible Composite groups")
+ return
+ }
+ if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolTypeSafeSystemOne, model, body); decision != nil && !decision.AllowNextStage {
+ h.anthropicSecurityAuditError(c, decision)
+ return
+ }
+
+ setOpsRequestContext(c, model, false)
+ setOpsEndpointContext(c, "", int16(service.RequestTypeSync))
+ service.SetOpsLatencyMs(c, service.OpsAuthLatencyMsKey, time.Since(requestStart).Milliseconds())
+ pricingCtx, pricingAt := service.WithGatewayTokenRequestPricing(c.Request.Context())
+ c.Request = c.Request.WithContext(pricingCtx)
+ channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, model)
+ subscription, _ := middleware2.GetSubscriptionFromContext(c)
+
+ streamStarted := false
+ userRelease, err := h.concurrencyHelper.AcquireUserSlotWithWait(c, subject.UserID, subject.Concurrency, false, &streamStarted)
+ if err != nil {
+ reqLog.Warn("systemone.user_slot_acquire_failed", zap.Error(err))
+ h.handleConcurrencyError(c, err, "user", false)
+ return
+ }
+ // 在请求结束或 Context 取消时确保释放槽位,避免客户端断开造成泄漏。
+ userRelease = wrapReleaseOnDone(c.Request.Context(), userRelease)
+ if userRelease != nil {
+ defer userRelease()
+ }
+ if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil {
+ reqLog.Info("systemone.billing_eligibility_check_failed", zap.Error(err))
+ status, code, message, retryAfter := billingErrorDetails(err)
+ if retryAfter > 0 {
+ c.Header("Retry-After", strconv.Itoa(retryAfter))
+ }
+ h.errorResponse(c, status, code, message)
+ return
+ }
+ // 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。
+ inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(model, body))
+ if err != nil {
+ reqLog.Info("systemone.inflight_reservation_rejected", zap.Error(err))
+ status, code, message, retryAfter := billingErrorDetails(err)
+ if retryAfter > 0 {
+ c.Header("Retry-After", strconv.Itoa(retryAfter))
+ }
+ h.errorResponse(c, status, code, message)
+ return
+ }
+ defer inflightRelease()
+
+ fs := NewFailoverState(h.maxAccountSwitches, false)
+ for {
+ if failoverClientGone(c) {
+ return
+ }
+ selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, "", model, fs.FailedAccountIDs, "", subject.UserID)
+ if err == nil && (selection == nil || selection.Account == nil) {
+ err = service.ErrNoAvailableAccounts
+ }
+ if err != nil {
+ if failoverClientGone(c) {
+ reqLog.Info("systemone.account_select_aborted_client_disconnected", zap.Error(err))
+ return
+ }
+ if len(fs.FailedAccountIDs) == 0 {
+ cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, model, model, service.PlatformTypeSafe)
+ cls = classifySelectionFailureError(err, cls)
+ if !cls.ModelNotFound {
+ markOpsRoutingCapacityLimitedIfNoAvailable(c, err)
+ }
+ reqLog.Warn("systemone.select_account_no_available", zap.Bool("model_not_found", cls.ModelNotFound), zap.Error(err))
+ h.errorResponse(c, cls.Status, cls.ErrType, cls.Message)
+ return
+ }
+ switch fs.HandleSelectionExhausted(c.Request.Context()) {
+ case FailoverContinue:
+ continue
+ case FailoverCanceled:
+ failoverClientGone(c)
+ return
+ default:
+ if fs.LastFailoverErr != nil {
+ h.handleFailoverExhausted(c, fs.LastFailoverErr, service.PlatformTypeSafe, false)
+ } else {
+ h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, false)
+ }
+ return
+ }
+ }
+ account := selection.Account
+
+ accountRelease := selection.ReleaseFunc
+ if !selection.Acquired {
+ if selection.WaitPlan == nil {
+ markOpsRoutingCapacityLimited(c)
+ h.errorResponse(c, http.StatusServiceUnavailable, "api_error", "No available accounts")
+ return
+ }
+ accountRelease, err = h.concurrencyHelper.AcquireAccountSlotWithWaitTimeout(c, account.ID, selection.WaitPlan.MaxConcurrency, selection.WaitPlan.Timeout, false, &streamStarted)
+ if err != nil {
+ reqLog.Warn("systemone.account_slot_acquire_failed", zap.Int64("account_id", account.ID), zap.Error(err))
+ h.handleConcurrencyError(c, err, "account", false)
+ return
+ }
+ }
+ // 准入终检:与其他网关入口一致,利润控制否决的账号不得承接本次请求。
+ admissionCtx := service.ContextWithSelectionProfitGate(c.Request.Context(), selection)
+ latest, vetoed, reason := h.gatewayService.GatewayProfitControlVetoLatest(admissionCtx, account)
+ if vetoed {
+ if accountRelease != nil {
+ accountRelease()
+ }
+ reqLog.Debug("systemone.account_slot_profit_vetoed", zap.Int64("account_id", account.ID), zap.String("reason", reason))
+ if fs.RecordProfitVeto(account.ID) == FailoverExhausted {
+ reqLog.Warn("systemone.profit_veto_attempts_exhausted", zap.Int("profit_veto_count", fs.ProfitVetoCount()))
+ h.errorResponse(c, http.StatusServiceUnavailable, "api_error", profitVetoExhaustedMessage)
+ return
+ }
+ continue
+ }
+ account = latest
+ accountRelease = wrapReleaseOnDone(c.Request.Context(), accountRelease)
+ setOpsSelectedAccount(c, account.ID, account.Platform)
+ service.SetOpsUpstreamModel(c, model)
+
+ forwardStart := time.Now()
+ result, forwardErr := h.gatewayService.ForwardSystemOne(c.Request.Context(), c, account, body)
+ if accountRelease != nil {
+ accountRelease()
+ }
+ service.SetOpsLatencyMs(c, service.OpsResponseLatencyMsKey, time.Since(forwardStart).Milliseconds())
+
+ if forwardErr != nil {
+ var failoverErr *service.UpstreamFailoverError
+ if errors.As(forwardErr, &failoverErr) {
+ switch fs.HandleFailoverError(c.Request.Context(), h.gatewayService, account.ID, account.Platform, account.GetPoolModeRetryCount(), failoverErr) {
+ case FailoverContinue:
+ reqLog.Warn("systemone.upstream_failover_switching",
+ zap.Int64("account_id", account.ID),
+ zap.Int("upstream_status", failoverErr.StatusCode),
+ zap.Int("switch_count", fs.SwitchCount),
+ )
+ continue
+ case FailoverExhausted:
+ h.handleFailoverExhausted(c, fs.LastFailoverErr, service.PlatformTypeSafe, false)
+ return
+ case FailoverCanceled:
+ failoverClientGone(c)
+ return
+ }
+ }
+ if failoverClientGone(c) {
+ return
+ }
+ var upstreamErr *service.SystemOneUpstreamError
+ if errors.As(forwardErr, &upstreamErr) {
+ status := upstreamErr.StatusCode
+ if !service.IsSystemOneRequestErrorStatus(status) {
+ status = http.StatusBadGateway
+ }
+ h.errorResponse(c, status, "upstream_error", "TypeSafe rejected the request")
+ return
+ }
+ reqLog.Warn("systemone.forward_failed", zap.Int64("account_id", account.ID), zap.Error(forwardErr))
+ if errors.Is(forwardErr, typesafe.ErrSystemOneResponseTooLarge) {
+ h.errorResponse(c, http.StatusBadGateway, "upstream_error", "TypeSafe response exceeds the gateway size limit")
+ return
+ }
+ h.errorResponse(c, http.StatusBadGateway, "upstream_error", "TypeSafe upstream request failed")
+ return
+ }
+
+ c.Data(result.StatusCode, result.ContentType, result.Body)
+ h.recordSystemOneUsage(c, apiKey, account, subscription, channelMapping, model, body, result, subject.UserID, pricingAt)
+ return
+ }
+}
+
+func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.APIKey, account *service.Account, subscription *service.UserSubscription, mapping service.ChannelMappingResult, model string, body []byte, result *service.SystemOneForwardResult, userID int64, pricingAt time.Time) {
+ userAgent := c.GetHeader("User-Agent")
+ clientIP := ip.GetClientIP(c)
+ inboundEndpoint := GetInboundEndpoint(c)
+ upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
+ quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
+ sessionID := service.ExtractClientSessionID(c)
+ requestPayloadHash := service.HashUsageRequestPayload(body)
+
+ h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
+ if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
+ Result: &result.ForwardResult,
+ APIKey: apiKey,
+ User: apiKey.User,
+ Account: account,
+ Subscription: subscription,
+ PricingAt: pricingAt,
+ InboundEndpoint: inboundEndpoint,
+ UpstreamEndpoint: upstreamEndpoint,
+ UserAgent: userAgent,
+ IPAddress: clientIP,
+ SessionID: sessionID,
+ RequestPayloadHash: requestPayloadHash,
+ APIKeyService: h.apiKeyService,
+ QuotaPlatform: quotaPlatform,
+ ChannelUsageFields: clientRequestedUsageFields(c, mapping, model, result.UpstreamModel),
+ }); err != nil {
+ logger.L().With(
+ zap.String("component", "handler.gateway.systemone"),
+ zap.Int64("user_id", userID),
+ zap.Int64("api_key_id", apiKey.ID),
+ zap.Int64("account_id", account.ID),
+ ).Error("systemone.record_usage_failed", zap.Error(err))
+ }
+ })
+}
diff --git a/backend/internal/handler/gateway_systemone_test.go b/backend/internal/handler/gateway_systemone_test.go
new file mode 100644
index 000000000..720fce41d
--- /dev/null
+++ b/backend/internal/handler/gateway_systemone_test.go
@@ -0,0 +1,109 @@
+package handler
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ middleware2 "github.com/MACOS-DO/sub4api/internal/server/middleware"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+const validSystemOneHandlerBody = `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"noul","instructions":"Evaluate"}}}`
+
+func newSystemOneHandlerContext(body string) (*gin.Context, *httptest.ResponseRecorder) {
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/systemone", strings.NewReader(body))
+ c.Request.Header.Set("Content-Type", "application/json")
+ return c, recorder
+}
+
+func TestSystemOneRequiresAuthentication(t *testing.T) {
+ c, recorder := newSystemOneHandlerContext(validSystemOneHandlerBody)
+ (&GatewayHandler{}).SystemOne(c)
+ require.Equal(t, http.StatusUnauthorized, recorder.Code)
+ require.Contains(t, recorder.Body.String(), "authentication_error")
+}
+
+func TestSystemOneRejectsNonTypeSafeGroupBeforeScheduling(t *testing.T) {
+ c, recorder := newSystemOneHandlerContext(validSystemOneHandlerBody)
+ groupID := int64(3)
+ c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ID: 4, UserID: 5, GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI}})
+ c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 5, Concurrency: 1})
+
+ (&GatewayHandler{cfg: &config.Config{Gateway: config.GatewayConfig{MaxBodySize: 1 << 20}}}).SystemOne(c)
+ require.Equal(t, http.StatusNotFound, recorder.Code)
+ require.Contains(t, recorder.Body.String(), "only available for TypeSafe")
+}
+
+func newTypeSafeGroupContext(t *testing.T, path, body, groupPlatform string) (*gin.Context, *httptest.ResponseRecorder) {
+ t.Helper()
+ c, recorder := newSystemOneHandlerContext(body)
+ c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
+ c.Request.Header.Set("Content-Type", "application/json")
+ groupID := int64(9)
+ c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ID: 4, UserID: 5, GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: groupPlatform}})
+ c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 5, Concurrency: 1})
+ return c, recorder
+}
+
+func TestRejectSystemOneOnlyPlatform(t *testing.T) {
+ write := func(c *gin.Context, status int, errType, message string) {
+ c.JSON(status, gin.H{"type": errType, "message": message})
+ }
+
+ c, recorder := newTypeSafeGroupContext(t, "/v1/messages", `{}`, service.PlatformTypeSafe)
+ require.True(t, rejectSystemOneOnlyPlatform(c, mustAPIKey(t, c), write))
+ require.Equal(t, http.StatusNotFound, recorder.Code)
+ require.Contains(t, recorder.Body.String(), systemOneOnlyPlatformMessage)
+
+ c, _ = newTypeSafeGroupContext(t, "/v1/messages", `{}`, service.PlatformComposite)
+ require.False(t, rejectSystemOneOnlyPlatform(c, mustAPIKey(t, c), write))
+ c.Request = c.Request.WithContext(service.WithResolvedTargetPlatform(c.Request.Context(), service.PlatformTypeSafe))
+ require.True(t, rejectSystemOneOnlyPlatform(c, mustAPIKey(t, c), write))
+
+ c, _ = newTypeSafeGroupContext(t, "/v1/messages", `{}`, service.PlatformAnthropic)
+ require.False(t, rejectSystemOneOnlyPlatform(c, mustAPIKey(t, c), write))
+
+ c, _ = newTypeSafeGroupContext(t, "/antigravity/v1/messages", `{}`, service.PlatformTypeSafe)
+ c.Set(string(middleware2.ContextKeyForcePlatform), service.PlatformAntigravity)
+ require.False(t, rejectSystemOneOnlyPlatform(c, mustAPIKey(t, c), write))
+}
+
+func mustAPIKey(t *testing.T, c *gin.Context) *service.APIKey {
+ t.Helper()
+ apiKey, ok := middleware2.GetAPIKeyFromContext(c)
+ require.True(t, ok)
+ return apiKey
+}
+
+func TestTypeSafeGroupsRejectNonSystemOneProtocolsBeforeScheduling(t *testing.T) {
+ h := &GatewayHandler{
+ cfg: &config.Config{Gateway: config.GatewayConfig{MaxBodySize: 1 << 20}},
+ gatewayService: &service.GatewayService{},
+ }
+ for _, tc := range []struct {
+ name string
+ path string
+ body string
+ handler func(*gin.Context)
+ }{
+ {"messages", "/v1/messages", `{"model":"jev-latest","max_tokens":1,"messages":[{"role":"user","content":"hi"}]}`, h.Messages},
+ {"count_tokens", "/v1/messages/count_tokens", `{"model":"jev-latest","messages":[{"role":"user","content":"hi"}]}`, h.CountTokens},
+ {"chat_completions", "/v1/chat/completions", `{"model":"jev-latest","messages":[{"role":"user","content":"hi"}]}`, h.ChatCompletions},
+ {"responses", "/v1/responses", `{"model":"jev-latest","input":"hi"}`, h.Responses},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c, recorder := newTypeSafeGroupContext(t, tc.path, tc.body, service.PlatformTypeSafe)
+ tc.handler(c)
+ require.Equal(t, http.StatusNotFound, recorder.Code, recorder.Body.String())
+ require.Contains(t, recorder.Body.String(), systemOneOnlyPlatformMessage)
+ })
+ }
+}
diff --git a/backend/internal/handler/openai_codex_models_handler_test.go b/backend/internal/handler/openai_codex_models_handler_test.go
index 8b3466738..f56568751 100644
--- a/backend/internal/handler/openai_codex_models_handler_test.go
+++ b/backend/internal/handler/openai_codex_models_handler_test.go
@@ -1001,3 +1001,32 @@ func TestCodexModelsPinnedAccountsETagMatchReturns304(t *testing.T) {
require.Equal(t, http.StatusNotModified, second.Code, second.Body.String())
require.Empty(t, second.Body.Bytes())
}
+
+func TestCodexModelsDiscoveryProjectsWildcardMappingWithoutAllowlist(t *testing.T) {
+ for _, mode := range []string{"ordinary", "pinned", "fallback"} {
+ t.Run(mode, func(t *testing.T) {
+ account := newPinnedCodexAccount(1, service.StatusActive, true, false)
+ account.Credentials["model_mapping"] = map[string]any{"gpt-*": "gpt-5.4"}
+ upstream := &codexModelsPinnedHTTPUpstream{bodies: map[int64]string{
+ 1: `{"models":[{"slug":"gpt-5.4"},{"slug":"blocked"},{"slug":"codex-auto-review"},{"slug":"gpt-image-2"}]}`,
+ }}
+ handler := newPinnedCodexTestHandler([]service.Account{account}, upstream, 3)
+ group := &service.Group{ID: 84, Platform: service.PlatformOpenAI,
+ ModelAllowlist: service.GroupModelAllowlist{Models: []string{"blocked"}},
+ }
+ if mode != "ordinary" {
+ group.CodexModelsManifestConfig = service.GroupCodexModelsManifestConfig{Enabled: true, AccountIDs: []int64{1}}
+ }
+ if mode == "fallback" {
+ group.CodexModelsManifestConfig.AccountIDs = []int64{999}
+ group.CodexModelsManifestConfig.FallbackToScheduler = true
+ }
+ first := performCodexModelsRequestForGroup(t, handler, group, "")
+ require.Equal(t, http.StatusOK, first.Code, first.Body.String())
+ require.Equal(t, []string{"gpt-5.4"}, codexHandlerManifestSlugs(t, first))
+ require.NotEmpty(t, first.Header().Get("ETag"))
+ second := performCodexModelsRequestForGroup(t, handler, group, first.Header().Get("ETag"))
+ require.Equal(t, http.StatusNotModified, second.Code)
+ })
+ }
+}
diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go
index 542b92f08..8e5506a87 100644
--- a/backend/internal/handler/openai_gateway_handler.go
+++ b/backend/internal/handler/openai_gateway_handler.go
@@ -17,6 +17,7 @@ import (
"time"
"github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/ctxkey"
"github.com/MACOS-DO/sub4api/internal/pkg/ip"
"github.com/MACOS-DO/sub4api/internal/pkg/logger"
@@ -330,9 +331,9 @@ func allowOpenAICompatibleMessagesDispatch(c *gin.Context, apiKey *service.APIKe
func openAICompatibleTextTargetAllowed(c *gin.Context, apiKey *service.APIKey, model string) bool {
return compositeTargetPlatformAllowed(c, apiKey, model,
- service.PlatformOpenAI, service.PlatformGrok,
- service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek,
- service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformOpenAIBPS)
+ domain.PlatformIDsWhere(func(spec domain.PlatformSpec) bool {
+ return spec.Gateway == domain.PlatformGatewayOpenAI
+ })...)
}
// isResponsesWebSocketCompositePlatform 限定 composite 分组在 Responses WebSocket
@@ -2143,6 +2144,101 @@ func (p *openAIWSTurnPricing) currentOr(fallback time.Time) time.Time {
return fallback
}
+// openAIWSTurnAPIKeyLookup 是后续 turn 重取 API Key 认证快照的入口
+// (APIKeyService.GetByKey:经 L1/L2 认证缓存,未命中才回源)。
+type openAIWSTurnAPIKeyLookup interface {
+ GetByKey(ctx context.Context, key string) (*service.APIKey, error)
+}
+
+// openAIWSTurnBillingAPIKeys 按 turn 号保存每个 turn 计费用的 API Key 快照。
+//
+// API Key 认证快照只在建连时取一次。若连接内所有 turn 共用它,分组定价(倍率、
+// 高峰、图片定价、利润门参数)会停留在建连时刻:管理员调价后,已打开的长连接
+// 在客户端重连前一直按旧价计费、按旧售价过利润门,而 HTTP 请求每次都经认证缓存
+// 取快照,缓存失效后即生效。
+//
+// 因此后续 turn 在 BeforeTurn(与 HTTP 请求进入认证中间件同位)经同一认证缓存
+// 重取快照,只采用其中的分组,作为该 turn 利润门准入与用量计费共同的分组;用户、
+// Key 限额、订阅仍沿用建连快照。只在同一把 Key、同一分组且平台与订阅类型未变时
+// 采用:Key 换组或分组改平台/订阅类型不是调价,该连接按建连分组调度,继续按建连
+// 快照计费;重取失败同样保留建连快照,不断连。
+//
+// 首轮沿用刚经认证中间件取得的建连快照;没有经过 BeforeTurn 的 turn 回退建连
+// 快照。只保留当前与上一个 turn:下一 turn 的 BeforeTurn 先于上一 turn 的
+// AfterTurn 执行时,上一 turn 仍取到自己的快照。
+type openAIWSTurnBillingAPIKeys struct {
+ mu sync.Mutex
+ keys map[int]*service.APIKey
+}
+
+// begin 在 BeforeTurn 重装利润门前调用:后续 turn 重取计费分组并按 turn 记下,
+// 返回换入该分组的上下文供本 turn 的利润门使用。
+func (k *openAIWSTurnBillingAPIKeys) begin(ctx context.Context, apiKeyService *service.APIKeyService, turn int, conn *service.APIKey) context.Context {
+ turnKey := conn
+ if turn > 1 && apiKeyService != nil {
+ turnKey = refreshOpenAIWSTurnBillingAPIKey(ctx, apiKeyService, conn)
+ }
+ k.set(turn, turnKey)
+ return withOpenAIWSTurnBillingGroup(ctx, turnKey)
+}
+
+func (k *openAIWSTurnBillingAPIKeys) set(turn int, key *service.APIKey) {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+ if k.keys == nil {
+ k.keys = make(map[int]*service.APIKey, 2)
+ }
+ for t := range k.keys {
+ if t < turn-1 {
+ delete(k.keys, t)
+ }
+ }
+ k.keys[turn] = key
+}
+
+func (k *openAIWSTurnBillingAPIKeys) forTurn(turn int, conn *service.APIKey) *service.APIKey {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+ if key := k.keys[turn]; key != nil {
+ return key
+ }
+ return conn
+}
+
+// refreshOpenAIWSTurnBillingAPIKey 返回本 turn 计费用的 API Key:分组取当前认证
+// 快照,其余字段与建连快照共享。不满足采用条件时原样返回建连快照。
+func refreshOpenAIWSTurnBillingAPIKey(ctx context.Context, lookup openAIWSTurnAPIKeyLookup, conn *service.APIKey) *service.APIKey {
+ if lookup == nil || conn == nil || conn.Key == "" || conn.GroupID == nil || conn.Group == nil {
+ return conn
+ }
+ latest, err := lookup.GetByKey(ctx, conn.Key)
+ if err != nil || latest == nil || latest.ID != conn.ID || latest.GroupID == nil || *latest.GroupID != *conn.GroupID {
+ return conn
+ }
+ group := latest.Group
+ if group == nil || group.ID != conn.Group.ID ||
+ group.Platform != conn.Group.Platform ||
+ group.SubscriptionType != conn.Group.SubscriptionType {
+ return conn
+ }
+ turnKey := *conn
+ turnKey.Group = group
+ return &turnKey
+}
+
+// withOpenAIWSTurnBillingGroup 把本 turn 的计费分组换进认证分组上下文,使利润门
+// 的售价与本 turn 计费同源。上下文里没有同 ID 的认证分组时不改动。
+func withOpenAIWSTurnBillingGroup(ctx context.Context, turnKey *service.APIKey) context.Context {
+ if turnKey == nil || turnKey.Group == nil {
+ return ctx
+ }
+ current, ok := ctx.Value(ctxkey.Group).(*service.Group)
+ if !ok || current == nil || current == turnKey.Group || current.ID != turnKey.Group.ID {
+ return ctx
+ }
+ return context.WithValue(ctx, ctxkey.Group, turnKey.Group)
+}
+
// recordOpenAIProfitVeto 记录 OpenAI 侧选号循环的一次利润门终检否决:把账号
// 加入本请求排除集并递增否决计数。返回 false 表示否决次数已达
// maxProfitVetoAttempts,调用方必须停止重选并按「无可用账号」终止。
@@ -2874,6 +2970,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// turn 级定价:首轮回退到 TurnStarted 的所属 turn 时刻;后续 turn 由
// BeforeTurn 重新冻结 pricingAt 并按最新门复核当前账号。
var turnPricing openAIWSTurnPricing
+ // 后续 turn 的计费分组同样在 BeforeTurn 经认证缓存重取,使分组调价对
+ // 已打开的连接生效。
+ var turnBillingAPIKeys openAIWSTurnBillingAPIKeys
// Passthrough ingress does not invoke BeforeTurn for the first frame.
if err := checkSimpleModeTurnBilling(); err != nil {
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed")
@@ -2961,7 +3060,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 长连接跨峰谷/倍率刷新防护:每个 turn 按当前时刻重装门并复核
// 当前账号,越线即要求客户端重连重选(连接绑定单一上游账号,
// 无法中途换号)。本 turn 的准入与计费共用同一 pricingAt。
- turnCtx, turnAt := h.gatewayService.WithOpenAITurnPricingContext(ctx, apiKey.GroupID)
+ turnBillingCtx := turnBillingAPIKeys.begin(ctx, h.apiKeyService, turn, apiKey)
+ turnCtx, turnAt := h.gatewayService.WithOpenAITurnPricingContext(turnBillingCtx, apiKey.GroupID)
if _, vetoed, reason := h.gatewayService.ProfitControlVetoLatest(turnCtx, account); vetoed {
reqLog.Info("openai.websocket_turn_profit_vetoed",
zap.Int("turn", turn),
@@ -3077,11 +3177,12 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
turnRecordPricingAt := turnPricing.currentOr(turnStart)
+ turnBillingAPIKey := turnBillingAPIKeys.forTurn(turn, apiKey)
cyberBlocked := service.GetOpsCyberPolicy(c) != nil
h.submitOpenAIUsageRecordTask(ctx, result, func(taskCtx context.Context) {
if err := h.gatewayService.RecordUsage(taskCtx, &service.OpenAIRecordUsageInput{
Result: result,
- APIKey: apiKey,
+ APIKey: turnBillingAPIKey,
User: apiKey.User,
Account: account,
Subscription: subscription,
diff --git a/backend/internal/handler/openai_gateway_handler_test.go b/backend/internal/handler/openai_gateway_handler_test.go
index c90e62f0a..9e06e4c69 100644
--- a/backend/internal/handler/openai_gateway_handler_test.go
+++ b/backend/internal/handler/openai_gateway_handler_test.go
@@ -15,6 +15,7 @@ import (
"time"
"github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/ctxkey"
pkghttputil "github.com/MACOS-DO/sub4api/internal/pkg/httputil"
"github.com/MACOS-DO/sub4api/internal/pkg/pagination"
"github.com/MACOS-DO/sub4api/internal/pkg/xai"
@@ -1948,6 +1949,12 @@ type openAIResponsesWSUsageLogCase struct {
afterFirstUpstreamRequest func(channelSvc *service.ChannelService) error
// group 覆盖 apiKey.Group(分组级模型白名单测试用);nil 保持原有无分组行为。
group *service.Group
+ // apiKeyService 非 nil 时模拟 API Key 认证中间件:连接认证快照经它按
+ // apiKeyCredential 取得,并把其分组放入请求 ctx;handler 也使用它。
+ apiKeyService *service.APIKeyService
+ apiKeyCredential string
+ // accountRateMultiplier 覆盖账号倍率(利润门测试用)。
+ accountRateMultiplier *float64
// firstFrameCloseExpected:首帧即被拒(连接被 1008 关闭),不期待任何响应帧。
firstFrameCloseExpected bool
// secondTurnCloseExpected:第二个 turn 被拒(连接被 1008 关闭)。
@@ -2962,6 +2969,7 @@ func runOpenAIResponsesWebSocketUsageLogCase(t *testing.T, tc openAIResponsesWSU
if tc.accountPlatform != "" {
account.Platform = tc.accountPlatform
}
+ account.RateMultiplier = tc.accountRateMultiplier
if strings.TrimSpace(tc.ingressMode) != "" {
account.Extra["openai_apikey_responses_websockets_v2_mode"] = tc.ingressMode
}
@@ -3050,6 +3058,12 @@ func runOpenAIResponsesWebSocketUsageLogCase(t *testing.T, tc openAIResponsesWSU
GroupID: &groupID,
User: &service.User{ID: 1701, Status: service.StatusActive},
}
+ if tc.apiKeyService != nil {
+ h.apiKeyService = tc.apiKeyService
+ authKey, err := tc.apiKeyService.GetByKey(context.Background(), tc.apiKeyCredential)
+ require.NoError(t, err)
+ apiKey = authKey
+ }
if tc.simpleModeRejectAtRead > 0 {
apiKey.RateLimit5h = 1
}
@@ -3060,6 +3074,9 @@ func runOpenAIResponsesWebSocketUsageLogCase(t *testing.T, tc openAIResponsesWSU
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})
+ if tc.apiKeyService != nil && apiKey.Group != nil {
+ c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, apiKey.Group))
+ }
c.Next()
})
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
diff --git a/backend/internal/handler/openai_gateway_ws_group_pricing_test.go b/backend/internal/handler/openai_gateway_ws_group_pricing_test.go
new file mode 100644
index 000000000..de8b86668
--- /dev/null
+++ b/backend/internal/handler/openai_gateway_ws_group_pricing_test.go
@@ -0,0 +1,293 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ coderws "github.com/coder/websocket"
+ "github.com/stretchr/testify/require"
+)
+
+// 分组调价对已打开的 WebSocket 连接生效:同一条连接的两个 turn 之间由管理端
+// 改分组倍率(并按分组失效认证缓存),第二个 turn 必须按新倍率计费、按新售价
+// 过利润门;HTTP 请求每次经认证缓存取快照,本来就是这个行为。
+
+const (
+ wsGroupPricingGroupID = int64(4201) // 与 runOpenAIResponsesWebSocketUsageLogCase 的调度分组一致
+ wsGroupPricingKey = "sk-ws-group-pricing"
+ wsGroupPricingFirst = `{"type":"response.create","model":"gpt-5.6-sol","stream":false}`
+ wsGroupPricingSecond = `{"type":"response.create","model":"gpt-5.6-sol","stream":false}`
+)
+
+// wsGroupPricingAPIKeyRepoStub 只实现认证查询与按分组列 Key(认证缓存失效用)。
+type wsGroupPricingAPIKeyRepoStub struct {
+ service.APIKeyRepository
+ mu sync.Mutex
+ apiKey service.APIKey
+ group service.Group
+ err error
+ lookups int
+}
+
+func newWSGroupPricingAPIKeyRepoStub(rate float64) *wsGroupPricingAPIKeyRepoStub {
+ groupID := wsGroupPricingGroupID
+ return &wsGroupPricingAPIKeyRepoStub{
+ apiKey: service.APIKey{
+ ID: 1801,
+ UserID: 1701,
+ Key: wsGroupPricingKey,
+ Status: service.StatusActive,
+ GroupID: &groupID,
+ User: &service.User{ID: 1701, Status: service.StatusActive, Concurrency: 1},
+ },
+ group: service.Group{
+ ID: groupID,
+ Name: "ws-group-pricing",
+ Platform: service.PlatformOpenAI,
+ Status: service.StatusActive,
+ RateMultiplier: rate,
+ Hydrated: true,
+ },
+ }
+}
+
+func (s *wsGroupPricingAPIKeyRepoStub) GetByKeyForAuth(ctx context.Context, key string) (*service.APIKey, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.lookups++
+ if s.err != nil {
+ return nil, s.err
+ }
+ if key != s.apiKey.Key {
+ return nil, service.ErrAPIKeyNotFound
+ }
+ apiKey := s.apiKey
+ user := *s.apiKey.User
+ apiKey.User = &user
+ group := s.group
+ apiKey.Group = &group
+ return &apiKey, nil
+}
+
+func (s *wsGroupPricingAPIKeyRepoStub) ListKeysByGroupID(ctx context.Context, groupID int64) ([]string, error) {
+ return []string{s.apiKey.Key}, nil
+}
+
+// adminUpdate 模拟管理端改 Key/分组后按分组失效认证缓存(与 admin 分组更新同一入口)。
+func (s *wsGroupPricingAPIKeyRepoStub) adminUpdate(apiKeyService *service.APIKeyService, fn func(apiKey *service.APIKey, group *service.Group)) error {
+ s.mu.Lock()
+ fn(&s.apiKey, &s.group)
+ s.mu.Unlock()
+ apiKeyService.InvalidateAuthCacheByGroupID(context.Background(), wsGroupPricingGroupID)
+ return nil
+}
+
+func (s *wsGroupPricingAPIKeyRepoStub) lookupCount() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.lookups
+}
+
+func newWSGroupPricingAPIKeyService(repo *wsGroupPricingAPIKeyRepoStub) *service.APIKeyService {
+ return service.NewAPIKeyService(repo, nil, nil, nil, nil, nil, &config.Config{})
+}
+
+func TestOpenAIResponsesWebSocket_GroupRateChangeAppliesToNextTurn(t *testing.T) {
+ for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeCtxPool} {
+ t.Run(mode, func(t *testing.T) {
+ repo := newWSGroupPricingAPIKeyRepoStub(3.0)
+ apiKeyService := newWSGroupPricingAPIKeyService(repo)
+ got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
+ firstPayload: wsGroupPricingFirst,
+ secondPayload: wsGroupPricingSecond,
+ ingressMode: mode,
+ apiKeyService: apiKeyService,
+ apiKeyCredential: wsGroupPricingKey,
+ afterFirstUpstreamRequest: func(*service.ChannelService) error {
+ return repo.adminUpdate(apiKeyService, func(_ *service.APIKey, group *service.Group) { group.RateMultiplier = 0.3 })
+ },
+ })
+
+ require.Len(t, got.logs, 2)
+ require.InDelta(t, 3.0, got.logs[0].RateMultiplier, 1e-12, "turn 1 bills at the rate in force at connect")
+ require.InDelta(t, 0.3, got.logs[1].RateMultiplier, 1e-12, "turn 2 must bill at the group rate in force when it starts")
+ require.Greater(t, got.logs[0].ActualCost, 0.0)
+ require.InDelta(t, got.logs[0].ActualCost/10, got.logs[1].ActualCost, 1e-15)
+ })
+ }
+}
+
+func TestOpenAIResponsesWebSocket_GroupRateChangeReachesProfitGateOnNextTurn(t *testing.T) {
+ repo := newWSGroupPricingAPIKeyRepoStub(3.0)
+ repo.group.ProfitControlEnabled = true
+ repo.group.ProfitMinMargin = 0.1
+ apiKeyService := newWSGroupPricingAPIKeyService(repo)
+ accountRate := 1.0
+ runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
+ firstPayload: wsGroupPricingFirst,
+ secondPayload: wsGroupPricingSecond,
+ apiKeyService: apiKeyService,
+ apiKeyCredential: wsGroupPricingKey,
+ accountRateMultiplier: &accountRate,
+ // 3.0 → 0.3:账号倍率 1.0 在新售价下已越线,第二个 turn 必须在转发上游前被拒。
+ afterFirstUpstreamRequest: func(*service.ChannelService) error {
+ return repo.adminUpdate(apiKeyService, func(_ *service.APIKey, group *service.Group) { group.RateMultiplier = 0.3 })
+ },
+ secondTurnCloseExpected: true,
+ closeStatus: coderws.StatusTryAgainLater,
+ closeReason: "no longer eligible for this connection",
+ })
+}
+
+func TestOpenAIResponsesWebSocket_KeyMovedToAnotherGroupKeepsConnectionGroup(t *testing.T) {
+ repo := newWSGroupPricingAPIKeyRepoStub(3.0)
+ apiKeyService := newWSGroupPricingAPIKeyService(repo)
+ got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
+ firstPayload: wsGroupPricingFirst,
+ secondPayload: wsGroupPricingSecond,
+ apiKeyService: apiKeyService,
+ apiKeyCredential: wsGroupPricingKey,
+ afterFirstUpstreamRequest: func(*service.ChannelService) error {
+ return repo.adminUpdate(apiKeyService, func(apiKey *service.APIKey, group *service.Group) {
+ other := wsGroupPricingGroupID + 1
+ apiKey.GroupID = &other
+ group.ID = other
+ group.RateMultiplier = 0.3
+ })
+ },
+ })
+
+ require.Len(t, got.logs, 2)
+ require.InDelta(t, 3.0, got.logs[1].RateMultiplier, 1e-12,
+ "a key moved to another group keeps the connection's group: the connection was scheduled from it")
+}
+
+func TestOpenAIResponsesWebSocket_FailedKeyRefreshKeepsConnectionGroup(t *testing.T) {
+ repo := newWSGroupPricingAPIKeyRepoStub(3.0)
+ apiKeyService := newWSGroupPricingAPIKeyService(repo)
+ got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
+ firstPayload: wsGroupPricingFirst,
+ secondPayload: wsGroupPricingSecond,
+ apiKeyService: apiKeyService,
+ apiKeyCredential: wsGroupPricingKey,
+ afterFirstUpstreamRequest: func(*service.ChannelService) error {
+ return repo.adminUpdate(apiKeyService, func(_ *service.APIKey, group *service.Group) {
+ group.RateMultiplier = 0.3
+ repo.err = errors.New("auth store unavailable")
+ })
+ },
+ })
+
+ require.Len(t, got.logs, 2)
+ require.InDelta(t, 3.0, got.logs[1].RateMultiplier, 1e-12, "a failed refresh keeps the connection snapshot")
+ require.GreaterOrEqual(t, repo.lookupCount(), 2, "the second turn must have attempted a refresh")
+}
+
+type wsTurnAPIKeyLookupFunc func(ctx context.Context, key string) (*service.APIKey, error)
+
+func (f wsTurnAPIKeyLookupFunc) GetByKey(ctx context.Context, key string) (*service.APIKey, error) {
+ return f(ctx, key)
+}
+
+func TestRefreshOpenAIWSTurnBillingAPIKey(t *testing.T) {
+ groupID := int64(77)
+ conn := &service.APIKey{
+ ID: 5,
+ Key: "sk-conn",
+ GroupID: &groupID,
+ User: &service.User{ID: 9},
+ Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, SubscriptionType: service.SubscriptionTypeStandard, RateMultiplier: 3},
+ }
+ latestWith := func(mutate func(k *service.APIKey)) *service.APIKey {
+ gid := groupID
+ k := &service.APIKey{
+ ID: 5,
+ Key: "sk-conn",
+ GroupID: &gid,
+ User: &service.User{ID: 9, Balance: 123},
+ Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, SubscriptionType: service.SubscriptionTypeStandard, RateMultiplier: 0.3},
+ }
+ if mutate != nil {
+ mutate(k)
+ }
+ return k
+ }
+
+ t.Run("same group adopts the latest group and nothing else", func(t *testing.T) {
+ got := refreshOpenAIWSTurnBillingAPIKey(context.Background(), wsTurnAPIKeyLookupFunc(func(ctx context.Context, key string) (*service.APIKey, error) {
+ require.Equal(t, "sk-conn", key)
+ return latestWith(nil), nil
+ }), conn)
+ require.NotSame(t, conn, got)
+ require.InDelta(t, 0.3, got.Group.RateMultiplier, 1e-12)
+ require.Same(t, conn.User, got.User, "only the group snapshot is refreshed")
+ require.Equal(t, conn.ID, got.ID)
+ require.InDelta(t, 3.0, conn.Group.RateMultiplier, 1e-12, "the connection snapshot is never mutated")
+ })
+
+ keep := map[string]wsTurnAPIKeyLookupFunc{
+ "lookup error": func(ctx context.Context, key string) (*service.APIKey, error) {
+ return nil, errors.New("boom")
+ },
+ "not found": func(ctx context.Context, key string) (*service.APIKey, error) {
+ return nil, service.ErrAPIKeyNotFound
+ },
+ "nil key": func(ctx context.Context, key string) (*service.APIKey, error) { return nil, nil },
+ "different key id": func(ctx context.Context, key string) (*service.APIKey, error) {
+ return latestWith(func(k *service.APIKey) { k.ID = 6 }), nil
+ },
+ "moved group": func(ctx context.Context, key string) (*service.APIKey, error) {
+ return latestWith(func(k *service.APIKey) { other := int64(78); k.GroupID = &other; k.Group.ID = other }), nil
+ },
+ "no group": func(ctx context.Context, key string) (*service.APIKey, error) {
+ return latestWith(func(k *service.APIKey) { k.Group = nil }), nil
+ },
+ "platform changed": func(ctx context.Context, key string) (*service.APIKey, error) {
+ return latestWith(func(k *service.APIKey) { k.Group.Platform = service.PlatformAnthropic }), nil
+ },
+ "billing type changed": func(ctx context.Context, key string) (*service.APIKey, error) {
+ return latestWith(func(k *service.APIKey) { k.Group.SubscriptionType = service.SubscriptionTypeSubscription }), nil
+ },
+ }
+ for name, lookup := range keep {
+ t.Run(name+" keeps the connection snapshot", func(t *testing.T) {
+ require.Same(t, conn, refreshOpenAIWSTurnBillingAPIKey(context.Background(), lookup, conn))
+ })
+ }
+
+ t.Run("no credential or no group skips the lookup", func(t *testing.T) {
+ called := false
+ lookup := wsTurnAPIKeyLookupFunc(func(ctx context.Context, key string) (*service.APIKey, error) {
+ called = true
+ return latestWith(nil), nil
+ })
+ noKey := *conn
+ noKey.Key = ""
+ require.Same(t, &noKey, refreshOpenAIWSTurnBillingAPIKey(context.Background(), lookup, &noKey))
+ noGroup := *conn
+ noGroup.Group = nil
+ require.Same(t, &noGroup, refreshOpenAIWSTurnBillingAPIKey(context.Background(), lookup, &noGroup))
+ require.Nil(t, refreshOpenAIWSTurnBillingAPIKey(context.Background(), lookup, nil))
+ require.Same(t, conn, refreshOpenAIWSTurnBillingAPIKey(context.Background(), nil, conn))
+ require.False(t, called)
+ })
+}
+
+func TestOpenAIWSTurnBillingAPIKeysKeepPreviousTurnUntilItIsRecorded(t *testing.T) {
+ conn := &service.APIKey{ID: 1}
+ turn2 := &service.APIKey{ID: 2}
+ turn3 := &service.APIKey{ID: 3}
+ var keys openAIWSTurnBillingAPIKeys
+ require.Same(t, conn, keys.forTurn(1, conn), "a turn without BeforeTurn bills with the connection snapshot")
+ keys.set(2, turn2)
+ keys.set(3, turn3) // turn 3 starts before turn 2's usage is submitted
+ require.Same(t, turn2, keys.forTurn(2, conn))
+ require.Same(t, turn3, keys.forTurn(3, conn))
+ keys.set(4, conn)
+ require.Same(t, conn, keys.forTurn(2, conn), "only the current and previous turn are kept")
+ require.Len(t, keys.keys, 2)
+}
diff --git a/backend/internal/handler/payment_handler.go b/backend/internal/handler/payment_handler.go
index d791c700b..9c361f4f8 100644
--- a/backend/internal/handler/payment_handler.go
+++ b/backend/internal/handler/payment_handler.go
@@ -149,6 +149,9 @@ func (h *PaymentHandler) GetCheckoutInfo(c *gin.Context) {
BalanceRechargeMultiplier: cfg.BalanceRechargeMultiplier,
SubscriptionUSDToCNYRate: cfg.SubscriptionUSDToCNYRate,
RechargeFeeRate: cfg.RechargeFeeRate,
+ RechargeBonusTiers: cfg.RechargeBonusTiers,
+ RechargeBonusMode: cfg.RechargeBonusMode,
+ RechargeBonusNotice: cfg.RechargeBonusNotice,
HelpText: cfg.HelpText,
HelpImageURL: cfg.HelpImageURL,
StripePublishableKey: cfg.StripePublishableKey,
@@ -166,6 +169,9 @@ type checkoutInfoResponse struct {
BalanceRechargeMultiplier float64 `json:"balance_recharge_multiplier"`
SubscriptionUSDToCNYRate float64 `json:"subscription_usd_to_cny_rate"`
RechargeFeeRate float64 `json:"recharge_fee_rate"`
+ RechargeBonusTiers []service.RechargeBonusTier `json:"recharge_bonus_tiers"`
+ RechargeBonusMode string `json:"recharge_bonus_mode"`
+ RechargeBonusNotice string `json:"recharge_bonus_notice"`
HelpText string `json:"help_text"`
HelpImageURL string `json:"help_image_url"`
StripePublishableKey string `json:"stripe_publishable_key"`
@@ -482,6 +488,7 @@ type PublicOrderResult struct {
Amount float64 `json:"amount"`
PayAmount float64 `json:"pay_amount"`
FeeRate float64 `json:"fee_rate"`
+ BonusAmount float64 `json:"bonus_amount"`
Currency string `json:"currency"`
PaymentType string `json:"payment_type"`
OrderType string `json:"order_type"`
@@ -517,6 +524,7 @@ func buildPublicOrderResult(order *dbent.PaymentOrder) PublicOrderResult {
Amount: order.Amount,
PayAmount: order.PayAmount,
FeeRate: order.FeeRate,
+ BonusAmount: order.BonusAmount,
Currency: service.PaymentOrderCurrency(order),
PaymentType: order.PaymentType,
OrderType: order.OrderType,
@@ -625,6 +633,7 @@ type PaymentOrderResult struct {
Amount float64 `json:"amount"`
PayAmount float64 `json:"pay_amount"`
FeeRate float64 `json:"fee_rate"`
+ BonusAmount float64 `json:"bonus_amount"`
Currency string `json:"currency"`
PaymentType string `json:"payment_type"`
OutTradeNo string `json:"out_trade_no"`
@@ -663,6 +672,7 @@ func sanitizePaymentOrderForResponse(order *dbent.PaymentOrder) *PaymentOrderRes
Amount: order.Amount,
PayAmount: order.PayAmount,
FeeRate: order.FeeRate,
+ BonusAmount: order.BonusAmount,
Currency: service.PaymentOrderCurrency(order),
PaymentType: order.PaymentType,
OutTradeNo: order.OutTradeNo,
diff --git a/backend/internal/handler/user_handler_test.go b/backend/internal/handler/user_handler_test.go
index 64b93cbbe..93b36efe0 100644
--- a/backend/internal/handler/user_handler_test.go
+++ b/backend/internal/handler/user_handler_test.go
@@ -6,6 +6,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
"testing"
@@ -811,3 +812,19 @@ func TestUserHandlerStartIdentityBindingReturnsAuthorizeURL(t *testing.T) {
require.Contains(t, resp.Data.AuthorizeURL, "intent=bind_current_user")
require.Contains(t, resp.Data.AuthorizeURL, "redirect=%2Fsettings%2Fprofile")
}
+
+func (s *userHandlerEmailCacheStub) IncrVerificationCodeAttempts(context.Context, string) (int, error) {
+ if s.data == nil {
+ return 0, errors.New("verification code not found")
+ }
+ s.data.Attempts++
+ return s.data.Attempts, nil
+}
+
+func (s *userHandlerEmailCacheStub) IncrNotifyVerifyCodeAttempts(context.Context, string) (int, error) {
+ return 0, errors.New("notify verification code not found")
+}
+
+func (s *userHandlerEmailCacheStub) ConsumePasswordResetToken(context.Context, string, string) (bool, error) {
+ return false, nil
+}
diff --git a/backend/internal/integration/e2e_user_flow_test.go b/backend/internal/integration/e2e_user_flow_test.go
index 5489d0a32..9a28c6623 100644
--- a/backend/internal/integration/e2e_user_flow_test.go
+++ b/backend/internal/integration/e2e_user_flow_test.go
@@ -264,10 +264,11 @@ func loginTestUser(t *testing.T) string {
t.Helper()
// 先尝试用管理员账户登录
- adminEmail := getEnv("ADMIN_EMAIL", "admin@sub2api.local")
+ // 管理员邮箱不再有固定默认值(未设置时安装阶段随机生成),需同时提供邮箱与密码。
+ adminEmail := getEnv("ADMIN_EMAIL", "")
adminPassword := getEnv("ADMIN_PASSWORD", "")
- if adminPassword == "" {
+ if adminEmail == "" || adminPassword == "" {
// 尝试用测试用户
adminEmail = testUserEmail
adminPassword = testUserPassword
diff --git a/backend/internal/model/error_passthrough_rule.go b/backend/internal/model/error_passthrough_rule.go
index a6df079ee..cf8483471 100644
--- a/backend/internal/model/error_passthrough_rule.go
+++ b/backend/internal/model/error_passthrough_rule.go
@@ -46,22 +46,12 @@ const (
PlatformDeepseek = domain.PlatformDeepseek
PlatformMiniMax = domain.PlatformMiniMax
PlatformOpenCodeGo = domain.PlatformOpenCodeGo
+ PlatformTypeSafe = domain.PlatformTypeSafe
)
-// AllPlatforms 返回所有支持的平台列表
+// AllPlatforms 返回所有支持的平台列表(平台清单,按展示顺序)。
func AllPlatforms() []string {
- return []string{
- PlatformAnthropic,
- PlatformOpenAI,
- PlatformGemini,
- PlatformAntigravity,
- PlatformGrok,
- PlatformKimi,
- PlatformZhipu,
- PlatformDeepseek,
- PlatformMiniMax,
- PlatformOpenCodeGo,
- }
+ return domain.ConcretePlatformIDs()
}
// Validate 验证规则配置的有效性
diff --git a/backend/internal/model/error_passthrough_rule_test.go b/backend/internal/model/error_passthrough_rule_test.go
index 34ceb414e..0d5c43cdd 100644
--- a/backend/internal/model/error_passthrough_rule_test.go
+++ b/backend/internal/model/error_passthrough_rule_test.go
@@ -10,6 +10,7 @@ func TestAllPlatformsIncludesEveryConcretePlatform(t *testing.T) {
require.ElementsMatch(t, []string{
"anthropic",
"openai",
+ "openai_bps",
"gemini",
"antigravity",
"grok",
@@ -18,5 +19,8 @@ func TestAllPlatformsIncludesEveryConcretePlatform(t *testing.T) {
"deepseek",
"minimax",
"opencode_go",
+ "typesafe",
+ "command_code",
+ "cline",
}, AllPlatforms())
}
diff --git a/backend/internal/payment/provider/easypay.go b/backend/internal/payment/provider/easypay.go
index 87ab38ca7..f58ac0c1b 100644
--- a/backend/internal/payment/provider/easypay.go
+++ b/backend/internal/payment/provider/easypay.go
@@ -376,6 +376,9 @@ func (e *EasyPay) VerifyNotification(_ context.Context, rawBody string, _ map[st
// url.ParseQuery already decodes values — no additional decode needed.
params := make(map[string]string)
for k := range values {
+ if !easyPayNotifyAllowedParams[k] {
+ return nil, fmt.Errorf("unexpected notify param: %s", k)
+ }
params[k] = values.Get(k)
}
sign := params["sign"]
@@ -601,3 +604,26 @@ func easyPaySign(params map[string]string, pkey string) string {
func easyPayVerifySign(params map[string]string, pkey string, sign string) bool {
return hmac.Equal([]byte(easyPaySign(params, pkey)), []byte(sign))
}
+
+// easyPayNotifyAllowedParams is the exact parameter set a genuine EasyPay
+// (彩虹易支付-compatible) async notification carries. Order-creation-only
+// fields (notify_url, return_url, cid, device, clientip, ...) must never
+// appear in a callback: because the sign base string concatenates values
+// unescaped, a signed order URL whose return_url embeds e.g.
+// "trade_status=TRADE_SUCCESS" could otherwise be replayed as a forged
+// payment-success notification (issue #7881). Rejecting unknown keys closes
+// the whole smuggling class; genuinely paid orders rejected by an exotic
+// upstream variant are still recovered by the upstream QueryOrder reconcile
+// path.
+var easyPayNotifyAllowedParams = map[string]bool{
+ "pid": true,
+ "trade_no": true,
+ "out_trade_no": true,
+ "type": true,
+ "name": true,
+ "money": true,
+ "trade_status": true,
+ "param": true,
+ "sign": true,
+ "sign_type": true,
+}
diff --git a/backend/internal/payment/provider/easypay_notify_security_test.go b/backend/internal/payment/provider/easypay_notify_security_test.go
new file mode 100644
index 000000000..2757b757f
--- /dev/null
+++ b/backend/internal/payment/provider/easypay_notify_security_test.go
@@ -0,0 +1,172 @@
+package provider
+
+// Regression tests for the EasyPay forged-callback vulnerability
+// (Wei-Shaw/sub2api issue #7875).
+//
+// Attack recap: the order-creation signature (visible to the payer in the
+// submit.php popup URL) signs return_url among other fields, and the sign
+// base string concatenates values unescaped. A client-supplied return_url
+// ending in "&trade_status=TRADE_SUCCESS" therefore produced a signature
+// that was byte-identical to a payment-success notification's signature
+// once the callback decoded return_url partially and promoted the smuggled
+// pair to a top-level parameter. Merchant-key rotation could not help
+// because the attacker never needed the key.
+//
+// Fixes covered here:
+// 1. service.CanonicalizeReturnURL drops client-supplied query parameters
+// (see payment_resume_service_test.go).
+// 2. VerifyNotification rejects any parameter outside the genuine async
+// notify set, so smuggled order-creation fields (return_url et al.)
+// fail closed even if a signed value smuggles a fake pair.
+
+import (
+ "context"
+ "net/url"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/payment"
+)
+
+// easyPayPoCProvider returns a provider with a fixed test credential set.
+func easyPayPoCProvider() *EasyPay {
+ return &EasyPay{config: map[string]string{
+ "pid": "1000",
+ "pkey": "MERCHANT_SECRET_KEY",
+ "apiBase": "https://pay.example.com",
+ "notifyUrl": "https://site.example.com/api/v1/payment/webhook/easypay",
+ "returnUrl": "https://site.example.com/payment/result",
+ }}
+}
+
+// TestEasyPayNotifyRejectsForgedSignReuseCallback is the exact PoC payload
+// that was accepted before the fix: the order's own submit.php signature
+// replayed with trade_status smuggled out of the return_url value.
+func TestEasyPayNotifyRejectsForgedSignReuseCallback(t *testing.T) {
+ t.Parallel()
+ e := easyPayPoCProvider()
+
+ // Order creation (popup mode): return_url carries the smuggled pair as
+ // its last sorted inner query key, exactly as buildPaymentReturnURL
+ // would have produced before CanonicalizeReturnURL stripped user query.
+ returnURL := "https://site.example.com/payment/result?order_id=99&out_trade_no=ORDER123&status=success&trade_status=TRADE_SUCCESS"
+ createParams := map[string]string{
+ "pid": "1000",
+ "type": "alipay",
+ "out_trade_no": "ORDER123",
+ "notify_url": e.config["notifyUrl"],
+ "return_url": returnURL,
+ "name": "balance recharge",
+ "money": "650.00",
+ }
+ sign := easyPaySign(createParams, e.config["pkey"])
+
+ // Forged callback: return_url encoded only up to status=success, then a
+ // raw &trade_status=TRADE_SUCCESS promotes it to a top-level parameter.
+ prefix := "https://site.example.com/payment/result?order_id=99&out_trade_no=ORDER123&status=success"
+ cb := url.Values{}
+ cb.Set("pid", "1000")
+ cb.Set("type", "alipay")
+ cb.Set("out_trade_no", "ORDER123")
+ cb.Set("notify_url", e.config["notifyUrl"])
+ cb.Set("name", "balance recharge")
+ cb.Set("money", "650.00")
+ cb.Set("return_url", prefix)
+ rawCallback := cb.Encode() + "&trade_status=TRADE_SUCCESS" + "&sign=" + sign + "&sign_type=MD5"
+
+ if _, err := e.VerifyNotification(context.Background(), rawCallback, nil); err == nil {
+ t.Fatal("forged sign-reuse callback must be rejected")
+ }
+}
+
+// TestEasyPayNotifyRejectsOrderURLReplay covers the milder variant where the
+// attacker replays the complete signed pay URL unchanged: return_url itself
+// is not a legitimate notify parameter and must also be rejected.
+func TestEasyPayNotifyRejectsOrderURLReplay(t *testing.T) {
+ t.Parallel()
+ e := easyPayPoCProvider()
+
+ createParams := map[string]string{
+ "pid": "1000",
+ "type": "alipay",
+ "out_trade_no": "ORDER123",
+ "notify_url": e.config["notifyUrl"],
+ "return_url": "https://site.example.com/payment/result",
+ "name": "balance recharge",
+ "money": "650.00",
+ }
+ createParams["sign"] = easyPaySign(createParams, e.config["pkey"])
+ createParams["sign_type"] = signTypeMD5
+ q := url.Values{}
+ for k, v := range createParams {
+ q.Set(k, v)
+ }
+
+ if _, err := e.VerifyNotification(context.Background(), q.Encode(), nil); err == nil {
+ t.Fatal("replayed order URL must be rejected")
+ }
+}
+
+// TestEasyPayNotifyAcceptsGenuineCallback locks in the legitimate notify
+// contract: the canonical parameter set with a valid signature succeeds.
+func TestEasyPayNotifyAcceptsGenuineCallback(t *testing.T) {
+ t.Parallel()
+ e := easyPayPoCProvider()
+
+ params := map[string]string{
+ "pid": "1000",
+ "trade_no": "2026100622001400000001",
+ "out_trade_no": "ORDER123",
+ "type": "alipay",
+ "name": "balance recharge",
+ "money": "650.00",
+ "trade_status": tradeStatusSuccess,
+ }
+ sign := easyPaySign(params, e.config["pkey"])
+ params["sign"] = sign
+ params["sign_type"] = signTypeMD5
+ q := url.Values{}
+ for k, v := range params {
+ q.Set(k, v)
+ }
+
+ n, err := e.VerifyNotification(context.Background(), q.Encode(), nil)
+ if err != nil {
+ t.Fatalf("genuine callback rejected: %v", err)
+ }
+ if n.Status != payment.ProviderStatusSuccess {
+ t.Fatalf("status = %v, want success", n.Status)
+ }
+ if n.OrderID != "ORDER123" || n.TradeNo != "2026100622001400000001" || n.Amount != 650.00 {
+ t.Fatalf("unexpected notification: %+v", n)
+ }
+}
+
+// TestEasyPayNotifyRejectsUnknownParam ensures any parameter outside the
+// canonical notify set fails closed, including empty-valued ones that the
+// signer itself would skip.
+func TestEasyPayNotifyRejectsUnknownParam(t *testing.T) {
+ t.Parallel()
+ e := easyPayPoCProvider()
+
+ params := map[string]string{
+ "pid": "1000",
+ "trade_no": "T1",
+ "out_trade_no": "ORDER123",
+ "type": "alipay",
+ "name": "balance recharge",
+ "money": "650.00",
+ "trade_status": tradeStatusSuccess,
+ }
+ sign := easyPaySign(params, e.config["pkey"])
+ q := url.Values{}
+ for k, v := range params {
+ q.Set(k, v)
+ }
+ q.Set("sign", sign)
+ q.Set("sign_type", signTypeMD5)
+ q.Set("device", "") // empty value: invisible to the signer, still rejected
+
+ if _, err := e.VerifyNotification(context.Background(), q.Encode(), nil); err == nil {
+ t.Fatal("callback with unknown param must be rejected")
+ }
+}
diff --git a/backend/internal/pkg/antigravity/claude_types.go b/backend/internal/pkg/antigravity/claude_types.go
index 23601c045..61e32b615 100644
--- a/backend/internal/pkg/antigravity/claude_types.go
+++ b/backend/internal/pkg/antigravity/claude_types.go
@@ -122,6 +122,20 @@ type ClaudeContentItem struct {
Input any `json:"input,omitempty"`
}
+// MarshalJSON 保证 thinking 块始终带 thinking/signature 字段(即使为空),
+// 与 Anthropic 官方一致;Grok Build 等严格客户端缺少 signature 会解析失败。
+func (c ClaudeContentItem) MarshalJSON() ([]byte, error) {
+ type claudeContentItem ClaudeContentItem
+ if c.Type != "thinking" {
+ return json.Marshal(claudeContentItem(c))
+ }
+ return json.Marshal(struct {
+ Thinking string `json:"thinking"`
+ Signature string `json:"signature"`
+ claudeContentItem
+ }{Thinking: c.Thinking, Signature: c.Signature, claudeContentItem: claudeContentItem(c)})
+}
+
// ClaudeUsage Claude 用量统计
type ClaudeUsage struct {
InputTokens int `json:"input_tokens"`
diff --git a/backend/internal/pkg/antigravity/claude_types_test.go b/backend/internal/pkg/antigravity/claude_types_test.go
index 4b49fdb9b..1aa5bca31 100644
--- a/backend/internal/pkg/antigravity/claude_types_test.go
+++ b/backend/internal/pkg/antigravity/claude_types_test.go
@@ -1,6 +1,9 @@
package antigravity
-import "testing"
+import (
+ "encoding/json"
+ "testing"
+)
func TestDefaultModels_ContainsNewAndLegacyImageModels(t *testing.T) {
t.Parallel()
@@ -44,3 +47,23 @@ func TestDefaultModels_ContainsNewAndLegacyImageModels(t *testing.T) {
}
}
}
+
+func TestClaudeContentItem_ThinkingAlwaysHasSignature(t *testing.T) {
+ t.Parallel()
+
+ data, err := json.Marshal(ClaudeContentItem{Type: "thinking", Thinking: "plan"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := string(data), `{"thinking":"plan","signature":"","type":"thinking"}`; got != want {
+ t.Fatalf("thinking block = %s, want %s", got, want)
+ }
+
+ data, err = json.Marshal(ClaudeContentItem{Type: "text", Text: "hi"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, want := string(data), `{"type":"text","text":"hi"}`; got != want {
+ t.Fatalf("text block = %s, want %s", got, want)
+ }
+}
diff --git a/backend/internal/pkg/antigravity/stream_transformer.go b/backend/internal/pkg/antigravity/stream_transformer.go
index 13471dddd..faecf233e 100644
--- a/backend/internal/pkg/antigravity/stream_transformer.go
+++ b/backend/internal/pkg/antigravity/stream_transformer.go
@@ -296,8 +296,9 @@ func (p *StreamingProcessor) processThinking(text, signature string) []byte {
// 开始或继续 thinking 块
if p.blockType != BlockTypeThinking {
_, _ = result.Write(p.startBlock(BlockTypeThinking, map[string]any{
- "type": "thinking",
- "thinking": "",
+ "type": "thinking",
+ "thinking": "",
+ "signature": "",
}))
}
@@ -475,8 +476,9 @@ func (p *StreamingProcessor) emitEmptyThinkingWithSignature(signature string) []
var result bytes.Buffer
_, _ = result.Write(p.startBlock(BlockTypeThinking, map[string]any{
- "type": "thinking",
- "thinking": "",
+ "type": "thinking",
+ "thinking": "",
+ "signature": "",
}))
_, _ = result.Write(p.emitDelta("thinking_delta", map[string]any{
"thinking": "",
diff --git a/backend/internal/pkg/apicompat/anthropic_responses_test.go b/backend/internal/pkg/apicompat/anthropic_responses_test.go
index 63d355eb7..5902128b9 100644
--- a/backend/internal/pkg/apicompat/anthropic_responses_test.go
+++ b/backend/internal/pkg/apicompat/anthropic_responses_test.go
@@ -844,7 +844,7 @@ func TestStreamingReasoning(t *testing.T) {
sse, err := ResponsesAnthropicEventToSSE(events[0])
require.NoError(t, err)
- assert.Contains(t, sse, `"content_block":{"thinking":"","type":"thinking"}`)
+ assert.Contains(t, sse, `"content_block":{"thinking":"","signature":"","type":"thinking"}`)
// reasoning text delta
events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
diff --git a/backend/internal/pkg/apicompat/chatcompletions_to_responses.go b/backend/internal/pkg/apicompat/chatcompletions_to_responses.go
index c2140c3d0..e7c447d0f 100644
--- a/backend/internal/pkg/apicompat/chatcompletions_to_responses.go
+++ b/backend/internal/pkg/apicompat/chatcompletions_to_responses.go
@@ -88,10 +88,11 @@ func ChatCompletionsToResponses(req *ChatCompletionsRequest) (*ResponsesRequest,
out.Tools = convertChatToolsToResponses(req.Tools, req.Functions)
}
- // tool_choice: already compatible format — pass through directly.
+ // tool_choice: strings and Responses-shaped objects pass through; a named
+ // Chat choice nests the name under "function" and must be flattened.
// Legacy function_call needs mapping.
if len(req.ToolChoice) > 0 {
- out.ToolChoice = req.ToolChoice
+ out.ToolChoice = convertChatToolChoiceToResponses(req.ToolChoice)
} else if len(req.FunctionCall) > 0 {
tc, err := convertChatFunctionCallToToolChoice(req.FunctionCall)
if err != nil {
@@ -107,7 +108,18 @@ func ChatCompletionsToResponses(req *ChatCompletionsRequest) (*ResponsesRequest,
// array into a Responses API input items array.
func convertChatMessagesToResponsesInput(msgs []ChatMessage) ([]ResponsesInputItem, error) {
var out []ResponsesInputItem
+ legacyIDs := legacyFunctionCallIDs{msgs: msgs}
for _, m := range msgs {
+ switch {
+ case m.Role == "assistant" && m.FunctionCall != nil && len(m.ToolCalls) == 0:
+ m.ToolCalls = []ChatToolCall{{
+ ID: legacyIDs.assign(m.FunctionCall.Name),
+ Type: "function",
+ Function: *m.FunctionCall,
+ }}
+ case m.Role == "function" && m.ToolCallID == "":
+ m.ToolCallID = legacyIDs.claim(m.Name)
+ }
items, err := chatMessageToResponsesItems(m)
if err != nil {
return nil, err
@@ -117,11 +129,63 @@ func convertChatMessagesToResponsesInput(msgs []ChatMessage) ([]ResponsesInputIt
return out, nil
}
+// legacyFunctionCallIDs pairs legacy function calls with their results. Legacy
+// function calling carries no call IDs: the assistant turn has function_call
+// and the role=function result refers to it only by name, while the Responses
+// API pairs function_call and function_call_output by call_id. IDs follow
+// message order, so a replayed history converts to the same input, and skip
+// IDs already used by tool_calls in the same conversation.
+type legacyFunctionCallIDs struct {
+ msgs []ChatMessage
+ used map[string]bool
+ next int
+ pending map[string][]string
+}
+
+// assign returns a new call ID for a legacy function call and queues it for
+// the next result with the same function name.
+func (ids *legacyFunctionCallIDs) assign(name string) string {
+ if ids.used == nil {
+ ids.used = make(map[string]bool)
+ ids.pending = make(map[string][]string)
+ for _, m := range ids.msgs {
+ for _, tc := range m.ToolCalls {
+ ids.used[tc.ID] = true
+ }
+ if m.ToolCallID != "" {
+ ids.used[m.ToolCallID] = true
+ }
+ }
+ }
+ var id string
+ for {
+ ids.next++
+ id = fmt.Sprintf("call_legacy_%d", ids.next)
+ if !ids.used[id] {
+ break
+ }
+ }
+ ids.used[id] = true
+ ids.pending[name] = append(ids.pending[name], id)
+ return id
+}
+
+// claim returns the oldest unanswered call ID for name, or "" when no legacy
+// call with that name precedes the result.
+func (ids *legacyFunctionCallIDs) claim(name string) string {
+ queue := ids.pending[name]
+ if len(queue) == 0 {
+ return ""
+ }
+ ids.pending[name] = queue[1:]
+ return queue[0]
+}
+
// chatMessageToResponsesItems converts a single ChatMessage into one or more
// ResponsesInputItem values.
func chatMessageToResponsesItems(m ChatMessage) ([]ResponsesInputItem, error) {
switch m.Role {
- case "system":
+ case "system", "developer":
return chatSystemToResponses(m)
case "user":
return chatUserToResponses(m)
@@ -136,7 +200,9 @@ func chatMessageToResponsesItems(m ChatMessage) ([]ResponsesInputItem, error) {
}
}
-// chatSystemToResponses converts a system message.
+// chatSystemToResponses converts a system or developer message, keeping its
+// role: the Responses API accepts both, and developer must not be demoted to
+// a user turn.
func chatSystemToResponses(m ChatMessage) ([]ResponsesInputItem, error) {
parsed, err := parseChatMessageContent(m.Content)
if err != nil {
@@ -146,7 +212,7 @@ func chatSystemToResponses(m ChatMessage) ([]ResponsesInputItem, error) {
if err != nil {
return nil, err
}
- return []ResponsesInputItem{{Type: "message", Role: "system", Content: content}}, nil
+ return []ResponsesInputItem{{Type: "message", Role: m.Role, Content: content}}, nil
}
// chatUserToResponses converts a user message, handling both plain strings and
@@ -303,8 +369,9 @@ func chatToolToResponses(m ChatMessage) ([]ResponsesInputItem, error) {
}
// chatFunctionToResponses converts a legacy function result message
-// (role=function) into a function_call_output item. The Name field is used as
-// call_id since legacy function calls do not carry a separate call_id.
+// (role=function) into a function_call_output item. ToolCallID holds the ID
+// assigned to the matching legacy call (see legacyFunctionCallIDs); without a
+// matching call the Name field is used as call_id.
func chatFunctionToResponses(m ChatMessage) ([]ResponsesInputItem, error) {
output, err := parseChatContent(m.Content)
if err != nil {
@@ -313,9 +380,13 @@ func chatFunctionToResponses(m ChatMessage) ([]ResponsesInputItem, error) {
if output == "" {
output = "(empty)"
}
+ callID := m.ToolCallID
+ if callID == "" {
+ callID = m.Name
+ }
return []ResponsesInputItem{{
Type: "function_call_output",
- CallID: m.Name,
+ CallID: callID,
Output: output,
}}, nil
}
@@ -490,6 +561,34 @@ func defaultStrictFalse(src *bool) *bool {
return src
}
+// convertChatToolChoiceToResponses maps a Chat Completions tool_choice to the
+// Responses API shape.
+//
+// {"type":"function","function":{"name":"X"}} → {"type":"function","name":"X"}
+//
+// Strings ("auto", "none", "required") and objects that already use the
+// Responses shape are returned unchanged.
+func convertChatToolChoiceToResponses(raw json.RawMessage) json.RawMessage {
+ var choice struct {
+ Type string `json:"type"`
+ Function *struct {
+ Name string `json:"name"`
+ } `json:"function"`
+ }
+ if err := json.Unmarshal(raw, &choice); err != nil || choice.Type != "function" || choice.Function == nil {
+ return raw
+ }
+ name := strings.TrimSpace(choice.Function.Name)
+ if name == "" {
+ return raw
+ }
+ flat, err := json.Marshal(map[string]string{"type": "function", "name": name})
+ if err != nil {
+ return raw
+ }
+ return flat
+}
+
// convertChatFunctionCallToToolChoice maps the legacy function_call field to a
// Responses API tool_choice value.
//
diff --git a/backend/internal/pkg/apicompat/chatcompletions_to_responses_developer_role_test.go b/backend/internal/pkg/apicompat/chatcompletions_to_responses_developer_role_test.go
new file mode 100644
index 000000000..d6fbcad6c
--- /dev/null
+++ b/backend/internal/pkg/apicompat/chatcompletions_to_responses_developer_role_test.go
@@ -0,0 +1,43 @@
+package apicompat
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// The Responses API accepts role "developer" in input messages. Converting it
+// to "user" silently demotes the caller's instructions to user turns.
+func TestChatCompletionsToResponses_DeveloperRolePreserved(t *testing.T) {
+ tests := []struct {
+ name string
+ content string
+ wantContent string
+ }{
+ {name: "string content", content: `"Answer in French."`, wantContent: `"Answer in French."`},
+ {name: "text parts", content: `[{"type":"text","text":"Answer in French."}]`, wantContent: `[{"type":"input_text","text":"Answer in French."}]`},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req := &ChatCompletionsRequest{
+ Model: "gpt-4o",
+ Messages: []ChatMessage{
+ {Role: "developer", Content: json.RawMessage(tt.content)},
+ {Role: "user", Content: json.RawMessage(`"Hello"`)},
+ },
+ }
+
+ resp, err := ChatCompletionsToResponses(req)
+ require.NoError(t, err)
+
+ var items []ResponsesInputItem
+ require.NoError(t, json.Unmarshal(resp.Input, &items))
+ require.Len(t, items, 2)
+ require.Equal(t, "message", items[0].Type)
+ require.Equal(t, "developer", items[0].Role)
+ require.JSONEq(t, tt.wantContent, string(items[0].Content))
+ require.Equal(t, "user", items[1].Role)
+ })
+ }
+}
diff --git a/backend/internal/pkg/apicompat/chatcompletions_to_responses_legacy_function_call_test.go b/backend/internal/pkg/apicompat/chatcompletions_to_responses_legacy_function_call_test.go
new file mode 100644
index 000000000..1c971fd08
--- /dev/null
+++ b/backend/internal/pkg/apicompat/chatcompletions_to_responses_legacy_function_call_test.go
@@ -0,0 +1,87 @@
+package apicompat
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func convertLegacyFunctionHistory(t *testing.T, msgs []ChatMessage) []ResponsesInputItem {
+ t.Helper()
+ resp, err := ChatCompletionsToResponses(&ChatCompletionsRequest{Model: "gpt-4o", Messages: msgs})
+ require.NoError(t, err)
+ var items []ResponsesInputItem
+ require.NoError(t, json.Unmarshal(resp.Input, &items))
+ return items
+}
+
+// Legacy function calling has no call IDs: the assistant turn carries
+// function_call and the result is a role=function message keyed by name. The
+// Responses API needs a function_call item and a function_call_output with the
+// same call_id, otherwise the output is rejected as having no matching call.
+func TestChatCompletionsToResponses_LegacyFunctionCallHistoryPaired(t *testing.T) {
+ msgs := []ChatMessage{
+ {Role: "user", Content: json.RawMessage(`"Weather in Paris and Rome?"`)},
+ {Role: "assistant", Content: json.RawMessage(`"Checking Paris."`), FunctionCall: &ChatFunctionCall{Name: "get_weather", Arguments: `{"city":"Paris"}`}},
+ {Role: "function", Name: "get_weather", Content: json.RawMessage(`"sunny"`)},
+ {Role: "assistant", FunctionCall: &ChatFunctionCall{Name: "get_weather", Arguments: `{"city":"Rome"}`}},
+ {Role: "function", Name: "get_weather", Content: json.RawMessage(`"rainy"`)},
+ }
+
+ items := convertLegacyFunctionHistory(t, msgs)
+ require.Len(t, items, 6)
+
+ require.Equal(t, "user", items[0].Role)
+ require.Equal(t, "assistant", items[1].Role)
+
+ firstCall, firstOutput := items[2], items[3]
+ require.Equal(t, "function_call", firstCall.Type)
+ require.Equal(t, "get_weather", firstCall.Name)
+ require.Equal(t, `{"city":"Paris"}`, firstCall.Arguments)
+ require.Equal(t, "function_call_output", firstOutput.Type)
+ require.Equal(t, "sunny", firstOutput.Output)
+ require.NotEmpty(t, firstCall.CallID)
+ require.Equal(t, firstCall.CallID, firstOutput.CallID)
+
+ secondCall, secondOutput := items[4], items[5]
+ require.Equal(t, "function_call", secondCall.Type)
+ require.Equal(t, `{"city":"Rome"}`, secondCall.Arguments)
+ require.Equal(t, "function_call_output", secondOutput.Type)
+ require.Equal(t, "rainy", secondOutput.Output)
+ require.Equal(t, secondCall.CallID, secondOutput.CallID)
+ require.NotEqual(t, firstCall.CallID, secondCall.CallID)
+
+ // Synthesized IDs must be stable across turns so the replayed history keeps
+ // the same prompt prefix.
+ require.Equal(t, items, convertLegacyFunctionHistory(t, msgs))
+}
+
+func TestChatCompletionsToResponses_LegacyFunctionCallIDAvoidsToolCallIDs(t *testing.T) {
+ items := convertLegacyFunctionHistory(t, []ChatMessage{
+ {Role: "user", Content: json.RawMessage(`"hi"`)},
+ {Role: "assistant", FunctionCall: &ChatFunctionCall{Name: "lookup", Arguments: `{}`}},
+ {Role: "function", Name: "lookup", Content: json.RawMessage(`"legacy result"`)},
+ {Role: "assistant", ToolCalls: []ChatToolCall{{ID: "call_legacy_1", Type: "function", Function: ChatFunctionCall{Name: "lookup", Arguments: `{}`}}}},
+ {Role: "tool", ToolCallID: "call_legacy_1", Content: json.RawMessage(`"tool result"`)},
+ })
+ require.Len(t, items, 5)
+
+ legacyCall, legacyOutput := items[1], items[2]
+ require.Equal(t, "function_call", legacyCall.Type)
+ require.Equal(t, legacyCall.CallID, legacyOutput.CallID)
+ require.NotEqual(t, "call_legacy_1", legacyCall.CallID)
+
+ require.Equal(t, "call_legacy_1", items[3].CallID)
+ require.Equal(t, "call_legacy_1", items[4].CallID)
+}
+
+func TestChatCompletionsToResponses_LegacyFunctionResultWithoutCallKeepsName(t *testing.T) {
+ items := convertLegacyFunctionHistory(t, []ChatMessage{
+ {Role: "user", Content: json.RawMessage(`"hi"`)},
+ {Role: "function", Name: "lookup", Content: json.RawMessage(`"orphan"`)},
+ })
+ require.Len(t, items, 2)
+ require.Equal(t, "function_call_output", items[1].Type)
+ require.Equal(t, "lookup", items[1].CallID)
+}
diff --git a/backend/internal/pkg/apicompat/chatcompletions_to_responses_tool_choice_test.go b/backend/internal/pkg/apicompat/chatcompletions_to_responses_tool_choice_test.go
new file mode 100644
index 000000000..736a0b5ac
--- /dev/null
+++ b/backend/internal/pkg/apicompat/chatcompletions_to_responses_tool_choice_test.go
@@ -0,0 +1,43 @@
+package apicompat
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// Chat Completions nests a named choice under "function"; the Responses API
+// expects the name at the top level and rejects the nested shape.
+func TestChatCompletionsToResponses_ToolChoiceShape(t *testing.T) {
+ tests := []struct {
+ name string
+ choice string
+ want string
+ }{
+ {name: "named chat function is flattened", choice: `{"type":"function","function":{"name":"get_weather"}}`, want: `{"type":"function","name":"get_weather"}`},
+ {name: "flat responses function is kept", choice: `{"type":"function","name":"get_weather"}`, want: `{"type":"function","name":"get_weather"}`},
+ {name: "auto string is kept", choice: `"auto"`, want: `"auto"`},
+ {name: "required string is kept", choice: `"required"`, want: `"required"`},
+ {name: "none string is kept", choice: `"none"`, want: `"none"`},
+ {name: "allowed_tools policy is kept", choice: `{"type":"allowed_tools","mode":"auto","tools":[{"type":"function","name":"get_weather"}]}`, want: `{"type":"allowed_tools","mode":"auto","tools":[{"type":"function","name":"get_weather"}]}`},
+ {name: "function without name is kept", choice: `{"type":"function","function":{}}`, want: `{"type":"function","function":{}}`},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req := &ChatCompletionsRequest{
+ Model: "gpt-4o",
+ Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"weather?"`)}},
+ Tools: []ChatTool{{
+ Type: "function",
+ Function: &ChatFunction{Name: "get_weather", Parameters: json.RawMessage(`{"type":"object"}`)},
+ }},
+ ToolChoice: json.RawMessage(tt.choice),
+ }
+
+ resp, err := ChatCompletionsToResponses(req)
+ require.NoError(t, err)
+ require.JSONEq(t, tt.want, string(resp.ToolChoice))
+ })
+ }
+}
diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go
index f402184f2..2b8f2b811 100644
--- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go
+++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go
@@ -15,7 +15,8 @@ import (
// ResponsesToChatCompletions converts a Responses API response into a Chat
// Completions response. Text output items are concatenated into
-// choices[0].message.content; function_call items become tool_calls.
+// choices[0].message.content, refusal parts into choices[0].message.refusal;
+// function_call items become tool_calls.
func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatCompletionsResponse {
id := resp.ID
if id == "" {
@@ -31,6 +32,7 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp
}
var contentText string
+ var refusalText string
var reasoningText string
var toolCalls []ChatToolCall
@@ -38,8 +40,11 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp
switch item.Type {
case "message":
for _, part := range item.Content {
- if part.Type == "output_text" && part.Text != "" {
+ switch {
+ case part.Type == "output_text" && part.Text != "":
contentText += part.Text
+ case part.Type == "refusal" && part.Refusal != "":
+ refusalText += part.Refusal
}
}
case "function_call":
@@ -62,7 +67,7 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp
}
}
- msg := ChatMessage{Role: "assistant"}
+ msg := ChatMessage{Role: "assistant", Refusal: refusalText}
if len(toolCalls) > 0 {
msg.ToolCalls = toolCalls
}
@@ -149,6 +154,8 @@ func ResponsesEventToChatChunks(evt *ResponsesStreamEvent, state *ResponsesEvent
return resToChatHandleCreated(evt, state)
case "response.output_text.delta":
return resToChatHandleTextDelta(evt, state)
+ case "response.refusal.delta":
+ return resToChatHandleRefusalDelta(evt, state)
case "response.output_item.added":
return resToChatHandleOutputItemAdded(evt, state)
case "response.function_call_arguments.delta",
@@ -248,6 +255,14 @@ func resToChatHandleTextDelta(evt *ResponsesStreamEvent, state *ResponsesEventTo
return []ChatCompletionsChunk{makeChatDeltaChunk(state, ChatDelta{Content: &content})}
}
+func resToChatHandleRefusalDelta(evt *ResponsesStreamEvent, state *ResponsesEventToChatState) []ChatCompletionsChunk {
+ if evt.Delta == "" {
+ return nil
+ }
+ refusal := evt.Delta
+ return []ChatCompletionsChunk{makeChatDeltaChunk(state, ChatDelta{Refusal: &refusal})}
+}
+
func resToChatHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesEventToChatState) []ChatCompletionsChunk {
// function_call 与 custom_tool_call(custom/freeform 工具)均按工具调用注册,
// 以便后续 *_input.delta / *_arguments.delta 能映射到正确的工具索引。
@@ -496,6 +511,7 @@ type bufferedFuncCall struct {
// (response.completed / response.done) carries an empty output array.
type BufferedResponseAccumulator struct {
text strings.Builder
+ refusal strings.Builder
reasoning strings.Builder
funcCalls []bufferedFuncCall
outputIndexToFuncIdx map[int]int
@@ -517,6 +533,10 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent)
if event.Delta != "" {
_, _ = a.text.WriteString(event.Delta)
}
+ case "response.refusal.delta":
+ if event.Delta != "" {
+ _, _ = a.refusal.WriteString(event.Delta)
+ }
case "response.output_item.added":
if event.Item != nil && (event.Item.Type == "function_call" || event.Item.Type == "custom_tool_call") {
idx := len(a.funcCalls)
@@ -553,7 +573,7 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent)
// HasContent reports whether any content has been accumulated.
func (a *BufferedResponseAccumulator) HasContent() bool {
- return a.text.Len() > 0 || len(a.funcCalls) > 0 || a.reasoning.Len() > 0
+ return a.text.Len() > 0 || a.refusal.Len() > 0 || len(a.funcCalls) > 0 || a.reasoning.Len() > 0
}
// BuildOutput constructs a []ResponsesOutput from the accumulated delta
@@ -572,14 +592,18 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput {
})
}
- if a.text.Len() > 0 {
+ if a.text.Len() > 0 || a.refusal.Len() > 0 {
+ var content []ResponsesContentPart
+ if a.text.Len() > 0 {
+ content = append(content, ResponsesContentPart{Type: "output_text", Text: a.text.String()})
+ }
+ if a.refusal.Len() > 0 {
+ content = append(content, ResponsesContentPart{Type: "refusal", Refusal: a.refusal.String()})
+ }
out = append(out, ResponsesOutput{
- Type: "message",
- Role: "assistant",
- Content: []ResponsesContentPart{{
- Type: "output_text",
- Text: a.text.String(),
- }},
+ Type: "message",
+ Role: "assistant",
+ Content: content,
})
}
diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions_refusal_test.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions_refusal_test.go
new file mode 100644
index 000000000..cf8f0bfa4
--- /dev/null
+++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions_refusal_test.go
@@ -0,0 +1,114 @@
+package apicompat
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+const refusalText = "I can't help with that."
+
+func decodeResponsesEvent(t *testing.T, raw string) ResponsesStreamEvent {
+ t.Helper()
+ var evt ResponsesStreamEvent
+ require.NoError(t, json.Unmarshal([]byte(raw), &evt))
+ return evt
+}
+
+func chatMessageJSON(t *testing.T, resp *ChatCompletionsResponse) map[string]any {
+ t.Helper()
+ raw, err := json.Marshal(resp)
+ require.NoError(t, err)
+ var decoded struct {
+ Choices []struct {
+ Message map[string]any `json:"message"`
+ } `json:"choices"`
+ }
+ require.NoError(t, json.Unmarshal(raw, &decoded))
+ require.Len(t, decoded.Choices, 1)
+ return decoded.Choices[0].Message
+}
+
+// A refusal arrives as a "refusal" content part, not output_text. Dropping it
+// leaves the Chat client with an empty assistant message.
+func TestResponsesToChatCompletions_RefusalPreserved(t *testing.T) {
+ var resp ResponsesResponse
+ require.NoError(t, json.Unmarshal([]byte(`{
+ "id":"resp_refusal",
+ "status":"completed",
+ "output":[{"type":"message","role":"assistant","content":[{"type":"refusal","refusal":"`+refusalText+`"}]}]
+ }`), &resp))
+
+ chat := ResponsesToChatCompletions(&resp, "gpt-4o")
+
+ msg := chatMessageJSON(t, chat)
+ require.Equal(t, refusalText, msg["refusal"])
+ require.NotContains(t, msg, "content")
+ require.Equal(t, "stop", chat.Choices[0].FinishReason)
+}
+
+func TestResponsesEventToChatChunks_RefusalDelta(t *testing.T) {
+ state := NewResponsesEventToChatState()
+ events := []string{
+ `{"type":"response.created","response":{"id":"resp_refusal","model":"gpt-4o"}}`,
+ `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","role":"assistant"}}`,
+ `{"type":"response.refusal.delta","output_index":0,"content_index":0,"delta":"I can't "}`,
+ `{"type":"response.refusal.delta","output_index":0,"content_index":0,"delta":"help with that."}`,
+ `{"type":"response.refusal.done","output_index":0,"content_index":0,"refusal":"` + refusalText + `"}`,
+ `{"type":"response.completed","response":{"id":"resp_refusal","status":"completed"}}`,
+ }
+
+ var refusal strings.Builder
+ var finishReason string
+ for _, raw := range events {
+ evt := decodeResponsesEvent(t, raw)
+ for _, chunk := range ResponsesEventToChatChunks(&evt, state) {
+ encoded, err := json.Marshal(chunk)
+ require.NoError(t, err)
+ var decoded struct {
+ Choices []struct {
+ Delta struct {
+ Refusal *string `json:"refusal"`
+ } `json:"delta"`
+ FinishReason *string `json:"finish_reason"`
+ } `json:"choices"`
+ }
+ require.NoError(t, json.Unmarshal(encoded, &decoded))
+ for _, choice := range decoded.Choices {
+ if choice.Delta.Refusal != nil {
+ _, _ = refusal.WriteString(*choice.Delta.Refusal)
+ }
+ if choice.FinishReason != nil {
+ finishReason = *choice.FinishReason
+ }
+ }
+ }
+ }
+
+ require.Equal(t, refusalText, refusal.String())
+ require.Equal(t, "stop", finishReason)
+}
+
+// Non-streaming Chat requests are served from a forced upstream stream; when
+// the terminal event carries an empty output array the message is rebuilt from
+// the accumulated deltas, which must include refusal deltas.
+func TestBufferedResponseAccumulator_RefusalRebuiltFromDeltas(t *testing.T) {
+ acc := NewBufferedResponseAccumulator()
+ for _, raw := range []string{
+ `{"type":"response.output_item.added","output_index":0,"item":{"type":"message","role":"assistant"}}`,
+ `{"type":"response.refusal.delta","output_index":0,"content_index":0,"delta":"I can't "}`,
+ `{"type":"response.refusal.delta","output_index":0,"content_index":0,"delta":"help with that."}`,
+ } {
+ evt := decodeResponsesEvent(t, raw)
+ acc.ProcessEvent(&evt)
+ }
+ require.True(t, acc.HasContent())
+
+ final := &ResponsesResponse{ID: "resp_refusal", Status: "completed"}
+ acc.SupplementResponseOutput(final)
+ chat := ResponsesToChatCompletions(final, "gpt-4o")
+
+ require.Equal(t, refusalText, chatMessageJSON(t, chat)["refusal"])
+}
diff --git a/backend/internal/pkg/apicompat/thinking_signature_wire_test.go b/backend/internal/pkg/apicompat/thinking_signature_wire_test.go
new file mode 100644
index 000000000..33924fd49
--- /dev/null
+++ b/backend/internal/pkg/apicompat/thinking_signature_wire_test.go
@@ -0,0 +1,24 @@
+package apicompat
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// Thinking blocks must always carry the `signature` key (Anthropic wire shape);
+// strict clients such as Grok Build fail with "missing field `signature`".
+func TestAnthropicContentBlock_ThinkingAlwaysHasSignature(t *testing.T) {
+ data, err := json.Marshal(AnthropicContentBlock{Type: "thinking", Thinking: "plan"})
+ require.NoError(t, err)
+ require.JSONEq(t, `{"type":"thinking","thinking":"plan","signature":""}`, string(data))
+
+ data, err = json.Marshal(AnthropicContentBlock{Type: "thinking", Signature: "sig"})
+ require.NoError(t, err)
+ require.JSONEq(t, `{"type":"thinking","thinking":"","signature":"sig"}`, string(data))
+
+ data, err = json.Marshal(AnthropicContentBlock{Type: "text", Text: "hi"})
+ require.NoError(t, err)
+ require.JSONEq(t, `{"type":"text","text":"hi"}`, string(data))
+}
diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go
index 859cb1dcb..b5864f2f2 100644
--- a/backend/internal/pkg/apicompat/types.go
+++ b/backend/internal/pkg/apicompat/types.go
@@ -95,10 +95,14 @@ func (b AnthropicContentBlock) MarshalJSON() ([]byte, error) {
anthropicContentBlock
}{Text: b.Text, anthropicContentBlock: anthropicContentBlock(b)})
case "thinking":
+ // Anthropic always sends `signature` on thinking blocks (empty on
+ // content_block_start); strict clients such as Grok Build reject the
+ // block with "missing field `signature`" when the key is absent.
return json.Marshal(struct {
- Thinking string `json:"thinking"`
+ Thinking string `json:"thinking"`
+ Signature string `json:"signature"`
anthropicContentBlock
- }{Thinking: b.Thinking, anthropicContentBlock: anthropicContentBlock(b)})
+ }{Thinking: b.Thinking, Signature: b.Signature, anthropicContentBlock: anthropicContentBlock(b)})
default:
return json.Marshal(base)
}
@@ -312,8 +316,9 @@ func (i *ResponsesInputItem) UnmarshalJSON(data []byte) error {
// ResponsesContentPart is a typed content part in a Responses message.
type ResponsesContentPart struct {
PromptCacheBreakpoint json.RawMessage `json:"prompt_cache_breakpoint,omitempty"`
- Type string `json:"type"` // "input_text" | "output_text" | "input_image" | "input_file"
+ Type string `json:"type"` // "input_text" | "output_text" | "refusal" | "input_image" | "input_file"
Text string `json:"text,omitempty"`
+ Refusal string `json:"refusal,omitempty"` // type=refusal
ImageURL string `json:"image_url,omitempty"` // data URI for input_image
// input_file fields.
@@ -690,6 +695,7 @@ type ChatStreamOptions struct {
type ChatMessage struct {
Role string `json:"role"` // "system" | "user" | "assistant" | "tool" | "function"
Content json.RawMessage `json:"content,omitempty"`
+ Refusal string `json:"refusal,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
Reasoning string `json:"reasoning,omitempty"`
Name string `json:"name,omitempty"`
@@ -830,6 +836,7 @@ type ChatChunkChoice struct {
type ChatDelta struct {
Role string `json:"role,omitempty"`
Content *string `json:"content,omitempty"` // pointer: omit when not present, null vs "" matters
+ Refusal *string `json:"refusal,omitempty"`
ReasoningContent *string `json:"reasoning_content,omitempty"`
Reasoning *string `json:"reasoning,omitempty"`
ToolCalls []ChatToolCall `json:"tool_calls,omitempty"`
diff --git a/backend/internal/pkg/claude/constants.go b/backend/internal/pkg/claude/constants.go
index 6c2aeebba..5e0f9fc27 100644
--- a/backend/internal/pkg/claude/constants.go
+++ b/backend/internal/pkg/claude/constants.go
@@ -20,6 +20,9 @@ const (
BetaFastMode = "fast-mode-2026-02-01"
// Legacy structured output compatibility; forwarded only when explicitly requested.
BetaStructuredOutputs = "structured-outputs-2025-11-13"
+ // Tool-change compatibility tokens; never enabled without an explicit client request.
+ BetaMidConversationToolChanges = "mid-conversation-tool-changes-2026-07-01"
+ BetaInlineTools = "inline-tools-2026-09-15"
// 新增(对齐官方 CLI 2.1.9x 以来的流量)
BetaPromptCachingScope = "prompt-caching-scope-2026-01-05"
diff --git a/backend/internal/pkg/typesafe/client.go b/backend/internal/pkg/typesafe/client.go
index 35783249e..0974204e2 100644
--- a/backend/internal/pkg/typesafe/client.go
+++ b/backend/internal/pkg/typesafe/client.go
@@ -13,6 +13,12 @@ import (
"strings"
)
+const (
+ DefaultBaseURL = "https://api.typesafe.ai"
+ SystemOnePath = "/v1/systemone"
+ JevLatestModel = "jev-latest"
+)
+
type Question struct {
Type string `json:"type"`
Instructions string `json:"instructions"`
@@ -35,22 +41,103 @@ type Usage struct {
OutputTokens int `json:"output_tokens"`
}
-// Evaluate performs one attempt. The caller owns timeouts, retries and key rotation.
-func Evaluate(ctx context.Context, client *http.Client, baseURL, key string, input Request) (*Result, int, error) {
- endpoint, err := url.JoinPath(strings.TrimRight(baseURL, "/"), "/v1/systemone")
+type SystemOneResponse struct {
+ Body []byte
+ Model string
+ Usage Usage
+}
+
+func NewSystemOneRequest(ctx context.Context, baseURL, key string, body []byte) (*http.Request, error) {
+ endpoint, err := url.JoinPath(strings.TrimRight(baseURL, "/"), SystemOnePath)
if err != nil {
- return nil, 0, errors.New("typesafe invalid endpoint")
+ return nil, errors.New("typesafe invalid endpoint")
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
+ if err != nil {
+ return nil, errors.New("typesafe invalid request")
+ }
+ req.Header.Set("Authorization", "Bearer "+key)
+ req.Header.Set("Content-Type", "application/json")
+ return req, nil
+}
+
+// MaxSystemOneResponseBytes bounds a buffered System One response body.
+const MaxSystemOneResponseBytes = 4 << 20
+
+var ErrSystemOneResponseTooLarge = errors.New("typesafe response exceeds size limit")
+
+func DecodeSystemOneResponse(r io.Reader) (*SystemOneResponse, error) {
+ body, err := io.ReadAll(io.LimitReader(r, MaxSystemOneResponseBytes+1))
+ if err != nil {
+ return nil, errors.New("typesafe invalid response")
+ }
+ // A truncated body would otherwise surface as a misleading "invalid JSON".
+ if len(body) > MaxSystemOneResponseBytes {
+ return nil, ErrSystemOneResponseTooLarge
+ }
+ if !json.Valid(body) {
+ return nil, errors.New("typesafe invalid response")
}
+ var envelope map[string]json.RawMessage
+ if err := json.Unmarshal(body, &envelope); err != nil || envelope == nil {
+ return nil, errors.New("typesafe invalid response")
+ }
+ // The upstream already answered (and charged); an unexpected model or usage
+ // shape must not discard the answer, so both are decoded leniently.
+ var model string
+ _ = json.Unmarshal(envelope["model"], &model)
+ var usage map[string]json.RawMessage
+ _ = json.Unmarshal(envelope["usage"], &usage)
+ return &SystemOneResponse{
+ Body: body,
+ Model: model,
+ Usage: Usage{
+ InputTokens: systemOneTokenCount(usage["input_tokens"]),
+ OutputTokens: systemOneTokenCount(usage["output_tokens"]),
+ },
+ }, nil
+}
+
+// maxSystemOneTokenCount bounds a reported token count before int conversion.
+const maxSystemOneTokenCount = 1 << 40
+
+// systemOneTokenCount accepts integer, float, or numeric-string token counts.
+func systemOneTokenCount(raw json.RawMessage) int {
+ raw = bytes.TrimSpace(raw)
+ if len(raw) == 0 {
+ return 0
+ }
+ if raw[0] == '"' {
+ var text string
+ if json.Unmarshal(raw, &text) != nil {
+ return 0
+ }
+ raw = json.RawMessage(strings.TrimSpace(text))
+ }
+ var number json.Number
+ if json.Unmarshal(raw, &number) != nil {
+ return 0
+ }
+ value, err := number.Float64()
+ if err != nil || math.IsNaN(value) || value <= 0 {
+ return 0
+ }
+ if value > maxSystemOneTokenCount {
+ value = maxSystemOneTokenCount
+ }
+ return int(math.Round(value))
+}
+
+// Evaluate performs one attempt. The caller owns timeouts, retries and key rotation.
+func Evaluate(ctx context.Context, client *http.Client, baseURL, key string, input Request) (*Result, int, error) {
body, err := json.Marshal(input)
if err != nil {
return nil, 0, errors.New("typesafe invalid request")
}
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
+ req, err := NewSystemOneRequest(ctx, baseURL, key, body)
if err != nil {
- return nil, 0, errors.New("typesafe invalid request")
+ return nil, 0, err
}
- req.Header.Set("Authorization", "Bearer "+key)
- req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
if ctx.Err() != nil {
diff --git a/backend/internal/pkg/typesafe/systemone.go b/backend/internal/pkg/typesafe/systemone.go
new file mode 100644
index 000000000..4fab1f1d6
--- /dev/null
+++ b/backend/internal/pkg/typesafe/systemone.go
@@ -0,0 +1,202 @@
+package typesafe
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+)
+
+var ErrStreamingUnsupported = errors.New("typesafe system one does not support streaming")
+
+type systemOneEnvelope struct {
+ Model json.RawMessage `json:"model"`
+ State json.RawMessage `json:"state"`
+ Questions json.RawMessage `json:"questions"`
+ Stream json.RawMessage `json:"stream"`
+}
+
+var (
+ systemOneRequestFields = []string{"model", "state", "questions", "stream"}
+ systemOneQuestionFields = []string{"type", "instructions", "criteria"}
+)
+
+func ValidateSystemOneRequest(body []byte) (string, error) {
+ var envelope systemOneEnvelope
+ if err := json.Unmarshal(body, &envelope); err != nil {
+ return "", errors.New("invalid JSON request")
+ }
+ // encoding/json matches struct fields case-insensitively and keeps the last
+ // duplicate, while the raw body is forwarded upstream unchanged. Reject any
+ // spelling the upstream could read differently from this validator.
+ if err := checkSystemOneObjectKeys(body, "request", systemOneRequestFields); err != nil {
+ return "", err
+ }
+
+ model, err := requiredString(envelope.Model, "model")
+ if err != nil {
+ return "", err
+ }
+ if model != JevLatestModel {
+ return "", fmt.Errorf("model must be %s", JevLatestModel)
+ }
+ if err := validateStringObjectOrArray(envelope.State, "state"); err != nil {
+ return "", err
+ }
+ questionsRaw := bytes.TrimSpace(envelope.Questions)
+ var questions map[string]json.RawMessage
+ if len(questionsRaw) == 0 || questionsRaw[0] != '{' || json.Unmarshal(questionsRaw, &questions) != nil || len(questions) == 0 {
+ return "", errors.New("questions must be a non-empty object")
+ }
+ if err := checkSystemOneObjectKeys(questionsRaw, "questions", nil); err != nil {
+ return "", err
+ }
+ if len(envelope.Stream) > 0 && string(envelope.Stream) != "null" {
+ var stream bool
+ if err := json.Unmarshal(envelope.Stream, &stream); err != nil {
+ return "", errors.New("stream must be a boolean")
+ }
+ if stream {
+ return "", ErrStreamingUnsupported
+ }
+ }
+ for id, raw := range questions {
+ if err := validateQuestion(id, raw); err != nil {
+ return "", err
+ }
+ }
+ return model, nil
+}
+
+func validateQuestion(id string, raw json.RawMessage) error {
+ raw = bytes.TrimSpace(raw)
+ var question struct {
+ Type json.RawMessage `json:"type"`
+ Instructions json.RawMessage `json:"instructions"`
+ Criteria json.RawMessage `json:"criteria"`
+ }
+ if len(raw) == 0 || raw[0] != '{' || json.Unmarshal(raw, &question) != nil {
+ return fmt.Errorf("question %q must be an object", id)
+ }
+ if err := checkSystemOneObjectKeys(raw, fmt.Sprintf("question %q", id), systemOneQuestionFields); err != nil {
+ return err
+ }
+ typ, err := requiredString(question.Type, "question type")
+ if err != nil {
+ return fmt.Errorf("question %q: %w", id, err)
+ }
+ // Mirror the wire schema generated from https://api.typesafe.ai/openapi.json
+ // in TypeSafe SDK v0.5.7: instructions are optional and nullable for all types.
+ if err := validateOptionalDescription(question.Instructions, "instructions"); err != nil {
+ return fmt.Errorf("question %q: %w", id, err)
+ }
+
+ switch typ {
+ case "noul":
+ criteria := bytes.TrimSpace(question.Criteria)
+ if len(criteria) == 0 || bytes.Equal(criteria, []byte("null")) {
+ return nil
+ }
+ var descriptions map[string]json.RawMessage
+ if criteria[0] != '{' || json.Unmarshal(criteria, &descriptions) != nil {
+ return fmt.Errorf("question %q: noul criteria must be an object", id)
+ }
+ for _, outcome := range []string{"true", "false"} {
+ if err := validateOptionalDescription(descriptions[outcome], "noul criteria "+outcome); err != nil {
+ return fmt.Errorf("question %q: %w", id, err)
+ }
+ }
+ case "choice":
+ var criteria map[string]json.RawMessage
+ if json.Unmarshal(question.Criteria, &criteria) != nil || criteria == nil {
+ return fmt.Errorf("question %q: choice criteria must be an object", id)
+ }
+ for _, value := range criteria {
+ if err := validateOptionalDescription(value, "choice criteria value"); err != nil {
+ return fmt.Errorf("question %q: %w", id, err)
+ }
+ }
+ case "score":
+ var criteria []json.RawMessage
+ if json.Unmarshal(question.Criteria, &criteria) != nil || len(criteria) == 0 {
+ return fmt.Errorf("question %q: score criteria must contain at least one level", id)
+ }
+ for _, value := range criteria {
+ if err := validateStringObjectOrArray(value, "score criteria value"); err != nil {
+ return fmt.Errorf("question %q: %w", id, err)
+ }
+ }
+ default:
+ return fmt.Errorf("question %q: unsupported type %q", id, typ)
+ }
+ return nil
+}
+
+func validateOptionalDescription(raw json.RawMessage, name string) error {
+ raw = bytes.TrimSpace(raw)
+ if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
+ return nil
+ }
+ return validateStringObjectOrArray(raw, name)
+}
+
+func requiredString(raw json.RawMessage, name string) (string, error) {
+ var value string
+ if len(raw) == 0 || json.Unmarshal(raw, &value) != nil || strings.TrimSpace(value) == "" {
+ return "", fmt.Errorf("%s must be a non-empty string", name)
+ }
+ return value, nil
+}
+
+func validateStringObjectOrArray(raw json.RawMessage, name string) error {
+ raw = bytes.TrimSpace(raw)
+ if len(raw) == 0 || string(raw) == "null" {
+ return fmt.Errorf("%s is required", name)
+ }
+ switch raw[0] {
+ case '{', '[':
+ return nil
+ case '"':
+ if rawString(raw) {
+ return nil
+ }
+ }
+ return fmt.Errorf("%s must be a string, object, or array", name)
+}
+
+func rawString(raw json.RawMessage) bool {
+ var value string
+ return json.Unmarshal(raw, &value) == nil
+}
+
+// checkSystemOneObjectKeys rejects duplicate keys and non-canonical spellings
+// (any case variant) of the known fields in one JSON object level.
+func checkSystemOneObjectKeys(raw []byte, scope string, canonical []string) error {
+ decoder := json.NewDecoder(bytes.NewReader(raw))
+ if token, err := decoder.Token(); err != nil || token != json.Delim('{') {
+ return fmt.Errorf("%s must be an object", scope)
+ }
+ seen := make(map[string]struct{})
+ for decoder.More() {
+ token, err := decoder.Token()
+ if err != nil {
+ return errors.New("invalid JSON request")
+ }
+ key, _ := token.(string)
+ if _, duplicate := seen[key]; duplicate {
+ return fmt.Errorf("%s contains duplicate field %q", scope, key)
+ }
+ seen[key] = struct{}{}
+ for _, field := range canonical {
+ if key != field && strings.EqualFold(key, field) {
+ return fmt.Errorf("%s field %q must be written as %q", scope, key, field)
+ }
+ }
+ var value json.RawMessage
+ if err := decoder.Decode(&value); err != nil {
+ return errors.New("invalid JSON request")
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/pkg/typesafe/systemone_test.go b/backend/internal/pkg/typesafe/systemone_test.go
new file mode 100644
index 000000000..65991cf14
--- /dev/null
+++ b/backend/internal/pkg/typesafe/systemone_test.go
@@ -0,0 +1,124 @@
+package typesafe
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestValidateSystemOneRequestValidQuestionTypes(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ }{
+ {"noul string state", `{"model":"jev-latest","state":"sample","questions":{"safety":{"type":"noul","instructions":"Evaluate safety","criteria":{"safe":"No harm"}}}}`},
+ {"choice object state", `{"model":"jev-latest","state":{"text":"sample"},"questions":{"label":{"type":"choice","instructions":{"task":"Classify"},"criteria":{"safe":"Allowed","unsafe":null}}},"stream":false}`},
+ {"score array state", `{"model":"jev-latest","state":["sample"],"questions":{"quality":{"type":"score","instructions":["Rate quality"],"criteria":["poor","good"]}}}`},
+ {"noul omitted instructions", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"noul"}}}`},
+ {"noul nullable instructions and criteria", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"noul","instructions":null,"criteria":null}}}`},
+ {"noul structured descriptions", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"noul","criteria":{"true":{"examples":["yes",null]},"false":["no",null],"extension":42}}}}`},
+ {"choice structured descriptions", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"choice","instructions":null,"criteria":{"a":{"description":"A","extra":null},"b":["B",null],"c":null}}}}`},
+ {"choice empty criteria", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"choice","criteria":{}}}}`},
+ {"score one level", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"score","criteria":["only"]}}}`},
+ {"score object level", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"score","instructions":null,"criteria":[{"description":"only","extra":null}]}}}`},
+ {"score array level", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"score","criteria":[["only",null]]}}}`},
+ {"native extensions preserved", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"noul","extension":{"kept":true}}},"extension":[1,null]}`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ model, err := ValidateSystemOneRequest([]byte(tc.body))
+ require.NoError(t, err)
+ require.Equal(t, JevLatestModel, model)
+ })
+ }
+}
+
+func TestValidateSystemOneRequestRejectsInvalidRequests(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ want string
+ }{
+ {"invalid json", `{`, "invalid JSON"},
+ {"missing model", `{"state":"x","questions":{"q":{"type":"noul","instructions":"x"}}}`, "model"},
+ {"illegal model", `{"model":"jev-old","state":"x","questions":{"q":{"type":"noul","instructions":"x"}}}`, "jev-latest"},
+ {"model with whitespace", `{"model":" jev-latest ","state":"x","questions":{"q":{"type":"noul","instructions":"x"}}}`, "jev-latest"},
+ {"missing state", `{"model":"jev-latest","questions":{"q":{"type":"noul","instructions":"x"}}}`, "state"},
+ {"scalar state", `{"model":"jev-latest","state":42,"questions":{"q":{"type":"noul","instructions":"x"}}}`, "state"},
+ {"empty questions", `{"model":"jev-latest","state":"x","questions":{}}`, "questions"},
+ {"array questions", `{"model":"jev-latest","state":"x","questions":[{"type":"noul"}]}`, "questions must be a non-empty object"},
+ {"null questions", `{"model":"jev-latest","state":"x","questions":null}`, "questions must be a non-empty object"},
+ {"unknown question type", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"boolean","instructions":"x"}}}`, "unsupported type"},
+ {"question type with whitespace", `{"model":"jev-latest","state":"x","questions":{"q":{"type":" noul ","instructions":"x"}}}`, "unsupported type"},
+ {"noul criteria array", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul","instructions":"x","criteria":[]}}}`, "noul criteria"},
+ {"noul numeric description", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul","criteria":{"true":1}}}}`, "noul criteria"},
+ {"noul boolean description", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul","criteria":{"false":false}}}}`, "noul criteria"},
+ {"missing choice criteria", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"choice"}}}`, "choice criteria"},
+ {"null choice criteria", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"choice","criteria":null}}}`, "choice criteria"},
+ {"choice criteria array", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"choice","criteria":[]}}}`, "choice criteria"},
+ {"choice numeric value", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"choice","instructions":"x","criteria":{"one":1}}}}`, "choice criteria"},
+ {"missing score criteria", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"score"}}}`, "score criteria"},
+ {"empty score criteria", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"score","criteria":[]}}}`, "score criteria"},
+ {"null score criteria", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"score","criteria":null}}}`, "score criteria"},
+ {"score map is not wire protocol", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"score","criteria":{"0":"low"}}}}`, "score criteria"},
+ {"numeric score level", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"score","criteria":["low",2]}}}`, "score criteria"},
+ {"null score level", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"score","criteria":[null]}}}`, "score criteria"},
+ {"numeric instructions", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul","instructions":1}}}`, "instructions"},
+ {"boolean instructions", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"choice","instructions":true,"criteria":{}}}}`, "instructions"},
+ {"stream true", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul","instructions":"x"}},"stream":true}`, "streaming"},
+ {"case variant model smuggles upstream model", `{"model":"jev-pro","MODEL":"jev-latest","state":"x","questions":{"q":{"type":"noul"}}}`, `must be written as "model"`},
+ {"case variant stream hides streaming", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul"}},"stream":true,"Stream":false}`, `must be written as "stream"`},
+ {"unicode fold variant state", `{"model":"jev-latest","state":"x","ſtate":"y","questions":{"q":{"type":"noul"}}}`, `must be written as "state"`},
+ {"duplicate model", `{"model":"jev-pro","model":"jev-latest","state":"x","questions":{"q":{"type":"noul"}}}`, `duplicate field "model"`},
+ {"escaped duplicate model", `{"\u006dodel":"jev-pro","model":"jev-latest","state":"x","questions":{"q":{"type":"noul"}}}`, `duplicate field "model"`},
+ {"duplicate state", `{"model":"jev-latest","state":"benign","state":"payload","questions":{"q":{"type":"noul"}}}`, `duplicate field "state"`},
+ {"duplicate question id", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul"},"q":{"type":"noul"}}}`, `duplicate field "q"`},
+ {"duplicate question instructions", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul","instructions":"a","instructions":"b"}}}`, `duplicate field "instructions"`},
+ {"case variant question type", `{"model":"jev-latest","state":"x","questions":{"q":{"type":"noul","Type":"choice"}}}`, `must be written as "type"`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := ValidateSystemOneRequest([]byte(tc.body))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), tc.want)
+ if tc.name == "stream true" {
+ require.True(t, errors.Is(err, ErrStreamingUnsupported))
+ }
+ })
+ }
+}
+
+func TestDecodeSystemOneResponseToleratesUsageShapes(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ model string
+ input, output int
+ }{
+ {"integers", `{"model":"jev-1","usage":{"input_tokens":12,"output_tokens":3}}`, "jev-1", 12, 3},
+ {"floats", `{"model":"jev-1","usage":{"input_tokens":12.0,"output_tokens":2.6}}`, "jev-1", 12, 3},
+ {"numeric strings", `{"usage":{"input_tokens":"15","output_tokens":" 4 "}}`, "", 15, 4},
+ {"non numeric usage", `{"model":7,"usage":{"input_tokens":"many","output_tokens":null}}`, "", 0, 0},
+ {"negative usage", `{"usage":{"input_tokens":-5}}`, "", 0, 0},
+ {"usage not object", `{"model":"jev-1","usage":"none","answers":{}}`, "jev-1", 0, 0},
+ {"missing usage", `{"answers":{}}`, "", 0, 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ decoded, err := DecodeSystemOneResponse(strings.NewReader(tc.body))
+ require.NoError(t, err)
+ require.Equal(t, []byte(tc.body), decoded.Body)
+ require.Equal(t, tc.model, decoded.Model)
+ require.Equal(t, tc.input, decoded.Usage.InputTokens)
+ require.Equal(t, tc.output, decoded.Usage.OutputTokens)
+ })
+ }
+}
+
+func TestDecodeSystemOneResponseRejectsNonObjects(t *testing.T) {
+ for _, body := range []string{`[]`, `"text"`, `null`, `{`, `data: {}`} {
+ _, err := DecodeSystemOneResponse(strings.NewReader(body))
+ require.Error(t, err, body)
+ }
+ _, err := DecodeSystemOneResponse(strings.NewReader(`{"pad":"` + strings.Repeat("a", MaxSystemOneResponseBytes) + `"}`))
+ require.ErrorIs(t, err, ErrSystemOneResponseTooLarge)
+}
diff --git a/backend/internal/pkg/xai/billing.go b/backend/internal/pkg/xai/billing.go
index 39e1a2c8b..735baa86d 100644
--- a/backend/internal/pkg/xai/billing.go
+++ b/backend/internal/pkg/xai/billing.go
@@ -19,10 +19,7 @@ const (
// repository and service layers build their own client identity from it, so
// one bump here covers OAuth traffic and billing probes together.
// Keep in sync with https://x.ai/cli/stable.
- CLIClientVersion = "0.2.120"
- // billingCLIUserAgent is the legacy pager/shell UA used by billing probes.
- // Distinct from CLIUserAgent() in cli_identity.go (workspace-style UA).
- billingCLIUserAgent = "grok-pager/" + CLIClientVersion + " grok-shell/" + CLIClientVersion + " (macos; aarch64)"
+ CLIClientVersion = "1.0.46"
BillingWeeklyPath = "/billing?format=credits"
BillingMonthlyPath = "/billing"
@@ -148,7 +145,8 @@ func ApplyCLIBillingHeaders(req *http.Request, accessToken string) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set(CLITokenAuthHeader, CLITokenAuthValue)
req.Header.Set(CLIClientVersionHeader, CLIClientVersion)
- req.Header.Set("User-Agent", billingCLIUserAgent)
+ req.Header.Set("User-Agent", CLIUserAgent(CLIClientVersion))
+ req.Header.Set("x-grok-client-mode", CLIClientMode)
}
// ParseBillingPayload unmarshals a billing API response body.
diff --git a/backend/internal/pkg/xai/billing_test.go b/backend/internal/pkg/xai/billing_test.go
index 3dbfc89bf..51e3f2b1b 100644
--- a/backend/internal/pkg/xai/billing_test.go
+++ b/backend/internal/pkg/xai/billing_test.go
@@ -38,7 +38,8 @@ func TestApplyCLIBillingHeaders(t *testing.T) {
require.Equal(t, "Bearer token", req.Header.Get("Authorization"))
require.Equal(t, CLITokenAuthValue, req.Header.Get(CLITokenAuthHeader))
require.Equal(t, CLIClientVersion, req.Header.Get(CLIClientVersionHeader))
- require.Equal(t, "grok-pager/"+CLIClientVersion+" grok-shell/"+CLIClientVersion+" (macos; aarch64)", req.UserAgent())
+ require.Equal(t, CLIUserAgent(CLIClientVersion), req.UserAgent())
+ require.Equal(t, "interactive", req.Header.Get("x-grok-client-mode"))
}
func TestBuildBillingSummaryWeeklyAndMonthly(t *testing.T) {
diff --git a/backend/internal/pkg/xai/cli_identity.go b/backend/internal/pkg/xai/cli_identity.go
index 480e2e40a..e930867f3 100644
--- a/backend/internal/pkg/xai/cli_identity.go
+++ b/backend/internal/pkg/xai/cli_identity.go
@@ -3,6 +3,7 @@ package xai
import (
"net/http"
"os"
+ "runtime"
"strings"
"golang.org/x/mod/semver"
@@ -16,7 +17,7 @@ const (
CLIProxyHost = "cli-chat-proxy.grok.com"
// CLIStableVersion is the known-good minimum client version accepted by cli-chat-proxy.
- CLIStableVersion = "0.2.93"
+ CLIStableVersion = "1.0.13"
// CLIVersionEnv is the optional operator override for CLIStableVersion.
CLIVersionEnv = "XAI_GROK_CLI_VERSION"
@@ -24,11 +25,11 @@ const (
// CLITokenAuth is required by cli-chat-proxy for Grok Build OAuth tokens.
CLITokenAuth = "xai-grok-cli"
- // CLIClientIdentifier is the x-grok-client-identifier value used by Grok shell/CLI.
- CLIClientIdentifier = "grok-shell"
+ // CLIClientIdentifier 对齐官方交互式 CLI 主请求的客户端标识。
+ CLIClientIdentifier = "grok-pager"
- // CLIClientMode is used by billing / quota probes on the CLI surface.
- CLIClientMode = "cli"
+ // CLIClientMode 对齐官方 CLI 正常交互模式。
+ CLIClientMode = "interactive"
)
// ResolveCLIVersion returns a supported CLI client version.
@@ -54,12 +55,24 @@ func IsSupportedCLIVersion(version string) bool {
semver.Compare(canonical, minimum) >= 0
}
-// CLIUserAgent builds the workspace-style User-Agent for a CLI client version.
+// CLIUserAgent 对齐官方交互式 CLI 的 UA,平台名称使用 Rust 的格式。
func CLIUserAgent(version string) string {
if strings.TrimSpace(version) == "" {
version = CLIClientVersion
}
- return "xai-grok-workspace/" + version
+ platform, arch := runtime.GOOS, runtime.GOARCH
+ if platform == "darwin" {
+ platform = "macos"
+ }
+ switch arch {
+ case "amd64":
+ arch = "x86_64"
+ case "arm64":
+ arch = "aarch64"
+ case "386":
+ arch = "x86"
+ }
+ return "grok-pager/" + version + " grok-shell/" + version + " (" + platform + "; " + arch + ")"
}
// ApplyCLIProxyHeaders stamps the fixed Grok CLI identity when the request
@@ -75,5 +88,7 @@ func ApplyCLIProxyHeaders(req *http.Request) {
req.Header.Set("X-XAI-Token-Auth", CLITokenAuth)
req.Header.Set("x-grok-client-version", version)
req.Header.Set("x-grok-client-identifier", CLIClientIdentifier)
+ req.Header.Set("x-grok-client-mode", CLIClientMode)
+ req.Header.Set("x-authenticateresponse", "authenticate-response")
req.Header.Set("User-Agent", CLIUserAgent(version))
}
diff --git a/backend/internal/pkg/xai/cli_identity_test.go b/backend/internal/pkg/xai/cli_identity_test.go
index 2057b9eff..015114919 100644
--- a/backend/internal/pkg/xai/cli_identity_test.go
+++ b/backend/internal/pkg/xai/cli_identity_test.go
@@ -2,11 +2,40 @@ package xai
import (
"net/http"
+ "runtime"
"testing"
"github.com/stretchr/testify/require"
+ "golang.org/x/mod/semver"
)
+func TestApplyCLIProxyHeadersMeetsUpstreamMinimumVersion(t *testing.T) {
+ // 上游 426 明确要求至少 1.0.13;断言独立于生产版本常量,防止旧覆盖值绕过下限。
+ for _, override := range []string{"", "0.2.93", "0.2.120", "1.0.12", "1.0.13-beta.1", "1.0.13", "1.0.14-alpha.1"} {
+ t.Run("override="+override, func(t *testing.T) {
+ t.Setenv(CLIVersionEnv, override)
+ req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil)
+ require.NoError(t, err)
+
+ ApplyCLIProxyHeaders(req)
+
+ version := req.Header.Get("x-grok-client-version")
+ require.True(t, semver.IsValid("v"+version))
+ require.GreaterOrEqual(t, semver.Compare("v"+version, "v1.0.13"), 0,
+ "Grok Responses 会以 426 拒绝版本 %s,最低要求为 1.0.13", version)
+ require.Contains(t, req.Header.Get("User-Agent"), "grok-shell/"+version+" (")
+ })
+ }
+}
+
+func TestCLIUserAgentMatchesOfficialInteractiveCapture(t *testing.T) {
+ // 来源:官方 CLI 1.0.46 交互式界面在 Linux x86_64 的主 Responses 请求抓包。
+ if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
+ t.Skip("该抓包样本来自 Linux x86_64")
+ }
+ require.Equal(t, "grok-pager/1.0.46 grok-shell/1.0.46 (linux; x86_64)", CLIUserAgent("1.0.46"))
+}
+
func TestResolveCLIVersionDefaultsToPinnedClientVersion(t *testing.T) {
t.Setenv(CLIVersionEnv, "")
// Default advertise pin is CLIClientVersion; CLIStableVersion is only the floor.
@@ -16,18 +45,18 @@ func TestResolveCLIVersionDefaultsToPinnedClientVersion(t *testing.T) {
}
func TestResolveCLIVersionAcceptsValidOverride(t *testing.T) {
- t.Setenv(CLIVersionEnv, "0.2.95-alpha.1")
- require.Equal(t, "0.2.95-alpha.1", ResolveCLIVersion())
+ t.Setenv(CLIVersionEnv, "1.0.14-alpha.1")
+ require.Equal(t, "1.0.14-alpha.1", ResolveCLIVersion())
}
func TestResolveCLIVersionRejectsUnsafeOrTooOld(t *testing.T) {
for _, version := range []string{
- "0.2.92",
- "0.2.93-beta.1",
- "0.2.95\r\nX-Injected: true",
- "0.2.093",
- "0.3",
- "1",
+ "1.0.12",
+ "1.0.13-beta.1",
+ "1.0.14\r\nX-Injected: true",
+ "1.0.014",
+ "1.1",
+ "2",
} {
t.Run(version, func(t *testing.T) {
t.Setenv(CLIVersionEnv, version)
@@ -48,11 +77,13 @@ func TestApplyCLIProxyHeaders(t *testing.T) {
require.Equal(t, CLIClientVersion, req.Header.Get("x-grok-client-version"))
require.Equal(t, CLIClientIdentifier, req.Header.Get("x-grok-client-identifier"))
require.Equal(t, CLITokenAuth, req.Header.Get("X-XAI-Token-Auth"))
+ require.Equal(t, "interactive", req.Header.Get("x-grok-client-mode"))
+ require.Equal(t, "authenticate-response", req.Header.Get("x-authenticateresponse"))
require.Equal(t, CLIUserAgent(CLIClientVersion), req.Header.Get("User-Agent"))
}
func TestApplyCLIProxyHeadersLeavesAPIHostUnchanged(t *testing.T) {
- t.Setenv(CLIVersionEnv, "0.2.95")
+ t.Setenv(CLIVersionEnv, "1.0.14")
req, err := http.NewRequest(http.MethodPost, "https://api.x.ai/v1/responses", nil)
require.NoError(t, err)
@@ -63,5 +94,7 @@ func TestApplyCLIProxyHeadersLeavesAPIHostUnchanged(t *testing.T) {
require.Empty(t, req.Header.Get("x-grok-client-version"))
require.Empty(t, req.Header.Get("x-grok-client-identifier"))
require.Empty(t, req.Header.Get("X-XAI-Token-Auth"))
+ require.Empty(t, req.Header.Get("x-grok-client-mode"))
+ require.Empty(t, req.Header.Get("x-authenticateresponse"))
require.Equal(t, "direct-api-client/1.0", req.Header.Get("User-Agent"))
}
diff --git a/backend/internal/pkg/xai/sso_device.go b/backend/internal/pkg/xai/sso_device.go
index 825616b93..5a06d24f9 100644
--- a/backend/internal/pkg/xai/sso_device.go
+++ b/backend/internal/pkg/xai/sso_device.go
@@ -1,6 +1,7 @@
package xai
import (
+ "bytes"
"context"
"encoding/base64"
"encoding/json"
@@ -14,6 +15,8 @@ import (
"strconv"
"strings"
"time"
+
+ "golang.org/x/net/html"
)
const (
@@ -147,7 +150,7 @@ func (f *ssoDeviceFlow) convert(ctx context.Context) (*TokenResponse, error) {
return nil, fmt.Errorf("open xAI device verification page: %w", SSOHTTPError{Status: status})
}
- status, finalURL, _, err = f.do(ctx, http.MethodPost, SSOVerifyURL, url.Values{"user_code": {device.UserCode}})
+ status, finalURL, body, err = f.do(ctx, http.MethodPost, SSOVerifyURL, url.Values{"user_code": {device.UserCode}})
if err != nil {
return nil, err
}
@@ -158,11 +161,19 @@ func (f *ssoDeviceFlow) convert(ctx context.Context) (*TokenResponse, error) {
return nil, errors.New("xAI device verification did not reach consent page")
}
- status, finalURL, _, err = f.do(ctx, http.MethodPost, SSOApproveURL, url.Values{
+ approval := url.Values{
"user_code": {device.UserCode},
"action": {"allow"},
"principal_type": {"User"},
"principal_id": {""},
+ }
+ if consentToken := ssoConsentToken(body); consentToken != "" {
+ approval.Set("consent_token", consentToken)
+ }
+ consentURL, _ := url.Parse(finalURL) // f.do only returns validated xAI URLs.
+ status, finalURL, _, err = f.do(ctx, http.MethodPost, SSOApproveURL, approval, http.Header{
+ "Origin": {consentURL.Scheme + "://" + consentURL.Host},
+ "Referer": {finalURL},
})
if err != nil {
return nil, err
@@ -177,6 +188,37 @@ func (f *ssoDeviceFlow) convert(ctx context.Context) (*TokenResponse, error) {
return f.pollToken(ctx, device.DeviceCode, time.Duration(device.Interval)*time.Second, time.Duration(device.ExpiresIn)*time.Second)
}
+// xAI binds device approval to a hidden token on the consent page. Keep it in
+// this flow only; older consent pages without the field remain supported.
+func ssoConsentToken(body []byte) string {
+ tokenizer := html.NewTokenizer(bytes.NewReader(body))
+ for {
+ switch tokenizer.Next() {
+ case html.ErrorToken:
+ return ""
+ case html.StartTagToken, html.SelfClosingTagToken:
+ token := tokenizer.Token()
+ if token.Data != "input" {
+ continue
+ }
+ var name, value, inputType string
+ for _, attr := range token.Attr {
+ switch attr.Key {
+ case "name":
+ name = attr.Val
+ case "value":
+ value = attr.Val
+ case "type":
+ inputType = attr.Val
+ }
+ }
+ if name == "consent_token" && strings.EqualFold(inputType, "hidden") {
+ return value
+ }
+ }
+ }
+}
+
func (f *ssoDeviceFlow) pollToken(ctx context.Context, deviceCode string, interval, expiresIn time.Duration) (*TokenResponse, error) {
if interval < time.Second {
interval = time.Second
@@ -241,7 +283,7 @@ func (f *ssoDeviceFlow) pollToken(ctx context.Context, deviceCode string, interv
return nil, errors.New("xAI device flow token polling timed out")
}
-func (f *ssoDeviceFlow) do(ctx context.Context, method, endpoint string, form url.Values) (int, string, []byte, error) {
+func (f *ssoDeviceFlow) do(ctx context.Context, method, endpoint string, form url.Values, headers ...http.Header) (int, string, []byte, error) {
if !safeXAIAuthURL(endpoint) {
return 0, "", nil, errors.New("xAI OAuth URL is not trusted")
}
@@ -260,6 +302,15 @@ func (f *ssoDeviceFlow) do(ctx context.Context, method, endpoint string, form ur
request.Header.Set("Accept", "application/json, text/html;q=0.9, */*;q=0.8")
request.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
request.Header.Set("User-Agent", f.userAgent)
+ if redirects == 0 {
+ for _, header := range headers {
+ for name, values := range header {
+ for _, value := range values {
+ request.Header.Add(name, value)
+ }
+ }
+ }
+ }
if cookie := f.cookieHeader(request.URL); cookie != "" {
request.Header.Set("Cookie", cookie)
}
diff --git a/backend/internal/pkg/xai/sso_device_test.go b/backend/internal/pkg/xai/sso_device_test.go
index cd3bae3aa..4b59dd4a5 100644
--- a/backend/internal/pkg/xai/sso_device_test.go
+++ b/backend/internal/pkg/xai/sso_device_test.go
@@ -23,6 +23,10 @@ type ssoDeviceFakeClient struct {
func (c *ssoDeviceFakeClient) Do(req *http.Request) (*http.Response, error) {
c.cookieHeaders = append(c.cookieHeaders, req.Header.Get("Cookie"))
+ if req.URL.String() != SSOApproveURL {
+ require.Empty(c.t, req.Header.Get("Origin"))
+ require.Empty(c.t, req.Header.Get("Referer"))
+ }
switch req.URL.String() {
case SSOAccountsURL:
require.Equal(c.t, http.MethodGet, req.Method)
@@ -43,13 +47,16 @@ func (c *ssoDeviceFakeClient) Do(req *http.Request) (*http.Response, error) {
return ssoDeviceResponse(http.StatusFound, http.Header{"Location": {"/oauth2/device/consent"}}, ``), nil
case "https://auth.x.ai/oauth2/device/consent":
require.Equal(c.t, http.MethodGet, req.Method)
- return ssoDeviceResponse(http.StatusOK, nil, `consent`), nil
+ return ssoDeviceResponse(http.StatusOK, nil, `
`), nil
case SSOApproveURL:
require.Equal(c.t, http.MethodPost, req.Method)
+ require.Equal(c.t, "https://auth.x.ai", req.Header.Get("Origin"))
+ require.Equal(c.t, "https://auth.x.ai/oauth2/device/consent", req.Header.Get("Referer"))
values := readSSODeviceForm(c.t, req)
require.Equal(c.t, "USER-1", values.Get("user_code"))
require.Equal(c.t, "allow", values.Get("action"))
require.Equal(c.t, "User", values.Get("principal_type"))
+ require.Equal(c.t, "consent&token", values.Get("consent_token"))
return ssoDeviceResponse(http.StatusSeeOther, http.Header{"Location": {"/oauth2/device/done"}}, ``), nil
case "https://auth.x.ai/oauth2/device/done":
require.Equal(c.t, http.MethodGet, req.Method)
@@ -87,6 +94,24 @@ func TestConvertSSOToBuildCompletesDeviceFlow(t *testing.T) {
require.Contains(t, client.cookieHeaders[0], "sso-rw=sso-token")
require.Contains(t, client.cookieHeaders[len(client.cookieHeaders)-1], "session=web-session")
require.Contains(t, client.cookieHeaders[len(client.cookieHeaders)-1], "csrf=csrf-token")
+ for _, cookie := range client.cookieHeaders {
+ require.NotContains(t, cookie, "consent&token")
+ }
+}
+
+func TestSSOConsentToken(t *testing.T) {
+ for _, tc := range []struct {
+ name, body, want string
+ }{
+ {"legacy page", `consent`, ""},
+ {"encoded hidden value", ``, "a&b+c"},
+ {"case insensitive HTML", ``, "token"},
+ {"ignore script and visible fields", ``, "real"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ require.Equal(t, tc.want, ssoConsentToken([]byte(tc.body)))
+ })
+ }
}
func TestNormalizeSSOTokenAcceptsCookieHeader(t *testing.T) {
diff --git a/backend/internal/repository/api_key_repo.go b/backend/internal/repository/api_key_repo.go
index 7744852a7..f92e1e731 100644
--- a/backend/internal/repository/api_key_repo.go
+++ b/backend/internal/repository/api_key_repo.go
@@ -652,6 +652,17 @@ func apiKeyListOrder(params pagination.PaginationParams) []func(*entsql.Selector
sortBy := strings.ToLower(strings.TrimSpace(params.SortBy))
sortOrder := params.NormalizedSortOrder(pagination.SortOrderDesc)
+ if sortBy == "group" {
+ // Sort before pagination, keeping ungrouped keys last in either direction.
+ opts := []entsql.OrderTermOption{entsql.OrderNullsLast()}
+ tieOrder := dbent.Asc(apikey.FieldID)
+ if sortOrder == pagination.SortOrderDesc {
+ opts = append(opts, entsql.OrderDesc())
+ tieOrder = dbent.Desc(apikey.FieldID)
+ }
+ return []func(*entsql.Selector){apikey.ByGroupField(group.FieldName, opts...), tieOrder}
+ }
+
var field string
switch sortBy {
case "name":
diff --git a/backend/internal/repository/api_key_repo_sort_test.go b/backend/internal/repository/api_key_repo_sort_test.go
new file mode 100644
index 000000000..bb8ea59c0
--- /dev/null
+++ b/backend/internal/repository/api_key_repo_sort_test.go
@@ -0,0 +1,78 @@
+package repository
+
+import (
+ "context"
+ "testing"
+
+ dbent "github.com/MACOS-DO/sub4api/ent"
+ "github.com/MACOS-DO/sub4api/internal/pkg/pagination"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/stretchr/testify/require"
+)
+
+func TestAPIKeyRepositoryListByUserIDSortByGroup(t *testing.T) {
+ repo, client := newAPIKeyRepoSQLite(t)
+ ctx := context.Background()
+ user := mustCreateAPIKeyRepoUser(t, ctx, client, "group-sort@test.com")
+ otherUser := mustCreateAPIKeyRepoUser(t, ctx, client, "other-group-sort@test.com")
+ createGroup := func(name string) *dbent.Group {
+ g, err := client.Group.Create().SetName(name).Save(ctx)
+ require.NoError(t, err)
+ return g
+ }
+ // Create groups in reverse name order so sorting by group ID cannot pass.
+ zulu := createGroup("Zulu")
+ alpha := createGroup("Alpha")
+ createKey := func(userID int64, name string, groupID *int64, status string) int64 {
+ key := &service.APIKey{
+ UserID: userID, Key: "sk-" + name, Name: name, GroupID: groupID, Status: status,
+ }
+ require.NoError(t, repo.Create(ctx, key))
+ return key.ID
+ }
+ zuluFirst := createKey(user.ID, "match-zulu-first", &zulu.ID, service.StatusActive)
+ ungroupedFirst := createKey(user.ID, "match-ungrouped-first", nil, service.StatusActive)
+ alphaFirst := createKey(user.ID, "match-alpha-first", &alpha.ID, service.StatusActive)
+ zuluSecond := createKey(user.ID, "match-zulu-second", &zulu.ID, service.StatusActive)
+ alphaSecond := createKey(user.ID, "match-alpha-second", &alpha.ID, service.StatusActive)
+ ungroupedSecond := createKey(user.ID, "match-ungrouped-second", nil, service.StatusActive)
+ createKey(otherUser.ID, "match-other-user", &alpha.ID, service.StatusActive)
+ createKey(user.ID, "excluded-search", &alpha.ID, service.StatusActive)
+ createKey(user.ID, "match-inactive", &alpha.ID, service.StatusDisabled)
+ deleted := createKey(user.ID, "match-deleted", &alpha.ID, service.StatusActive)
+ require.NoError(t, repo.Delete(ctx, deleted))
+
+ ungroupedID := int64(0)
+ for _, tc := range []struct {
+ name string
+ order string
+ groupID *int64
+ want []int64
+ }{
+ {"ascending", "asc", nil, []int64{alphaFirst, alphaSecond, zuluFirst, zuluSecond, ungroupedFirst, ungroupedSecond}},
+ {"descending", "desc", nil, []int64{zuluSecond, zuluFirst, alphaSecond, alphaFirst, ungroupedSecond, ungroupedFirst}},
+ {"group filter", "asc", &alpha.ID, []int64{alphaFirst, alphaSecond}},
+ {"ungrouped filter", "desc", &ungroupedID, []int64{ungroupedSecond, ungroupedFirst}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var got []int64
+ const pageSize = 3
+ pages := (len(tc.want) + pageSize - 1) / pageSize
+ for page := 1; page <= pages; page++ {
+ keys, result, err := repo.ListByUserID(ctx, user.ID, pagination.PaginationParams{
+ Page: page, PageSize: pageSize, SortBy: "group", SortOrder: tc.order,
+ }, service.APIKeyListFilters{Search: "match", Status: service.StatusActive, GroupID: tc.groupID})
+ require.NoError(t, err)
+ require.EqualValues(t, len(tc.want), result.Total)
+ require.Equal(t, pages, result.Pages)
+ for _, key := range keys {
+ got = append(got, key.ID)
+ if key.GroupID != nil {
+ require.NotNil(t, key.Group, "sorting must preserve group preloading")
+ }
+ }
+ }
+ require.Equal(t, tc.want, got)
+ })
+ }
+}
diff --git a/backend/internal/repository/email_cache.go b/backend/internal/repository/email_cache.go
index 09ea234e2..1d60a769e 100644
--- a/backend/internal/repository/email_cache.go
+++ b/backend/internal/repository/email_cache.go
@@ -17,8 +17,42 @@ const (
passwordResetKeyPrefix = "password_reset:"
passwordResetSentAtKeyPrefix = "password_reset_sent:"
notifyCodeUserRateKeyPrefix = "notify_code_user_rate:"
+
+ // attemptsKeySuffix stores the failed-attempt counter next to a verification code.
+ // Kept in a separate key so it can be incremented atomically with INCR.
+ attemptsKeySuffix = ":attempts"
)
+// incrAttemptsScript atomically increments the attempt counter for an existing
+// verification code and aligns the counter TTL with the code TTL.
+// KEYS[1] = code key, KEYS[2] = attempts key. Returns -1 when the code is missing.
+var incrAttemptsScript = redis.NewScript(`
+if redis.call('EXISTS', KEYS[1]) == 0 then
+ return -1
+end
+local n = redis.call('INCR', KEYS[2])
+local ttl = redis.call('PTTL', KEYS[1])
+if ttl > 0 then
+ redis.call('PEXPIRE', KEYS[2], ttl)
+end
+return n
+`)
+
+// consumeResetTokenScript atomically compares the stored token hash and deletes it.
+// KEYS[1] = reset key, ARGV[1] = expected token hash. Returns 1 on success, 0 otherwise.
+var consumeResetTokenScript = redis.NewScript(`
+local v = redis.call('GET', KEYS[1])
+if not v then
+ return 0
+end
+local ok, d = pcall(cjson.decode, v)
+if not ok or type(d) ~= 'table' or d['Token'] ~= ARGV[1] then
+ return 0
+end
+redis.call('DEL', KEYS[1])
+return 1
+`)
+
// verifyCodeKey generates the Redis key for email verification code.
// Email is lowercased for case-insensitive consistency.
func verifyCodeKey(email string) string {
@@ -50,8 +84,7 @@ func NewEmailCache(rdb *redis.Client) service.EmailCache {
return &emailCache{rdb: rdb}
}
-func (c *emailCache) GetVerificationCode(ctx context.Context, email string) (*service.VerificationCodeData, error) {
- key := verifyCodeKey(email)
+func (c *emailCache) getCode(ctx context.Context, key string) (*service.VerificationCodeData, error) {
val, err := c.rdb.Get(ctx, key).Result()
if err != nil {
return nil, err
@@ -60,21 +93,56 @@ func (c *emailCache) GetVerificationCode(ctx context.Context, email string) (*se
if err := json.Unmarshal([]byte(val), &data); err != nil {
return nil, err
}
+ if n, err := c.rdb.Get(ctx, key+attemptsKeySuffix).Int(); err == nil && n > data.Attempts {
+ data.Attempts = n
+ }
return &data, nil
}
-func (c *emailCache) SetVerificationCode(ctx context.Context, email string, data *service.VerificationCodeData, ttl time.Duration) error {
- key := verifyCodeKey(email)
+func (c *emailCache) setCode(ctx context.Context, key string, data *service.VerificationCodeData, ttl time.Duration) error {
val, err := json.Marshal(data)
if err != nil {
return err
}
- return c.rdb.Set(ctx, key, val, ttl).Err()
+ pipe := c.rdb.TxPipeline()
+ pipe.Set(ctx, key, val, ttl)
+ pipe.Del(ctx, key+attemptsKeySuffix)
+ if data.Attempts > 0 {
+ pipe.Set(ctx, key+attemptsKeySuffix, data.Attempts, ttl)
+ }
+ _, err = pipe.Exec(ctx)
+ return err
+}
+
+func (c *emailCache) incrCodeAttempts(ctx context.Context, key string) (int, error) {
+ n, err := incrAttemptsScript.Run(ctx, c.rdb, []string{key, key + attemptsKeySuffix}).Int()
+ if err != nil {
+ return 0, err
+ }
+ if n < 0 {
+ return 0, redis.Nil
+ }
+ return n, nil
+}
+
+func (c *emailCache) deleteCode(ctx context.Context, key string) error {
+ return c.rdb.Del(ctx, key, key+attemptsKeySuffix).Err()
+}
+
+func (c *emailCache) GetVerificationCode(ctx context.Context, email string) (*service.VerificationCodeData, error) {
+ return c.getCode(ctx, verifyCodeKey(email))
+}
+
+func (c *emailCache) SetVerificationCode(ctx context.Context, email string, data *service.VerificationCodeData, ttl time.Duration) error {
+ return c.setCode(ctx, verifyCodeKey(email), data, ttl)
+}
+
+func (c *emailCache) IncrVerificationCodeAttempts(ctx context.Context, email string) (int, error) {
+ return c.incrCodeAttempts(ctx, verifyCodeKey(email))
}
func (c *emailCache) DeleteVerificationCode(ctx context.Context, email string) error {
- key := verifyCodeKey(email)
- return c.rdb.Del(ctx, key).Err()
+ return c.deleteCode(ctx, verifyCodeKey(email))
}
// Password reset token methods
@@ -101,6 +169,16 @@ func (c *emailCache) SetPasswordResetToken(ctx context.Context, email string, da
return c.rdb.Set(ctx, key, val, ttl).Err()
}
+// ConsumePasswordResetToken atomically deletes the stored reset token when its
+// stored hash equals tokenHash. Returns true only for the single winning caller.
+func (c *emailCache) ConsumePasswordResetToken(ctx context.Context, email, tokenHash string) (bool, error) {
+ n, err := consumeResetTokenScript.Run(ctx, c.rdb, []string{passwordResetKey(email)}, tokenHash).Int()
+ if err != nil {
+ return false, err
+ }
+ return n == 1, nil
+}
+
func (c *emailCache) DeletePasswordResetToken(ctx context.Context, email string) error {
key := passwordResetKey(email)
return c.rdb.Del(ctx, key).Err()
@@ -122,30 +200,19 @@ func (c *emailCache) SetPasswordResetEmailCooldown(ctx context.Context, email st
// Notify email verification code methods
func (c *emailCache) GetNotifyVerifyCode(ctx context.Context, email string) (*service.VerificationCodeData, error) {
- key := notifyVerifyKey(email)
- val, err := c.rdb.Get(ctx, key).Result()
- if err != nil {
- return nil, err
- }
- var data service.VerificationCodeData
- if err := json.Unmarshal([]byte(val), &data); err != nil {
- return nil, err
- }
- return &data, nil
+ return c.getCode(ctx, notifyVerifyKey(email))
}
func (c *emailCache) SetNotifyVerifyCode(ctx context.Context, email string, data *service.VerificationCodeData, ttl time.Duration) error {
- key := notifyVerifyKey(email)
- val, err := json.Marshal(data)
- if err != nil {
- return err
- }
- return c.rdb.Set(ctx, key, val, ttl).Err()
+ return c.setCode(ctx, notifyVerifyKey(email), data, ttl)
+}
+
+func (c *emailCache) IncrNotifyVerifyCodeAttempts(ctx context.Context, email string) (int, error) {
+ return c.incrCodeAttempts(ctx, notifyVerifyKey(email))
}
func (c *emailCache) DeleteNotifyVerifyCode(ctx context.Context, email string) error {
- key := notifyVerifyKey(email)
- return c.rdb.Del(ctx, key).Err()
+ return c.deleteCode(ctx, notifyVerifyKey(email))
}
// User-level rate limiting for notify email verification codes
diff --git a/backend/internal/repository/email_cache_atomic_test.go b/backend/internal/repository/email_cache_atomic_test.go
new file mode 100644
index 000000000..dd7374eb8
--- /dev/null
+++ b/backend/internal/repository/email_cache_atomic_test.go
@@ -0,0 +1,150 @@
+package repository
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/alicebob/miniredis/v2"
+ "github.com/redis/go-redis/v9"
+ "github.com/stretchr/testify/require"
+)
+
+func newMiniredisEmailCache(t *testing.T) (service.EmailCache, *miniredis.Miniredis, *redis.Client) {
+ t.Helper()
+ mr := miniredis.RunT(t)
+ rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
+ t.Cleanup(func() { _ = rdb.Close() })
+ return NewEmailCache(rdb), mr, rdb
+}
+
+func TestEmailCache_ConcurrentWrongCodesCannotExceedAttemptCap(t *testing.T) {
+ cache, _, _ := newMiniredisEmailCache(t)
+ ctx := context.Background()
+ email := "user@example.com"
+
+ svc := service.NewEmailService(nil, cache)
+ require.NoError(t, cache.SetVerificationCode(ctx, email, &service.VerificationCodeData{
+ Code: "123456",
+ CreatedAt: time.Now(),
+ ExpiresAt: time.Now().Add(15 * time.Minute),
+ }, 15*time.Minute))
+
+ const workers = 50
+ var invalid, maxed atomic.Int32
+ var wg sync.WaitGroup
+ for i := 0; i < workers; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ err := svc.VerifyCode(ctx, email, "000000")
+ switch {
+ case errors.Is(err, service.ErrInvalidVerifyCode):
+ invalid.Add(1)
+ case errors.Is(err, service.ErrVerifyCodeMaxAttempts):
+ maxed.Add(1)
+ default:
+ t.Errorf("unexpected result: %v", err)
+ }
+ }()
+ }
+ wg.Wait()
+
+ // Only attempts 1..4 may return "invalid"; every other guess is rejected by the cap.
+ require.LessOrEqual(t, int(invalid.Load()), 4)
+ require.Equal(t, workers, int(invalid.Load()+maxed.Load()))
+
+ // Even the correct code is now rejected.
+ require.ErrorIs(t, svc.VerifyCode(ctx, email, "123456"), service.ErrVerifyCodeMaxAttempts)
+
+ data, err := cache.GetVerificationCode(ctx, email)
+ require.NoError(t, err)
+ require.GreaterOrEqual(t, data.Attempts, 5)
+}
+
+func TestEmailCache_AttemptsResetOnNewCodeAndTTLFollowsCode(t *testing.T) {
+ cache, mr, _ := newMiniredisEmailCache(t)
+ ctx := context.Background()
+ email := "User@Example.com"
+
+ require.NoError(t, cache.SetVerificationCode(ctx, email, &service.VerificationCodeData{Code: "1"}, time.Minute))
+ n, err := cache.IncrVerificationCodeAttempts(ctx, email)
+ require.NoError(t, err)
+ require.Equal(t, 1, n)
+ require.Greater(t, mr.TTL(verifyCodeKey(email)+attemptsKeySuffix), time.Duration(0))
+
+ require.NoError(t, cache.SetVerificationCode(ctx, email, &service.VerificationCodeData{Code: "2"}, time.Minute))
+ data, err := cache.GetVerificationCode(ctx, email)
+ require.NoError(t, err)
+ require.Equal(t, 0, data.Attempts)
+
+ require.NoError(t, cache.DeleteVerificationCode(ctx, email))
+ _, err = cache.IncrVerificationCodeAttempts(ctx, email)
+ require.Error(t, err)
+ require.False(t, mr.Exists(verifyCodeKey(email)+attemptsKeySuffix))
+}
+
+func TestEmailCache_PasswordResetTokenHashedAndSingleUse(t *testing.T) {
+ cache, mr, _ := newMiniredisEmailCache(t)
+ ctx := context.Background()
+ email := "reset@example.com"
+
+ svc := service.NewEmailService(nil, cache)
+
+ // Seed the token the same way SendPasswordResetEmail does (hash only).
+ token, err := svc.GeneratePasswordResetToken()
+ require.NoError(t, err)
+ sum := sha256.Sum256([]byte(token))
+ require.NoError(t, cache.SetPasswordResetToken(ctx, email, &service.PasswordResetTokenData{
+ Token: hex.EncodeToString(sum[:]), CreatedAt: time.Now(),
+ }, 30*time.Minute))
+
+ raw, err := mr.Get(passwordResetKey(email))
+ require.NoError(t, err)
+ require.False(t, strings.Contains(raw, token), "plaintext token must not be stored")
+
+ require.NoError(t, svc.VerifyPasswordResetToken(ctx, email, token))
+ require.ErrorIs(t, svc.ConsumePasswordResetToken(ctx, email, "wrong"), service.ErrInvalidResetToken)
+
+ const workers = 30
+ var ok atomic.Int32
+ var wg sync.WaitGroup
+ for i := 0; i < workers; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if svc.ConsumePasswordResetToken(ctx, email, token) == nil {
+ ok.Add(1)
+ }
+ }()
+ }
+ wg.Wait()
+ require.Equal(t, int32(1), ok.Load())
+ require.False(t, mr.Exists(passwordResetKey(email)))
+}
+
+func TestEmailCache_ConsumePasswordResetTokenMismatchKeepsToken(t *testing.T) {
+ cache, mr, _ := newMiniredisEmailCache(t)
+ ctx := context.Background()
+ email := "keep@example.com"
+ require.NoError(t, cache.SetPasswordResetToken(ctx, email, &service.PasswordResetTokenData{Token: "abc"}, time.Minute))
+
+ ok, err := cache.ConsumePasswordResetToken(ctx, email, "xyz")
+ require.NoError(t, err)
+ require.False(t, ok)
+ require.True(t, mr.Exists(passwordResetKey(email)))
+
+ ok, err = cache.ConsumePasswordResetToken(ctx, email, "abc")
+ require.NoError(t, err)
+ require.True(t, ok)
+ ok, err = cache.ConsumePasswordResetToken(ctx, email, "abc")
+ require.NoError(t, err)
+ require.False(t, ok)
+}
diff --git a/backend/internal/repository/http_upstream.go b/backend/internal/repository/http_upstream.go
index edd192b69..5eda7fd2e 100644
--- a/backend/internal/repository/http_upstream.go
+++ b/backend/internal/repository/http_upstream.go
@@ -467,6 +467,8 @@ func newGrokOfficialAPIFallbackRequest(req *http.Request) (*http.Request, error)
for _, header := range []string{
"X-XAI-Token-Auth",
"X-Grok-Client-Version",
+ "X-Grok-Client-Mode",
+ "X-Authenticateresponse",
"X-Grok-Client-Surface",
"X-UserID",
"X-Email",
@@ -532,6 +534,8 @@ func applyGrokCLIProxyHeaders(req *http.Request) {
req.Header.Set("X-XAI-Token-Auth", xai.CLITokenAuth)
req.Header.Set("x-grok-client-version", version)
req.Header.Set("x-grok-client-identifier", xai.CLIClientIdentifier)
+ req.Header.Set("x-grok-client-mode", xai.CLIClientMode)
+ req.Header.Set("x-authenticateresponse", "authenticate-response")
req.Header.Set("User-Agent", xai.CLIUserAgent(version))
}
diff --git a/backend/internal/repository/http_upstream_test.go b/backend/internal/repository/http_upstream_test.go
index f27abfb45..b625be4d7 100644
--- a/backend/internal/repository/http_upstream_test.go
+++ b/backend/internal/repository/http_upstream_test.go
@@ -237,6 +237,10 @@ func TestHTTPUpstreamDoAppliesGrokCLIIdentityBeforeOAuthRoundTrip(t *testing.T)
require.NoError(t, resp.Body.Close())
require.Equal(t, xai.CLIClientVersion, capturedHeaders.Get("x-grok-client-version"))
+ require.Equal(t, "1.0.46", capturedHeaders.Get("x-grok-client-version"))
+ require.Equal(t, "grok-pager", capturedHeaders.Get("x-grok-client-identifier"))
+ require.Equal(t, "interactive", capturedHeaders.Get("x-grok-client-mode"))
+ require.Equal(t, "authenticate-response", capturedHeaders.Get("x-authenticateresponse"))
require.Equal(t, "xai-grok-cli", capturedHeaders.Get("X-XAI-Token-Auth"))
require.Equal(t, xai.CLIUserAgent(xai.CLIClientVersion), capturedHeaders.Get("User-Agent"))
})
@@ -309,6 +313,8 @@ func TestHTTPUpstreamDoFallsBackToOfficialGrokAPIOnCLIAccessDenied(t *testing.T)
require.Equal(t, "Bearer oauth-token", fallbackHeaders.Get("Authorization"))
require.Empty(t, fallbackHeaders.Get("X-XAI-Token-Auth"))
require.Empty(t, fallbackHeaders.Get("x-grok-client-version"))
+ require.Empty(t, fallbackHeaders.Get("x-grok-client-mode"))
+ require.Empty(t, fallbackHeaders.Get("x-authenticateresponse"))
require.Empty(t, fallbackHeaders.Get("User-Agent"))
}
@@ -465,18 +471,18 @@ func TestApplyGrokCLIProxyHeaders(t *testing.T) {
})
t.Run("accepts a valid operator override", func(t *testing.T) {
- t.Setenv("XAI_GROK_CLI_VERSION", "0.2.121-alpha.1")
+ t.Setenv("XAI_GROK_CLI_VERSION", "1.0.47-alpha.1")
req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/chat/completions", nil)
require.NoError(t, err)
applyGrokCLIProxyHeaders(req)
- require.Equal(t, "0.2.121-alpha.1", req.Header.Get("x-grok-client-version"))
- require.Equal(t, xai.CLIUserAgent("0.2.121-alpha.1"), req.Header.Get("User-Agent"))
+ require.Equal(t, "1.0.47-alpha.1", req.Header.Get("x-grok-client-version"))
+ require.Equal(t, xai.CLIUserAgent("1.0.47-alpha.1"), req.Header.Get("User-Agent"))
})
t.Run("rejects an unsafe override", func(t *testing.T) {
- t.Setenv("XAI_GROK_CLI_VERSION", "0.2.121\r\nX-Injected: true")
+ t.Setenv("XAI_GROK_CLI_VERSION", "1.0.47\r\nX-Injected: true")
req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil)
require.NoError(t, err)
@@ -487,7 +493,7 @@ func TestApplyGrokCLIProxyHeaders(t *testing.T) {
})
t.Run("rejects an override below the supported minimum", func(t *testing.T) {
- t.Setenv("XAI_GROK_CLI_VERSION", "0.2.119")
+ t.Setenv("XAI_GROK_CLI_VERSION", "1.0.45")
req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil)
require.NoError(t, err)
@@ -498,7 +504,7 @@ func TestApplyGrokCLIProxyHeaders(t *testing.T) {
})
t.Run("rejects a prerelease override at the minimum version", func(t *testing.T) {
- t.Setenv("XAI_GROK_CLI_VERSION", "0.2.120-beta.1")
+ t.Setenv("XAI_GROK_CLI_VERSION", "1.0.46-beta.1")
req, err := http.NewRequest(http.MethodPost, "https://cli-chat-proxy.grok.com/v1/responses", nil)
require.NoError(t, err)
@@ -511,11 +517,11 @@ func TestApplyGrokCLIProxyHeaders(t *testing.T) {
// Every entry sits above the pinned minimum, so a rejection here can only be
// caused by the malformed semver and never by the version being too old.
for _, version := range []string{
- "0.2.0121",
- "0.2.121-alpha..1",
- "0.3",
- "1",
- "0.2.121+build.1",
+ "1.0.047",
+ "1.0.47-alpha..1",
+ "1.1",
+ "2",
+ "1.0.47+build.1",
} {
t.Run("rejects invalid semver "+version, func(t *testing.T) {
t.Setenv("XAI_GROK_CLI_VERSION", version)
@@ -530,7 +536,7 @@ func TestApplyGrokCLIProxyHeaders(t *testing.T) {
}
t.Run("leaves direct xAI API requests unchanged", func(t *testing.T) {
- t.Setenv("XAI_GROK_CLI_VERSION", "0.2.95")
+ t.Setenv("XAI_GROK_CLI_VERSION", "1.0.47")
req, err := http.NewRequest(http.MethodPost, "https://api.x.ai/v1/responses", nil)
require.NoError(t, err)
req.Header.Set("User-Agent", "direct-api-client/1.0")
diff --git a/backend/internal/repository/ops_repo_dashboard.go b/backend/internal/repository/ops_repo_dashboard.go
index 009a265dd..72743611d 100644
--- a/backend/internal/repository/ops_repo_dashboard.go
+++ b/backend/internal/repository/ops_repo_dashboard.go
@@ -33,18 +33,63 @@ func (r *opsRepository) GetDashboardOverview(ctx context.Context, filter *servic
mode = service.OpsQueryModeRaw
}
+ var overview *service.OpsDashboardOverview
+ var err error
switch mode {
case service.OpsQueryModePreagg:
- return r.getDashboardOverviewPreaggregated(ctx, filter)
+ overview, err = r.getDashboardOverviewPreaggregated(ctx, filter)
case service.OpsQueryModeAuto:
- out, err := r.getDashboardOverviewPreaggregated(ctx, filter)
- if err != nil && errors.Is(err, service.ErrOpsPreaggregatedNotPopulated) {
- return r.getDashboardOverviewRaw(ctx, filter)
+ overview, err = r.getDashboardOverviewPreaggregated(ctx, filter)
+ if errors.Is(err, service.ErrOpsPreaggregatedNotPopulated) {
+ overview, err = r.getDashboardOverviewRaw(ctx, filter)
}
- return out, err
default:
- return r.getDashboardOverviewRaw(ctx, filter)
+ overview, err = r.getDashboardOverviewRaw(ctx, filter)
+ }
+ if err != nil {
+ return nil, err
+ }
+ // Percentiles must use individual rates over the entire window, even in
+ // preagg mode: hourly percentiles cannot be averaged into window percentiles.
+ rateCtx, cancelRate := context.WithTimeout(ctx, opsRawLatencyQueryTimeout)
+ defer cancelRate()
+ overview.OutputTPS, err = r.queryOutputTPS(rateCtx, filter)
+ if err != nil && !isQueryTimeoutErr(err) {
+ return nil, err
+ }
+ return overview, nil
+}
+
+func (r *opsRepository) queryOutputTPS(ctx context.Context, filter *service.OpsDashboardFilter) (*service.OpsOutputTPS, error) {
+ join, where, args, _ := buildUsageWhere(filter, filter.StartTime.UTC(), filter.EndTime.UTC(), 1)
+ query := `
+SELECT
+ percentile_cont(0.05) WITHIN GROUP (ORDER BY output_tps),
+ percentile_cont(0.10) WITHIN GROUP (ORDER BY output_tps),
+ percentile_cont(0.50) WITHIN GROUP (ORDER BY output_tps),
+ AVG(output_tps),
+ COUNT(*)
+FROM (
+ SELECT ul.output_tokens * 1000.0 / NULLIF(ul.duration_ms, 0) AS output_tps
+ FROM usage_logs ul
+ ` + join + `
+ ` + where + `
+ AND ul.output_tokens > 0 AND ul.duration_ms > 0
+ AND ul.image_count = 0 AND ul.image_output_tokens = 0
+ AND COALESCE(ul.billing_mode, '') <> 'image'
+ ` + fmt.Sprintf("AND ul.request_type IN (%d, %d, %d, %d)",
+ service.RequestTypeSync, service.RequestTypeStream, service.RequestTypeWSV2, service.RequestTypeCyberBlocked) + `
+) rates`
+ var stats service.OpsOutputTPS
+ if err := r.db.QueryRowContext(ctx, query, args...).Scan(&stats.P5, &stats.P10, &stats.P50, &stats.Avg, &stats.SampleCount); err != nil {
+ // lib/pq reports query cancellation without wrapping the context error.
+ // Preserve deadline vs caller cancellation for the overview's timeout policy.
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return nil, ctxErr
+ }
+ return nil, err
}
+ return &stats, nil
}
func (r *opsRepository) getDashboardOverviewRaw(ctx context.Context, filter *service.OpsDashboardFilter) (*service.OpsDashboardOverview, error) {
diff --git a/backend/internal/repository/ops_repo_dashboard_integration_test.go b/backend/internal/repository/ops_repo_dashboard_integration_test.go
new file mode 100644
index 000000000..9406343b6
--- /dev/null
+++ b/backend/internal/repository/ops_repo_dashboard_integration_test.go
@@ -0,0 +1,124 @@
+//go:build integration
+
+package repository
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/stretchr/testify/require"
+)
+
+func TestOpsOutputTPSDistribution(t *testing.T) {
+ ctx := context.Background()
+ client := testEntClient(t)
+ user := mustCreateUser(t, client, &service.User{})
+ key := mustCreateApiKey(t, client, &service.APIKey{UserID: user.ID})
+ account := mustCreateAccount(t, client, &service.Account{Name: "output-tps", Platform: service.PlatformAnthropic})
+ group := mustCreateGroup(t, client, &service.Group{Name: "output-tps", Platform: service.PlatformOpenAI})
+ otherGroup := mustCreateGroup(t, client, &service.Group{Name: "other-output-tps", Platform: service.PlatformOpenAI})
+ start := time.Date(2021, 1, 17, 0, 30, 0, 0, time.UTC)
+ end := start.Add(6 * time.Hour)
+ t.Cleanup(func() {
+ _, _ = integrationDB.ExecContext(ctx, "DELETE FROM usage_logs WHERE user_id = $1", user.ID)
+ _, _ = integrationDB.ExecContext(ctx, "DELETE FROM api_keys WHERE id = $1", key.ID)
+ _, _ = integrationDB.ExecContext(ctx, "DELETE FROM accounts WHERE id = $1", account.ID)
+ _, _ = integrationDB.ExecContext(ctx, "DELETE FROM ops_metrics_hourly WHERE bucket_start >= $1 AND bucket_start < $2", start.Truncate(time.Hour), end)
+ _, _ = integrationDB.ExecContext(ctx, "DELETE FROM groups WHERE id IN ($1, $2)", group.ID, otherGroup.ID)
+ _, _ = integrationDB.ExecContext(ctx, "DELETE FROM users WHERE id = $1", user.ID)
+ })
+ insert := func(at time.Time, groupID *int64, output int, duration *int, requestType service.RequestType, imageCount, imageTokens int, billingMode string) {
+ t.Helper()
+ _, err := integrationDB.ExecContext(ctx, `INSERT INTO usage_logs
+ (user_id, api_key_id, account_id, group_id, request_id, model, input_tokens, output_tokens, duration_ms, request_type, image_count, image_output_tokens, billing_mode, created_at, image_size)
+ VALUES ($1,$2,$3,$4,$5,'gpt-test',100000,$6,$7,$8,$9,$10,$11,$12,CASE WHEN $9 > 0 THEN '1K' ELSE NULL END)`,
+ user.ID, key.ID, account.ID, groupID, fmt.Sprintf("output-tps-%d-%d", user.ID, time.Now().UnixNano()), output, duration, requestType, imageCount, imageTokens, billingMode, at)
+ require.NoError(t, err)
+ }
+ // Rates 1, 10, 100, 1000: unequal durations catch ratio-of-sums mistakes.
+ // Put samples in the raw head, stable hourly buckets, and raw tail.
+ for _, sample := range []struct {
+ output, duration int
+ kind service.RequestType
+ at time.Time
+ }{
+ {1, 1000, service.RequestTypeSync, start},
+ {20, 2000, service.RequestTypeStream, start.Add(time.Hour)},
+ {100, 1000, service.RequestTypeWSV2, start.Add(2 * time.Hour)},
+ {500, 500, service.RequestTypeCyberBlocked, end.Add(-time.Minute)},
+ } {
+ insert(sample.at, &group.ID, sample.output, &sample.duration, sample.kind, 0, 0, "token")
+ }
+ positive, zero, negative := 1000, 0, -1
+ for _, d := range []*int{nil, &zero, &negative} {
+ insert(start, &group.ID, 9999, d, service.RequestTypeSync, 0, 0, "token")
+ }
+ for _, n := range []int{0, -1} {
+ insert(start, &group.ID, n, &positive, service.RequestTypeSync, 0, 0, "token")
+ }
+ for _, kind := range []service.RequestType{service.RequestTypeLive, service.RequestTypeUnknown} {
+ insert(start, &group.ID, 9999, &positive, kind, 0, 0, "token")
+ }
+ insert(start, &group.ID, 9999, &positive, service.RequestTypeSync, 1, 0, "token")
+ insert(start, &group.ID, 9999, &positive, service.RequestTypeSync, 0, 1, "token")
+ insert(start, &group.ID, 9999, &positive, service.RequestTypeSync, 0, 0, "image")
+ insert(start.Add(-time.Second), &group.ID, 9999, &positive, service.RequestTypeSync, 0, 0, "token")
+ insert(end, &group.ID, 9999, &positive, service.RequestTypeSync, 0, 0, "token")
+ insert(start, &otherGroup.ID, 9999, &positive, service.RequestTypeSync, 0, 0, "token")
+ insert(start, nil, 50, &positive, service.RequestTypeSync, 0, 0, "token")
+ repo := NewOpsRepository(integrationDB).(*opsRepository)
+ filter := &service.OpsDashboardFilter{StartTime: start, EndTime: end, Platform: " OpenAI ", GroupID: &group.ID}
+ assertStats := func(stats *service.OpsOutputTPS) {
+ t.Helper()
+ require.NotNil(t, stats)
+ require.EqualValues(t, 4, stats.SampleCount)
+ require.NotNil(t, stats.P5)
+ require.NotNil(t, stats.P10)
+ require.NotNil(t, stats.P50)
+ require.NotNil(t, stats.Avg)
+ require.InDelta(t, 2.35, *stats.P5, 1e-9)
+ require.InDelta(t, 3.7, *stats.P10, 1e-9)
+ require.InDelta(t, 55, *stats.P50, 1e-9)
+ require.InDelta(t, 277.75, *stats.Avg, 1e-9)
+ }
+ // Auto first exercises fallback before hourly rows exist.
+ for _, mode := range []service.OpsQueryMode{service.OpsQueryModeRaw, service.OpsQueryModeAuto} {
+ filter.QueryMode = mode
+ overview, err := repo.GetDashboardOverview(ctx, filter)
+ require.NoError(t, err)
+ assertStats(overview.OutputTPS)
+ }
+ require.NoError(t, repo.UpsertHourlyMetrics(ctx, start.Truncate(time.Hour), end))
+ for _, mode := range []service.OpsQueryMode{service.OpsQueryModePreagg, service.OpsQueryModeAuto} {
+ filter.QueryMode = mode
+ overview, err := repo.GetDashboardOverview(ctx, filter)
+ require.NoError(t, err)
+ assertStats(overview.OutputTPS)
+ }
+ filter.Platform = service.PlatformAnthropic
+ empty, err := repo.queryOutputTPS(ctx, filter)
+ require.NoError(t, err)
+ require.Equal(t, &service.OpsOutputTPS{}, empty)
+ // Ungrouped logs use the account platform; group platform takes precedence.
+ filter.GroupID = nil
+ fallback, err := repo.queryOutputTPS(ctx, filter)
+ require.NoError(t, err)
+ require.EqualValues(t, 1, fallback.SampleCount)
+ require.Equal(t, 50.0, *fallback.P50)
+}
+
+func TestOpsOutputTPSQueryDeadline(t *testing.T) {
+ tx := testTx(t)
+ _, err := tx.ExecContext(context.Background(), "LOCK TABLE usage_logs IN ACCESS EXCLUSIVE MODE")
+ require.NoError(t, err)
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ repo := NewOpsRepository(integrationDB).(*opsRepository)
+ now := time.Now().UTC()
+ stats, err := repo.queryOutputTPS(ctx, &service.OpsDashboardFilter{StartTime: now.Add(-time.Hour), EndTime: now})
+ require.ErrorIs(t, err, context.DeadlineExceeded)
+ require.Nil(t, stats)
+}
diff --git a/backend/internal/repository/ops_repo_dashboard_timeout_test.go b/backend/internal/repository/ops_repo_dashboard_timeout_test.go
index 76332ca0a..170c09c59 100644
--- a/backend/internal/repository/ops_repo_dashboard_timeout_test.go
+++ b/backend/internal/repository/ops_repo_dashboard_timeout_test.go
@@ -2,8 +2,15 @@ package repository
import (
"context"
+ "database/sql/driver"
+ "errors"
"fmt"
"testing"
+ "time"
+
+ "github.com/DATA-DOG/go-sqlmock"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/stretchr/testify/require"
)
func TestIsQueryTimeoutErr(t *testing.T) {
@@ -20,3 +27,42 @@ func TestIsQueryTimeoutErr(t *testing.T) {
t.Fatalf("wrapped context.Canceled should not be treated as query timeout")
}
}
+
+func TestOpsOutputTPSOverviewFailurePolicy(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ err error
+ wantError bool
+ }{
+ {"timeout keeps overview", context.DeadlineExceeded, false},
+ {"cancellation propagates", context.Canceled, true},
+ {"database errors propagate", errors.New("database unavailable"), true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ db, mock := newSQLMock(t)
+ repo := &opsRepository{db: db}
+ // The six existing raw overview queries run before the output-rate query.
+ for _, count := range []int{2, 13, 6, 2, 6, 2} {
+ columns := make([]string, count)
+ values := make([]driver.Value, count)
+ for i := range columns {
+ columns[i] = fmt.Sprint(i)
+ values[i] = int64(0)
+ }
+ mock.ExpectQuery("SELECT|WITH").WillReturnRows(sqlmock.NewRows(columns).AddRow(values...))
+ }
+ mock.ExpectQuery(`percentile_cont\(0.05\)`).WillReturnError(tc.err)
+ start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
+ overview, err := repo.GetDashboardOverview(context.Background(), &service.OpsDashboardFilter{StartTime: start, EndTime: start.Add(time.Hour), QueryMode: service.OpsQueryModeRaw})
+ if tc.wantError {
+ require.ErrorIs(t, err, tc.err)
+ require.Nil(t, overview)
+ } else {
+ require.NoError(t, err)
+ require.NotNil(t, overview)
+ require.Nil(t, overview.OutputTPS)
+ }
+ require.NoError(t, mock.ExpectationsWereMet())
+ })
+ }
+}
diff --git a/backend/internal/repository/platform_list_db_integration_test.go b/backend/internal/repository/platform_list_db_integration_test.go
new file mode 100644
index 000000000..d0ba5d16f
--- /dev/null
+++ b/backend/internal/repository/platform_list_db_integration_test.go
@@ -0,0 +1,143 @@
+//go:build integration
+
+package repository
+
+import (
+ "context"
+ "testing"
+
+ dbent "github.com/MACOS-DO/sub4api/ent"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ dbmigrations "github.com/MACOS-DO/sub4api/migrations"
+ "github.com/stretchr/testify/require"
+)
+
+func platformConstraintExists(t *testing.T, ctx context.Context, client *dbent.Client, table, constraint string) bool {
+ t.Helper()
+ rows, err := client.QueryContext(ctx, `
+SELECT 1
+FROM pg_constraint c
+JOIN pg_class tbl ON tbl.oid = c.conrelid
+JOIN pg_namespace ns ON ns.oid = tbl.relnamespace
+WHERE ns.nspname = 'public' AND tbl.relname = $1 AND c.conname = $2`, table, constraint)
+ require.NoError(t, err)
+ defer func() { _ = rows.Close() }()
+ exists := rows.Next()
+ require.NoError(t, rows.Err())
+ return exists
+}
+
+// 迁移 242 删除平台白名单 CHECK 约束:旧库(约束仍在)上可重复执行,执行后
+// 新登记的平台无需再做数据库迁移即可写入。
+func TestMigration242DropsPlatformCheckConstraints(t *testing.T) {
+ ctx := context.Background()
+ tx := testEntTx(t)
+ client := tx.Client()
+
+ // 还原迁移 241_add_typesafe_platform 之后、242 之前的约束状态。
+ for _, stmt := range []string{
+ `ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check`,
+ `ALTER TABLE user_platform_quotas ADD CONSTRAINT user_platform_quotas_platform_check
+ CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok',
+ 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))`,
+ `ALTER TABLE composite_model_routes DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check`,
+ `ALTER TABLE composite_model_routes ADD CONSTRAINT composite_model_routes_target_platform_check
+ CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok',
+ 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))`,
+ } {
+ _, err := client.ExecContext(ctx, stmt)
+ require.NoError(t, err)
+ }
+ require.True(t, platformConstraintExists(t, ctx, client, "user_platform_quotas", "user_platform_quotas_platform_check"))
+ require.True(t, platformConstraintExists(t, ctx, client, "composite_model_routes", "composite_model_routes_target_platform_check"))
+
+ migrationSQL, err := dbmigrations.FS.ReadFile("242_drop_platform_check_constraints.sql")
+ require.NoError(t, err)
+ for range 2 {
+ _, err = client.ExecContext(ctx, string(migrationSQL))
+ require.NoError(t, err)
+ }
+ require.False(t, platformConstraintExists(t, ctx, client, "user_platform_quotas", "user_platform_quotas_platform_check"))
+ require.False(t, platformConstraintExists(t, ctx, client, "composite_model_routes", "composite_model_routes_target_platform_check"))
+ // 渠道监控的 provider 约束表示探测能力,保留。
+ require.True(t, platformConstraintExists(t, ctx, client, "channel_monitors", "channel_monitors_provider_check"))
+ require.True(t, platformConstraintExists(t, ctx, client, "channel_monitor_request_templates", "channel_monitor_request_templates_provider_check"))
+
+ // 数据库层不再限制平台取值:模拟未来新登记的平台。
+ userID := mustCreateUserForQuota(t, client)
+ _, err = client.ExecContext(ctx, `
+INSERT INTO user_platform_quotas (user_id, platform, daily_limit_usd, daily_usage_usd, weekly_usage_usd, monthly_usage_usd, created_at, updated_at)
+VALUES ($1, 'future_platform', 1, 0, 0, 0, NOW(), NOW())`, userID)
+ require.NoError(t, err)
+ group := mustCreateGroup(t, client, &service.Group{Name: "platform-list-composite", Platform: service.PlatformComposite})
+ _, err = client.ExecContext(ctx, `
+INSERT INTO composite_model_routes (group_id, public_model, target_platform)
+VALUES ($1, 'future-model', 'future_platform')`, group.ID)
+ require.NoError(t, err)
+}
+
+// 删除 CHECK 约束后,平台合法性由应用层保证:原生 SQL 写入前的 repository 校验。
+func TestUserPlatformQuotaRepository_RejectsUnregisteredPlatform(t *testing.T) {
+ ctx := context.Background()
+ tx := testEntTx(t)
+ txCtx := dbent.NewTxContext(ctx, tx)
+ client := tx.Client()
+
+ userID := mustCreateUserForQuota(t, client)
+ repo := NewUserPlatformQuotaRepository(client)
+ daily := 5.0
+ require.NoError(t, repo.UpsertForUser(txCtx, userID, []UserPlatformQuotaRecord{
+ {UserID: userID, Platform: service.PlatformOpenCodeGo, DailyLimitUSD: &daily},
+ }))
+
+ for _, platform := range []string{"bogus", "moonshot", "Kimi", service.PlatformComposite} {
+ err := repo.BulkInsertInitial(txCtx, []UserPlatformQuotaRecord{
+ {UserID: userID, Platform: service.PlatformAnthropic, DailyLimitUSD: &daily},
+ {UserID: userID, Platform: platform, DailyLimitUSD: &daily},
+ })
+ require.ErrorContains(t, err, "is not allowed", platform)
+ err = repo.UpsertForUser(txCtx, userID, []UserPlatformQuotaRecord{
+ {UserID: userID, Platform: platform, DailyLimitUSD: &daily},
+ })
+ require.ErrorContains(t, err, "is not allowed", platform)
+ }
+
+ // 被拒绝的写入不产生任何副作用:既有记录保留、未新增任何行。
+ got, err := repo.ListByUser(txCtx, userID)
+ require.NoError(t, err)
+ require.Len(t, got, 1)
+ require.Equal(t, service.PlatformOpenCodeGo, got[0].Platform)
+
+ // 三档全空的记录不写入,也不参与校验(与既有 configuredRecords 语义一致)。
+ require.NoError(t, repo.BulkInsertInitial(txCtx, []UserPlatformQuotaRecord{{UserID: userID, Platform: "bogus"}}))
+}
+
+func TestCompositeModelRouteRepository_RejectsUnregisteredTargetPlatform(t *testing.T) {
+ ctx := context.Background()
+ tx := testEntTx(t)
+ txCtx := dbent.NewTxContext(ctx, tx)
+ client := tx.Client()
+
+ group := mustCreateGroup(t, client, &service.Group{Name: "platform-list-routes", Platform: service.PlatformComposite})
+ repo := NewCompositeModelRouteRepository(client)
+
+ route := &service.CompositeModelRoute{
+ GroupID: group.ID, PublicModel: "glm-5", MatchType: "exact", TargetPlatform: service.PlatformZhipu,
+ UpstreamModel: "glm-5", Endpoint: "any", Priority: 100, Enabled: true,
+ }
+ require.NoError(t, repo.Create(txCtx, route))
+
+ bad := &service.CompositeModelRoute{
+ GroupID: group.ID, PublicModel: "bogus-model", MatchType: "exact", TargetPlatform: "bogus",
+ UpstreamModel: "bogus-model", Endpoint: "any", Priority: 100, Enabled: true,
+ }
+ require.Error(t, repo.Create(txCtx, bad))
+
+ route.TargetPlatform = service.PlatformComposite
+ require.Error(t, repo.Update(txCtx, route))
+
+ routes, err := repo.ListByGroup(txCtx, group.ID, true)
+ require.NoError(t, err)
+ require.Len(t, routes, 1)
+ require.Equal(t, service.PlatformZhipu, routes[0].TargetPlatform)
+}
diff --git a/backend/internal/repository/usage_billing_repo.go b/backend/internal/repository/usage_billing_repo.go
index 079ff0bab..8f5379fb8 100644
--- a/backend/internal/repository/usage_billing_repo.go
+++ b/backend/internal/repository/usage_billing_repo.go
@@ -187,16 +187,17 @@ func (r *usageBillingRepository) applyUsageBillingEffects(ctx context.Context, t
result.BalanceOverdrafted = !sufficient
}
+ // Key 已不存在时跳过其自身的额度/限速计数,其余结算项不受影响。
if cmd.APIKeyQuotaCost > 0 {
exhausted, err := incrementUsageBillingAPIKeyQuota(ctx, tx, cmd.APIKeyID, cmd.APIKeyQuotaCost)
- if err != nil {
+ if err != nil && !errors.Is(err, service.ErrAPIKeyNotFound) {
return err
}
result.APIKeyQuotaExhausted = exhausted
}
if cmd.APIKeyRateLimitCost > 0 {
- if err := incrementUsageBillingAPIKeyRateLimit(ctx, tx, cmd.APIKeyID, cmd.APIKeyRateLimitCost); err != nil {
+ if err := incrementUsageBillingAPIKeyRateLimit(ctx, tx, cmd.APIKeyID, cmd.APIKeyRateLimitCost); err != nil && !errors.Is(err, service.ErrAPIKeyNotFound) {
return err
}
}
diff --git a/backend/internal/repository/usage_billing_repo_integration_test.go b/backend/internal/repository/usage_billing_repo_integration_test.go
index bfc2873a0..54a0b3e41 100644
--- a/backend/internal/repository/usage_billing_repo_integration_test.go
+++ b/backend/internal/repository/usage_billing_repo_integration_test.go
@@ -162,6 +162,61 @@ func TestUsageBillingRepositoryApply_RequestFingerprintConflict(t *testing.T) {
require.ErrorIs(t, err, service.ErrUsageBillingRequestConflict)
}
+func TestUsageBillingRepositoryApply_DeletedAPIKeyStillBillsBalance(t *testing.T) {
+ ctx := context.Background()
+ client := testEntClient(t)
+ repo := NewUsageBillingRepository(client, integrationDB)
+
+ user := mustCreateUser(t, client, &service.User{
+ Email: fmt.Sprintf("usage-billing-deleted-key-user-%d@example.com", time.Now().UnixNano()),
+ PasswordHash: "hash",
+ Balance: 100,
+ })
+ apiKey := mustCreateApiKey(t, client, &service.APIKey{
+ UserID: user.ID,
+ Key: "sk-usage-billing-deleted-key-" + uuid.NewString(),
+ Name: "billing-deleted-key",
+ Quota: 50,
+ RateLimit5h: 50,
+ })
+ account := mustCreateAccount(t, client, &service.Account{
+ Name: "usage-billing-deleted-key-account-" + uuid.NewString(),
+ Type: service.AccountTypeAPIKey,
+ })
+
+ _, err := integrationDB.ExecContext(ctx, "UPDATE api_keys SET deleted_at = NOW() WHERE id = $1", apiKey.ID)
+ require.NoError(t, err)
+
+ requestID := uuid.NewString()
+ result, err := repo.Apply(ctx, &service.UsageBillingCommand{
+ RequestID: requestID,
+ APIKeyID: apiKey.ID,
+ UserID: user.ID,
+ AccountID: account.ID,
+ AccountType: service.AccountTypeAPIKey,
+ BalanceCost: 1.25,
+ APIKeyQuotaCost: 1.25,
+ APIKeyRateLimitCost: 1.25,
+ })
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.True(t, result.Applied)
+ require.False(t, result.APIKeyQuotaExhausted)
+
+ var balance float64
+ require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT balance FROM users WHERE id = $1", user.ID).Scan(&balance))
+ require.InDelta(t, 98.75, balance, 0.000001)
+
+ var quotaUsed, usage5h float64
+ require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT quota_used, usage_5h FROM api_keys WHERE id = $1", apiKey.ID).Scan("aUsed, &usage5h))
+ require.InDelta(t, 0, quotaUsed, 0.000001)
+ require.InDelta(t, 0, usage5h, 0.000001)
+
+ var dedupCount int
+ require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_billing_dedup WHERE request_id = $1 AND api_key_id = $2", requestID, apiKey.ID).Scan(&dedupCount))
+ require.Equal(t, 1, dedupCount)
+}
+
func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) {
ctx := context.Background()
client := testEntClient(t)
diff --git a/backend/internal/repository/usage_billing_repo_unit_test.go b/backend/internal/repository/usage_billing_repo_unit_test.go
index 610f84b03..8e0f3a6cf 100644
--- a/backend/internal/repository/usage_billing_repo_unit_test.go
+++ b/backend/internal/repository/usage_billing_repo_unit_test.go
@@ -20,6 +20,8 @@ const (
captureBatchImageHoldSQL = `(?s)UPDATE users\s+SET balance = balance\s+\+ CASE WHEN \$1 > \$2 THEN \$1 - \$2 ELSE 0 END\s+- CASE WHEN \$2 > \$1 THEN \$2 - \$1 ELSE 0 END,\s+frozen_balance = COALESCE\(frozen_balance, 0\) - \$1,\s+updated_at = NOW\(\)\s+WHERE id = \$3 AND deleted_at IS NULL AND COALESCE\(frozen_balance, 0\) >= \$1\s+RETURNING balance, frozen_balance`
releaseBatchImageHoldSQL = `(?s)UPDATE users\s+SET balance = balance \+ \$1,\s+frozen_balance = COALESCE\(frozen_balance, 0\) - \$1,\s+updated_at = NOW\(\)\s+WHERE id = \$2 AND deleted_at IS NULL AND COALESCE\(frozen_balance, 0\) >= \$1\s+RETURNING balance, frozen_balance`
userExistsForBillingSQL = `(?s)SELECT 1\s+FROM users\s+WHERE id = \$1 AND deleted_at IS NULL`
+ apiKeyQuotaIncrementSQL = `(?s)UPDATE api_keys\s+SET quota_used = quota_used \+ \$1,.*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING`
+ apiKeyRateLimitIncrementSQL = `(?s)UPDATE api_keys SET\s+usage_5h = .*WHERE id = \$2 AND deleted_at IS NULL`
)
func TestDeductUsageBillingBalance_UsesSufficientBalanceGuard(t *testing.T) {
@@ -99,6 +101,66 @@ func TestApplyUsageBillingEffects_FlagsBalanceOverdraft(t *testing.T) {
require.NoError(t, mock.ExpectationsWereMet())
}
+func TestApplyUsageBillingEffects_DeletedAPIKeyStillBillsBalance(t *testing.T) {
+ ctx := context.Background()
+ db, mock, err := sqlmock.New()
+ require.NoError(t, err)
+ defer func() { _ = db.Close() }()
+
+ mock.ExpectBegin()
+ tx, err := db.BeginTx(ctx, nil)
+ require.NoError(t, err)
+ mock.ExpectQuery(conditionalBalanceDeductSQL).
+ WithArgs(10.0, int64(42)).
+ WillReturnRows(sqlmock.NewRows([]string{"balance"}).AddRow(90.0))
+ mock.ExpectQuery(apiKeyQuotaIncrementSQL).
+ WithArgs(10.0, int64(7), service.StatusAPIKeyActive, service.StatusAPIKeyQuotaExhausted).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectExec(apiKeyRateLimitIncrementSQL).
+ WithArgs(10.0, int64(7)).
+ WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectCommit()
+
+ result := &service.UsageBillingApplyResult{Applied: true}
+ err = (&usageBillingRepository{}).applyUsageBillingEffects(ctx, tx, &service.UsageBillingCommand{
+ UserID: 42,
+ APIKeyID: 7,
+ BalanceCost: 10,
+ APIKeyQuotaCost: 10,
+ APIKeyRateLimitCost: 10,
+ }, result)
+ require.NoError(t, err)
+ require.NotNil(t, result.NewBalance)
+ require.InDelta(t, 90.0, *result.NewBalance, 0.000001)
+ require.False(t, result.APIKeyQuotaExhausted)
+ require.NoError(t, tx.Commit())
+ require.NoError(t, mock.ExpectationsWereMet())
+}
+
+func TestApplyUsageBillingEffects_APIKeyCounterErrorStillFails(t *testing.T) {
+ ctx := context.Background()
+ db, mock, err := sqlmock.New()
+ require.NoError(t, err)
+ defer func() { _ = db.Close() }()
+
+ mock.ExpectBegin()
+ tx, err := db.BeginTx(ctx, nil)
+ require.NoError(t, err)
+ mock.ExpectExec(apiKeyRateLimitIncrementSQL).
+ WithArgs(10.0, int64(7)).
+ WillReturnError(sql.ErrConnDone)
+ mock.ExpectRollback()
+
+ err = (&usageBillingRepository{}).applyUsageBillingEffects(ctx, tx, &service.UsageBillingCommand{
+ UserID: 42,
+ APIKeyID: 7,
+ APIKeyRateLimitCost: 10,
+ }, &service.UsageBillingApplyResult{Applied: true})
+ require.ErrorIs(t, err, sql.ErrConnDone)
+ require.NoError(t, tx.Rollback())
+ require.NoError(t, mock.ExpectationsWereMet())
+}
+
func TestDeductUsageBillingBalance_ReturnsUserNotFoundWhenNoUserUpdated(t *testing.T) {
ctx := context.Background()
db, mock, err := sqlmock.New()
diff --git a/backend/internal/repository/user_platform_quota_repo.go b/backend/internal/repository/user_platform_quota_repo.go
index 47b754961..bf7d2aef1 100644
--- a/backend/internal/repository/user_platform_quota_repo.go
+++ b/backend/internal/repository/user_platform_quota_repo.go
@@ -9,6 +9,7 @@ import (
dbent "github.com/MACOS-DO/sub4api/ent"
"github.com/MACOS-DO/sub4api/ent/userplatformquota"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/timezone"
)
@@ -95,6 +96,9 @@ func (r *userPlatformQuotaRepository) BulkInsertInitial(ctx context.Context, rec
if len(records) == 0 {
return nil
}
+ if err := validateQuotaPlatforms(records); err != nil {
+ return err
+ }
client := clientFromContext(ctx, r.client)
@@ -318,6 +322,9 @@ func monthlyMaybeReset(prevUsage float64, prevStart *time.Time, cost float64, no
// 清空某平台的限额即软删该行并放弃其累计用量;之后再次配置限额会新建行、从新窗口起算。
func (r *userPlatformQuotaRepository) UpsertForUser(ctx context.Context, userID int64, records []UserPlatformQuotaRecord) error {
records = configuredRecords(records)
+ if err := validateQuotaPlatforms(records); err != nil {
+ return err
+ }
return r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error {
platforms := make([]string, 0, len(records))
for _, rec := range records {
@@ -484,6 +491,17 @@ func (r *userPlatformQuotaRepository) BatchSnapshotUsage(ctx context.Context, sn
return nil
}
+// validateQuotaPlatforms 在原生 SQL 写入前校验平台须为平台清单中的具体平台,
+// 取代迁移 242 删除的 user_platform_quotas_platform_check 约束(原生 SQL 不经过 ent Validate)。
+func validateQuotaPlatforms(records []UserPlatformQuotaRecord) error {
+ for _, rec := range records {
+ if !domain.IsConcretePlatform(rec.Platform) {
+ return fmt.Errorf("user_platform_quotas: platform %q is not allowed", rec.Platform)
+ }
+ }
+ return nil
+}
+
// configuredRecords 过滤出至少配置了一档限额的记录;三档全空的记录视为未配置。
func configuredRecords(records []UserPlatformQuotaRecord) []UserPlatformQuotaRecord {
out := make([]UserPlatformQuotaRecord, 0, len(records))
diff --git a/backend/internal/securityaudit/prompt_snapshot.go b/backend/internal/securityaudit/prompt_snapshot.go
index b47e84674..74a0d2597 100644
--- a/backend/internal/securityaudit/prompt_snapshot.go
+++ b/backend/internal/securityaudit/prompt_snapshot.go
@@ -106,6 +106,8 @@ func extractProtocolSegments(protocol string, document any) []promptSegment {
return append(extractInstructions(root["instructions"]), extractResponses(root["input"])...)
case "openai_images", "grok_media", "media", "images":
return userPromptSegments(extractMediaPrompts(root))
+ case "typesafe_systemone":
+ return extractSystemOneSegments(root)
default:
if segments := extractChatLikeSegments(root); len(segments) > 0 {
return segments
@@ -120,6 +122,79 @@ func extractProtocolSegments(protocol string, document any) []promptSegment {
}
}
+// extractSystemOneSegments collects every client-controlled text of a TypeSafe
+// System One request: question IDs, every question field except the validated
+// type, unknown top-level extension fields, and the evaluated state. Object keys
+// are text too (Jev reads the whole JSON), so they are collected with values.
+// The state comes last so it is the prioritized segment, and keys are visited
+// in sorted order to keep the prompt hash stable across requests.
+func extractSystemOneSegments(root map[string]any) []promptSegment {
+ if root == nil {
+ return nil
+ }
+ texts := make([]string, 0, 4)
+ questions, isObject := root["questions"].(map[string]any)
+ if !isObject {
+ texts = appendJSONStringLeaves(texts, root["questions"])
+ }
+ for _, id := range sortedJSONKeys(questions) {
+ texts = appendJSONStringLeaves(texts, id)
+ question, ok := questions[id].(map[string]any)
+ if !ok {
+ texts = appendJSONStringLeaves(texts, questions[id])
+ continue
+ }
+ for _, field := range sortedJSONKeys(question) {
+ switch field {
+ case "type":
+ continue
+ case "instructions", "criteria":
+ default:
+ texts = appendJSONStringLeaves(texts, field)
+ }
+ texts = appendJSONStringLeaves(texts, question[field])
+ }
+ }
+ for _, field := range sortedJSONKeys(root) {
+ switch field {
+ case "model", "stream", "state", "questions":
+ continue
+ }
+ texts = appendJSONStringLeaves(texts, field)
+ texts = appendJSONStringLeaves(texts, root[field])
+ }
+ texts = appendJSONStringLeaves(texts, root["state"])
+ return userPromptSegments(texts)
+}
+
+func appendJSONStringLeaves(texts []string, value any) []string {
+ switch typed := value.(type) {
+ case string:
+ if text := strings.TrimSpace(typed); text != "" {
+ texts = append(texts, text)
+ }
+ case []any:
+ for _, item := range typed {
+ texts = appendJSONStringLeaves(texts, item)
+ }
+ case map[string]any:
+ for _, key := range sortedJSONKeys(typed) {
+ texts = appendJSONStringLeaves(texts, key)
+ texts = appendJSONStringLeaves(texts, typed[key])
+ }
+ }
+ return texts
+}
+
+func sortedJSONKeys(values map[string]any) []string {
+ keys := make([]string, 0, len(values))
+ for key := range values {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ return keys
+}
+
// clientInstructionRoles are roles a client may freely populate. Attackers can
// place jailbreak/PII text in assistant/tool turns, so blocking audit must scan
// them too—not only user/system/developer instructions.
diff --git a/backend/internal/securityaudit/prompt_snapshot_test.go b/backend/internal/securityaudit/prompt_snapshot_test.go
index 70d26f925..751043f55 100644
--- a/backend/internal/securityaudit/prompt_snapshot_test.go
+++ b/backend/internal/securityaudit/prompt_snapshot_test.go
@@ -412,3 +412,53 @@ func mustJSON(t *testing.T, value string) []byte {
func metadataTextForTest(scanText string) string {
return strings.Replace(scanText, promptAuditPrioritySeparator, "\n\n", 1)
}
+
+func TestPromptSnapshotTypeSafeSystemOneCollectsStateAndQuestions(t *testing.T) {
+ body := `{"model":"jev-latest","state":{"STATE_KEY":"STATE_TITLE","items":["STATE_ITEM",{"text":"STATE_NESTED"},3]},` +
+ `"questions":{"b":{"type":"choice","instructions":"CHOICE_INSTRUCTIONS","criteria":{"OPTION_LABEL":{"description":"OPTION_DESC"},"empty":null}},` +
+ `"a":{"type":"noul","instructions":["NOUL_INSTRUCTIONS"],"criteria":{"true":"NOUL_TRUE","false":"NOUL_FALSE"},"EXTENSION_KEY":"EXTENSION_VALUE"},` +
+ `"QUESTION_ID":{"type":"score","criteria":["SCORE_LOW",{"description":"SCORE_HIGH"}]}},"TOP_EXTENSION":{"x":"TOP_VALUE"}}`
+
+ snapshot, err := ExtractPromptSnapshot(Request{Protocol: "typesafe_systemone", Body: []byte(body)})
+ require.NoError(t, err)
+ for _, text := range []string{"STATE_KEY", "STATE_TITLE", "STATE_ITEM", "STATE_NESTED", "CHOICE_INSTRUCTIONS", "OPTION_LABEL", "OPTION_DESC",
+ "NOUL_INSTRUCTIONS", "NOUL_TRUE", "NOUL_FALSE", "EXTENSION_KEY", "EXTENSION_VALUE", "QUESTION_ID", "SCORE_LOW", "SCORE_HIGH",
+ "TOP_EXTENSION", "TOP_VALUE"} {
+ require.Contains(t, snapshot.ScanText, text)
+ }
+ // Canonical field names and validated enum values are not client text.
+ for _, text := range []string{"jev-latest", "instructions", "criteria", "questions", "choice", "score"} {
+ require.NotContains(t, snapshot.ScanText, text)
+ }
+
+ // Map iteration order must not change the audited text or its hash.
+ for range 20 {
+ again, err := ExtractPromptSnapshot(Request{Protocol: "typesafe_systemone", Body: []byte(body)})
+ require.NoError(t, err)
+ require.Equal(t, snapshot.PromptHash, again.PromptHash)
+ require.Equal(t, snapshot.ScanText, again.ScanText)
+ }
+
+ blocking, err := ExtractBlockingPromptSnapshot(Request{Protocol: "typesafe_systemone", Body: []byte(body)}, true)
+ require.NoError(t, err)
+ require.Contains(t, blocking.ScanText, "STATE_TITLE")
+ require.Contains(t, blocking.ScanText, "CHOICE_INSTRUCTIONS")
+ require.Contains(t, blocking.ScanText, "QUESTION_ID")
+}
+
+func TestPromptSnapshotTypeSafeSystemOneStringStateIsPrioritized(t *testing.T) {
+ snapshot, err := ExtractPromptSnapshot(Request{Protocol: "typesafe_systemone", Body: []byte(`{"model":"jev-latest","state":"plain state","questions":{"q":{"type":"noul"}}}`)})
+ require.NoError(t, err)
+ require.True(t, strings.HasPrefix(snapshot.ScanText, "plain state"))
+ require.Equal(t, 2, snapshot.MessageCount)
+}
+
+func TestPromptSnapshotTypeSafeSystemOneAuditsKeyOnlyPayloads(t *testing.T) {
+ body := `{"model":"jev-latest","state":{"HIDDEN_STATE_KEY":1},"questions":{"HIDDEN_QUESTION_ID":{"type":"noul"}}}`
+ for _, latestTurnOnly := range []bool{false, true} {
+ snapshot, err := ExtractBlockingPromptSnapshot(Request{Protocol: "typesafe_systemone", Body: []byte(body)}, latestTurnOnly)
+ require.NoError(t, err)
+ require.Contains(t, snapshot.ScanText, "HIDDEN_STATE_KEY")
+ require.Contains(t, snapshot.ScanText, "HIDDEN_QUESTION_ID")
+ }
+}
diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go
index 76e6c6b7a..81b87fe01 100644
--- a/backend/internal/server/api_contract_test.go
+++ b/backend/internal/server/api_contract_test.go
@@ -866,7 +866,7 @@ func TestAPIContracts(t *testing.T) {
"force_email_on_third_party_signup": false,
"default_concurrency": 5,
"default_balance": 1.25,
- "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"openai_bps":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
+ "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"cline":{"daily":null,"weekly":null,"monthly":null},"command_code":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"openai_bps":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
"auth_source_default_email_platform_quotas": null,
"auth_source_default_github_platform_quotas": null,
"auth_source_default_google_platform_quotas": null,
@@ -980,6 +980,9 @@ func TestAPIContracts(t *testing.T) {
"payment_balance_recharge_multiplier": 0,
"payment_subscription_usd_to_cny_rate": 0,
"payment_recharge_fee_rate": 0,
+ "payment_recharge_bonus_tiers": [],
+ "payment_recharge_bonus_mode": "bonus",
+ "payment_recharge_bonus_notice": "",
"payment_load_balance_strategy": "",
"payment_product_name_prefix": "",
"payment_product_name_suffix": "",
@@ -1195,7 +1198,7 @@ func TestAPIContracts(t *testing.T) {
"purchase_subscription_url": "",
"table_default_page_size": 20,
"table_page_size_options": [10, 20, 50],
- "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"openai_bps":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
+ "default_platform_quotas": {"anthropic":{"daily":null,"weekly":null,"monthly":null},"antigravity":{"daily":null,"weekly":null,"monthly":null},"cline":{"daily":null,"weekly":null,"monthly":null},"command_code":{"daily":null,"weekly":null,"monthly":null},"deepseek":{"daily":null,"weekly":null,"monthly":null},"gemini":{"daily":null,"weekly":null,"monthly":null},"grok":{"daily":null,"weekly":null,"monthly":null},"kimi":{"daily":null,"weekly":null,"monthly":null},"minimax":{"daily":null,"weekly":null,"monthly":null},"openai":{"daily":null,"weekly":null,"monthly":null},"openai_bps":{"daily":null,"weekly":null,"monthly":null},"opencode_go":{"daily":null,"weekly":null,"monthly":null},"typesafe":{"daily":null,"weekly":null,"monthly":null},"zhipu":{"daily":null,"weekly":null,"monthly":null}},
"auth_source_default_email_platform_quotas": null,
"auth_source_default_github_platform_quotas": null,
"auth_source_default_google_platform_quotas": null,
@@ -1306,6 +1309,9 @@ func TestAPIContracts(t *testing.T) {
"payment_balance_recharge_multiplier": 0,
"payment_subscription_usd_to_cny_rate": 0,
"payment_recharge_fee_rate": 0,
+ "payment_recharge_bonus_tiers": [],
+ "payment_recharge_bonus_mode": "bonus",
+ "payment_recharge_bonus_notice": "",
"payment_load_balance_strategy": "",
"payment_product_name_prefix": "",
"payment_product_name_suffix": "",
diff --git a/backend/internal/server/router.go b/backend/internal/server/router.go
index 528c283bc..b2159251e 100644
--- a/backend/internal/server/router.go
+++ b/backend/internal/server/router.go
@@ -130,7 +130,7 @@ func registerRoutes(
routes.RegisterAdminRoutes(v1, h, adminAuth, auditLog, stepUpAuth, settingService, panelRateLimiter)
routes.RegisterGatewayRoutes(r, h, apiKeyAuth, apiKeyService, subscriptionService, opsService, settingService, compositeResolver, cfg)
h.Admin.Account.SetCodexTicketDiagnosticRouter(r, apiKeyService)
- routes.RegisterPaymentRoutes(v1, h.Payment, h.PaymentWebhook, h.Admin.Payment, jwtAuth, adminAuth, auditLog, settingService, panelRateLimiter)
+ routes.RegisterPaymentRoutes(v1, h.Payment, h.PaymentWebhook, h.Admin.Payment, jwtAuth, adminAuth, auditLog, settingService, panelRateLimiter, redisClient)
handler.RegisterPageRoutes(v1, cfg.Pricing.DataDir, gin.HandlerFunc(jwtAuth), gin.HandlerFunc(adminAuth), settingService)
}
diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go
index 6b779c3ab..2cb46e9a8 100644
--- a/backend/internal/server/routes/gateway.go
+++ b/backend/internal/server/routes/gateway.go
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/handler"
pkghttputil "github.com/MACOS-DO/sub4api/internal/pkg/httputil"
"github.com/MACOS-DO/sub4api/internal/pkg/requestmodel"
@@ -46,22 +47,15 @@ func RegisterGatewayRoutes(
groupModelAllowlist := middleware.GroupModelAllowlist()
isOpenAIResponsesCompatibleGatewayPlatform := func(c *gin.Context) bool {
- switch getGroupPlatform(c) {
- case service.PlatformOpenAI, service.PlatformOpenAIBPS, service.PlatformGrok,
- service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek,
- service.PlatformMiniMax, service.PlatformOpenCodeGo:
- // 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。
- return true
- default:
- return false
- }
+ // openai、grok 与多协议 API Key 供应商经 OpenAI 网关转发(平台清单)。
+ return domain.UsesOpenAIGateway(getGroupPlatform(c))
}
countTokensHandler := func(c *gin.Context) {
- switch getGroupPlatform(c) {
- case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo:
- h.OpenAIGateway.CountTokens(c)
- case service.PlatformGrok:
+ switch platform := getGroupPlatform(c); {
+ case platform == service.PlatformGrok:
h.OpenAIGateway.GrokCountTokens(c)
+ case domain.UsesOpenAIGateway(platform):
+ h.OpenAIGateway.CountTokens(c)
default:
h.Gateway.CountTokens(c)
}
@@ -203,6 +197,8 @@ func RegisterGatewayRoutes(
}
h.Gateway.Messages(c)
})
+ // System One carries only JSON text, so it uses the text body limit.
+ gateway.POST("/systemone", textBodyLimit, h.Gateway.SystemOne)
// /v1/messages/count_tokens: OpenAI bridges upstream, Grok estimates
// locally, and Anthropic-compatible platforms retain their existing path.
gateway.POST("/messages/count_tokens", countTokensHandler)
diff --git a/backend/internal/server/routes/gateway_model_allowlist_test.go b/backend/internal/server/routes/gateway_model_allowlist_test.go
index a00b6022c..f766d7d8a 100644
--- a/backend/internal/server/routes/gateway_model_allowlist_test.go
+++ b/backend/internal/server/routes/gateway_model_allowlist_test.go
@@ -152,6 +152,7 @@ func TestGatewayRoutesGroupModelAllowlistCoversRootAliasRoutes(t *testing.T) {
{http.MethodGet, "/realtime?model=gpt-4.1", ""},
{http.MethodPost, "/v1/responses", `{"model":"gpt-4.1"}`},
{http.MethodPost, "/v1/messages", `{"model":"gpt-4.1"}`},
+ {http.MethodPost, "/v1/systemone", `{"model":"gpt-4.1","state":"x","questions":{"q":{"type":"noul","instructions":"x"}}}`},
{http.MethodPost, "/v1/messages/count_tokens", `{"model":"gpt-4.1","messages":[]}`},
{http.MethodPost, "/v1/chat/completions", `{"model":"gpt-4.1"}`},
{http.MethodPost, "/v1/embeddings", `{"model":"gpt-4.1","input":"hi"}`},
diff --git a/backend/internal/server/routes/payment.go b/backend/internal/server/routes/payment.go
index 162f35a38..ebfbdf47b 100644
--- a/backend/internal/server/routes/payment.go
+++ b/backend/internal/server/routes/payment.go
@@ -1,12 +1,25 @@
package routes
import (
+ "time"
+
"github.com/MACOS-DO/sub4api/internal/handler"
"github.com/MACOS-DO/sub4api/internal/handler/admin"
+ ratelimit "github.com/MACOS-DO/sub4api/internal/middleware"
"github.com/MACOS-DO/sub4api/internal/server/middleware"
"github.com/MACOS-DO/sub4api/internal/service"
"github.com/gin-gonic/gin"
+ "github.com/redis/go-redis/v9"
+)
+
+// publicOrderVerifyRateLimit caps anonymous legacy out_trade_no lookups per
+// client IP. The payment result page polls at most a handful of times per
+// order, so this leaves ample headroom for real users while making
+// out_trade_no enumeration impractical.
+const (
+ publicOrderVerifyRateLimit = 20
+ publicOrderVerifyRateLimitWindow = time.Minute
)
// RegisterPaymentRoutes registers all payment-related routes:
@@ -21,6 +34,7 @@ func RegisterPaymentRoutes(
auditLog middleware.AuditLogMiddleware,
settingService *service.SettingService,
panelRateLimiter *middleware.PanelRateLimiter,
+ redisClient *redis.Client,
) {
// --- User-facing payment endpoints (authenticated) ---
authenticated := v1.Group("/payment")
@@ -50,9 +64,15 @@ func RegisterPaymentRoutes(
// Signed resume-token recovery is the preferred public lookup path.
// The legacy anonymous out_trade_no verify endpoint remains available as a
// persisted-state compatibility path for staggered upgrades.
+ // The anonymous verify endpoint is IP rate-limited to prevent out_trade_no
+ // enumeration. It fails open on Redis errors so an outage never blocks a
+ // user who is mid-payment from seeing their result.
+ publicRateLimiter := ratelimit.NewRateLimiter(redisClient)
public := v1.Group("/payment/public")
{
- public.POST("/orders/verify", paymentHandler.VerifyOrderPublic)
+ public.POST("/orders/verify",
+ publicRateLimiter.Limit("payment-public-order-verify", publicOrderVerifyRateLimit, publicOrderVerifyRateLimitWindow),
+ paymentHandler.VerifyOrderPublic)
public.POST("/orders/resolve", paymentHandler.ResolveOrderPublicByResumeToken)
}
diff --git a/backend/internal/server/routes/payment_public_rate_limit_test.go b/backend/internal/server/routes/payment_public_rate_limit_test.go
new file mode 100644
index 000000000..a7f6a656a
--- /dev/null
+++ b/backend/internal/server/routes/payment_public_rate_limit_test.go
@@ -0,0 +1,84 @@
+package routes
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/handler"
+ "github.com/MACOS-DO/sub4api/internal/handler/admin"
+ servermiddleware "github.com/MACOS-DO/sub4api/internal/server/middleware"
+ "github.com/alicebob/miniredis/v2"
+ "github.com/gin-gonic/gin"
+ "github.com/redis/go-redis/v9"
+ "github.com/stretchr/testify/require"
+)
+
+func newPaymentRoutesTestRouter(redisClient *redis.Client) *gin.Engine {
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ v1 := router.Group("/api/v1")
+ noop := func(c *gin.Context) { c.Next() }
+
+ RegisterPaymentRoutes(
+ v1,
+ &handler.PaymentHandler{},
+ &handler.PaymentWebhookHandler{},
+ &admin.PaymentHandler{},
+ servermiddleware.JWTAuthMiddleware(noop),
+ servermiddleware.AdminAuthMiddleware(noop),
+ servermiddleware.AuditLogMiddleware(noop),
+ nil,
+ nil,
+ redisClient,
+ )
+ return router
+}
+
+func postPublicOrderVerify(router *gin.Engine, remoteAddr string) *httptest.ResponseRecorder {
+ // Empty body fails binding in the handler, so no service is touched and a
+ // non-429 response proves the request passed the limiter.
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/payment/public/orders/verify", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.RemoteAddr = remoteAddr
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ return w
+}
+
+func TestPublicOrderVerifyRateLimitedPerIP(t *testing.T) {
+ mr := miniredis.RunT(t)
+ rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
+ t.Cleanup(func() { _ = rdb.Close() })
+
+ router := newPaymentRoutesTestRouter(rdb)
+
+ for i := 1; i <= publicOrderVerifyRateLimit; i++ {
+ w := postPublicOrderVerify(router, "198.51.100.20:1234")
+ require.Equal(t, http.StatusBadRequest, w.Code, "request %d should reach the handler", i)
+ }
+
+ w := postPublicOrderVerify(router, "198.51.100.20:1234")
+ require.Equal(t, http.StatusTooManyRequests, w.Code)
+ require.Contains(t, w.Body.String(), "rate limit exceeded")
+
+ // A different client IP has its own budget.
+ w = postPublicOrderVerify(router, "198.51.100.21:1234")
+ require.Equal(t, http.StatusBadRequest, w.Code)
+}
+
+func TestPublicOrderVerifyRateLimitFailsOpenWhenRedisUnavailable(t *testing.T) {
+ rdb := redis.NewClient(&redis.Options{
+ Addr: "127.0.0.1:1",
+ DialTimeout: 50 * time.Millisecond,
+ ReadTimeout: 50 * time.Millisecond,
+ WriteTimeout: 50 * time.Millisecond,
+ })
+ t.Cleanup(func() { _ = rdb.Close() })
+
+ router := newPaymentRoutesTestRouter(rdb)
+ w := postPublicOrderVerify(router, "203.0.113.30:1234")
+ require.Equal(t, http.StatusBadRequest, w.Code, "users mid-payment must not be blocked by a Redis outage")
+}
diff --git a/backend/internal/server/routes/prompt_audit_route_coverage_test.go b/backend/internal/server/routes/prompt_audit_route_coverage_test.go
index c155dd741..49f8b68fa 100644
--- a/backend/internal/server/routes/prompt_audit_route_coverage_test.go
+++ b/backend/internal/server/routes/prompt_audit_route_coverage_test.go
@@ -29,6 +29,7 @@ func TestEveryGatewayPOSTRouteIsClassifiedForPromptAuditCoverage(t *testing.T) {
audited := map[string][]string{
"/messages": {"gateway_handler.go", "openai_gateway_handler.go"},
+ "/systemone": {"gateway_systemone.go"},
"/responses": {"gateway_handler_responses.go", "openai_gateway_handler.go"},
"/responses/*subpath": {"gateway_handler_responses.go", "openai_gateway_handler.go"},
"/chat/completions": {"gateway_handler_chat_completions.go", "openai_chat_completions.go"},
diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go
index 04420717c..dc9b05edd 100644
--- a/backend/internal/service/account.go
+++ b/backend/internal/service/account.go
@@ -17,6 +17,7 @@ import (
"github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/geminicli"
"github.com/MACOS-DO/sub4api/internal/pkg/openai_compat"
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
"github.com/MACOS-DO/sub4api/internal/pkg/xai"
)
@@ -275,6 +276,10 @@ func (a *Account) IsGrok() bool {
return a.Platform == PlatformGrok
}
+func (a *Account) IsTypeSafe() bool {
+ return a != nil && a.Platform == PlatformTypeSafe
+}
+
func (a *Account) IsGrokOAuth() bool {
return a.IsGrok() && a.Type == AccountTypeOAuth
}
@@ -305,7 +310,7 @@ func (a *Account) IsCNProvider() bool {
// openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions
// 兼容上游,也经 OpenAI 网关转发。OpenCode 同样经 OpenAI 网关按模型分流。
func (a *Account) IsOpenAICompatible() bool {
- return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformOpenAIBPS || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo())
+ return a != nil && domain.UsesOpenAIGateway(a.Platform)
}
func (a *Account) GeminiOAuthType() string {
@@ -987,6 +992,10 @@ func (a *Account) GetBaseURL() string {
}
baseURL := a.GetCredential("base_url")
if baseURL == "" {
+ // TypeSafe keys must never fall back to the Anthropic host.
+ if a.Platform == PlatformTypeSafe {
+ return typesafe.DefaultBaseURL
+ }
return "https://api.anthropic.com"
}
if a.Platform == PlatformAntigravity {
@@ -1008,6 +1017,28 @@ func (a *Account) GetGeminiBaseURL(defaultBaseURL string) string {
return baseURL
}
+func (a *Account) GetTypeSafeBaseURL() string {
+ if a == nil || !a.IsTypeSafe() || a.Type != AccountTypeAPIKey {
+ return ""
+ }
+ baseURL := strings.TrimRight(strings.TrimSpace(a.GetCredential("base_url")), "/")
+ // The System One path already carries /v1; accept a base URL pasted with it.
+ if len(baseURL) >= 3 && strings.EqualFold(baseURL[len(baseURL)-3:], "/v1") {
+ baseURL = strings.TrimRight(baseURL[:len(baseURL)-3], "/")
+ }
+ if baseURL == "" {
+ return typesafe.DefaultBaseURL
+ }
+ return baseURL
+}
+
+func (a *Account) GetTypeSafeAPIKey() string {
+ if a == nil || !a.IsTypeSafe() || a.Type != AccountTypeAPIKey {
+ return ""
+ }
+ return strings.TrimSpace(a.GetCredential("api_key"))
+}
+
func (a *Account) GetExtraString(key string) string {
if a.Extra == nil {
return ""
@@ -1360,7 +1391,7 @@ func (a *Account) IsOpenAIApiKey() bool {
// 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go;
// grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。
func (a *Account) GetOpenAIBaseURL() string {
- if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() {
+ if !a.IsOpenAI() && !a.IsMultiProtocolAPIKey() {
return ""
}
if a.IsMultiProtocolAPIKey() && a.IsAdaptiveAPIProtocol() {
@@ -1375,27 +1406,11 @@ func (a *Account) GetOpenAIBaseURL() string {
return baseURL
}
}
- // 平台默认 base_url:CN 供应商按 account_mode 选择 payg / coding 默认值。
- switch a.Platform {
- case PlatformKimi:
- if a.GetAccountMode() == AccountModeCoding {
- return DefaultKimiCodingBaseURL
- }
- return DefaultKimiPayGBaseURL
- case PlatformZhipu:
- if a.GetAccountMode() == AccountModeCoding {
- return DefaultZhipuCodingBaseURL
- }
- return DefaultZhipuPayGBaseURL
- case PlatformDeepseek:
- return DefaultDeepseekBaseURL
- case PlatformMiniMax:
- return DefaultMiniMaxBaseURL
- case PlatformOpenCodeGo:
- return a.openCodeDefaultChatBaseURL()
- default:
- return "https://api.openai.com"
+ // 平台默认 base_url:多协议供应商按 account_mode 查 provider profile。
+ if baseURL := a.defaultProviderBaseURL(APIProtocolChatCompletions); baseURL != "" {
+ return baseURL
}
+ return "https://api.openai.com"
}
// GetAccountMode 返回国产供应商账号的接入模式(payg / coding);非国产供应商或未设置时
@@ -1436,7 +1451,8 @@ func (a *Account) GetAPIProtocol() string {
case APIProtocolChatCompletions:
return APIProtocolChatCompletions
}
- if a.IsOpenCodeGo() {
+ // 按模型分流的供应商(多模型聚合平台)未显式配置时默认 adaptive。
+ if a.routesByModel() {
return APIProtocolAdaptive
}
return APIProtocolChatCompletions
@@ -1446,15 +1462,7 @@ func (a *Account) GetAPIProtocol() string {
// DeepSeek 官方为 /responses(无 /v1);Kimi 按量付费与 Coding Plan 均为
// /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses。
func (a *Account) SupportsNativeCNResponses() bool {
- if a == nil {
- return false
- }
- switch a.Platform {
- case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo:
- return true
- default:
- return false
- }
+ return a.providerSupportsProtocol(APIProtocolResponses)
}
// UsesNativeCNResponses 报告当前账号是否应按原生 Responses 协议转发
@@ -1495,48 +1503,7 @@ func (a *Account) GetCNProtocolBaseURL(protocol string) string {
}
}
}
- return a.defaultCNProtocolBaseURL(protocol)
-}
-
-func (a *Account) defaultCNProtocolBaseURL(protocol string) string {
- switch protocol {
- case APIProtocolAnthropic:
- switch a.Platform {
- case PlatformKimi:
- if a.GetAccountMode() == AccountModeCoding {
- return DefaultKimiCodingAnthropicBaseURL
- }
- return DefaultKimiPayGAnthropicBaseURL
- case PlatformZhipu:
- return DefaultZhipuAnthropicBaseURL
- case PlatformDeepseek:
- return DefaultDeepseekAnthropicBaseURL
- case PlatformMiniMax:
- return DefaultMiniMaxAnthropicBaseURL
- case PlatformOpenCodeGo:
- return a.openCodeDefaultAnthropicBaseURL()
- }
- case APIProtocolChatCompletions, APIProtocolResponses:
- switch a.Platform {
- case PlatformKimi:
- if a.GetAccountMode() == AccountModeCoding {
- return DefaultKimiCodingBaseURL
- }
- return DefaultKimiPayGBaseURL
- case PlatformZhipu:
- if a.GetAccountMode() == AccountModeCoding {
- return DefaultZhipuCodingBaseURL
- }
- return DefaultZhipuPayGBaseURL
- case PlatformDeepseek:
- return DefaultDeepseekBaseURL
- case PlatformMiniMax:
- return DefaultMiniMaxBaseURL
- case PlatformOpenCodeGo:
- return a.openCodeDefaultChatBaseURL()
- }
- }
- return ""
+ return a.defaultProviderBaseURL(protocol)
}
// IsAnthropicProtocol 报告账号是否以原生 Anthropic 协议接入上游
@@ -1560,23 +1527,7 @@ func (a *Account) GetAnthropicProtocolBaseURL() string {
return baseURL
}
}
- switch a.Platform {
- case PlatformKimi:
- if a.GetAccountMode() == AccountModeCoding {
- return DefaultKimiCodingAnthropicBaseURL
- }
- return DefaultKimiPayGAnthropicBaseURL
- case PlatformZhipu:
- return DefaultZhipuAnthropicBaseURL
- case PlatformDeepseek:
- return DefaultDeepseekAnthropicBaseURL
- case PlatformMiniMax:
- return DefaultMiniMaxAnthropicBaseURL
- case PlatformOpenCodeGo:
- return a.openCodeDefaultAnthropicBaseURL()
- default:
- return ""
- }
+ return a.defaultProviderBaseURL(APIProtocolAnthropic)
}
// GetOpenAIFormatBaseURL 返回供 OpenAI 格式端点(/v1/models、/v1/chat/completions
@@ -1588,26 +1539,10 @@ func (a *Account) GetOpenAIFormatBaseURL() string {
if a == nil || !a.IsAnthropicProtocol() {
return a.GetOpenAIBaseURL()
}
- switch a.Platform {
- case PlatformKimi:
- if a.GetAccountMode() == AccountModeCoding {
- return DefaultKimiCodingBaseURL
- }
- return DefaultKimiPayGBaseURL
- case PlatformZhipu:
- if a.GetAccountMode() == AccountModeCoding {
- return DefaultZhipuCodingBaseURL
- }
- return DefaultZhipuPayGBaseURL
- case PlatformDeepseek:
- return DefaultDeepseekBaseURL
- case PlatformMiniMax:
- return DefaultMiniMaxBaseURL
- case PlatformOpenCodeGo:
- return a.openCodeDefaultChatBaseURL()
- default:
- return a.GetOpenAIBaseURL()
+ if baseURL := a.defaultProviderBaseURL(APIProtocolChatCompletions); baseURL != "" {
+ return baseURL
}
+ return a.GetOpenAIBaseURL()
}
// GetCNAPIKey 返回国产 OpenAI 兼容供应商账号的 api_key 凭据(kimi/zhipu/deepseek)。
@@ -1619,7 +1554,8 @@ func (a *Account) GetCNAPIKey() string {
return a.GetCredential("api_key")
}
-// GetCodingPlanProvider 根据 base_url 识别 Coding Plan 供应商(kimi / zhipu / minimax),
+// GetCodingPlanProvider 根据 base_url 识别 Coding Plan 供应商(kimi / zhipu / minimax;
+// OpenCode Go 订阅与官方主机上的 Command Code、Cline 账号按平台识别),
// 用于路由到对应的额度查询端点。非 coding 模式或无法识别时返回空串。
// 只认官方域名:自定义中转不得把第三方 Key 发往厂商官方额度端点。
func (a *Account) GetCodingPlanProvider() string {
@@ -1629,6 +1565,18 @@ func (a *Account) GetCodingPlanProvider() string {
if a.IsOpenCodeGoPlan() {
return PlatformOpenCodeGo
}
+ if a.IsCommandCode() {
+ if a.commandCodeUsageSupported() {
+ return PlatformCommandCode
+ }
+ return ""
+ }
+ if a.IsCline() {
+ if a.clineAccountAPISupported() {
+ return PlatformCline
+ }
+ return ""
+ }
if a.GetAccountMode() != AccountModeCoding {
return ""
}
diff --git a/backend/internal/service/account_header_override.go b/backend/internal/service/account_header_override.go
index dc8c7c765..2b010824a 100644
--- a/backend/internal/service/account_header_override.go
+++ b/backend/internal/service/account_header_override.go
@@ -77,10 +77,10 @@ func (a *Account) IsHeaderOverrideEligible() bool {
if a == nil {
return false
}
- switch a.Platform {
- case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo:
+ switch {
+ case a.Platform == PlatformAnthropic, a.Platform == PlatformOpenAI, IsMultiProtocolAPIKeyProvider(a.Platform):
return a.Type == AccountTypeAPIKey
- case PlatformGrok:
+ case a.Platform == PlatformGrok:
return a.Type == AccountTypeAPIKey || a.Type == AccountTypeOAuth
default:
return false
diff --git a/backend/internal/service/account_scheduling_threshold_eval.go b/backend/internal/service/account_scheduling_threshold_eval.go
index 0e1a40934..951629658 100644
--- a/backend/internal/service/account_scheduling_threshold_eval.go
+++ b/backend/internal/service/account_scheduling_threshold_eval.go
@@ -58,7 +58,7 @@ func EvaluateAccountSchedulingThreshold(account *Account, thresholds map[string]
winner = pickLatestResetSchedulingCandidate(anthropicThresholdCandidates(account), threshold, now)
case PlatformGrok:
winner = pickLatestResetSchedulingCandidate(grokThresholdCandidates(account), threshold, now)
- case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo:
+ case PlatformKimi, PlatformZhipu, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode:
winner = pickLatestResetSchedulingCandidate(cnProviderThresholdCandidates(account, decision.Platform), threshold, now)
default:
return decision
@@ -353,25 +353,33 @@ func grokThresholdCandidates(account *Account) []*accountSchedulingThresholdCand
}
}
-// cnProviderThresholdCandidates 读取国产供应商 Coding Plan 账号的 5h / weekly 滚动窗口
-// 用量快照(由 CNProviderQuotaService 写入 account.Extra,键形如
-// _5h_used_percent / _weekly_reset_at)。payg 账号无此快照,
+// cnProviderThresholdCandidates 读取国产供应商 Coding Plan、OpenCode Go 与 Command Code
+// 账号的 5h / weekly(及月度)窗口用量快照(由 CNProviderQuotaService 写入 account.Extra,
+// 键形如 _5h_used_percent / _weekly_reset_at)。payg 账号无此快照,
// 候选为空 → 不触发阈值停调(余额型走余额检测)。与 openai 的快照驱动停调一致:
// 仅当用量超阈值且窗口尚未重置时才停调。
func cnProviderThresholdCandidates(account *Account, provider string) []*accountSchedulingThresholdCandidate {
if account == nil || len(account.Extra) == 0 {
return nil
}
+ if provider == PlatformCommandCode && !commandCodeWindowsBinding(account.Extra) {
+ return nil
+ }
candidates := []*accountSchedulingThresholdCandidate{
cnThresholdCandidate(account.Extra, provider, "5h"),
cnThresholdCandidate(account.Extra, provider, "weekly"),
}
- if provider == PlatformOpenCodeGo {
+ if cnQuotaHasMonthlyWindow(provider) {
candidates = append(candidates, cnThresholdCandidate(account.Extra, provider, "monthly"))
}
return candidates
}
+// cnQuotaHasMonthlyWindow 报告供应商的额度快照是否含月度窗口(OpenCode Go、Command Code)。
+func cnQuotaHasMonthlyWindow(provider string) bool {
+ return provider == PlatformOpenCodeGo || provider == PlatformCommandCode
+}
+
func cnThresholdCandidate(extra map[string]any, provider, window string) *accountSchedulingThresholdCandidate {
var usedKey, resetKey string
switch window {
diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go
index 539d6aad5..d5bf46157 100644
--- a/backend/internal/service/account_service.go
+++ b/backend/internal/service/account_service.go
@@ -2,6 +2,7 @@ package service
import (
"context"
+ "errors"
"fmt"
"time"
@@ -223,6 +224,9 @@ func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository)
// Create 创建账号
func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) (*Account, error) {
+ if req.Platform == PlatformTypeSafe && req.Type != AccountTypeAPIKey {
+ return nil, errors.New("typesafe accounts only support apikey credentials")
+ }
// 验证分组是否存在(如果指定了分组)
if len(req.GroupIDs) > 0 {
if err := s.validateGroupIDsExist(ctx, req.GroupIDs); err != nil {
@@ -518,10 +522,15 @@ func (s *AccountService) TestCredentials(ctx context.Context, id int64) error {
case PlatformOpenAIBPS:
_, err := NormalizeOpenAIBPSCredentials(account.Type, account.Credentials, nil)
return err
- case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo:
- // 国产 OpenAI 兼容供应商与 OpenCode:凭证为 API Key,实际可用性经余额/额度探测与转发路径验证。
+ case PlatformTypeSafe:
+ // TypeSafe credentials are API keys; inference failures drive health and cooldown state.
return nil
default:
+ if IsMultiProtocolAPIKeyProvider(account.Platform) {
+ // 多协议 API Key 供应商(国产厂商与聚合平台):凭证为 API Key,实际可用性
+ // 经余额/额度探测与转发路径验证。
+ return nil
+ }
return fmt.Errorf("unsupported platform: %s", account.Platform)
}
}
diff --git a/backend/internal/service/account_test_logging.go b/backend/internal/service/account_test_logging.go
new file mode 100644
index 000000000..d5bbd8e8e
--- /dev/null
+++ b/backend/internal/service/account_test_logging.go
@@ -0,0 +1,48 @@
+package service
+
+import (
+ "github.com/MACOS-DO/sub4api/internal/pkg/logger"
+ "github.com/MACOS-DO/sub4api/internal/util/logredact"
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "go.uber.org/zap"
+)
+
+const accountTestBackgroundKey = "account_test_background"
+
+// Bind attribution before lookup so missing accounts are identifiable too. The
+// request logger retains HTTP request IDs or the caller's background correlation.
+func initAccountTestLogger(c *gin.Context, accountID int64, modelID, mode string) {
+ source := "http"
+ if c.GetBool(accountTestBackgroundKey) {
+ source = "background"
+ }
+ ctx := c.Request.Context()
+ l := logger.FromContext(ctx).With(
+ zap.String("component", "service.account_test"),
+ zap.Int64("account_id", accountID),
+ zap.String("test_id", uuid.NewString()),
+ zap.String("test_source", source),
+ zap.String("requested_model", modelID),
+ zap.String("test_mode", normalizeAccountTestMode(mode)),
+ )
+ c.Request = c.Request.WithContext(logger.IntoContext(ctx, l))
+}
+
+func bindAccountTestPlatform(c *gin.Context, account *Account) {
+ ctx := c.Request.Context()
+ l := logger.FromContext(ctx).With(
+ zap.String("platform", account.Platform),
+ zap.String("account_type", account.Type),
+ )
+ c.Request = c.Request.WithContext(logger.IntoContext(ctx, l))
+}
+
+func logAccountTestError(c *gin.Context, message string) {
+ // Redact known credential fields before bounding text; truncating first can
+ // cut a quoted credential in half and prevent the redactor from matching it.
+ message = logredact.RedactText(message, "api_key", "authorization")
+ logger.FromContext(c.Request.Context()).Warn("account_test.failed",
+ zap.String("error", truncateString(message, 2048)),
+ )
+}
diff --git a/backend/internal/service/account_test_logging_test.go b/backend/internal/service/account_test_logging_test.go
new file mode 100644
index 000000000..afb916c0a
--- /dev/null
+++ b/backend/internal/service/account_test_logging_test.go
@@ -0,0 +1,93 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/logger"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "go.uber.org/zap"
+ "go.uber.org/zap/zaptest/observer"
+)
+
+type accountTestLoggingRepo struct {
+ AccountRepository
+ account *Account
+}
+
+func (r *accountTestLoggingRepo) GetByID(context.Context, int64) (*Account, error) {
+ if r.account == nil {
+ return nil, errors.New("missing")
+ }
+ return r.account, nil
+}
+
+func TestAccountTestFailureLogAttribution(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, background := range []bool{false, true} {
+ for _, missing := range []bool{false, true} {
+ core, logs := observer.New(zap.WarnLevel)
+ ctx := logger.IntoContext(context.Background(), zap.New(core).With(zap.String("request_id", "req-test")))
+ repo := &accountTestLoggingRepo{}
+ if !missing {
+ repo.account = &Account{ID: 77, Platform: PlatformAnthropic, Type: AccountTypeAPIKey}
+ }
+ svc := &AccountTestService{accountRepo: repo}
+ if background {
+ result, err := svc.RunTestBackground(ctx, 77, "test-model")
+ require.NoError(t, err)
+ require.Equal(t, "failed", result.Status)
+ require.NotEmpty(t, result.ErrorMessage)
+ } else {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/accounts/77/test", nil).WithContext(ctx)
+ err := svc.TestAccountConnection(c, 77, "test-model", "private prompt", "")
+ require.Error(t, err)
+ require.Contains(t, rec.Body.String(), `"type":"error"`)
+ }
+ entries := logs.FilterMessage("account_test.failed").All()
+ require.Len(t, entries, 1)
+ fields := entries[0].ContextMap()
+ require.Equal(t, int64(77), fields["account_id"])
+ require.Equal(t, "req-test", fields["request_id"])
+ require.Equal(t, "test-model", fields["requested_model"])
+ require.NotEmpty(t, fields["test_id"])
+ if background {
+ require.Equal(t, "background", fields["test_source"])
+ } else {
+ require.Equal(t, "http", fields["test_source"])
+ }
+ if !missing {
+ require.Equal(t, PlatformAnthropic, fields["platform"])
+ }
+ require.NotContains(t, fields, "prompt")
+ }
+ }
+}
+
+func TestAccountTestErrorLogRedaction(t *testing.T) {
+ core, logs := observer.New(zap.WarnLevel)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest("POST", "/test", nil).WithContext(logger.IntoContext(context.Background(), zap.New(core)))
+ initAccountTestLogger(c, 1, "", "")
+ message := `API returned 403: {"api_key":"secret-key","access_token":"secret-token","message":"denied"}`
+ err := (&AccountTestService{}).sendErrorAndEnd(c, message)
+ require.EqualError(t, err, message)
+ entry := logs.FilterMessage("account_test.failed").All()[0]
+ logged, ok := entry.ContextMap()["error"].(string)
+ require.True(t, ok)
+ require.NotContains(t, logged, "secret-key")
+ require.NotContains(t, logged, "secret-token")
+ require.Contains(t, logged, "denied")
+ logAccountTestError(c, strings.Repeat("x", 10000))
+ last, ok := logs.All()[1].ContextMap()["error"].(string)
+ require.True(t, ok)
+ require.Less(t, len(last), 2100)
+}
diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go
index 45124c9a2..cd26e957e 100644
--- a/backend/internal/service/account_test_service.go
+++ b/backend/internal/service/account_test_service.go
@@ -363,6 +363,7 @@ func createTestPayload(modelID string) (map[string]any, error) {
// mode is optional - "compact" routes OpenAI accounts to the /responses/compact probe path
// opts is optional media (image/audio data URLs for real generation / STT).
func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int64, modelID string, prompt string, mode string, opts ...AccountTestOptions) error {
+ initAccountTestLogger(c, accountID, modelID, mode)
ctx := c.Request.Context()
testOpts := firstAccountTestOptions(opts)
@@ -371,6 +372,7 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
if err != nil {
return s.sendErrorAndEnd(c, "Account not found")
}
+ bindAccountTestPlatform(c, account)
// Synthetic UI load-test accounts exercise the real SSE parsing and modal
// interactions, but intentionally do not send their placeholder credentials
@@ -387,7 +389,8 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
}
// Route to platform-specific test method
- if account.IsCNProvider() {
+ // 按入站协议分流的多协议供应商(国产厂商等):按账号协议选测试路径。
+ if account.RoutesProtocolByInbound() {
switch account.GetAPIProtocol() {
case APIProtocolAdaptive:
return s.testCNProviderAdaptiveConnection(c, account, modelID, prompt)
@@ -419,43 +422,54 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
return s.routeAntigravityTest(c, account, modelID, prompt)
}
- if account.IsOpenCodeGo() {
- return s.testOpenCodeGoAccountConnection(c, account, modelID, prompt)
+ // 按模型分流的多模型聚合平台(OpenCode、Command Code 等)。
+ if account.routesByModel() {
+ return s.testModelRoutedAccountConnection(c, account, modelID, prompt)
+ }
+
+ if account.IsTypeSafe() {
+ return s.testTypeSafeAccountConnection(c, account, prompt)
}
return s.testClaudeAccountConnection(c, account, modelID)
}
-// testOpenCodeGoAccountConnection probes the native endpoint for the selected
-// model. Adaptive accounts (the default) follow OpenCodeGoModelProtocol:
+// testModelRoutedAccountConnection probes the native endpoint for the selected
+// model on providers that route by model (see ProviderRoutingByModel). Adaptive
+// accounts (the default) follow the provider's protocol rules, e.g. OpenCode Go:
// grok/gpt/muse-spark → Responses, minimax/qwen → Anthropic, everything else
// (including deepseek-v4-flash) → Chat Completions. A pinned api_protocol
// overrides that catalog. Falling through to the generic Claude tester used
// credentials.base_url + /v1/messages?beta=true, which 404s as HTML on
// https://opencode.ai/zen/go/v1/v1/messages.
-func (s *AccountTestService) testOpenCodeGoAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
+func (s *AccountTestService) testModelRoutedAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
testModelID := strings.TrimSpace(modelID)
if testModelID == "" {
- testModelID = DefaultOpenCodeGoTestModel
+ testModelID = account.providerDefaultTestModel()
+ }
+ if testModelID == "" {
+ testModelID = openai.DefaultTestModel
}
testModelID = account.GetMappedModel(testModelID)
- proto := account.GetAPIProtocol()
- switch proto {
- case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses:
- default:
- proto = openCodeGoNativeProtocol(account, testModelID)
+ if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(testModelID) {
+ return fmt.Errorf("model %q is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)", testModelID)
+ }
+ // 与网关同一判定(含上游模型目录);测试没有入站协议,取模型的首选协议。
+ protocol := account.resolveModelRoutedProtocol(testModelID)
+ if s.openaiGatewayService != nil {
+ protocol = s.openaiGatewayService.resolveUpstreamProtocolFor(c.Request.Context(), account, "", testModelID)
}
- switch proto {
+ switch protocol {
case APIProtocolAnthropic:
return s.testCNProviderAnthropicConnection(c, account, testModelID)
case APIProtocolResponses:
- return s.testOpenCodeGoResponsesConnection(c, account, testModelID)
+ return s.testModelRoutedResponsesConnection(c, account, testModelID)
default:
return s.testCNProviderChatCompletionsConnection(c, account, testModelID, prompt)
}
}
-func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, account *Account, testModelID string) error {
+func (s *AccountTestService) testModelRoutedResponsesConnection(c *gin.Context, account *Account, testModelID string) error {
authToken := strings.TrimSpace(account.GetOpenAIProtocolAPIKey())
if authToken == "" {
return s.sendErrorAndEnd(c, "No API key available")
@@ -471,6 +485,9 @@ func (s *AccountTestService) testOpenCodeGoResponsesConnection(c *gin.Context, a
func (s *AccountTestService) testCNProviderChatCompletionsConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
testModelID := strings.TrimSpace(modelID)
+ if testModelID == "" {
+ testModelID = account.providerDefaultTestModel()
+ }
if testModelID == "" {
testModelID = openai.DefaultTestModel
}
@@ -3274,7 +3291,7 @@ func (s *AccountTestService) sendEvent(c *gin.Context, event TestEvent) {
// sendErrorAndEnd sends an error event and ends the stream
func (s *AccountTestService) sendErrorAndEnd(c *gin.Context, errorMsg string) error {
- log.Printf("Account test error: %s", errorMsg)
+ logAccountTestError(c, errorMsg)
s.sendEvent(c, TestEvent{Type: "error", Error: errorMsg})
return fmt.Errorf("%s", errorMsg)
}
@@ -3287,6 +3304,7 @@ func (s *AccountTestService) RunTestBackground(ctx context.Context, accountID in
w := httptest.NewRecorder()
ginCtx, _ := gin.CreateTestContext(w)
ginCtx.Request = (&http.Request{}).WithContext(ctx)
+ ginCtx.Set(accountTestBackgroundKey, true)
testErr := s.TestAccountConnection(ginCtx, accountID, modelID, "", AccountTestModeDefault)
diff --git a/backend/internal/service/account_test_service_cn_adaptive.go b/backend/internal/service/account_test_service_cn_adaptive.go
index abc72eff5..32d63edc3 100644
--- a/backend/internal/service/account_test_service_cn_adaptive.go
+++ b/backend/internal/service/account_test_service_cn_adaptive.go
@@ -18,14 +18,19 @@ import (
const accountTestSuppressCompletionContextKey = "account_test_suppress_completion"
// testCNProviderAdaptiveConnection verifies every native endpoint used by an
-// adaptive CN-provider account. Zhipu uses Chat Completions plus Anthropic;
-// DeepSeek and Kimi additionally use their native Responses endpoints.
+// adaptive account of a provider that routes by inbound protocol. Zhipu uses
+// Chat Completions plus Anthropic; DeepSeek and Kimi additionally use their
+// native Responses endpoints. Endpoints the provider profile does not offer are
+// skipped.
func (s *AccountTestService) testCNProviderAdaptiveConnection(c *gin.Context, account *Account, modelID string, prompt string) error {
- testModelID := strings.TrimSpace(modelID)
- if testModelID == "" {
- testModelID = openai.DefaultTestModel
+ requestedModelID := strings.TrimSpace(modelID)
+ if requestedModelID == "" {
+ requestedModelID = account.providerDefaultTestModel()
}
- testModelID = account.GetMappedModel(testModelID)
+ if requestedModelID == "" {
+ requestedModelID = openai.DefaultTestModel
+ }
+ testModelID := account.GetMappedModel(requestedModelID)
authToken := strings.TrimSpace(account.GetOpenAIProtocolAPIKey())
if authToken == "" {
@@ -36,12 +41,14 @@ func (s *AccountTestService) testCNProviderAdaptiveConnection(c *gin.Context, ac
// completion events until every native adaptive endpoint has passed.
c.Set(accountTestSuppressCompletionContextKey, true)
defer c.Set(accountTestSuppressCompletionContextKey, false)
- if err := s.testCNProviderChatCompletionsConnection(c, account, modelID, prompt); err != nil {
+ if err := s.testCNProviderChatCompletionsConnection(c, account, requestedModelID, prompt); err != nil {
return err
}
- if err := s.testCNProviderAdaptiveAnthropicConnection(c, account, testModelID, authToken); err != nil {
- return err
+ if account.providerSupportsProtocol(APIProtocolAnthropic) {
+ if err := s.testCNProviderAdaptiveAnthropicConnection(c, account, testModelID, authToken); err != nil {
+ return err
+ }
}
if account.SupportsNativeCNResponses() {
@@ -237,10 +244,10 @@ func (s *AccountTestService) testCNProviderAnthropicConnection(c *gin.Context, a
if err != nil {
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid Anthropic base URL: %s", err.Error()))
}
- if hint := cnAnthropicBaseURLMisconfigHint(baseURL); hint != "" {
+ if hint := cnAnthropicBaseURLMisconfigHint(baseURL, account.routesByModel()); hint != "" {
return s.sendErrorAndEnd(c, hint)
}
- apiURL := strings.TrimRight(baseURL, "/") + "/v1/messages"
+ apiURL := nativeAnthropicMessagesURL(account, baseURL)
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
@@ -295,7 +302,9 @@ func (s *AccountTestService) testCNProviderAnthropicConnection(c *gin.Context, a
// endpoint (paas path, version segment, or chat/completions / responses
// suffix). The naive {base}/v1/messages join would 404 (e.g.
// .../api/paas/v4/v1/messages) with no hint about the actual misconfiguration.
-func cnAnthropicBaseURLMisconfigHint(baseURL string) string {
+// versionAware is set for providers whose join is version-aware (see
+// nativeAnthropicMessagesURL), where a trailing version segment is valid.
+func cnAnthropicBaseURLMisconfigHint(baseURL string, versionAware bool) string {
parsed, err := url.Parse(strings.TrimSpace(baseURL))
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
return ""
@@ -307,7 +316,7 @@ func cnAnthropicBaseURLMisconfigHint(baseURL string) string {
openAICompatShaped := strings.Contains(path, "/paas/") ||
strings.HasSuffix(path, "/chat/completions") ||
strings.HasSuffix(path, "/responses") ||
- openAIBaseURLHasVersionSuffix(path)
+ (!versionAware && openAIBaseURLHasVersionSuffix(path))
if !openAICompatShaped {
return ""
}
diff --git a/backend/internal/service/account_test_service_typesafe.go b/backend/internal/service/account_test_service_typesafe.go
new file mode 100644
index 000000000..5a2713270
--- /dev/null
+++ b/backend/internal/service/account_test_service_typesafe.go
@@ -0,0 +1,95 @@
+package service
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
+ "github.com/gin-gonic/gin"
+)
+
+const (
+ typeSafeTestDefaultState = "Sub2API connection test"
+ typeSafeTestQuestionID = "connection_test"
+ typeSafeTestMaxPreviewBytes = 2000
+)
+
+// testTypeSafeAccountConnection probes a TypeSafe account with a minimal native
+// System One request. TypeSafe accounts never speak the Claude protocol, so
+// they must not fall through to testClaudeAccountConnection (which would send
+// the key to /v1/messages and could misclassify the account).
+func (s *AccountTestService) testTypeSafeAccountConnection(c *gin.Context, account *Account, prompt string) error {
+ ctx := c.Request.Context()
+ if account.Type != AccountTypeAPIKey {
+ return s.sendErrorAndEnd(c, fmt.Sprintf("Unsupported account type: %s", account.Type))
+ }
+ apiKey := account.GetTypeSafeAPIKey()
+ if apiKey == "" {
+ return s.sendErrorAndEnd(c, "No API key available")
+ }
+ baseURL, err := s.validateUpstreamBaseURL(account.GetTypeSafeBaseURL())
+ if err != nil {
+ return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid base URL: %s", err.Error()))
+ }
+
+ state := strings.TrimSpace(prompt)
+ if state == "" {
+ state = typeSafeTestDefaultState
+ }
+ payload, err := json.Marshal(map[string]any{
+ "model": typesafe.JevLatestModel,
+ "state": state,
+ "questions": map[string]any{
+ typeSafeTestQuestionID: map[string]any{
+ "type": "noul",
+ "instructions": "Is this text a connection test?",
+ },
+ },
+ })
+ if err != nil {
+ return s.sendErrorAndEnd(c, "Failed to create test payload")
+ }
+
+ c.Writer.Header().Set("Content-Type", "text/event-stream")
+ c.Writer.Header().Set("Cache-Control", "no-cache")
+ c.Writer.Header().Set("Connection", "keep-alive")
+ c.Writer.Header().Set("X-Accel-Buffering", "no")
+ c.Writer.Flush()
+
+ s.sendEvent(c, TestEvent{Type: "test_start", Model: typesafe.JevLatestModel})
+
+ req, err := typesafe.NewSystemOneRequest(ctx, baseURL, apiKey, payload)
+ if err != nil {
+ return s.sendErrorAndEnd(c, "Failed to create request")
+ }
+ proxyURL := ""
+ if account.ProxyID != nil && account.Proxy != nil {
+ proxyURL = account.Proxy.URL()
+ }
+ resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency)
+ if err != nil {
+ return s.sendErrorAndEnd(c, fmt.Sprintf("Request failed: %s", sanitizeUpstreamErrorMessage(err.Error())))
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
+ errMsg := fmt.Sprintf("API returned %d: %s", resp.StatusCode, truncateString(string(body), typeSafeTestMaxPreviewBytes))
+ // 401/403 表示 API Key 无效或被上游拒绝,标记为 error 状态。
+ if (resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden) && s.accountRepo != nil {
+ _ = s.accountRepo.SetError(ctx, account.ID, errMsg)
+ }
+ return s.sendErrorAndEnd(c, errMsg)
+ }
+
+ decoded, err := typesafe.DecodeSystemOneResponse(resp.Body)
+ if err != nil {
+ return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid System One response: %s", err.Error()))
+ }
+ s.sendEvent(c, TestEvent{Type: "content", Text: truncateString(string(decoded.Body), typeSafeTestMaxPreviewBytes)})
+ s.sendEvent(c, TestEvent{Type: "test_complete", Success: true})
+ return nil
+}
diff --git a/backend/internal/service/account_test_service_typesafe_test.go b/backend/internal/service/account_test_service_typesafe_test.go
new file mode 100644
index 000000000..879b2a0d2
--- /dev/null
+++ b/backend/internal/service/account_test_service_typesafe_test.go
@@ -0,0 +1,92 @@
+package service
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func newTypeSafeAccountTestFixture(t *testing.T, status int, responseBody string) (*AccountTestService, *systemOnePolicyAccountRepo, *[]*http.Request, *gin.Context, *httptest.ResponseRecorder) {
+ t.Helper()
+ account := &Account{ID: 31, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "ts-secret"}}
+ repo := &systemOnePolicyAccountRepo{account: account}
+ var requests []*http.Request
+ upstream := &systemOneHTTPUpstream{do: func(req *http.Request) (*http.Response, error) {
+ requests = append(requests, req)
+ return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(responseBody))}, nil
+ }}
+ svc := &AccountTestService{
+ accountRepo: repo,
+ httpUpstream: upstream,
+ cfg: &config.Config{},
+ }
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/31/test", nil)
+ return svc, repo, &requests, c, rec
+}
+
+func TestTypeSafeAccountTestSendsNativeSystemOneRequest(t *testing.T) {
+ svc, repo, requests, c, rec := newTypeSafeAccountTestFixture(t, http.StatusOK, `{"model":"jev-1.13.0","answers":{"connection_test":{"type":"noul"}},"usage":{"input_tokens":9}}`)
+
+ // The Claude default model must be ignored: TypeSafe only serves jev-latest.
+ require.NoError(t, svc.TestAccountConnection(c, 31, "claude-sonnet-4-5", "", AccountTestModeDefault))
+
+ require.Len(t, *requests, 1)
+ req := (*requests)[0]
+ require.Equal(t, typesafe.DefaultBaseURL+typesafe.SystemOnePath, req.URL.String())
+ require.Equal(t, "Bearer ts-secret", req.Header.Get("Authorization"))
+ require.Empty(t, req.Header.Get("x-api-key"))
+ body, err := io.ReadAll(req.Body)
+ require.NoError(t, err)
+ model, err := typesafe.ValidateSystemOneRequest(body)
+ require.NoError(t, err)
+ require.Equal(t, typesafe.JevLatestModel, model)
+
+ output := rec.Body.String()
+ require.Contains(t, output, `"type":"test_start"`)
+ require.Contains(t, output, `"model":"jev-latest"`)
+ require.Contains(t, output, `"type":"test_complete"`)
+ require.Contains(t, output, "jev-1.13.0")
+ require.Zero(t, repo.errorCalls)
+}
+
+func TestTypeSafeAccountTestMarksRejectedKey(t *testing.T) {
+ for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ svc, repo, _, c, rec := newTypeSafeAccountTestFixture(t, status, `{"detail":"invalid key"}`)
+ require.Error(t, svc.TestAccountConnection(c, 31, "", "", AccountTestModeDefault))
+ require.Equal(t, 1, repo.errorCalls)
+ responseText, errMsg := parseTestSSEOutput(rec.Body.String())
+ require.Empty(t, responseText)
+ require.Contains(t, errMsg, "API returned")
+ })
+ }
+}
+
+func TestTypeSafeAccountTestTransientFailureKeepsAccountState(t *testing.T) {
+ svc, repo, _, c, _ := newTypeSafeAccountTestFixture(t, http.StatusServiceUnavailable, `{"detail":"busy"}`)
+ require.Error(t, svc.TestAccountConnection(c, 31, "", "", AccountTestModeDefault))
+ require.Zero(t, repo.errorCalls)
+}
+
+func TestTypeSafeAccountTestUsesPromptAsState(t *testing.T) {
+ svc, _, requests, c, _ := newTypeSafeAccountTestFixture(t, http.StatusOK, `{"answers":{}}`)
+ require.NoError(t, svc.TestAccountConnection(c, 31, "", "custom state", AccountTestModeDefault))
+ body, err := io.ReadAll((*requests)[0].Body)
+ require.NoError(t, err)
+ var payload struct {
+ State string `json:"state"`
+ }
+ require.NoError(t, json.Unmarshal(body, &payload))
+ require.Equal(t, "custom state", payload.State)
+}
diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go
index 9b7020b28..da292ad19 100644
--- a/backend/internal/service/admin_account.go
+++ b/backend/internal/service/admin_account.go
@@ -323,7 +323,7 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
return nil, err
}
- if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil {
+ if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil {
return nil, err
}
duplicate, err := buildAccountForCreate(input, accountExtra)
@@ -411,6 +411,9 @@ func normalizeOpenAILongContextBillingUpdateExtra(account *Account, input *Updat
// Grok media eligibility helpers live in account_grok_media_eligibility.go.
func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]any) (*Account, error) {
+ if input.Platform == PlatformTypeSafe && input.Type != AccountTypeAPIKey {
+ return nil, errors.New("typesafe accounts only support apikey credentials")
+ }
if input.Platform == PlatformOpenAIBPS {
creds, err := NormalizeOpenAIBPSCredentials(input.Type, input.Credentials, nil)
if err != nil {
@@ -532,7 +535,7 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
return nil, err
}
- if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil {
+ if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil {
return nil, err
}
// Never persist ephemeral SSO/password secrets after OAuth conversion.
@@ -592,6 +595,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
if err != nil {
return nil, err
}
+ if account.Platform == PlatformTypeSafe && input.Type != "" && input.Type != AccountTypeAPIKey {
+ return nil, errors.New("typesafe accounts only support apikey credentials")
+ }
var normalizedExtra map[string]any
if input.Extra != nil {
normalizedExtra, err = normalizeOpenAILongContextBillingUpdateExtra(account, input)
@@ -691,7 +697,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
if err := NormalizeHeaderOverrideCredentials(account.Credentials); err != nil {
return nil, err
}
- if err := NormalizeOpenCodeGoProtocolRulesCredentials(account.Credentials); err != nil {
+ if err := NormalizeProtocolRulesCredentials(account.Credentials); err != nil {
return nil, err
}
// Strip SSO/password residue that must never sit next to OAuth tokens.
@@ -1171,7 +1177,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
return nil, err
}
- if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil {
+ if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil {
return nil, err
}
// Bulk may mix platforms; always drop ephemeral SSO/password keys (cookie
diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go
index dd627cfae..e1401f6ec 100644
--- a/backend/internal/service/admin_group.go
+++ b/backend/internal/service/admin_group.go
@@ -10,6 +10,7 @@ import (
dbent "github.com/MACOS-DO/sub4api/ent"
"github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/antigravity"
"github.com/MACOS-DO/sub4api/internal/pkg/claude"
infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
@@ -17,6 +18,7 @@ import (
"github.com/MACOS-DO/sub4api/internal/pkg/logger"
"github.com/MACOS-DO/sub4api/internal/pkg/openai"
"github.com/MACOS-DO/sub4api/internal/pkg/pagination"
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
"github.com/MACOS-DO/sub4api/internal/pkg/xai"
)
@@ -298,6 +300,8 @@ func defaultModelsListCandidateIDs(platform string) []string {
return xai.DefaultModelIDs()
case PlatformOpenCodeGo:
return DefaultOpenCodeGoModelIDs()
+ case PlatformTypeSafe:
+ return []string{typesafe.JevLatestModel}
case PlatformComposite:
return compositeDefaultModelsListCandidateIDs()
default:
@@ -318,7 +322,13 @@ func defaultAllowImageGenerationForPlatform(platform string) bool {
func compositeDefaultModelsListCandidateIDs() []string {
seen := make(map[string]struct{})
ids := make([]string, 0)
- for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
+ for _, platform := range domain.CompositePrecedencePlatformIDs() {
+ // TypeSafe stays out of the static composite candidates (jev-latest only works
+ // through /v1/systemone); groups with TypeSafe accounts still get it from the
+ // account model mappings collected by GetGroupModelsListCandidates.
+ if platform == PlatformTypeSafe {
+ continue
+ }
for _, id := range defaultModelsListCandidateIDs(platform) {
if _, ok := seen[id]; ok {
continue
diff --git a/backend/internal/service/anthropic_apikey_auth.go b/backend/internal/service/anthropic_apikey_auth.go
index 8bd8c4ba8..a7f396307 100644
--- a/backend/internal/service/anthropic_apikey_auth.go
+++ b/backend/internal/service/anthropic_apikey_auth.go
@@ -21,7 +21,7 @@ func (a *Account) GetAnthropicAPIKeyAuthScheme() string {
if a == nil || a.Type != AccountTypeAPIKey {
return AnthropicAPIKeyAuthSchemeXAPIKey
}
- if a.Platform != PlatformAnthropic && !a.IsCNProvider() {
+ if a.Platform != PlatformAnthropic && !a.RoutesProtocolByInbound() {
return AnthropicAPIKeyAuthSchemeXAPIKey
}
diff --git a/backend/internal/service/anthropic_buffered_negative_index_test.go b/backend/internal/service/anthropic_buffered_negative_index_test.go
new file mode 100644
index 000000000..6684ce235
--- /dev/null
+++ b/backend/internal/service/anthropic_buffered_negative_index_test.go
@@ -0,0 +1,97 @@
+package service
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/apicompat"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// anthropicSSEWithNegativeBlockIndex is a buffered Anthropic stream in which a
+// malformed upstream sends content_block_delta with a negative index. The
+// buffered aggregators only bounded the index from above, so indexing
+// finalResp.Content with it panicked.
+func anthropicSSEWithNegativeBlockIndex() string {
+ return strings.Join([]string{
+ `event: message_start`,
+ `data: {"type":"message_start","message":{"id":"msg_neg","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","usage":{"input_tokens":10}}}`,
+ ``,
+ `event: content_block_start`,
+ `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
+ ``,
+ `event: content_block_delta`,
+ `data: {"type":"content_block_delta","index":-1,"delta":{"type":"text_delta","text":"IGNORED"}}`,
+ ``,
+ `event: content_block_delta`,
+ `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}`,
+ ``,
+ `event: message_delta`,
+ `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":5}}`,
+ ``,
+ `event: message_stop`,
+ `data: {"type":"message_stop"}`,
+ ``,
+ }, "\n")
+}
+
+func TestAnthropicBufferedAggregators_IgnoreNegativeBlockIndex(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ tests := []struct {
+ name string
+ run func(resp *http.Response, c *gin.Context) error
+ }{
+ {
+ name: "gateway chat completions",
+ run: func(resp *http.Response, c *gin.Context) error {
+ _, err := (&GatewayService{}).handleCCBufferedFromAnthropic(resp, c, "gpt-5", "claude-sonnet-4.5", nil, time.Now())
+ return err
+ },
+ },
+ {
+ name: "gateway responses",
+ run: func(resp *http.Response, c *gin.Context) error {
+ _, err := (&GatewayService{}).handleResponsesBufferedStreamingResponse(resp, c, "claude-sonnet-4.5", "claude-sonnet-4.5", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
+ return err
+ },
+ },
+ {
+ name: "openai native anthropic chat completions",
+ run: func(resp *http.Response, c *gin.Context) error {
+ _, err := newNativeAnthropicHangTestService(5).handleCCBufferedFromNativeAnthropic(resp, c, "glm-4.7", "glm-4.7", "glm-4.7", nil, time.Now())
+ return err
+ },
+ },
+ {
+ name: "openai native anthropic responses",
+ run: func(resp *http.Response, c *gin.Context) error {
+ _, err := newNativeAnthropicHangTestService(5).handleResponsesBufferedFromNativeAnthropic(resp, c, "glm-4.7", "glm-4.7", "glm-4.7", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
+ return err
+ },
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
+ resp := &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{},
+ Body: io.NopCloser(strings.NewReader(anthropicSSEWithNegativeBlockIndex())),
+ }
+
+ var err error
+ require.NotPanics(t, func() { err = tt.run(resp, c) })
+ require.NoError(t, err)
+ require.Contains(t, rec.Body.String(), "Hello")
+ require.NotContains(t, rec.Body.String(), "IGNORED")
+ })
+ }
+}
diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go
index d46d1342d..5a12ef074 100644
--- a/backend/internal/service/antigravity_gateway_gemini.go
+++ b/backend/internal/service/antigravity_gateway_gemini.go
@@ -194,7 +194,6 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
// 处理错误响应
if resp.StatusCode >= 400 {
respBody := s.readUpstreamErrorBody(resp)
- contentType := resp.Header.Get("Content-Type")
// 尽早关闭原始响应体,释放连接;后续逻辑仍可能需要读取 body,因此用内存副本重新包装。
_ = resp.Body.Close()
resp.Body = io.NopCloser(bytes.NewReader(respBody))
@@ -301,7 +300,6 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
Header: retryResp.Header.Clone(),
Body: io.NopCloser(bytes.NewReader(retryRespBody)),
}
- contentType = resp.Header.Get("Content-Type")
}
} else {
if switchErr, ok := IsAntigravityAccountSwitchError(retryErr); ok {
@@ -393,9 +391,6 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
})
return nil, &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: unwrappedForOps}
}
- if contentType == "" {
- contentType = "application/json"
- }
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
@@ -410,7 +405,8 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
})
logger.LegacyPrintf("service.antigravity_gateway", "[antigravity-Forward] upstream error status=%d body=%s", resp.StatusCode, truncateForLog(unwrappedForOps, 500))
MarkResponseCommitted(c)
- c.Data(resp.StatusCode, contentType, unwrappedForOps)
+ // 原始上游错误体仅保留在 ops 日志中;返回客户端的错误体需脱敏,避免泄露账号池身份(项目号/服务账号等)
+ c.Data(resp.StatusCode, "application/json", buildAntigravityClientErrorBody(resp.StatusCode, unwrappedForOps))
return nil, fmt.Errorf("antigravity upstream error: %d", resp.StatusCode)
}
diff --git a/backend/internal/service/antigravity_upstream_error_sanitize.go b/backend/internal/service/antigravity_upstream_error_sanitize.go
new file mode 100644
index 000000000..b937970d6
--- /dev/null
+++ b/backend/internal/service/antigravity_upstream_error_sanitize.go
@@ -0,0 +1,97 @@
+package service
+
+import (
+ "encoding/json"
+ "net/http"
+ "regexp"
+ "strings"
+)
+
+var (
+ antigravityProjectRefRegex = regexp.MustCompile(`(?i)\bprojects/[a-z0-9][a-z0-9._:-]*`)
+ antigravityEmailRegex = regexp.MustCompile(`[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}`)
+ antigravityConsumerRegex = regexp.MustCompile(`(?i)\b(consumer|project(?:[ _-]?(?:id|number))?)(\s*[:=]?\s*['"]?)[0-9]{6,}`)
+)
+
+// sanitizeAntigravityErrorText 清除上游错误文本中的 GCP 项目号/项目 ID、服务账号邮箱及敏感查询参数。
+func sanitizeAntigravityErrorText(msg string) string {
+ if msg == "" {
+ return msg
+ }
+ msg = sanitizeUpstreamErrorMessage(msg)
+ msg = antigravityProjectRefRegex.ReplaceAllString(msg, "projects/***")
+ msg = antigravityEmailRegex.ReplaceAllString(msg, "***")
+ msg = antigravityConsumerRegex.ReplaceAllString(msg, "$1$2***")
+ return msg
+}
+
+// buildAntigravityClientErrorBody 为客户端构造 Gemini 风格的错误体:
+// 仅保留 code/status/message(message 已脱敏),丢弃 details 等可能含账号身份的字段。
+func buildAntigravityClientErrorBody(statusCode int, body []byte) []byte {
+ code := statusCode
+ status := ""
+ message := ""
+
+ var parsed struct {
+ Error struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+ Status string `json:"status"`
+ } `json:"error"`
+ }
+ if err := json.Unmarshal(body, &parsed); err == nil {
+ if parsed.Error.Code != 0 {
+ code = parsed.Error.Code
+ }
+ status = parsed.Error.Status
+ message = parsed.Error.Message
+ }
+ if strings.TrimSpace(message) == "" {
+ message = strings.TrimSpace(extractUpstreamErrorMessage(body))
+ }
+ if strings.TrimSpace(message) == "" {
+ message = http.StatusText(statusCode)
+ if message == "" {
+ message = "Upstream request failed"
+ }
+ }
+ if status == "" {
+ status = antigravityGeminiStatusFromHTTP(statusCode)
+ }
+
+ out, err := json.Marshal(map[string]any{
+ "error": map[string]any{
+ "code": code,
+ "message": sanitizeAntigravityErrorText(message),
+ "status": status,
+ },
+ })
+ if err != nil {
+ return []byte(`{"error":{"code":500,"message":"Upstream request failed","status":"INTERNAL"}}`)
+ }
+ return out
+}
+
+func antigravityGeminiStatusFromHTTP(statusCode int) string {
+ switch statusCode {
+ case http.StatusBadRequest:
+ return "INVALID_ARGUMENT"
+ case http.StatusUnauthorized:
+ return "UNAUTHENTICATED"
+ case http.StatusForbidden:
+ return "PERMISSION_DENIED"
+ case http.StatusNotFound:
+ return "NOT_FOUND"
+ case http.StatusTooManyRequests:
+ return "RESOURCE_EXHAUSTED"
+ case http.StatusServiceUnavailable:
+ return "UNAVAILABLE"
+ case http.StatusGatewayTimeout:
+ return "DEADLINE_EXCEEDED"
+ default:
+ if statusCode >= 500 {
+ return "INTERNAL"
+ }
+ return "UNKNOWN"
+ }
+}
diff --git a/backend/internal/service/antigravity_upstream_error_sanitize_test.go b/backend/internal/service/antigravity_upstream_error_sanitize_test.go
new file mode 100644
index 000000000..3f4abf04a
--- /dev/null
+++ b/backend/internal/service/antigravity_upstream_error_sanitize_test.go
@@ -0,0 +1,50 @@
+//go:build unit
+
+package service
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildAntigravityClientErrorBody_ScrubsPoolIdentity(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ upstream := []byte(`{"error":{"code":403,"message":"Permission denied on resource project projects/123456789 for consumer: projects/123456789; caller pool-sa@my-gcp-proj.iam.gserviceaccount.com","status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","metadata":{"consumer":"projects/123456789","service":"cloudcode-pa.googleapis.com"}}]}}`)
+
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Data(http.StatusForbidden, "application/json", buildAntigravityClientErrorBody(http.StatusForbidden, upstream))
+
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ out := rec.Body.String()
+ require.NotContains(t, out, "123456789")
+ require.NotContains(t, out, "pool-sa@")
+ require.NotContains(t, out, "gserviceaccount.com")
+ require.NotContains(t, out, "details")
+
+ var parsed struct {
+ Error struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+ Status string `json:"status"`
+ } `json:"error"`
+ }
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &parsed))
+ require.Equal(t, 403, parsed.Error.Code)
+ require.Equal(t, "PERMISSION_DENIED", parsed.Error.Status)
+ require.True(t, strings.Contains(parsed.Error.Message, "Permission denied"))
+}
+
+func TestBuildAntigravityClientErrorBody_NonJSONBody(t *testing.T) {
+ out := string(buildAntigravityClientErrorBody(http.StatusTooManyRequests, []byte("quota exceeded for consumer 987654321 sa@x.iam.gserviceaccount.com")))
+ require.NotContains(t, out, "987654321")
+ require.NotContains(t, out, "gserviceaccount")
+ require.Contains(t, out, `"status":"RESOURCE_EXHAUSTED"`)
+ require.Contains(t, out, `"code":429`)
+}
diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go
index 2d5125cd7..f903c0538 100644
--- a/backend/internal/service/auth_service.go
+++ b/backend/internal/service/auth_service.go
@@ -1937,9 +1937,9 @@ func (s *AuthService) snapshotPlatformQuotaDefaults(ctx context.Context, userID
return nil
}
// 平台配额快照是 best-effort(fail-open):必须脱离调用方事务执行。
- // 否则某平台违反 user_platform_quotas 的 CHECK 约束(如尚未进约束的新平台)会让
- // 整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认配额快照"放大成
- // "整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。
+ // 否则写入时的任何数据库错误(历史上是新平台尚未加入 user_platform_quotas 的
+ // CHECK 约束)都会让整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认
+ // 配额快照"放大成"整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。
ctx = dbent.WithoutTx(ctx)
// 仅为至少配置了一档限额的平台建行:user_platform_quotas 中不存在的行等价于不限额,
// 三档全空的记录不携带任何可执行的限额。
diff --git a/backend/internal/service/auth_service_email_bind_test.go b/backend/internal/service/auth_service_email_bind_test.go
index 9fcc08d59..7f6a24408 100644
--- a/backend/internal/service/auth_service_email_bind_test.go
+++ b/backend/internal/service/auth_service_email_bind_test.go
@@ -1165,3 +1165,19 @@ func cloneEmailBindUser(user *service.User) *service.User {
cloned := *user
return &cloned
}
+
+func (s *emailBindCacheStub) IncrVerificationCodeAttempts(context.Context, string) (int, error) {
+ if s.data == nil {
+ return 0, errors.New("verification code not found")
+ }
+ s.data.Attempts++
+ return s.data.Attempts, nil
+}
+
+func (s *emailBindCacheStub) IncrNotifyVerifyCodeAttempts(context.Context, string) (int, error) {
+ return 0, errors.New("notify verification code not found")
+}
+
+func (s *emailBindCacheStub) ConsumePasswordResetToken(context.Context, string, string) (bool, error) {
+ return false, nil
+}
diff --git a/backend/internal/service/auth_service_register_test.go b/backend/internal/service/auth_service_register_test.go
index 10dac1fd7..b37a0cccb 100644
--- a/backend/internal/service/auth_service_register_test.go
+++ b/backend/internal/service/auth_service_register_test.go
@@ -1010,3 +1010,19 @@ func TestCanBypassRegistrationDisabledForOAuth(t *testing.T) {
})
}
}
+
+func (s *emailCacheStub) IncrVerificationCodeAttempts(context.Context, string) (int, error) {
+ if s.data == nil {
+ return 0, errors.New("verification code not found")
+ }
+ s.data.Attempts++
+ return s.data.Attempts, nil
+}
+
+func (s *emailCacheStub) IncrNotifyVerifyCodeAttempts(context.Context, string) (int, error) {
+ return 0, errors.New("notify verification code not found")
+}
+
+func (s *emailCacheStub) ConsumePasswordResetToken(context.Context, string, string) (bool, error) {
+ return false, nil
+}
diff --git a/backend/internal/service/billing_service.go b/backend/internal/service/billing_service.go
index 971a575bd..13b0b33f6 100644
--- a/backend/internal/service/billing_service.go
+++ b/backend/internal/service/billing_service.go
@@ -698,6 +698,12 @@ func (s *BillingService) initFallbackPricing() {
SupportsCacheBreakdown: false,
}
+ // TypeSafe Jev bills input tokens only: $0.042 per million tokens.
+ s.fallbackPrices["jev-latest"] = &ModelPricing{
+ InputPricePerToken: 0.042 / 1_000_000,
+ OutputPricePerToken: 0,
+ }
+
// ---- 智谱 GLM(Z.AI)----
// Source: https://docs.z.ai/guides/overview/pricing (USD per 1M tokens)
// 注意:CacheReadPricePerToken 即"缓存命中"价格,CacheCreationPricePerToken 留空(智谱未公开写入价,按 0 处理)。
@@ -994,6 +1000,9 @@ func (s *BillingService) initFallbackPricing() {
// getFallbackPricing 根据模型系列获取回退价格
func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
modelLower := strings.ToLower(model)
+ if modelLower == "jev-latest" {
+ return s.fallbackPrices["jev-latest"]
+ }
// 按模型系列匹配
if isClaudeFable51Model(modelLower) {
diff --git a/backend/internal/service/billing_service_test.go b/backend/internal/service/billing_service_test.go
index 07f6060ac..4d180337c 100644
--- a/backend/internal/service/billing_service_test.go
+++ b/backend/internal/service/billing_service_test.go
@@ -130,6 +130,20 @@ func TestGetModelPricing_CaseInsensitive(t *testing.T) {
require.Equal(t, p1.InputPricePerToken, p2.InputPricePerToken)
}
+func TestGetModelPricing_JevLatestInputOnlyAndChannelOverride(t *testing.T) {
+ svc := newTestBillingService()
+ pricing, err := svc.GetModelPricing("jev-latest")
+ require.NoError(t, err)
+ require.InDelta(t, 0.042/1_000_000, pricing.InputPricePerToken, 1e-15)
+ require.Zero(t, pricing.OutputPricePerToken)
+
+ input, output := 0.25/1_000_000, 0.5/1_000_000
+ pricing, err = svc.GetModelPricingWithChannel("jev-latest", &ChannelModelPricing{InputPrice: &input, OutputPrice: &output})
+ require.NoError(t, err)
+ require.Equal(t, input, pricing.InputPricePerToken)
+ require.Equal(t, output, pricing.OutputPricePerToken)
+}
+
// issue #3394: fallback warn 应按模型名去重,每个模型每进程最多打一条,
// 避免热路径每请求刷屏 ops_system_logs。
func TestGetModelPricing_FallbackWarnLoggedOncePerModel(t *testing.T) {
diff --git a/backend/internal/service/channel_monitor_checker.go b/backend/internal/service/channel_monitor_checker.go
index 61c7af20a..d8d29e895 100644
--- a/backend/internal/service/channel_monitor_checker.go
+++ b/backend/internal/service/channel_monitor_checker.go
@@ -302,7 +302,7 @@ func callProvider(ctx context.Context, provider, endpoint, apiKey, model, prompt
return "", "", 0, err
}
headers := mergeHeaders(adapter.buildHeaders(apiKey), opts)
- full := joinURL(endpoint, adapter.buildPath(model))
+ full := joinURL(endpoint, monitorRequestPath(provider, endpoint, adapter, model))
respBytes, status, err := postRawJSON(ctx, full, body, headers)
if err != nil {
return "", "", status, err
@@ -562,6 +562,37 @@ func postRawJSON(ctx context.Context, fullURL string, payload []byte, headers ma
return respBody, resp.StatusCode, nil
}
+// monitorRequestPath 返回探测请求路径。智谱按 endpoint 区分:
+// - 已带 /paas/v4(含 Coding Plan 的 /api/coding/paas/v4):只追加 /chat/completions
+// - 官方域名根地址:/api/paas/v4/chat/completions
+// - 中转站 / 本站网关:只暴露 OpenAI 兼容的 /v1/chat/completions,与 Kimi / DeepSeek 一致
+func monitorRequestPath(provider, endpoint string, adapter providerAdapter, model string) string {
+ if provider != MonitorProviderZhipu {
+ return adapter.buildPath(model)
+ }
+ u, err := url.Parse(strings.TrimSpace(endpoint))
+ if err != nil {
+ return providerOpenAIPath
+ }
+ if strings.Contains(u.EscapedPath(), "/paas/v4") {
+ return "/chat/completions"
+ }
+ if isZhipuOfficialHost(u) {
+ return adapter.buildPath(model)
+ }
+ return providerOpenAIPath
+}
+
+func isZhipuOfficialHost(u *url.URL) bool {
+ host := strings.ToLower(u.Hostname())
+ for _, official := range []string{"bigmodel.cn", "z.ai"} {
+ if host == official || strings.HasSuffix(host, "."+official) {
+ return true
+ }
+ }
+ return false
+}
+
// joinURL 保留 base 的上游路径前缀,并避免重复追加已有的 API 路径前缀。
// 使用 EscapedPath 匹配完整路径段,避免把 hostname 或编码斜杠当作路径。
func joinURL(base, path string) string {
diff --git a/backend/internal/service/channel_monitor_endpoint_test.go b/backend/internal/service/channel_monitor_endpoint_test.go
index 91482dd84..7bb95aaa1 100644
--- a/backend/internal/service/channel_monitor_endpoint_test.go
+++ b/backend/internal/service/channel_monitor_endpoint_test.go
@@ -84,6 +84,9 @@ func TestCallProvider_BasePath(t *testing.T) {
{"openai responses version", MonitorProviderOpenAI, MonitorAPIModeResponses, "/relay/v1", "/relay/v1/responses"},
{"gemini version", MonitorProviderGemini, "", "/relay/v1beta", "/relay/v1beta/models/test-model:generateContent"},
{"zhipu version", MonitorProviderZhipu, "", "/api/paas/v4", "/api/paas/v4/chat/completions"},
+ {"zhipu coding plan", MonitorProviderZhipu, "", "/api/coding/paas/v4", "/api/coding/paas/v4/chat/completions"},
+ {"zhipu relay origin", MonitorProviderZhipu, "", "", "/v1/chat/completions"},
+ {"zhipu relay version", MonitorProviderZhipu, "", "/relay/v1", "/relay/v1/chat/completions"},
} {
t.Run(tc.name, func(t *testing.T) {
_, _, status, err := callProvider(context.Background(), tc.provider,
@@ -94,3 +97,19 @@ func TestCallProvider_BasePath(t *testing.T) {
})
}
}
+
+func TestMonitorRequestPath_Zhipu(t *testing.T) {
+ adapter := providerAdapters[MonitorProviderZhipu]
+ for endpoint, want := range map[string]string{
+ "https://open.bigmodel.cn": providerZhipuPath,
+ "https://api.z.ai": providerZhipuPath,
+ "https://open.bigmodel.cn/api/coding/paas/v4": "/chat/completions",
+ "https://birdapi.up.railway.app": providerOpenAIPath,
+ "https://notbigmodel.cn": providerOpenAIPath,
+ "https://relay.example.com/v1": providerOpenAIPath,
+ } {
+ require.Equal(t, want, monitorRequestPath(MonitorProviderZhipu, endpoint, adapter, "glm-5.3-flash"), endpoint)
+ }
+ require.Equal(t, providerOpenAIPath,
+ monitorRequestPath(MonitorProviderDeepseek, "https://birdapi.up.railway.app", providerAdapters[MonitorProviderDeepseek], "m"))
+}
diff --git a/backend/internal/service/channel_monitor_v2.go b/backend/internal/service/channel_monitor_v2.go
index cb2251de7..d4aed72dc 100644
--- a/backend/internal/service/channel_monitor_v2.go
+++ b/backend/internal/service/channel_monitor_v2.go
@@ -963,6 +963,9 @@ func ChannelMonitorV2HealthForWithThresholds(metrics ChannelMonitorV2Metric, thr
Overall: "unknown", ErrorRate: "unknown", TTFT: "unknown", Cache: "unknown",
MinimumSample: thresholds.MinimumSample, Thresholds: thresholds,
}
+ if metrics.RequestCount < result.MinimumSample {
+ return result
+ }
type scored struct {
score float64
diff --git a/backend/internal/service/channel_monitor_v2_test.go b/backend/internal/service/channel_monitor_v2_test.go
index d26f43eef..c30f01cb7 100644
--- a/backend/internal/service/channel_monitor_v2_test.go
+++ b/backend/internal/service/channel_monitor_v2_test.go
@@ -252,6 +252,81 @@ func TestChannelMonitorV2HealthBlendsErrorTTFTAndCache(t *testing.T) {
require.Nil(t, health.Score)
}
+func TestChannelMonitorV2HealthRequiresRequestSamples(t *testing.T) {
+ for _, requestCount := range []int64{0, 8, 9, 49} {
+ t.Run(fmt.Sprintf("requests_%d", requestCount), func(t *testing.T) {
+ thresholds := DefaultChannelMonitorV2HealthThresholds()
+ thresholds.WarningCacheRate = 0.85
+ thresholds.CriticalCacheRate = 0.60
+ metrics := ChannelMonitorV2Metric{SuccessRequests: requestCount, RequestCount: requestCount}
+ if requestCount > 0 {
+ metrics.CacheRateDenominator = 448
+ }
+ health := ChannelMonitorV2HealthForWithThresholds(metrics, thresholds)
+ require.Equal(t, ChannelMonitorV2Health{
+ Overall: "unknown", ErrorRate: "unknown", TTFT: "unknown", Cache: "unknown",
+ MinimumSample: 50, Thresholds: NormalizeChannelMonitorV2HealthThresholds(thresholds),
+ }, health)
+ })
+ }
+}
+
+func TestChannelMonitorV2HealthMinimumSampleBoundaries(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ minimumSample int64
+ wantMinimum int64
+ }{
+ {name: "configured", minimumSample: 20, wantMinimum: 20},
+ {name: "configured_one", minimumSample: 1, wantMinimum: 1},
+ {name: "normalized_zero", minimumSample: 0, wantMinimum: 50},
+ {name: "normalized_negative", minimumSample: -1, wantMinimum: 50},
+ {name: "normalized_maximum", minimumSample: 10001, wantMinimum: 10000},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ thresholds := DefaultChannelMonitorV2HealthThresholds()
+ thresholds.MinimumSample = test.minimumSample
+ thresholds.WarningCacheRate = 0.85
+ thresholds.CriticalCacheRate = 0.60
+ p50 := int64(1000)
+ metrics := ChannelMonitorV2Metric{
+ SuccessRequests: test.wantMinimum - 1, RequestCount: test.wantMinimum - 1,
+ CacheRateDenominator: 20000,
+ TTFT: ChannelMonitorV2Latency{SampleCount: 20000, P50Ms: &p50},
+ }
+ health := ChannelMonitorV2HealthForWithThresholds(metrics, thresholds)
+ require.Equal(t, ChannelMonitorV2Health{
+ Overall: "unknown", ErrorRate: "unknown", TTFT: "unknown", Cache: "unknown",
+ MinimumSample: test.wantMinimum, Thresholds: NormalizeChannelMonitorV2HealthThresholds(thresholds),
+ }, health)
+
+ metrics.RequestCount = test.wantMinimum
+ metrics.SuccessRequests = test.wantMinimum
+ health = ChannelMonitorV2HealthForWithThresholds(metrics, thresholds)
+ require.Equal(t, test.wantMinimum, health.MinimumSample)
+ require.Equal(t, "healthy", health.ErrorRate)
+ require.Equal(t, "healthy", health.TTFT)
+ require.Equal(t, "critical", health.Cache)
+ require.NotNil(t, health.ErrorRateScore)
+ require.NotNil(t, health.TTFTScore)
+ require.NotNil(t, health.CacheScore)
+ require.NotNil(t, health.Score)
+ require.InDelta(t, 80.0, *health.Score, 0.01)
+ require.Equal(t, "healthy", health.Overall)
+ })
+ }
+}
+
+func TestChannelMonitorV2HealthSufficientHighErrorIsCritical(t *testing.T) {
+ health := ChannelMonitorV2HealthFor(ChannelMonitorV2Metric{
+ RequestCount: 50, ErrorRequests: 50, ErrorRate: 1,
+ })
+ require.Equal(t, "critical", health.ErrorRate)
+ require.Equal(t, "critical", health.Overall)
+ require.NotNil(t, health.Score)
+ require.Zero(t, *health.Score)
+}
+
func TestChannelMonitorV2HealthLeavesMissingTTFTUnknown(t *testing.T) {
health := ChannelMonitorV2HealthFor(ChannelMonitorV2Metric{
RequestCount: 200,
@@ -452,6 +527,9 @@ func TestSnapshotRedactsPublicConfigPolicyFields(t *testing.T) {
Metrics: ChannelMonitorV2Metric{RequestCount: 100, ErrorRate: 0.1, SuccessRate: 0.9, RPM: 5},
},
}
+ repo.snap.Health = ChannelMonitorV2HealthFor(repo.snap.Metrics)
+ wantHealth := repo.snap.Health
+ require.NotNil(t, wantHealth.Score)
svc := NewChannelMonitorV2Service(repo)
snap, err := svc.Snapshot(context.Background(), ChannelMonitorV2Filter{}, false)
require.NoError(t, err)
@@ -461,6 +539,7 @@ func TestSnapshotRedactsPublicConfigPolicyFields(t *testing.T) {
require.Empty(t, snap.Config.Platforms[0].Models)
require.Equal(t, 300, snap.Config.RefreshIntervalSeconds)
require.Zero(t, snap.Metrics.RequestCount)
+ require.Equal(t, wantHealth, snap.Health)
require.InDelta(t, 0.1, snap.Metrics.ErrorRate, 0.0001)
require.Zero(t, snap.Metrics.RPM)
}
diff --git a/backend/internal/service/channel_service.go b/backend/internal/service/channel_service.go
index e88ca8003..c7d2d114d 100644
--- a/backend/internal/service/channel_service.go
+++ b/backend/internal/service/channel_service.go
@@ -9,6 +9,7 @@ import (
"sync/atomic"
"time"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/ctxkey"
infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
"github.com/MACOS-DO/sub4api/internal/pkg/pagination"
@@ -368,7 +369,7 @@ func isPlatformPricingMatch(groupPlatform, pricingPlatform string) bool {
// fallback used before a request target has been resolved.
func matchingPlatforms(groupPlatform string) []string {
if groupPlatform == PlatformComposite {
- return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS}
+ return domain.CompositePrecedencePlatformIDs()
}
return []string{groupPlatform}
}
diff --git a/backend/internal/service/channel_service_test.go b/backend/internal/service/channel_service_test.go
index f683e278d..979b74142 100644
--- a/backend/internal/service/channel_service_test.go
+++ b/backend/internal/service/channel_service_test.go
@@ -2127,7 +2127,7 @@ func TestMatchingPlatforms(t *testing.T) {
{"anthropic returns itself", PlatformAnthropic, []string{PlatformAnthropic}},
{"gemini returns itself", PlatformGemini, []string{PlatformGemini}},
{"openai returns itself", PlatformOpenAI, []string{PlatformOpenAI}},
- {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS}},
+ {"composite returns concrete platforms", PlatformComposite, []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline, PlatformOpenAIBPS}},
}
for _, tt := range tests {
diff --git a/backend/internal/service/cline.go b/backend/internal/service/cline.go
new file mode 100644
index 000000000..75d54c0ad
--- /dev/null
+++ b/backend/internal/service/cline.go
@@ -0,0 +1,85 @@
+package service
+
+import (
+ "net/url"
+ "strings"
+)
+
+// Cline API(https://docs.cline.bot/api/overview):OpenAI 兼容的多模型聚合端点,
+// 基址 https://api.cline.bot/api/v1,只提供 Chat Completions(Cline 自己的客户端同样
+// 只走该端点),模型名带厂商前缀(如 anthropic/claude-sonnet-4-6)。Responses 与
+// Anthropic 入站由网关转换为 Chat Completions。
+//
+// 同一个 API Key 下有两个互不影响的额度来源(下称"钱包"),由模型名决定扣哪一个:
+// - 积分:cline-pass/* 与 cline-free/* 以外的模型按量扣账户积分,余额可查;
+// - ClinePass 订阅:cline-pass/* 模型,受 5 小时 / 7 天 / 30 天三档滚动用量上限限制,
+// 各档已用百分比与重置时间可查(/api/v1/users/me/plan/usage-limits);
+// - cline-free/* 免费模型不扣任何一边,只有逐模型的每日额度。
+//
+// 一边用完只影响该边的模型,所以超限冷却按钱包落在模型级冷却键上(见
+// clineWalletRateLimitKey),不停整个账号,也不需要管理员声明账号类型。
+
+const (
+ // DefaultClineTestModel 是连接测试的默认模型(按量积分,价格低、长期在售)。
+ DefaultClineTestModel = "deepseek/deepseek-v4-flash"
+ // DefaultClinePassTestModel 是订阅了 ClinePass 的账号连接测试的默认模型。
+ DefaultClinePassTestModel = "cline-pass/glm-5.3-flash"
+
+ clineAPIHost = "api.cline.bot"
+
+ clinePassModelPrefix = "cline-pass/"
+ clineFreeModelPrefix = "cline-free/"
+
+ // clinePassRateLimitKey / clineCreditsRateLimitKey 是两个钱包的模型级冷却键:
+ // 命中后该钱包的全部模型都不再调度到该账号,另一边不受影响。
+ clinePassRateLimitKey = "cline:pass"
+ clineCreditsRateLimitKey = "cline:credits"
+)
+
+// IsCline 报告账号是否为 Cline 平台账号。
+func (a *Account) IsCline() bool {
+ return a != nil && a.Platform == PlatformCline
+}
+
+// clineWalletRateLimitKey 返回模型所属钱包的冷却键;免费模型不属于任何钱包,返回空串。
+func clineWalletRateLimitKey(model string) string {
+ model = strings.ToLower(strings.TrimSpace(model))
+ switch {
+ case model == "":
+ return ""
+ case strings.HasPrefix(model, clinePassModelPrefix):
+ return clinePassRateLimitKey
+ case strings.HasPrefix(model, clineFreeModelPrefix):
+ return ""
+ default:
+ return clineCreditsRateLimitKey
+ }
+}
+
+// isOfficialClineHost 报告 URL 是否指向官方 Cline API 主机。
+func isOfficialClineHost(target string) bool {
+ parsed, err := url.Parse(strings.TrimSpace(target))
+ if err != nil {
+ return false
+ }
+ return strings.EqualFold(parsed.Scheme, "https") && strings.EqualFold(parsed.Hostname(), clineAPIHost)
+}
+
+// clineAccountAPISupported 报告账号能否查询积分余额与 ClinePass 用量:API Key 账号且
+// 推理端点指向官方主机。自定义中转的 Key 不发往官方账号接口。
+func (a *Account) clineAccountAPISupported() bool {
+ return a.IsCline() && a.Type == AccountTypeAPIKey && isOfficialClineHost(a.GetOpenAIBaseURL())
+}
+
+// clinePassSubscribed 报告最近一次用量探测是否显示账号订阅了 ClinePass(有窗口快照)。
+func (a *Account) clinePassSubscribed() bool {
+ if a == nil || a.Extra == nil {
+ return false
+ }
+ for _, suffix := range []string{cnExtraSuffix5hUsed, cnExtraSuffixWeeklyUsed, cnExtraSuffixMonthlyUsed} {
+ if value, ok := a.Extra[cnExtraKey(PlatformCline, suffix)]; ok && value != nil {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/internal/service/cline_test.go b/backend/internal/service/cline_test.go
new file mode 100644
index 000000000..bfcfbad4e
--- /dev/null
+++ b/backend/internal/service/cline_test.go
@@ -0,0 +1,648 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// clineTestAccount 只带 api_key:端点与测试模型全部来自 provider profile。
+func clineTestAccount(id int64) *Account {
+ return &Account{
+ ID: id,
+ Name: "cline",
+ Platform: PlatformCline,
+ Type: AccountTypeAPIKey,
+ Status: StatusActive,
+ Schedulable: true,
+ Concurrency: 1,
+ Credentials: map[string]any{"api_key": "cline_test_key", "api_protocol": APIProtocolAdaptive},
+ }
+}
+
+// withClinePassSnapshot 模拟用量探测写入的 ClinePass 窗口快照。
+func withClinePassSnapshot(account *Account, extra map[string]any) *Account {
+ account.Extra = map[string]any{"cline_5h_used_percent": 10.0, "cline_weekly_used_percent": 20.0, "cline_monthly_used_percent": 30.0}
+ for key, value := range extra {
+ account.Extra[key] = value
+ }
+ return account
+}
+
+func TestClineProfileSingleModeChatCompletionsOnly(t *testing.T) {
+ profile := LookupProviderProfile(PlatformCline)
+ require.NotNil(t, profile)
+ require.Len(t, profile.Modes, 1)
+
+ account := clineTestAccount(1)
+ require.True(t, account.IsMultiProtocolAPIKey())
+ require.True(t, account.RoutesProtocolByInbound())
+ require.False(t, account.routesByModel())
+ require.Equal(t, APIProtocolAdaptive, account.GetAPIProtocol())
+ require.Equal(t, DefaultClineBaseURL, account.GetOpenAIBaseURL())
+ require.False(t, account.SupportsNativeCNResponses())
+ require.False(t, account.providerSupportsProtocol(APIProtocolAnthropic))
+ for _, inbound := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic} {
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, inbound, "anthropic/claude-sonnet-4-6", nil), inbound)
+ }
+
+ require.False(t, account.clinePassSubscribed())
+ require.Equal(t, DefaultClineTestModel, account.providerDefaultTestModel())
+ subscribed := withClinePassSnapshot(clineTestAccount(2), nil)
+ require.True(t, subscribed.clinePassSubscribed())
+ require.Equal(t, DefaultClinePassTestModel, subscribed.providerDefaultTestModel())
+ // 取消订阅后探测把窗口写成 nil。
+ cancelled := withClinePassSnapshot(clineTestAccount(3), map[string]any{
+ "cline_5h_used_percent": nil, "cline_weekly_used_percent": nil, "cline_monthly_used_percent": nil,
+ })
+ require.False(t, cancelled.clinePassSubscribed())
+}
+
+// 经真实入口:三种入站都转换 / 直通到 Chat Completions,模型名带厂商前缀原样发往上游。
+func TestClineGatewayForwardsToChatCompletions(t *testing.T) {
+ for _, ingress := range routingMatrixIngresses() {
+ upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+ body := routingMatrixCase{ingress: ingress, model: "anthropic/claude-sonnet-4-6"}.body()
+ _ = ingress.forward(svc, adaptiveProtocolTestContext(ingress.path, body), clineTestAccount(3), body)
+
+ require.NotEmpty(t, upstream.requests, ingress.name)
+ require.Equal(t, "https://api.cline.bot/api/v1/chat/completions", upstream.requests[len(upstream.requests)-1].URL.String(), ingress.name)
+ require.Equal(t, "Bearer cline_test_key", upstream.requests[len(upstream.requests)-1].Header.Get("Authorization"), ingress.name)
+ require.True(t, gjson.GetBytes(upstream.lastBody, "messages").Exists(), ingress.name)
+ require.Equal(t, "anthropic/claude-sonnet-4-6", gjson.GetBytes(upstream.lastBody, "model").String(), ingress.name)
+ }
+}
+
+// 连接测试未指定模型时:订阅了 ClinePass 用订阅模型(不消耗积分),否则用按量模型;
+// ClinePass 钱包冷却中也用按量模型;自适应与固定 Chat Completions 一致。
+func TestAccountTestService_ClineDefaultTestModel(t *testing.T) {
+ cases := []struct {
+ subscribed bool
+ passCooling bool
+ apiProtocol string
+ want string
+ }{
+ {false, false, "", DefaultClineTestModel},
+ {true, false, "", DefaultClinePassTestModel},
+ {false, false, APIProtocolChatCompletions, DefaultClineTestModel},
+ {true, false, APIProtocolChatCompletions, DefaultClinePassTestModel},
+ {true, true, "", DefaultClineTestModel},
+ }
+ for i, tc := range cases {
+ account := clineTestAccount(int64(600 + i))
+ if tc.subscribed {
+ withClinePassSnapshot(account, nil)
+ }
+ if tc.passCooling {
+ now := time.Now()
+ setAccountModelRateLimitSnapshot(account, clinePassRateLimitKey, now.Add(time.Hour), clinePassLimitReason, now)
+ }
+ if tc.apiProtocol != "" {
+ account.Credentials["api_protocol"] = tc.apiProtocol
+ }
+ svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
+ c, recorder := newTestContext()
+
+ err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
+
+ require.NoError(t, err, tc)
+ require.Len(t, upstream.requests, 1, tc)
+ require.Equal(t, "https://api.cline.bot/api/v1/chat/completions", upstream.requests[0].URL.String(), tc)
+ require.Equal(t, tc.want, gjson.GetBytes(upstream.lastBody, "model").String(), tc)
+ require.Contains(t, recorder.Body.String(), `"type":"test_complete"`, tc)
+ }
+}
+
+// 响应体样例取自 Cline 客户端的判定文案与官方错误文档。
+const (
+ clineInsufficientCreditsBody = `{"error":{"code":"insufficient_credits","message":"Insufficient credits","details":{"current_balance":0}}}`
+ clineSpendLimitBody = `{"error":{"code":"SPEND_LIMIT_EXCEEDED","message":"Organization spend limit exceeded"}}`
+ clineInferenceCapBody = `{"error":{"code":"INFERENCE_CAP_ERROR","message":"Inference cap reached"}}`
+ clinePass5hBody = `{"error":{"code":429,"message":"You have reached your 5-hour ClinePass limit. Please try again later."}}`
+ clinePassWeeklyBody = `{"error":{"code":429,"message":"You have reached your weekly ClinePass limit. Please try again later."}}`
+ clinePassMonthlyBody = `{"error":{"code":429,"message":"You have reached your monthly ClinePass limit. Please try again later."}}`
+ clineNotSubscribedBody = `{"error":{"code":403,"message":"The user is not subscribed to required model plan"}}`
+ clineOrgPassBody = `{"error":{"code":403,"message":"Organization accounts cannot use individual model inference subscriptions"}}`
+ clineFreeModelLimitBody = `{"error":{"code":429,"message":"Free limit reached on model cline-free/kimi-k3. Try again in 3h 20m"}}`
+ clineRateLimitBody = `{"error":{"code":429,"message":"Rate limit exceeded"}}`
+)
+
+func TestClassifyClineError(t *testing.T) {
+ cases := map[string]clineErrorKind{
+ clineInsufficientCreditsBody: clineCreditsExhausted,
+ clineSpendLimitBody: clineSpendLimit,
+ clineInferenceCapBody: clineInferenceCap,
+ clinePass5hBody: clinePassLimit,
+ clinePassWeeklyBody: clinePassLimit,
+ clineNotSubscribedBody: clinePassUnavailable,
+ clineOrgPassBody: clinePassUnavailable,
+ clineFreeModelLimitBody: clineFreeModelLimit,
+ clineRateLimitBody: clineErrorNone,
+ `{"error":{"message":"You have reached your limit. Please try again later."}}`: clineErrorNone,
+ }
+ for body, want := range cases {
+ kind, _ := parseClineError([]byte(body))
+ require.Equal(t, want, kind, body)
+ }
+
+ require.Equal(t, "5h", clinePassWindow([]byte(clinePass5hBody)))
+ require.Equal(t, "weekly", clinePassWindow([]byte(clinePassWeeklyBody)))
+ require.Equal(t, "monthly", clinePassWindow([]byte(clinePassMonthlyBody)))
+ require.Equal(t, 3*time.Hour+20*time.Minute, clineFreeModelResetAfter([]byte(clineFreeModelLimitBody)))
+ require.Zero(t, clineFreeModelResetAfter([]byte(`Free limit reached on model x. Try again in 3 weeks`)))
+}
+
+// ClinePass 超限冷却到快照中该窗口的重置时间;没有可用快照时按窗口估计。
+func TestClinePassLimitCooldown(t *testing.T) {
+ now := time.Now()
+ require.Equal(t, clineLimitRecheck, clinePassLimitCooldown(clineTestAccount(1), "5h", now))
+ require.Equal(t, clinePassWeeklyRecheck, clinePassLimitCooldown(clineTestAccount(1), "weekly", now))
+ require.Equal(t, clinePassMonthlyRecheck, clinePassLimitCooldown(clineTestAccount(1), "monthly", now))
+
+ account := withClinePassSnapshot(clineTestAccount(2), map[string]any{
+ "cline_weekly_reset_at": now.Add(50 * time.Hour).UTC().Format(time.RFC3339),
+ "cline_5h_reset_at": now.Add(-time.Minute).UTC().Format(time.RFC3339),
+ })
+ require.InDelta(t, (50 * time.Hour).Seconds(), clinePassLimitCooldown(account, "weekly", now).Seconds(), 1)
+ require.Equal(t, clineLimitRecheck, clinePassLimitCooldown(account, "5h", now), "past reset falls back to the estimate")
+}
+
+// cline-pass/* 与其余付费模型各自落在钱包冷却键上,免费模型不属于任何钱包;调度按
+// 请求模型检查所属钱包。
+func TestClineWalletRateLimitKeys(t *testing.T) {
+ require.Equal(t, clinePassRateLimitKey, clineWalletRateLimitKey("cline-pass/glm-5.3"))
+ require.Equal(t, clinePassRateLimitKey, clineWalletRateLimitKey(" Cline-Pass/GLM-5.3 "))
+ require.Equal(t, clineCreditsRateLimitKey, clineWalletRateLimitKey("deepseek/deepseek-v4-flash"))
+ require.Empty(t, clineWalletRateLimitKey("cline-free/kimi-k3"))
+ require.Empty(t, clineWalletRateLimitKey(""))
+
+ account := clineTestAccount(1)
+ setAccountModelRateLimitSnapshot(account, clinePassRateLimitKey, time.Now().Add(time.Hour), clinePassLimitReason, time.Now())
+ ctx := context.Background()
+ require.True(t, account.isModelRateLimitedWithContext(ctx, "cline-pass/glm-5.3"))
+ require.False(t, account.isModelRateLimitedWithContext(ctx, "deepseek/deepseek-v4-flash"))
+ require.False(t, account.isModelRateLimitedWithContext(ctx, "cline-free/kimi-k3"))
+
+ setAccountModelRateLimitSnapshot(account, clineCreditsRateLimitKey, time.Now().Add(time.Hour), clineCreditsReason, time.Now())
+ require.True(t, account.isModelRateLimitedWithContext(ctx, "deepseek/deepseek-v4-flash"))
+ require.False(t, account.isModelRateLimitedWithContext(ctx, "cline-free/kimi-k3"))
+ require.Equal(t, clineCreditsReason, account.modelRateLimitReason(clineCreditsRateLimitKey))
+
+ // 其他平台不受 Cline 钱包键影响。
+ other := &Account{Platform: PlatformDeepseek, Extra: account.Extra}
+ require.False(t, other.isModelRateLimitedWithContext(ctx, "cline-pass/glm-5.3"))
+}
+
+// 已识别的错误只冷却请求模型所属的钱包(或免费模型本身),不停整个账号、不置 error。
+func TestHandleUpstreamError_ClineCoolsDownWallet(t *testing.T) {
+ paid := "deepseek/deepseek-v4-flash"
+ pass := "cline-pass/glm-5.3"
+ now := time.Now()
+ snapshot := withClinePassSnapshot(clineTestAccount(1), map[string]any{
+ "cline_5h_reset_at": now.Add(2 * time.Hour).UTC().Format(time.RFC3339),
+ })
+ cases := []struct {
+ name string
+ account *Account
+ model string
+ status int
+ body string
+ scope string
+ wait time.Duration
+ reason string
+ }{
+ {"pass weekly", clineTestAccount(10), pass, http.StatusTooManyRequests, clinePassWeeklyBody, clinePassRateLimitKey, clinePassWeeklyRecheck, clinePassLimitReason},
+ {"pass 5h from snapshot", snapshot, pass, http.StatusTooManyRequests, clinePass5hBody, clinePassRateLimitKey, 2 * time.Hour, clinePassLimitReason},
+ {"not subscribed", clineTestAccount(11), pass, http.StatusForbidden, clineNotSubscribedBody, clinePassRateLimitKey, clineLimitRecheck, clinePassUnavailableReason},
+ {"credits", clineTestAccount(12), paid, http.StatusPaymentRequired, clineInsufficientCreditsBody, clineCreditsRateLimitKey, cnBalanceCheckCooldown(nil), clineCreditsReason},
+ {"unrecognized 402", clineTestAccount(13), paid, http.StatusPaymentRequired, `{"error":{"message":"Payment required"}}`, clineCreditsRateLimitKey, cnBalanceCheckCooldown(nil), clineCreditsReason},
+ {"spend limit", clineTestAccount(14), paid, http.StatusTooManyRequests, clineSpendLimitBody, clineCreditsRateLimitKey, clineLimitRecheck, clineSpendLimitReason},
+ {"inference cap on paid model", clineTestAccount(15), paid, http.StatusTooManyRequests, clineInferenceCapBody, clineCreditsRateLimitKey, clineLimitRecheck, clineInferenceCapReason},
+ {"inference cap on pass model", clineTestAccount(16), pass, http.StatusTooManyRequests, clineInferenceCapBody, clinePassRateLimitKey, clineLimitRecheck, clineInferenceCapReason},
+ {"unknown model uses the error's wallet", clineTestAccount(17), "", http.StatusForbidden, clineOrgPassBody, clinePassRateLimitKey, clineLimitRecheck, clinePassUnavailableReason},
+ {"free model", clineTestAccount(18), "cline-free/kimi-k3", http.StatusTooManyRequests, clineFreeModelLimitBody, "cline-free/kimi-k3", 3*time.Hour + 20*time.Minute, clineFreeModelLimitReason},
+ }
+ for _, tc := range cases {
+ ctx := context.Background()
+ if tc.model != "" {
+ ctx = withTempUnschedulableModel(ctx, []string{tc.model})
+ }
+ repo := &commandCodeRateLimitRepo{}
+
+ shouldDisable := NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(ctx, tc.account,
+ tc.status, http.Header{}, []byte(tc.body))
+
+ require.False(t, shouldDisable, tc.name)
+ require.Equal(t, 0, repo.tempCalls, tc.name)
+ require.Equal(t, 0, repo.setErrorCalls, tc.name)
+ require.Equal(t, 0, repo.rateLimitedCalls, tc.name)
+ require.Len(t, repo.modelLimits, 1, tc.name)
+ require.WithinDuration(t, time.Now().Add(tc.wait), repo.modelLimits[tc.scope], time.Minute, tc.name)
+ require.True(t, strings.HasPrefix(repo.reasons[tc.scope], tc.reason), tc.name+": "+repo.reasons[tc.scope])
+ require.True(t, tc.account.isRateLimitActiveForKey(tc.scope), tc.name)
+ }
+
+ // 普通频率限制交回默认 429 逻辑。
+ plain := &commandCodeRateLimitRepo{}
+ NewRateLimitService(plain, nil, &config.Config{}, nil, nil).HandleUpstreamError(withTempUnschedulableModel(context.Background(), []string{paid}),
+ clineTestAccount(30), http.StatusTooManyRequests, http.Header{}, []byte(clineRateLimitBody))
+ require.Empty(t, plain.modelLimits)
+ require.Equal(t, 0, plain.tempCalls)
+}
+
+// clineModelLimitFailRepo 让钱包冷却写入失败。
+type clineModelLimitFailRepo struct {
+ commandCodeRateLimitRepo
+}
+
+func (r *clineModelLimitFailRepo) SetModelRateLimit(context.Context, int64, string, time.Time, ...string) error {
+ return errors.New("db unavailable")
+}
+
+// 积分冷却写入失败时 402 也不落入默认分支永久置 error:探测只覆盖激活账号,置 error 后
+// 充值也无法自动恢复。
+func TestHandleUpstreamError_Cline402KeepsAccountWhenCooldownWriteFails(t *testing.T) {
+ ctx := withTempUnschedulableModel(context.Background(), []string{"deepseek/deepseek-v4-flash"})
+ for _, body := range []string{clineInsufficientCreditsBody, `{"error":{"message":"Payment required"}}`} {
+ repo := &clineModelLimitFailRepo{}
+
+ shouldDisable := NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(ctx, clineTestAccount(19),
+ http.StatusPaymentRequired, http.Header{}, []byte(body))
+
+ require.False(t, shouldDisable, body)
+ require.Equal(t, 0, repo.setErrorCalls, body)
+ require.Equal(t, 0, repo.tempCalls, body)
+ }
+}
+
+// clineAccountRepo 为余额 / 用量探测与周期检测提供 Cline 账号,并记录写入。
+type clineAccountRepo struct {
+ AccountRepository
+ accounts []Account
+ mu sync.Mutex
+ extraWrites map[int64][]map[string]any
+ modelLimits map[int64]map[string]time.Time
+ reasons map[int64]map[string]string
+ paused []int64
+}
+
+func (r *clineAccountRepo) ListByPlatform(_ context.Context, platform string) ([]Account, error) {
+ if platform == PlatformCline {
+ return r.accounts, nil
+ }
+ return nil, nil
+}
+
+func (r *clineAccountRepo) GetByID(_ context.Context, id int64) (*Account, error) {
+ for i := range r.accounts {
+ if r.accounts[i].ID == id {
+ return &r.accounts[i], nil
+ }
+ }
+ return nil, errors.New("not found")
+}
+
+func (r *clineAccountRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.extraWrites == nil {
+ r.extraWrites = map[int64][]map[string]any{}
+ }
+ r.extraWrites[id] = append(r.extraWrites[id], updates)
+ return nil
+}
+
+func (r *clineAccountRepo) SetModelRateLimit(_ context.Context, id int64, scope string, resetAt time.Time, reason ...string) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.modelLimits == nil {
+ r.modelLimits = map[int64]map[string]time.Time{}
+ r.reasons = map[int64]map[string]string{}
+ }
+ if r.modelLimits[id] == nil {
+ r.modelLimits[id] = map[string]time.Time{}
+ r.reasons[id] = map[string]string{}
+ }
+ r.modelLimits[id][scope] = resetAt
+ if len(reason) > 0 {
+ r.reasons[id][scope] = reason[0]
+ }
+ return nil
+}
+
+func (r *clineAccountRepo) SetTempUnschedulable(_ context.Context, id int64, _ time.Time, _ string) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.paused = append(r.paused, id)
+ return nil
+}
+
+const (
+ clineUsageLimitsPath = "/api/v1/users/me/plan/usage-limits"
+ clineUsageLimitsBody = `{"data":{"limits":[{"type":"five_hour","percentUsed":12.5,"resetsAt":"2099-01-01T05:00:00.123456Z"},{"type":"weekly","percentUsed":40},{"type":"monthly","percentUsed":0}]},"success":true}`
+)
+
+func newClineAccountUpstream(usageLimits commandCodeAlphaResponse, balance string) *commandCodeAlphaUpstream {
+ return &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
+ clineUsageLimitsPath: usageLimits,
+ "/api/v1/users/me": {status: http.StatusOK, body: `{"success":true,"data":{"id":"u-1","email":"a@example.com"}}`},
+ "/api/v1/users/u-1/balance": {status: http.StatusOK, body: balance},
+ }}
+}
+
+// balance 是百万分之一积分(1 积分 = 1 美元),按 Cline 的展示精度保留 4 位小数。
+func TestClineBalanceProbeConvertsMicrocredits(t *testing.T) {
+ for _, tc := range []struct {
+ balance string
+ want float64
+ }{
+ {`{"balance":12340000,"userId":"u-1"}`, 12.34},
+ {`{"success":true,"data":{"balance":"500000","userId":"u-1"}}`, 0.5},
+ {`{"balance":1234567,"userId":"u-1"}`, 1.2346},
+ } {
+ account := clineTestAccount(40)
+ upstream := newClineAccountUpstream(commandCodeAlphaResponse{}, tc.balance)
+ repo := &cnBalanceProbeRepo{account: account}
+ svc := NewCNProviderBalanceService(repo, nil, upstream, &config.Config{})
+
+ result, err := svc.QueryBalance(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.True(t, result.Persisted)
+ require.InDelta(t, tc.want, result.Balance, 1e-9)
+ require.Equal(t, "USD", result.Currency)
+ require.Len(t, upstream.requests, 2)
+ require.Equal(t, "Bearer cline_test_key", upstream.requests[0].Header.Get("Authorization"))
+ require.InDelta(t, tc.want, repo.extraWrites[0]["cline_balance"], 1e-9)
+ }
+}
+
+func TestClineBalanceProbeFailures(t *testing.T) {
+ account := clineTestAccount(41)
+ upstream := &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
+ "/api/v1/users/me": {status: http.StatusUnauthorized, body: `{"error":"Unauthorized"}`},
+ }}
+ repo := &cnBalanceProbeRepo{account: account}
+ result, err := NewCNProviderBalanceService(repo, nil, upstream, &config.Config{}).QueryBalance(context.Background(), account.ID)
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Equal(t, http.StatusUnauthorized, result.StatusCode)
+ require.Contains(t, result.Error, "HTTP 401")
+ require.Empty(t, repo.extraWrites)
+
+ envelope := &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
+ "/api/v1/users/me": {status: http.StatusOK, body: `{"success":false,"error":"token expired"}`},
+ }}
+ result, err = NewCNProviderBalanceService(&cnBalanceProbeRepo{account: account}, nil, envelope, &config.Config{}).QueryBalance(context.Background(), account.ID)
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Contains(t, result.Error, "token expired")
+}
+
+// 余额与用量只查官方主机上的 API Key 账号:自定义中转的 Key 不发往官方账号接口。
+func TestClineAccountAPIRequiresOfficialHost(t *testing.T) {
+ require.NoError(t, validatePayGAccount(clineTestAccount(50)))
+ require.NoError(t, validateCodingPlanAccount(clineTestAccount(50)))
+ require.Equal(t, PlatformCline, clineTestAccount(50).GetCodingPlanProvider())
+
+ relay := clineTestAccount(52)
+ relay.Credentials["base_url"] = "https://relay.example.com/v1"
+ relay.Credentials["api_protocol"] = APIProtocolChatCompletions
+ require.Error(t, validatePayGAccount(relay))
+ require.Error(t, validateCodingPlanAccount(relay))
+ require.Empty(t, relay.GetCodingPlanProvider())
+}
+
+func clineUsageTestConfig() *config.Config {
+ cfg := &config.Config{}
+ cfg.Gateway.CNProviders.BalanceThreshold = 0.5
+ return cfg
+}
+
+// 一次探测刷新三档窗口与积分余额;两个钱包都可用时不写冷却。
+func TestClineUsageProbeWritesWindowsAndBalance(t *testing.T) {
+ account := clineTestAccount(60)
+ repo := &clineAccountRepo{accounts: []Account{*account}}
+ upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, `{"success":true,"data":{"balance":12340000}}`)
+
+ result, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.True(t, result.CredentialValid)
+ require.True(t, result.Persisted)
+ require.Equal(t, "ClinePass", result.PlanLevel)
+ require.Equal(t, []CNQuotaTier{
+ {Window: "5h", UsedPercent: 12.5, ResetAt: "2099-01-01T05:00:00Z"},
+ {Window: "weekly", UsedPercent: 40},
+ {Window: "monthly", UsedPercent: 0},
+ }, result.Tiers)
+ require.NotNil(t, result.Balance)
+ require.InDelta(t, 12.34, result.Balance.Balance, 1e-9)
+ require.Equal(t, "Bearer cline_test_key", upstream.requests[0].Header.Get("Authorization"))
+
+ written := repo.extraWrites[60][0]
+ require.Equal(t, 12.5, written["cline_5h_used_percent"])
+ require.Equal(t, "2099-01-01T05:00:00Z", written["cline_5h_reset_at"])
+ require.Equal(t, 40.0, written["cline_weekly_used_percent"])
+ require.Contains(t, written, "cline_weekly_reset_at")
+ require.Nil(t, written["cline_weekly_reset_at"], "a window that has not started has no reset time")
+ require.InDelta(t, 12.34, written["cline_balance"], 1e-9)
+ require.Empty(t, repo.modelLimits)
+}
+
+// 窗口用满冷却 ClinePass 到重置时间;积分低于阈值冷却积分钱包;都不停整个账号。
+func TestClineUsageProbeCoolsDownExhaustedWallets(t *testing.T) {
+ resetAt := time.Now().Add(72 * time.Hour).UTC().Truncate(time.Second)
+ body := `{"data":{"limits":[{"type":"five_hour","percentUsed":30},{"type":"weekly","percentUsed":100,"resetsAt":"` +
+ resetAt.Format(time.RFC3339) + `"}]},"success":true}`
+ account := clineTestAccount(61)
+ repo := &clineAccountRepo{accounts: []Account{*account}}
+ upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: body}, `{"success":true,"data":{"balance":200000}}`)
+
+ _, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.True(t, repo.modelLimits[61][clinePassRateLimitKey].Equal(resetAt))
+ require.Equal(t, clinePassLimitReason+": weekly window used up", repo.reasons[61][clinePassRateLimitKey])
+ require.WithinDuration(t, time.Now().Add(cnBalanceCheckCooldown(nil)), repo.modelLimits[61][clineCreditsRateLimitKey], time.Minute)
+ require.True(t, strings.HasPrefix(repo.reasons[61][clineCreditsRateLimitKey], clineCreditsLowReason), repo.reasons[61][clineCreditsRateLimitKey])
+ require.Empty(t, repo.paused)
+}
+
+// 没有订阅(404 或空列表):清掉旧窗口快照,ClinePass 模型不调度到该账号。
+func TestClineUsageProbeWithoutSubscription(t *testing.T) {
+ for _, usage := range []commandCodeAlphaResponse{
+ {status: http.StatusNotFound, body: `{"success":false,"error":"no plan history found for user"}`},
+ {status: http.StatusOK, body: `{"success":true,"data":{"limits":[]}}`},
+ } {
+ account := withClinePassSnapshot(clineTestAccount(62), nil)
+ repo := &clineAccountRepo{accounts: []Account{*account}}
+ upstream := newClineAccountUpstream(usage, `{"success":true,"data":{"balance":5000000}}`)
+
+ result, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.Empty(t, result.Tiers)
+ require.Empty(t, result.PlanLevel)
+ written := repo.extraWrites[62][0]
+ for _, key := range []string{"cline_5h_used_percent", "cline_weekly_used_percent", "cline_monthly_used_percent"} {
+ require.Contains(t, written, key)
+ require.Nil(t, written[key])
+ }
+ require.True(t, strings.HasPrefix(repo.reasons[62][clinePassRateLimitKey], clinePassUnavailableReason))
+ require.NotContains(t, repo.modelLimits[62], clineCreditsRateLimitKey)
+ }
+}
+
+// 数据显示钱包恢复可用时解除冷却;组织花费上限无从探测,不提前解除。
+func TestClineUsageProbeClearsRecoveredWallets(t *testing.T) {
+ for _, tc := range []struct {
+ creditsReason string
+ cleared bool
+ }{
+ {clineCreditsReason + ": Insufficient credits", true},
+ {clineCreditsLowReason + ": balance 0.1 USD below threshold 0.50", true},
+ {clineSpendLimitReason + ": Organization spend limit exceeded", false},
+ } {
+ account := clineTestAccount(63)
+ now := time.Now()
+ setAccountModelRateLimitSnapshot(account, clinePassRateLimitKey, now.Add(6*time.Hour), clinePassLimitReason, now)
+ setAccountModelRateLimitSnapshot(account, clineCreditsRateLimitKey, now.Add(time.Hour), tc.creditsReason, now)
+ repo := &clineAccountRepo{accounts: []Account{*account}}
+ upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, `{"success":true,"data":{"balance":5000000}}`)
+
+ _, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.False(t, repo.modelLimits[63][clinePassRateLimitKey].After(time.Now()), tc.creditsReason)
+ _, touched := repo.modelLimits[63][clineCreditsRateLimitKey]
+ require.Equal(t, tc.cleared, touched, tc.creditsReason)
+ if tc.cleared {
+ require.False(t, repo.modelLimits[63][clineCreditsRateLimitKey].After(time.Now()), tc.creditsReason)
+ }
+ }
+}
+
+// ClinePass 同样只解除探测能证明已恢复的冷却(窗口用满、未订阅):组织账户、所需订阅
+// 档位与推理额度上限反映不到用量接口里,提前解除会让每个检测周期都重放一次失败请求。
+func TestClineUsageProbeClearsOnlyProvablePassCooldowns(t *testing.T) {
+ ctx := withTempUnschedulableModel(context.Background(), []string{"cline-pass/glm-5.3"})
+ balance := `{"success":true,"data":{"balance":5000000}}`
+ for _, tc := range []struct {
+ status int
+ body string
+ cleared bool
+ }{
+ {http.StatusTooManyRequests, clinePassWeeklyBody, true},
+ {http.StatusForbidden, clineNotSubscribedBody, false},
+ {http.StatusForbidden, clineOrgPassBody, false},
+ {http.StatusTooManyRequests, clineInferenceCapBody, false},
+ } {
+ account := clineTestAccount(65)
+ NewRateLimitService(&commandCodeRateLimitRepo{}, nil, &config.Config{}, nil, nil).HandleUpstreamError(ctx, account,
+ tc.status, http.Header{}, []byte(tc.body))
+ require.True(t, account.isRateLimitActiveForKey(clinePassRateLimitKey), tc.body)
+ repo := &clineAccountRepo{accounts: []Account{*account}}
+ upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, balance)
+
+ _, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ _, touched := repo.modelLimits[65][clinePassRateLimitKey]
+ require.Equal(t, tc.cleared, touched, tc.body)
+ }
+
+ // 探测发现未订阅设的冷却,订阅后的下一次探测解除。
+ repo := &clineAccountRepo{accounts: []Account{*clineTestAccount(66)}}
+ unsubscribed := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusNotFound,
+ body: `{"success":false,"error":"no plan history found for user"}`}, balance)
+ _, err := NewCNProviderQuotaService(repo, nil, unsubscribed, clineUsageTestConfig()).QueryUsage(context.Background(), 66)
+ require.NoError(t, err)
+ require.True(t, repo.modelLimits[66][clinePassRateLimitKey].After(time.Now()))
+
+ subscribed := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, balance)
+ _, err = NewCNProviderQuotaService(repo, nil, subscribed, clineUsageTestConfig()).QueryUsage(context.Background(), 66)
+ require.NoError(t, err)
+ require.False(t, repo.modelLimits[66][clinePassRateLimitKey].After(time.Now()))
+}
+
+// 用量接口鉴权失败:探测失败但不写快照、不动冷却。
+func TestClineUsageProbeAuthFailure(t *testing.T) {
+ account := clineTestAccount(64)
+ repo := &clineAccountRepo{accounts: []Account{*account}}
+ upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusUnauthorized, body: `{"error":"Unauthorized"}`}, `{}`)
+
+ result, err := NewCNProviderQuotaService(repo, nil, upstream, clineUsageTestConfig()).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.False(t, result.CredentialValid)
+ require.Equal(t, http.StatusUnauthorized, result.StatusCode)
+ require.Empty(t, repo.extraWrites)
+ require.Empty(t, repo.modelLimits)
+}
+
+// 周期检测探测官方主机上的全部激活账号(含手动停调的,钱包冷却与调度开关无关),
+// 只冷却钱包,不停整个账号。
+func TestCNProviderBalanceCheckRunOnceProbesClineUsage(t *testing.T) {
+ official := *clineTestAccount(1)
+ manualOff := *clineTestAccount(2)
+ manualOff.Schedulable = false
+ relay := *clineTestAccount(3)
+ relay.Credentials["base_url"] = "https://relay.example.com/v1"
+ relay.Credentials["api_protocol"] = APIProtocolChatCompletions
+
+ repo := &clineAccountRepo{accounts: []Account{official, manualOff, relay}}
+ upstream := newClineAccountUpstream(commandCodeAlphaResponse{status: http.StatusOK, body: clineUsageLimitsBody}, `{"success":true,"data":{"balance":200000}}`)
+ cfg := clineUsageTestConfig()
+ svc := &CNProviderBalanceCheckService{
+ accountRepo: repo,
+ balanceService: NewCNProviderBalanceService(repo, nil, upstream, cfg),
+ quotaService: NewCNProviderQuotaService(repo, nil, upstream, cfg),
+ cfg: cfg,
+ }
+
+ svc.runOnce()
+
+ require.Len(t, upstream.requests, 6, "usage-limits + me + balance for each official account")
+ require.Len(t, repo.extraWrites, 2)
+ require.Contains(t, repo.modelLimits[1], clineCreditsRateLimitKey)
+ require.Contains(t, repo.modelLimits[2], clineCreditsRateLimitKey)
+ require.Empty(t, repo.paused)
+}
+
+// 同一轮检测里每个账号走自己平台登记的检测函数:积分同样低于阈值,Command Code 停整个
+// 账号,Cline 不停(钱包冷却在探测中处理)。
+func TestCNProviderBalanceCheckRunOnceDispatchesAccountProbesByPlatform(t *testing.T) {
+ commandCode := *commandCodeUsageAccount()
+ commandCode.ID, commandCode.Schedulable = 1, true
+ cline := *clineTestAccount(2)
+ repo := &commandCodeCheckRepo{accounts: []Account{commandCode, cline}}
+ prober := &commandCodeBalanceProber{balance: 0.2}
+ svc := &CNProviderBalanceCheckService{accountRepo: repo, quotaService: prober, cfg: clineUsageTestConfig()}
+
+ svc.runOnce()
+
+ require.ElementsMatch(t, []int64{1, 2}, prober.probed)
+ require.Equal(t, []int64{1}, repo.paused)
+}
+
+// 官方主机不做上游计费探测:中转站的计费接口在官方 API 上不存在,只会把 Key 发往官方主机。
+func TestClineOfficialHostSkipsUpstreamBillingProbe(t *testing.T) {
+ require.True(t, upstreamBillingProbeTargetIsOfficialAPI(DefaultClineBaseURL))
+ require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://relay.example.com/v1"))
+}
diff --git a/backend/internal/service/cline_usage.go b/backend/internal/service/cline_usage.go
new file mode 100644
index 000000000..a3e689bde
--- /dev/null
+++ b/backend/internal/service/cline_usage.go
@@ -0,0 +1,368 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "math"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+ "github.com/tidwall/gjson"
+)
+
+// Cline 积分余额与 ClinePass 用量来自账号接口(Cline 控制台与客户端同源),账号 API Key
+// 可直接访问(Bearer ;实测带 workos: 前缀反而 401):
+//
+// GET /api/v1/users/me -> {id, email, ...}
+// GET /api/v1/users/{id}/balance -> {balance, userId}
+// GET /api/v1/users/me/plan/usage-limits -> {limits:[{type, percentUsed, resetsAt?}]}
+//
+// 响应包在 {success, error, data} 信封里。balance 单位为百万分之一积分(1 积分 =
+// 1 美元;Cline CLI 的 normalizeCreditBalance 除以 1e6,扩展先除 100 再除 10000),
+// 按 Cline 的展示精度保留 4 位小数。usage-limits 的 type 为 five_hour / weekly /
+// monthly(套餐里对应最近 5 小时 / 7 天 / 30 天的滚动用量上限),percentUsed 为 0-100,
+// 窗口未开始时没有 resetsAt;未订阅时返回 404(no plan history found for user)或空列表。
+
+const clineAPIBase = "https://" + clineAPIHost
+
+var errClineInvalidResponse = errors.New("invalid cline account response")
+
+// clineHTTPError 是账号接口的非 2xx 响应。
+type clineHTTPError struct {
+ status int
+ body string
+}
+
+func (e *clineHTTPError) Error() string {
+ return fmt.Sprintf("HTTP %d: %s", e.status, e.body)
+}
+
+type clineAccountClient struct {
+ cfg *config.Config
+ httpUpstream HTTPUpstream
+ account *Account
+ apiKey string
+ proxyURL string
+ // errPrefix 是应用错误码前缀(CN_BALANCE / CN_QUOTA),与调用方服务的错误码一致。
+ errPrefix string
+}
+
+func newClineAccountClient(cfg *config.Config, httpUpstream HTTPUpstream, account *Account, proxyURL, errPrefix string) *clineAccountClient {
+ return &clineAccountClient{
+ cfg: cfg,
+ httpUpstream: httpUpstream,
+ account: account,
+ apiKey: strings.TrimSpace(account.GetCNAPIKey()),
+ proxyURL: proxyURL,
+ errPrefix: errPrefix,
+ }
+}
+
+// get 请求一个账号接口,返回拆掉 {success, error, data} 信封后的 JSON。
+func (c *clineAccountClient) get(ctx context.Context, path string) (gjson.Result, error) {
+ validatedURL, err := cnValidateProbeURL(c.cfg, clineAPIBase+path)
+ if err != nil {
+ return gjson.Result{}, infraerrors.New(http.StatusForbidden, c.errPrefix+"_URL_REJECTED", err.Error())
+ }
+ callCtx, cancel := context.WithTimeout(ctx, cnQuotaUpstreamTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(callCtx, http.MethodGet, validatedURL, nil)
+ if err != nil {
+ return gjson.Result{}, infraerrors.Newf(http.StatusInternalServerError, c.errPrefix+"_REQUEST_BUILD_FAILED", "build request: %v", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+c.apiKey)
+ req.Header.Set("Accept", "application/json")
+ c.account.ApplyHeaderOverrides(req.Header)
+
+ resp, err := c.httpUpstream.Do(req, c.proxyURL, c.account.ID, maxInt(c.account.Concurrency, 1))
+ if err != nil {
+ return gjson.Result{}, fmt.Errorf("upstream request failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, cnQuotaMaxBodyBytes))
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return gjson.Result{}, &clineHTTPError{status: resp.StatusCode, body: truncate(strings.TrimSpace(string(body)), 240)}
+ }
+ if !gjson.ValidBytes(body) {
+ return gjson.Result{}, fmt.Errorf("%w: %s", errClineInvalidResponse, path)
+ }
+ parsed := gjson.ParseBytes(body)
+ if success := parsed.Get("success"); success.Exists() {
+ if !success.Bool() {
+ return gjson.Result{}, &clineHTTPError{status: resp.StatusCode, body: truncate(parsed.Get("error").String(), 240)}
+ }
+ return parsed.Get("data"), nil
+ }
+ return parsed, nil
+}
+
+// balance 查询积分余额(美元)。
+func (c *clineAccountClient) balance(ctx context.Context) (float64, error) {
+ me, err := c.get(ctx, "/api/v1/users/me")
+ if err != nil {
+ return 0, err
+ }
+ userID := strings.TrimSpace(me.Get("id").String())
+ if userID == "" {
+ return 0, fmt.Errorf("%w: missing user id", errClineInvalidResponse)
+ }
+ balance, err := c.get(ctx, "/api/v1/users/"+url.PathEscape(userID)+"/balance")
+ if err != nil {
+ return 0, err
+ }
+ micro := balance.Get("balance")
+ if !micro.Exists() || (micro.Type != gjson.Number && micro.Type != gjson.String) {
+ return 0, fmt.Errorf("%w: missing balance", errClineInvalidResponse)
+ }
+ return math.Round(micro.Float()/100) / 10000, nil
+}
+
+// passLimits 查询 ClinePass 三档窗口;subscribed=false 表示没有订阅。
+func (c *clineAccountClient) passLimits(ctx context.Context) (tiers []CNQuotaTier, subscribed bool, err error) {
+ data, err := c.get(ctx, "/api/v1/users/me/plan/usage-limits")
+ if err != nil {
+ var httpErr *clineHTTPError
+ if errors.As(err, &httpErr) && httpErr.status == http.StatusNotFound {
+ return nil, false, nil
+ }
+ return nil, false, err
+ }
+ limits := data.Get("limits")
+ if !limits.IsArray() {
+ return nil, false, fmt.Errorf("%w: missing limits", errClineInvalidResponse)
+ }
+ windows := map[string]string{"five_hour": "5h", "weekly": "weekly", "monthly": "monthly"}
+ for _, item := range limits.Array() {
+ window, ok := windows[strings.ToLower(strings.TrimSpace(item.Get("type").String()))]
+ used := item.Get("percentUsed")
+ if !ok || used.Type != gjson.Number {
+ continue
+ }
+ tier := CNQuotaTier{Window: window, UsedPercent: used.Float()}
+ if resetAt, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(item.Get("resetsAt").String())); err == nil {
+ tier.ResetAt = resetAt.UTC().Format(time.RFC3339)
+ }
+ tiers = append(tiers, tier)
+ }
+ return tiers, len(tiers) > 0, nil
+}
+
+// clineFetchFailure 把取数错误转换为探测失败的状态码与文案;ok=false 表示应作为错误返回。
+func clineFetchFailure(err error) (status int, message string, ok bool) {
+ var httpErr *clineHTTPError
+ switch {
+ case errors.As(err, &httpErr):
+ return httpErr.status, fmt.Sprintf("API error (HTTP %d): %s", httpErr.status, httpErr.body), true
+ case errors.Is(err, errClineInvalidResponse):
+ return http.StatusOK, "Invalid response", true
+ default:
+ return 0, "", false
+ }
+}
+
+func clineApplicationError(err error, errPrefix string) error {
+ if isApplicationError(err) {
+ return err
+ }
+ return infraerrors.Newf(http.StatusBadGateway, errPrefix+"_REQUEST_FAILED", "%v", err)
+}
+
+func clineBalanceResult(usd float64, now time.Time) *CNProviderBalanceResult {
+ return &CNProviderBalanceResult{
+ Provider: PlatformCline,
+ Success: true,
+ Balance: usd,
+ Currency: "USD",
+ Balances: []CNProviderBalanceEntry{{Currency: "USD", Balance: usd}},
+ Available: true,
+ StatusCode: http.StatusOK,
+ FetchedAt: now.Unix(),
+ }
+}
+
+// queryClineBalance 只查积分余额(美元)并落余额快照。
+func (s *CNProviderBalanceService) queryClineBalance(ctx context.Context, account *Account) (*CNProviderBalanceResult, error) {
+ client := newClineAccountClient(s.cfg, s.httpUpstream, account, s.resolveProxyURL(ctx, account), "CN_BALANCE")
+ if client.apiKey == "" {
+ return nil, infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_APIKEY", "account api_key is empty")
+ }
+ now := time.Now().UTC()
+ usd, err := client.balance(ctx)
+ if err != nil {
+ status, message, ok := clineFetchFailure(err)
+ if !ok {
+ return nil, clineApplicationError(err, "CN_BALANCE")
+ }
+ return &CNProviderBalanceResult{Provider: PlatformCline, StatusCode: status, FetchedAt: now.Unix(), Available: true,
+ Error: "Balance query failed: " + message}, nil
+ }
+ result := clineBalanceResult(usd, now)
+ if err := s.accountRepo.UpdateExtra(ctx, account.ID, cnBalanceExtraUpdates(PlatformCline, result, now)); err != nil {
+ slog.Warn("cn_balance_persist_failed", "account_id", account.ID, "provider", PlatformCline, "error", err)
+ } else {
+ result.Persisted = true
+ }
+ return result, nil
+}
+
+// queryClineUsage 查询 ClinePass 窗口与积分余额,落快照,并按结果设置或解除两个钱包的
+// 冷却(见 applyClineWallets)。余额查询失败不影响窗口结果。
+func (s *CNProviderQuotaService) queryClineUsage(ctx context.Context, account *Account) (*CNProviderQuotaProbeResult, error) {
+ client := newClineAccountClient(s.cfg, s.httpUpstream, account, s.resolveProxyURL(ctx, account), "CN_QUOTA")
+ if client.apiKey == "" {
+ return nil, infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NO_APIKEY", "account api_key is empty")
+ }
+ now := time.Now().UTC()
+ result := &CNProviderQuotaProbeResult{
+ Provider: PlatformCline,
+ Source: "cline_usage_limits",
+ FetchedAt: now.Unix(),
+ }
+ tiers, subscribed, err := client.passLimits(ctx)
+ if err != nil {
+ status, message, ok := clineFetchFailure(err)
+ if !ok {
+ return nil, clineApplicationError(err, "CN_QUOTA")
+ }
+ result.StatusCode = status
+ result.Error = message
+ result.CredentialValid = status != http.StatusUnauthorized && status != http.StatusForbidden
+ return result, nil
+ }
+ result.StatusCode = http.StatusOK
+ result.Success = true
+ result.CredentialValid = true
+ result.Tiers = tiers
+ if subscribed {
+ result.PlanLevel = "ClinePass"
+ }
+
+ updates := cnQuotaExtraUpdates(PlatformCline, tiers, now)
+ present := make(map[string]CNQuotaTier, len(tiers))
+ for _, tier := range tiers {
+ present[tier.Window] = tier
+ }
+ // 缺席的窗口写 nil:取消订阅后不沿用旧快照(clinePassSubscribed 据此判断);窗口尚未
+ // 开始时没有重置时间,同样清掉上一次的值。
+ for _, window := range []struct{ name, used, reset string }{
+ {"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset},
+ {"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset},
+ {"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset},
+ } {
+ tier, ok := present[window.name]
+ if !ok {
+ updates[cnExtraKey(PlatformCline, window.used)] = nil
+ }
+ if tier.ResetAt == "" {
+ updates[cnExtraKey(PlatformCline, window.reset)] = nil
+ }
+ }
+ if usd, err := client.balance(ctx); err != nil {
+ slog.Warn("cline_balance_probe_failed", "account_id", account.ID, "error", err)
+ } else {
+ result.Balance = clineBalanceResult(usd, now)
+ for key, value := range cnBalanceExtraUpdates(PlatformCline, result.Balance, now) {
+ updates[key] = value
+ }
+ }
+ if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
+ slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", PlatformCline, "error", err)
+ } else {
+ result.Persisted = true
+ if result.Balance != nil {
+ result.Balance.Persisted = true
+ }
+ }
+ s.applyClineWallets(ctx, account, subscribed, tiers, result.Balance, now)
+ return result, nil
+}
+
+const (
+ clineCreditsLowReason = "cline_credits_low"
+ // clinePassNoSubscriptionReason 是探测发现未订阅时的原因;与请求侧的未订阅 / 组织账户
+ // 共用 clinePassUnavailableReason 前缀,单独区分出探测能证明已恢复的这一种。
+ clinePassNoSubscriptionReason = clinePassUnavailableReason + ": no ClinePass subscription"
+)
+
+// applyClineWallets 按探测结果设置或解除两个钱包的冷却:
+// - ClinePass:未订阅,或有窗口用满(≥100%)时冷却到该窗口的重置时间;可用时只解除
+// 窗口用满与未订阅的冷却(组织账户、所需订阅档位与推理额度上限反映不到用量接口里,
+// 仍等到期后由请求重新确认);
+// - 积分:余额低于阈值时冷却,恢复后只解除积分类原因的冷却(组织花费上限无从探测,
+// 仍等到期后由请求重新确认)。
+//
+// 没有重置时间时冷却 2 个检测周期,由下一次探测续期或解除。
+func (s *CNProviderQuotaService) applyClineWallets(ctx context.Context, account *Account, subscribed bool, tiers []CNQuotaTier, balance *CNProviderBalanceResult, now time.Time) {
+ fallback := now.Add(cnBalanceCheckCooldown(s.cfg))
+
+ switch until, reason := clinePassWalletState(subscribed, tiers, now, fallback); {
+ case until != nil:
+ s.setClineWalletLimit(ctx, account, clinePassRateLimitKey, *until, reason, now)
+ case account.isRateLimitActiveForKey(clinePassRateLimitKey):
+ reason := account.modelRateLimitReason(clinePassRateLimitKey)
+ if strings.HasPrefix(reason, clinePassLimitReason) || strings.HasPrefix(reason, clinePassNoSubscriptionReason) {
+ s.setClineWalletLimit(ctx, account, clinePassRateLimitKey, now, "", now)
+ }
+ }
+
+ if balance == nil {
+ return
+ }
+ threshold := 0.0
+ if s.cfg != nil {
+ threshold = s.cfg.Gateway.CNProviders.BalanceThreshold
+ }
+ switch low := balance.Balance <= 0 || balance.Balance < threshold; {
+ case low:
+ s.setClineWalletLimit(ctx, account, clineCreditsRateLimitKey, fallback,
+ fmt.Sprintf("%s: balance %.4g USD below threshold %.2f", clineCreditsLowReason, balance.Balance, threshold), now)
+ case account.isRateLimitActiveForKey(clineCreditsRateLimitKey):
+ reason := account.modelRateLimitReason(clineCreditsRateLimitKey)
+ if strings.HasPrefix(reason, clineCreditsReason) || strings.HasPrefix(reason, clineCreditsLowReason) {
+ s.setClineWalletLimit(ctx, account, clineCreditsRateLimitKey, now, "", now)
+ }
+ }
+}
+
+// clinePassWalletState 返回 ClinePass 钱包应冷却到的时间;nil 表示可用。
+func clinePassWalletState(subscribed bool, tiers []CNQuotaTier, now, fallback time.Time) (*time.Time, string) {
+ if !subscribed {
+ return &fallback, clinePassNoSubscriptionReason
+ }
+ var until *time.Time
+ var exhausted []string
+ for _, tier := range tiers {
+ if tier.UsedPercent < 100 {
+ continue
+ }
+ exhausted = append(exhausted, tier.Window)
+ resetAt := fallback
+ if parsed := parseSchedulingResetAt(tier.ResetAt); parsed != nil && parsed.After(now) && parsed.Sub(now) <= clinePassMaxCooldown {
+ resetAt = *parsed
+ }
+ if until == nil || resetAt.After(*until) {
+ until = &resetAt
+ }
+ }
+ if until == nil {
+ return nil, ""
+ }
+ return until, clinePassLimitReason + ": " + strings.Join(exhausted, ", ") + " window used up"
+}
+
+// setClineWalletLimit 写钱包冷却;until 不晚于 now 时即解除。
+func (s *CNProviderQuotaService) setClineWalletLimit(ctx context.Context, account *Account, scope string, until time.Time, reason string, now time.Time) {
+ setAccountModelRateLimitSnapshot(account, scope, until, reason, now)
+ if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, scope, until, reason); err != nil {
+ slog.Warn("cline_wallet_limit_set_failed", "account_id", account.ID, "scope", scope, "error", err)
+ return
+ }
+ slog.Info("cline_wallet_limit", "account_id", account.ID, "scope", scope, "until", until.UTC(), "cleared", !until.After(now))
+}
diff --git a/backend/internal/service/cn_provider_balance_check_service.go b/backend/internal/service/cn_provider_balance_check_service.go
index 1590693d5..838099446 100644
--- a/backend/internal/service/cn_provider_balance_check_service.go
+++ b/backend/internal/service/cn_provider_balance_check_service.go
@@ -27,6 +27,8 @@ const cnQuotaProbeConcurrency = 4
// 克隆自 AccountExpiryService 的 Start/Stop/runOnce + ticker 骨架。
// 余额探测仅覆盖有公开余额端点的 kimi / deepseek;智谱无余额端点,仅靠响应式 429/402。
// 额度探测覆盖 kimi / zhipu 的 coding plan 账号(deepseek 无 coding 套餐)。
+// Command Code 账号一次探测同时刷新窗口快照与积分余额,积分低于阈值时同样临时停调。
+// Cline 账号同样一次探测刷新 ClinePass 窗口与积分,只冷却用完的一边(见 cline_usage.go)。
type CNProviderBalanceCheckService struct {
accountRepo AccountRepository
balanceService *CNProviderBalanceService
@@ -154,7 +156,8 @@ func (s *CNProviderBalanceCheckService) runOnce() {
}
// 预算按工作量放大:4 并发 × 15s/批 + payg 每账号 5s,下限 30s 上限 300s。
- batches := (len(quotaTargets) + cnQuotaProbeConcurrency - 1) / cnQuotaProbeConcurrency
+ accountTargets := s.collectAccountProbeTargets()
+ batches := (len(quotaTargets) + len(accountTargets) + cnQuotaProbeConcurrency - 1) / cnQuotaProbeConcurrency
timeout := 30*time.Second + time.Duration(batches)*15*time.Second + time.Duration(len(paygTargets))*5*time.Second
if timeout > 300*time.Second {
timeout = 300 * time.Second
@@ -188,11 +191,106 @@ func (s *CNProviderBalanceCheckService) runOnce() {
wg.Wait()
}
+ if len(accountTargets) > 0 {
+ sem := make(chan struct{}, cnQuotaProbeConcurrency)
+ var wg sync.WaitGroup
+ var mu sync.Mutex
+ for _, target := range accountTargets {
+ wg.Add(1)
+ go func(t accountProbeTarget) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+ switch t.check(ctx, t.account, threshold) {
+ case cnBalancePaused:
+ mu.Lock()
+ paused++
+ mu.Unlock()
+ case cnBalanceCleared:
+ mu.Lock()
+ cleared++
+ mu.Unlock()
+ }
+ }(target)
+ }
+ wg.Wait()
+ }
+
if paused > 0 || cleared > 0 {
log.Printf("[CNBalance] paused=%d cleared=%d (threshold=%.2f)", paused, cleared, threshold)
}
}
+// accountProbeCheck 是走账号接口探测的平台的周期检测函数。
+type accountProbeCheck func(ctx context.Context, account *Account, threshold float64) cnBalanceCheckOutcome
+
+// accountProbeTarget 是一个待检测账号与其平台的检测函数。
+type accountProbeTarget struct {
+ account *Account
+ check accountProbeCheck
+}
+
+// collectAccountProbeTargets 选出走账号接口探测的平台上、官方主机上激活的账号,并配上
+// 该平台的检测函数。一次探测同时刷新窗口快照与积分余额:
+// - Command Code:手动可调度的账号再按积分余额停调 / 恢复(窗口快照供阈值停调读取);
+// - Cline:探测中按结果设置或解除两个钱包的冷却,不停整个账号。
+func (s *CNProviderBalanceCheckService) collectAccountProbeTargets() []accountProbeTarget {
+ if s.quotaService == nil {
+ return nil
+ }
+ var targets []accountProbeTarget
+ for _, p := range []struct {
+ platform string
+ supported func(*Account) bool
+ check accountProbeCheck
+ }{
+ {PlatformCommandCode, (*Account).commandCodeUsageSupported, s.checkCommandCode},
+ {PlatformCline, (*Account).clineAccountAPISupported, s.checkCline},
+ } {
+ accounts, err := s.accountRepo.ListByPlatform(context.Background(), p.platform)
+ if err != nil {
+ log.Printf("[CNBalance] list %s accounts failed: %v", p.platform, err)
+ continue
+ }
+ for i := range accounts {
+ if account := &accounts[i]; account.IsActive() && p.supported(account) {
+ targets = append(targets, accountProbeTarget{account: account, check: p.check})
+ }
+ }
+ }
+ return targets
+}
+
+// checkCommandCode 探测 Command Code 窗口与积分;手动可调度的账号再按积分余额停调 / 恢复。
+func (s *CNProviderBalanceCheckService) checkCommandCode(ctx context.Context, account *Account, threshold float64) cnBalanceCheckOutcome {
+ result, err := s.quotaService.QueryUsage(ctx, account.ID)
+ if err != nil {
+ log.Printf("[CNBalance] command code usage account %d failed: %v", account.ID, err)
+ return cnBalanceNoChange
+ }
+ if result == nil || !result.Success || result.Balance == nil {
+ if result != nil && result.Error != "" {
+ log.Printf("[CNBalance] command code usage account %d error: %s", account.ID, result.Error)
+ }
+ return cnBalanceNoChange
+ }
+ if !account.Schedulable {
+ return cnBalanceNoChange
+ }
+ return s.applyBalanceResult(ctx, account, result.Balance, threshold)
+}
+
+// checkCline 探测 Cline 窗口与积分;钱包冷却在探测中按结果设置或解除,不停整个账号。
+func (s *CNProviderBalanceCheckService) checkCline(ctx context.Context, account *Account, _ float64) cnBalanceCheckOutcome {
+ result, err := s.quotaService.QueryUsage(ctx, account.ID)
+ if err != nil {
+ log.Printf("[CNBalance] cline usage account %d failed: %v", account.ID, err)
+ } else if result != nil && !result.Success && result.Error != "" {
+ log.Printf("[CNBalance] cline usage account %d error: %s", account.ID, result.Error)
+ }
+ return cnBalanceNoChange
+}
+
// probeQuota 探测单个 coding plan 账号的滚动窗口用量并落 extra 快照。
// 不在此处做停调/恢复决策:调度阈值评估读取快照统一判定(含暂停账号的续停)。
func (s *CNProviderBalanceCheckService) probeQuota(ctx context.Context, accountID int64, platform string) {
@@ -224,7 +322,11 @@ func (s *CNProviderBalanceCheckService) checkOne(ctx context.Context, account *A
if err != nil || result == nil || !result.Success {
return cnBalanceNoChange
}
+ return s.applyBalanceResult(ctx, account, result, threshold)
+}
+// applyBalanceResult 按余额探测结果停调或恢复账号。
+func (s *CNProviderBalanceCheckService) applyBalanceResult(ctx context.Context, account *Account, result *CNProviderBalanceResult, threshold float64) cnBalanceCheckOutcome {
// 双币种(deepseek CNY+USD)任一币种余额达标即可继续调度;仅当全部低于
// 阈值(或不可用)才停调。
low := !result.Available || allCNBalancesBelowThreshold(result, threshold)
@@ -274,15 +376,5 @@ func allCNBalancesBelowThreshold(result *CNProviderBalanceResult, threshold floa
// cooldown 返回临时停调持续时长(= 2× 检测周期),与响应式 402/429 路径一致。
func (s *CNProviderBalanceCheckService) cooldown() time.Duration {
- minutes := 10
- if s.cfg != nil {
- if cfgMin := s.cfg.Gateway.CNProviders.BalanceCheckIntervalMinutes; cfgMin > 0 {
- minutes = cfgMin
- }
- }
- cooldown := time.Duration(minutes) * time.Minute * 2
- if cooldown < time.Minute {
- cooldown = 10 * time.Minute
- }
- return cooldown
+ return cnBalanceCheckCooldown(s.cfg)
}
diff --git a/backend/internal/service/cn_provider_balance_service.go b/backend/internal/service/cn_provider_balance_service.go
index e72c98b24..3202de483 100644
--- a/backend/internal/service/cn_provider_balance_service.go
+++ b/backend/internal/service/cn_provider_balance_service.go
@@ -123,6 +123,12 @@ func (s *CNProviderBalanceService) QueryBalanceForAccount(ctx context.Context, a
}
func (s *CNProviderBalanceService) queryBalanceForAccount(ctx context.Context, account *Account) (*CNProviderBalanceResult, error) {
+ if account.IsCommandCode() {
+ return s.queryCommandCodeBalance(ctx, account)
+ }
+ if account.IsCline() {
+ return s.queryClineBalance(ctx, account)
+ }
provider := account.Platform
if provider != PlatformKimi && provider != PlatformDeepseek {
return nil, infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_ENDPOINT", "account provider has no balance endpoint")
@@ -219,28 +225,33 @@ func (s *CNProviderBalanceService) queryBalanceForAccount(ctx context.Context, a
result.Available = available
result.Success = true
- balanceUpdates := make([]any, 0, len(entries))
- for _, entry := range entries {
+ updates := cnBalanceExtraUpdates(provider, result, now)
+ if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
+ slog.Warn("cn_balance_persist_failed", "account_id", account.ID, "provider", provider, "error", err)
+ } else {
+ result.Persisted = true
+ }
+ return result, nil
+}
+
+// cnBalanceExtraUpdates 构造 provider 维度的余额快照更新。
+func cnBalanceExtraUpdates(provider string, result *CNProviderBalanceResult, now time.Time) map[string]any {
+ balanceUpdates := make([]any, 0, len(result.Balances))
+ for _, entry := range result.Balances {
balanceUpdates = append(balanceUpdates, map[string]any{
"currency": entry.Currency,
"balance": entry.Balance,
})
}
- updates := map[string]any{
+ return map[string]any{
cnExtraKey(provider, cnBalanceExtraSuffixBalance): result.Balance,
cnExtraKey(provider, cnBalanceExtraSuffixCurrency): result.Currency,
- cnExtraKey(provider, cnBalanceExtraSuffixAvailable): available,
+ cnExtraKey(provider, cnBalanceExtraSuffixAvailable): result.Available,
cnExtraKey(provider, cnBalanceExtraSuffixUpdated): now.Format(time.RFC3339),
cnExtraKey(provider, cnBalanceExtraSuffixBalances): balanceUpdates,
// 余额探测成功即清除响应式 402/429 写下的 balance_low 标记。
cnExtraKey(provider, cnBalanceExtraSuffixLow): false,
}
- if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
- slog.Warn("cn_balance_persist_failed", "account_id", account.ID, "provider", provider, "error", err)
- } else {
- result.Persisted = true
- }
- return result, nil
}
// loadPayGAccount 加载 payg 模式的国产供应商账号(余额仅对 payg 有意义;coding 走额度)。
@@ -261,6 +272,20 @@ func validatePayGAccount(account *Account) error {
if account == nil {
return infraerrors.New(http.StatusNotFound, "CN_BALANCE_ACCOUNT_NOT_FOUND", "account not found")
}
+ // Cline 积分余额只查官方主机。
+ if account.IsCline() {
+ if !account.clineAccountAPISupported() {
+ return infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_ENDPOINT", "cline balance is only available for api key accounts on the official host")
+ }
+ return nil
+ }
+ // Command Code 积分余额与套餐窗口同源,只查官方主机。
+ if account.IsCommandCode() {
+ if !account.commandCodeUsageSupported() {
+ return infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_ENDPOINT", "command code balance is only available for api key accounts on the official host")
+ }
+ return nil
+ }
if !account.IsCNProvider() {
return infraerrors.New(http.StatusBadRequest, "CN_BALANCE_INVALID_PLATFORM", "account is not a CN provider account")
}
diff --git a/backend/internal/service/cn_provider_quota_service.go b/backend/internal/service/cn_provider_quota_service.go
index dec8b929c..39acdadde 100644
--- a/backend/internal/service/cn_provider_quota_service.go
+++ b/backend/internal/service/cn_provider_quota_service.go
@@ -62,9 +62,13 @@ type CNProviderQuotaProbeResult struct {
FetchedAt int64 `json:"fetched_at"`
Persisted bool `json:"persisted"`
Error string `json:"error,omitempty"`
+
+ // Balance 为同一次探测得到的余额(Command Code 积分与窗口同源),其余供应商为空。
+ Balance *CNProviderBalanceResult `json:"balance,omitempty"`
}
-// CNProviderQuotaService 探测 Kimi / Zhipu Coding Plan 的滚动窗口用量。
+// CNProviderQuotaService 探测 Kimi / Zhipu / MiniMax Coding Plan、OpenCode Go、
+// Command Code 与 Cline(ClinePass)的滚动窗口用量。
type CNProviderQuotaService struct {
accountRepo AccountRepository
proxyRepo ProxyRepository
@@ -131,6 +135,12 @@ func (s *CNProviderQuotaService) QueryUsageForAccount(ctx context.Context, accou
func (s *CNProviderQuotaService) queryUsageForAccount(ctx context.Context, account *Account) (*CNProviderQuotaProbeResult, error) {
provider := account.GetCodingPlanProvider()
+ if provider == PlatformCommandCode {
+ return s.queryCommandCodeUsage(ctx, account)
+ }
+ if provider == PlatformCline {
+ return s.queryClineUsage(ctx, account)
+ }
if provider != PlatformKimi && provider != PlatformZhipu && provider != PlatformMiniMax && provider != PlatformOpenCodeGo {
return nil, infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NOT_CODING_PLAN", "account is not a kimi/zhipu/minimax coding plan or opencode go account")
}
@@ -290,6 +300,18 @@ func validateCodingPlanAccount(account *Account) error {
if account.IsOpenCodeGoPlan() {
return nil
}
+ if account.IsCommandCode() {
+ if !account.commandCodeUsageSupported() {
+ return infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NOT_CODING_PLAN", "command code usage is only available for api key accounts on the official host")
+ }
+ return nil
+ }
+ if account.IsCline() {
+ if !account.clineAccountAPISupported() {
+ return infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NOT_CODING_PLAN", "cline usage is only available for api key accounts on the official host")
+ }
+ return nil
+ }
if account.IsOpenCodeGo() {
return infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NOT_CODING_PLAN", "opencode zen accounts have no subscription quota window")
}
diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go
index 7d1aff9ec..b623c1eeb 100644
--- a/backend/internal/service/cn_providers_test.go
+++ b/backend/internal/service/cn_providers_test.go
@@ -668,8 +668,9 @@ func TestAdaptiveProtocolBaseURLs(t *testing.T) {
}{
{"kimi payg", PlatformKimi, AccountModePayG, DefaultKimiPayGBaseURL, DefaultKimiPayGAnthropicBaseURL, DefaultKimiPayGBaseURL},
{"kimi coding", PlatformKimi, AccountModeCoding, DefaultKimiCodingBaseURL, DefaultKimiCodingAnthropicBaseURL, DefaultKimiCodingBaseURL},
- {"zhipu payg", PlatformZhipu, AccountModePayG, DefaultZhipuPayGBaseURL, DefaultZhipuAnthropicBaseURL, DefaultZhipuPayGBaseURL},
- {"zhipu coding", PlatformZhipu, AccountModeCoding, DefaultZhipuCodingBaseURL, DefaultZhipuAnthropicBaseURL, DefaultZhipuCodingBaseURL},
+ // 智谱没有原生 Responses 端点:profile 不登记 responses 条目,默认基址为空。
+ {"zhipu payg", PlatformZhipu, AccountModePayG, DefaultZhipuPayGBaseURL, DefaultZhipuAnthropicBaseURL, ""},
+ {"zhipu coding", PlatformZhipu, AccountModeCoding, DefaultZhipuCodingBaseURL, DefaultZhipuAnthropicBaseURL, ""},
{"deepseek", PlatformDeepseek, AccountModePayG, DefaultDeepseekBaseURL, DefaultDeepseekAnthropicBaseURL, DefaultDeepseekBaseURL},
{"minimax payg", PlatformMiniMax, AccountModePayG, DefaultMiniMaxBaseURL, DefaultMiniMaxAnthropicBaseURL, DefaultMiniMaxBaseURL},
{"minimax coding", PlatformMiniMax, AccountModeCoding, DefaultMiniMaxBaseURL, DefaultMiniMaxAnthropicBaseURL, DefaultMiniMaxBaseURL},
diff --git a/backend/internal/service/command_code.go b/backend/internal/service/command_code.go
new file mode 100644
index 000000000..41b9d49cf
--- /dev/null
+++ b/backend/internal/service/command_code.go
@@ -0,0 +1,27 @@
+package service
+
+// Command Code Provider API(https://commandcode.ai/docs/provider):同一 API Key 下
+// 按模型分流到三种原生端点,基址 https://api.commandcode.ai/provider/v1:
+// - Claude 系模型只在 /messages(Anthropic Messages)提供,发往其他端点返回 400;
+// - OpenAI 与开源模型提供 /chat/completions,多数也提供 /responses。
+// 每个模型支持的端点由 /models 的 supported_endpoints 给出(公开接口),网关据此在
+// 模型支持入站协议时同协议直通(见 model_protocol_catalog.go);目录就绪前使用下面的
+// 内置规则。模型名可带厂商前缀(如 deepseek/deepseek-v4-flash),原样发往上游。
+
+// DefaultCommandCodeTestModel 是管理端连接测试未指定模型时使用的模型(Chat Completions)。
+const DefaultCommandCodeTestModel = "deepseek/deepseek-v4-flash"
+
+// DefaultCommandCodeProtocolRules 是 Command Code 的内置分流表:Claude 只走 Anthropic;
+// GPT 同时支持 Responses 与 Chat Completions(入站同协议直通,其余入站首选 Responses);
+// 其余模型只保证 Chat Completions,是否支持 Responses 以上游模型目录为准。
+func DefaultCommandCodeProtocolRules() []ProtocolRule {
+ return []ProtocolRule{
+ {Pattern: "claude-*", Protocol: APIProtocolAnthropic},
+ {Pattern: "gpt-*", Protocol: APIProtocolResponses, Protocols: []string{APIProtocolResponses, APIProtocolChatCompletions}},
+ }
+}
+
+// IsCommandCode 报告账号是否为 Command Code 平台账号。
+func (a *Account) IsCommandCode() bool {
+ return a != nil && a.Platform == PlatformCommandCode
+}
diff --git a/backend/internal/service/command_code_test.go b/backend/internal/service/command_code_test.go
new file mode 100644
index 000000000..aabc96db5
--- /dev/null
+++ b/backend/internal/service/command_code_test.go
@@ -0,0 +1,176 @@
+//go:build unit
+
+package service
+
+import (
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// commandCodeTestAccount 只带 api_key:端点与分流规则全部来自 provider profile。
+func commandCodeTestAccount(id int64) *Account {
+ return &Account{
+ ID: id,
+ Name: "cc",
+ Platform: PlatformCommandCode,
+ Type: AccountTypeAPIKey,
+ Status: StatusActive,
+ Concurrency: 1,
+ Credentials: map[string]any{"api_key": "user_test_key"},
+ }
+}
+
+func TestCommandCodeProfileRoutesByModel(t *testing.T) {
+ account := commandCodeTestAccount(1)
+ require.True(t, account.IsMultiProtocolAPIKey())
+ require.True(t, account.routesByModel())
+ require.False(t, account.RoutesProtocolByInbound())
+ require.Equal(t, APIProtocolAdaptive, account.GetAPIProtocol())
+ require.Equal(t, DefaultCommandCodeBaseURL, account.GetOpenAIBaseURL())
+ require.Equal(t, DefaultCommandCodeAnthropicBaseURL, account.GetCNProtocolBaseURL(APIProtocolAnthropic))
+ require.Equal(t, DefaultCommandCodeBaseURL, account.GetCNProtocolBaseURL(APIProtocolResponses))
+
+ // 未取到模型目录时按内置规则:Claude 只走 Anthropic;GPT 支持 Responses 与 Chat
+ // Completions(同协议直通,Anthropic 入站走首选 Responses);其余只保证 Chat Completions。
+ for _, inbound := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic} {
+ require.Equal(t, APIProtocolAnthropic, resolveUpstreamProtocol(account, inbound, "claude-sonnet-4-6", nil), inbound)
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, inbound, "deepseek/deepseek-v4-flash", nil), inbound)
+ }
+ require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolResponses, "gpt-5.5", nil))
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolChatCompletions, "gpt-5.5", nil))
+ require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolAnthropic, "gpt-5.5", nil))
+
+ // 显式协议优先于内置规则。
+ account.Credentials["api_protocol"] = APIProtocolChatCompletions
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolAnthropic, "claude-sonnet-4-6", nil))
+}
+
+func TestCommandCodeNativeAnthropicTargetURL(t *testing.T) {
+ svc := &OpenAIGatewayService{}
+ targetURL, err := svc.nativeAnthropicTargetURL(commandCodeTestAccount(2))
+ require.NoError(t, err)
+ require.Equal(t, "https://api.commandcode.ai/provider/v1/messages", targetURL)
+}
+
+func TestAccountTestService_CommandCodeClaudeUsesAnthropicMessages(t *testing.T) {
+ account := commandCodeTestAccount(501)
+ svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse())
+ c, recorder := newTestContext()
+
+ err := svc.TestAccountConnection(c, account.ID, "claude-sonnet-4-6", "hi", AccountTestModeDefault)
+
+ require.NoError(t, err)
+ require.Len(t, upstream.requests, 1)
+ require.Equal(t, "https://api.commandcode.ai/provider/v1/messages", upstream.requests[0].URL.String())
+ require.Equal(t, "user_test_key", upstream.requests[0].Header.Get("x-api-key"))
+ require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
+}
+
+// 连接测试与转发共用端点拼接:按模型分流的平台,Anthropic 基址带 /v1 也合法。
+func TestAccountTestService_CommandCodeAnthropicBaseWithVersion(t *testing.T) {
+ account := commandCodeTestAccount(504)
+ account.Credentials["api_base_urls"] = map[string]any{APIProtocolAnthropic: "https://api.commandcode.ai/provider/v1"}
+ svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNAnthropicTestResponse())
+ c, recorder := newTestContext()
+
+ err := svc.TestAccountConnection(c, account.ID, "claude-sonnet-4-6", "hi", AccountTestModeDefault)
+
+ require.NoError(t, err)
+ require.Len(t, upstream.requests, 1)
+ require.Equal(t, "https://api.commandcode.ai/provider/v1/messages", upstream.requests[0].URL.String())
+ require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
+
+ target, err := (&OpenAIGatewayService{cfg: rawChatCompletionsTestConfig()}).nativeAnthropicTargetURL(account)
+ require.NoError(t, err)
+ require.Equal(t, upstream.requests[0].URL.String(), target)
+}
+
+// 连接测试与网关同一判定:模型目录决定协议时,测试也按目录选择端点。
+func TestAccountTestService_CommandCodeUsesModelCatalog(t *testing.T) {
+ base := fmt.Sprintf("http://cc-test-%d.example/provider/v1", time.Now().UnixNano())
+ account := commandCodeTestAccount(505)
+ account.Credentials["api_base_urls"] = map[string]any{
+ APIProtocolChatCompletions: base,
+ APIProtocolResponses: base,
+ }
+ url := buildOpenAIModelsURL(base)
+ upstreamModelProtocols.store(modelProtocolCatalogKey(account, url),
+ map[string][]string{"vendor/responses-only": {APIProtocolResponses}}, nil, time.Now())
+ svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse())
+ svc.openaiGatewayService = &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+ c, recorder := newTestContext()
+
+ err := svc.TestAccountConnection(c, account.ID, "vendor/responses-only", "hi", AccountTestModeDefault)
+
+ require.NoError(t, err)
+ require.Len(t, upstream.requests, 1)
+ require.Equal(t, base+"/responses", upstream.requests[0].URL.String())
+ require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
+}
+
+func TestAccountTestService_CommandCodeGPTUsesResponses(t *testing.T) {
+ account := commandCodeTestAccount(502)
+ svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNResponsesTestResponse())
+ c, recorder := newTestContext()
+
+ err := svc.TestAccountConnection(c, account.ID, "gpt-5.5", "hi", AccountTestModeDefault)
+
+ require.NoError(t, err)
+ require.Len(t, upstream.requests, 1)
+ require.Equal(t, "https://api.commandcode.ai/provider/v1/responses", upstream.requests[0].URL.String())
+ require.Equal(t, "Bearer user_test_key", upstream.requests[0].Header.Get("Authorization"))
+ require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
+}
+
+func TestAccountTestService_CommandCodeEmptyModelUsesProfileDefault(t *testing.T) {
+ account := commandCodeTestAccount(503)
+ svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
+ c, recorder := newTestContext()
+
+ err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
+
+ require.NoError(t, err)
+ require.Len(t, upstream.requests, 1)
+ require.Equal(t, "https://api.commandcode.ai/provider/v1/chat/completions", upstream.requests[0].URL.String())
+ require.Equal(t, DefaultCommandCodeTestModel, gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
+}
+
+// 仅在 profile 登记、按入站协议分流的新供应商:adaptive 测试走原生端点探测,
+// 跳过 profile 未提供的 Anthropic 端点,不再落入 Claude 测试路径。
+func TestAccountTestService_ByInboundProviderSkipsMissingNativeEndpoints(t *testing.T) {
+ const platform = "test_inbound_only_chat"
+ providerProfiles[platform] = &ProviderProfile{
+ Platform: platform, DefaultMode: AccountModePayG, Routing: ProviderRoutingByInbound,
+ DefaultTestModel: "inbound-test-model",
+ Modes: map[string]ProviderEndpoints{AccountModePayG: {BaseURLs: map[string]string{
+ APIProtocolChatCompletions: "https://inbound.example.com/v1",
+ }}},
+ }
+ t.Cleanup(func() { delete(providerProfiles, platform) })
+
+ account := &Account{
+ ID: 601, Name: "inbound", Platform: platform, Type: AccountTypeAPIKey, Status: StatusActive, Concurrency: 1,
+ Credentials: map[string]any{"api_key": "sk-inbound", "api_protocol": APIProtocolAdaptive},
+ }
+ svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
+ c, recorder := newTestContext()
+
+ err := svc.TestAccountConnection(c, account.ID, "", "hi", AccountTestModeDefault)
+
+ require.NoError(t, err)
+ require.Len(t, upstream.requests, 1)
+ require.Equal(t, "https://inbound.example.com/v1/chat/completions", upstream.requests[0].URL.String())
+ require.Equal(t, "inbound-test-model", gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Contains(t, recorder.Body.String(), `"type":"test_complete"`)
+}
+
+// 官方主机不做上游计费探测:中转站的计费接口在官方 API 上不存在,只会把 Key 发往官方主机。
+func TestCommandCodeOfficialHostSkipsUpstreamBillingProbe(t *testing.T) {
+ require.True(t, upstreamBillingProbeTargetIsOfficialAPI(DefaultCommandCodeBaseURL))
+ require.True(t, upstreamBillingProbeTargetIsOfficialAPI(DefaultCommandCodeAnthropicBaseURL))
+}
diff --git a/backend/internal/service/command_code_usage.go b/backend/internal/service/command_code_usage.go
new file mode 100644
index 000000000..ed34098e2
--- /dev/null
+++ b/backend/internal/service/command_code_usage.go
@@ -0,0 +1,511 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "math"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+)
+
+// Command Code 的积分与用量窗口来自 /alpha 下四个只读接口(官方 CLI /usage 同源,
+// 社区插件实测复核),全部使用账号 API Key(Bearer):
+//
+// GET /alpha/whoami -> {user, org};个人账户 org 为 null
+// GET /alpha/billing/credits[?orgId=] -> {credits:{monthlyCredits, purchasedCredits, freeCredits},
+// windowLimits:{limited, fiveHour, weekly}}
+// GET /alpha/billing/subscriptions[?orgId=] -> {data:{planId, currentPeriodStart, currentPeriodEnd}}
+// GET /alpha/usage/summary[?orgId=][&since=] -> {totalCost, totalMonthlyCredits}
+//
+// 积分单位为美元。windowLimits 与 credits 平级;fiveHour / weekly 的 used、cap 为积分,
+// resetAt 为 epoch 毫秒;limited=false(按量计费)时没有滚动窗口。月度窗口上游只给
+// 剩余量(credits.monthlyCredits),上限按「本周期已用 + 剩余」还原。个人账户不能带
+// orgId 参数(空值返回 400),只有组织账户才带。
+//
+// 订阅套餐的滚动窗口只限制套餐内积分:有充值积分时请求跳过窗口检查,此时窗口快照
+// 不参与阈值停调与 429 冷却(见 commandCodeWindowsBinding),已有的窗口冷却在探测到
+// 充值积分后解除(见 clearCommandCodeWindowCooldown)。
+
+const (
+ commandCodeAPIBase = "https://api.commandcode.ai"
+
+ // commandCodeExtraSuffixPurchasedCredits 记录充值积分,供阈值停调与 429 冷却判断
+ // 滚动窗口是否生效。
+ commandCodeExtraSuffixPurchasedCredits = "purchased_credits"
+)
+
+var errCommandCodeInvalidResponse = errors.New("invalid command code usage response")
+
+// commandCodePlanNames 与官方 CLI 的 planId 展示名一致;未收录的原样展示。
+var commandCodePlanNames = map[string]string{
+ "individual-go": "Go",
+ "individual-goat": "GOAT",
+ "individual-pro": "Pro",
+ "individual-pro-v1": "Pro",
+ "individual-provider": "Provider",
+ "individual-max": "Max",
+ "individual-ultra": "Ultra",
+ "teams-pro": "Teams Pro",
+}
+
+// commandCodeUsageSupported 报告账号能否查询 Command Code 用量:API Key 账号且推理
+// 端点指向官方主机。自定义中转的 Key 不发往官方用量接口。
+func (a *Account) commandCodeUsageSupported() bool {
+ return a.IsCommandCode() && a.Type == AccountTypeAPIKey && isOfficialCommandCodeHost(a.GetOpenAIBaseURL())
+}
+
+// commandCodeNumber 兼容数字与数字字符串。
+type commandCodeNumber float64
+
+func (n *commandCodeNumber) UnmarshalJSON(data []byte) error {
+ data = bytes.TrimSpace(data)
+ if len(data) == 0 || bytes.Equal(data, []byte("null")) {
+ *n = 0
+ return nil
+ }
+ if data[0] == '"' {
+ var s string
+ if err := json.Unmarshal(data, &s); err != nil {
+ return err
+ }
+ v, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
+ if err != nil {
+ return err
+ }
+ *n = commandCodeNumber(v)
+ return nil
+ }
+ var v float64
+ if err := json.Unmarshal(data, &v); err != nil {
+ return err
+ }
+ *n = commandCodeNumber(v)
+ return nil
+}
+
+type commandCodeWindow struct {
+ Used commandCodeNumber `json:"used"`
+ Cap commandCodeNumber `json:"cap"`
+ ResetAt commandCodeNumber `json:"resetAt"`
+}
+
+type commandCodeCredits struct {
+ MonthlyCredits commandCodeNumber `json:"monthlyCredits"`
+ PurchasedCredits commandCodeNumber `json:"purchasedCredits"`
+ FreeCredits commandCodeNumber `json:"freeCredits"`
+}
+
+type commandCodeCreditsPayload struct {
+ Credits *commandCodeCredits `json:"credits"`
+ WindowLimits struct {
+ Limited bool `json:"limited"`
+ FiveHour *commandCodeWindow `json:"fiveHour"`
+ Weekly *commandCodeWindow `json:"weekly"`
+ } `json:"windowLimits"`
+}
+
+type commandCodeSubscriptionPayload struct {
+ Data struct {
+ PlanID string `json:"planId"`
+ CurrentPeriodStart string `json:"currentPeriodStart"`
+ CurrentPeriodEnd string `json:"currentPeriodEnd"`
+ } `json:"data"`
+}
+
+type commandCodeSummaryPayload struct {
+ TotalCost *commandCodeNumber `json:"totalCost"`
+ TotalMonthlyCredits *commandCodeNumber `json:"totalMonthlyCredits"`
+}
+
+// commandCodeUsage 是一次取数的汇总;subscription / summary 取数失败时为 nil,并置
+// periodFetchFailed:此时无从判断月度窗口是否存在,不能当作没有月度窗口。
+type commandCodeUsage struct {
+ credits commandCodeCreditsPayload
+ subscription *commandCodeSubscriptionPayload
+ summary *commandCodeSummaryPayload
+ periodFetchFailed bool
+}
+
+// commandCodeHTTPError 是 /alpha 接口的非 2xx 响应。
+type commandCodeHTTPError struct {
+ status int
+ body string
+}
+
+func (e *commandCodeHTTPError) Error() string {
+ return fmt.Sprintf("HTTP %d: %s", e.status, e.body)
+}
+
+func (e *commandCodeHTTPError) unauthorized() bool {
+ return e.status == http.StatusUnauthorized || e.status == http.StatusForbidden
+}
+
+func isCommandCodeAuthError(err error) bool {
+ var httpErr *commandCodeHTTPError
+ return errors.As(err, &httpErr) && httpErr.unauthorized()
+}
+
+type commandCodeUsageClient struct {
+ cfg *config.Config
+ httpUpstream HTTPUpstream
+ account *Account
+ apiKey string
+ proxyURL string
+}
+
+// get 请求一个 /alpha 接口并解码 JSON。
+func (c *commandCodeUsageClient) get(ctx context.Context, path string, query url.Values, out any) error {
+ target := commandCodeAPIBase + path
+ if len(query) > 0 {
+ target += "?" + query.Encode()
+ }
+ validatedURL, err := cnValidateProbeURL(c.cfg, target)
+ if err != nil {
+ return infraerrors.New(http.StatusForbidden, "CN_QUOTA_URL_REJECTED", err.Error())
+ }
+ callCtx, cancel := context.WithTimeout(ctx, cnQuotaUpstreamTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(callCtx, http.MethodGet, validatedURL, nil)
+ if err != nil {
+ return infraerrors.Newf(http.StatusInternalServerError, "CN_QUOTA_REQUEST_BUILD_FAILED", "build request: %v", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+c.apiKey)
+ req.Header.Set("Accept", "application/json")
+ c.account.ApplyHeaderOverrides(req.Header)
+
+ resp, err := c.httpUpstream.Do(req, c.proxyURL, c.account.ID, maxInt(c.account.Concurrency, 1))
+ if err != nil {
+ return fmt.Errorf("upstream request failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, cnQuotaMaxBodyBytes))
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return &commandCodeHTTPError{status: resp.StatusCode, body: truncate(strings.TrimSpace(string(body)), 240)}
+ }
+ if err := json.Unmarshal(body, out); err != nil {
+ return fmt.Errorf("%w: %s: %v", errCommandCodeInvalidResponse, path, err)
+ }
+ return nil
+}
+
+// fetch 取积分与窗口;withPeriod 时再取订阅周期与本周期用量以还原月度窗口。
+// whoami 用来取 orgId,任何失败都整体返回:无从判断是否组织账户时,按个人账户查会把
+// 组织账号查成成员的个人钱包,并据此按余额停调。
+func (c *commandCodeUsageClient) fetch(ctx context.Context, withPeriod bool) (*commandCodeUsage, error) {
+ var whoami struct {
+ Org *struct {
+ ID string `json:"id"`
+ } `json:"org"`
+ }
+ query := url.Values{}
+ if err := c.get(ctx, "/alpha/whoami", nil, &whoami); err != nil {
+ return nil, err
+ }
+ if whoami.Org != nil && strings.TrimSpace(whoami.Org.ID) != "" {
+ query.Set("orgId", strings.TrimSpace(whoami.Org.ID))
+ }
+
+ usage := &commandCodeUsage{}
+ if err := c.get(ctx, "/alpha/billing/credits", query, &usage.credits); err != nil {
+ return nil, err
+ }
+ if usage.credits.Credits == nil {
+ return nil, fmt.Errorf("%w: credits missing", errCommandCodeInvalidResponse)
+ }
+ if !withPeriod {
+ return usage, nil
+ }
+
+ var subscription commandCodeSubscriptionPayload
+ if err := c.get(ctx, "/alpha/billing/subscriptions", query, &subscription); err != nil {
+ if isCommandCodeAuthError(err) {
+ return nil, err
+ }
+ slog.Warn("command_code_subscription_failed", "account_id", c.account.ID, "error", err)
+ usage.periodFetchFailed = true
+ return usage, nil
+ }
+ usage.subscription = &subscription
+ periodStart := strings.TrimSpace(subscription.Data.CurrentPeriodStart)
+ if periodStart == "" {
+ return usage, nil
+ }
+ summaryQuery := url.Values{}
+ for key, values := range query {
+ summaryQuery[key] = values
+ }
+ summaryQuery.Set("since", periodStart)
+ var summary commandCodeSummaryPayload
+ if err := c.get(ctx, "/alpha/usage/summary", summaryQuery, &summary); err != nil {
+ if isCommandCodeAuthError(err) {
+ return nil, err
+ }
+ slog.Warn("command_code_usage_summary_failed", "account_id", c.account.ID, "error", err)
+ usage.periodFetchFailed = true
+ return usage, nil
+ }
+ usage.summary = &summary
+ return usage, nil
+}
+
+func isApplicationError(err error) bool {
+ var appErr *infraerrors.ApplicationError
+ return errors.As(err, &appErr)
+}
+
+func commandCodePercent(used, limit float64) float64 {
+ percent := used / limit * 100
+ if percent < 0 {
+ percent = 0
+ }
+ return math.Round(percent*100) / 100
+}
+
+// tiers 返回 5h / weekly(限额套餐)与月度窗口。
+func (u *commandCodeUsage) tiers() []CNQuotaTier {
+ var tiers []CNQuotaTier
+ limits := u.credits.WindowLimits
+ if limits.Limited {
+ for _, item := range []struct {
+ window string
+ limit *commandCodeWindow
+ }{
+ {window: "5h", limit: limits.FiveHour},
+ {window: "weekly", limit: limits.Weekly},
+ } {
+ if item.limit == nil || item.limit.Cap <= 0 {
+ continue
+ }
+ tiers = append(tiers, CNQuotaTier{
+ Window: item.window,
+ UsedPercent: commandCodePercent(float64(item.limit.Used), float64(item.limit.Cap)),
+ ResetAt: cnMillisToRFC3339(int64(item.limit.ResetAt)),
+ })
+ }
+ }
+ if u.summary != nil && u.subscription != nil {
+ used := 0.0
+ switch {
+ case u.summary.TotalMonthlyCredits != nil:
+ used = float64(*u.summary.TotalMonthlyCredits)
+ case u.summary.TotalCost != nil:
+ used = float64(*u.summary.TotalCost)
+ }
+ if limit := used + float64(u.credits.Credits.MonthlyCredits); limit > 0 {
+ tiers = append(tiers, CNQuotaTier{
+ Window: "monthly",
+ UsedPercent: commandCodePercent(used, limit),
+ ResetAt: cnNormalizeResetTime(u.subscription.Data.CurrentPeriodEnd),
+ })
+ }
+ }
+ return tiers
+}
+
+func (u *commandCodeUsage) planName() string {
+ if u.subscription == nil {
+ return ""
+ }
+ planID := strings.TrimSpace(u.subscription.Data.PlanID)
+ if name, ok := commandCodePlanNames[planID]; ok {
+ return name
+ }
+ return planID
+}
+
+// balance 返回可用积分合计(套餐剩余 + 充值 + 赠送,美元)。
+func (u *commandCodeUsage) balance(now time.Time) *CNProviderBalanceResult {
+ credits := u.credits.Credits
+ total := float64(credits.MonthlyCredits + credits.PurchasedCredits + credits.FreeCredits)
+ total = math.Round(total*10000) / 10000
+ return &CNProviderBalanceResult{
+ Provider: PlatformCommandCode,
+ Success: true,
+ Balance: total,
+ Currency: "USD",
+ Balances: []CNProviderBalanceEntry{{Currency: "USD", Balance: total}},
+ Available: true,
+ StatusCode: http.StatusOK,
+ FetchedAt: now.Unix(),
+ }
+}
+
+// clearCommandCodeWindowCooldown 在探测到充值积分时解除窗口用满的临时停调:充值积分
+// 不受滚动窗口限制,上游已允许继续请求。只清除 commandCodeUsageLimitReason 前缀的停调,
+// 积分不足、花费上限、管理员规则等其他原因的停调不受影响。
+func clearCommandCodeWindowCooldown(ctx context.Context, repo AccountRepository, account *Account, usage *commandCodeUsage, now time.Time) bool {
+ if usage == nil || usage.credits.Credits == nil || usage.credits.Credits.PurchasedCredits <= 0 {
+ return false
+ }
+ if account.TempUnschedulableUntil == nil || !now.Before(*account.TempUnschedulableUntil) ||
+ !strings.HasPrefix(account.TempUnschedulableReason, commandCodeUsageLimitReason) {
+ return false
+ }
+ if err := repo.ClearTempUnschedulable(ctx, account.ID); err != nil {
+ slog.Warn("command_code_usage_limit_clear_failed", "account_id", account.ID, "error", err)
+ return false
+ }
+ slog.Info("command_code_usage_limit_cleared", "account_id", account.ID,
+ "purchased_credits", float64(usage.credits.Credits.PurchasedCredits))
+ return true
+}
+
+// commandCodeWindowsBinding 报告账号快照中的滚动 / 月度窗口是否限制调度:
+// 有充值积分时上游跳过窗口检查,窗口用满也不会被拒绝。
+func commandCodeWindowsBinding(extra map[string]any) bool {
+ purchased, ok := cnParseF64(extra[cnExtraKey(PlatformCommandCode, commandCodeExtraSuffixPurchasedCredits)])
+ return !ok || purchased <= 0
+}
+
+// commandCodeUsageExtraUpdates 构造窗口 + 余额快照。缺席的窗口写 nil,避免套餐
+// 变化后沿用旧快照;窗口尚未开始时没有重置时间,同样清掉上一个窗口的值;月度窗口
+// 取数失败时保留旧快照;传 nil tiers 时只写余额。
+func commandCodeUsageExtraUpdates(usage *commandCodeUsage, tiers []CNQuotaTier, balance *CNProviderBalanceResult, now time.Time, withTiers bool) map[string]any {
+ updates := cnBalanceExtraUpdates(PlatformCommandCode, balance, now)
+ updates[cnExtraKey(PlatformCommandCode, commandCodeExtraSuffixPurchasedCredits)] = float64(usage.credits.Credits.PurchasedCredits)
+ if !withTiers {
+ return updates
+ }
+ for key, value := range cnQuotaExtraUpdates(PlatformCommandCode, tiers, now) {
+ updates[key] = value
+ }
+ present := make(map[string]CNQuotaTier, len(tiers))
+ for _, tier := range tiers {
+ present[tier.Window] = tier
+ }
+ for _, window := range []struct {
+ name, used, reset string
+ }{
+ {"5h", cnExtraSuffix5hUsed, cnExtraSuffix5hReset},
+ {"weekly", cnExtraSuffixWeeklyUsed, cnExtraSuffixWeeklyReset},
+ {"monthly", cnExtraSuffixMonthlyUsed, cnExtraSuffixMonthlyReset},
+ } {
+ tier, ok := present[window.name]
+ if !ok && window.name == "monthly" && usage.periodFetchFailed {
+ continue
+ }
+ if !ok {
+ updates[cnExtraKey(PlatformCommandCode, window.used)] = nil
+ }
+ if tier.ResetAt == "" {
+ updates[cnExtraKey(PlatformCommandCode, window.reset)] = nil
+ }
+ }
+ return updates
+}
+
+func newCommandCodeUsageClient(cfg *config.Config, httpUpstream HTTPUpstream, account *Account, proxyURL string) *commandCodeUsageClient {
+ return &commandCodeUsageClient{
+ cfg: cfg,
+ httpUpstream: httpUpstream,
+ account: account,
+ apiKey: strings.TrimSpace(account.GetCNAPIKey()),
+ proxyURL: proxyURL,
+ }
+}
+
+// commandCodeFetchFailure 把取数错误转换为探测失败文案;ok=false 表示应作为错误返回。
+func commandCodeFetchFailure(err error) (status int, message string, ok bool) {
+ var httpErr *commandCodeHTTPError
+ switch {
+ case errors.As(err, &httpErr) && httpErr.unauthorized():
+ return httpErr.status, fmt.Sprintf("Authentication failed (HTTP %d)", httpErr.status), true
+ case errors.As(err, &httpErr):
+ return httpErr.status, fmt.Sprintf("API error (HTTP %d): %s", httpErr.status, httpErr.body), true
+ case errors.Is(err, errCommandCodeInvalidResponse):
+ return http.StatusOK, "Invalid usage response", true
+ default:
+ return 0, "", false
+ }
+}
+
+// queryCommandCodeUsage 查询 Command Code 积分与窗口,落窗口与余额快照。
+func (s *CNProviderQuotaService) queryCommandCodeUsage(ctx context.Context, account *Account) (*CNProviderQuotaProbeResult, error) {
+ client := newCommandCodeUsageClient(s.cfg, s.httpUpstream, account, s.resolveProxyURL(ctx, account))
+ if client.apiKey == "" {
+ return nil, infraerrors.New(http.StatusBadRequest, "CN_QUOTA_NO_APIKEY", "account api_key is empty")
+ }
+ now := time.Now().UTC()
+ result := &CNProviderQuotaProbeResult{
+ Provider: PlatformCommandCode,
+ Source: "command_code_usage",
+ FetchedAt: now.Unix(),
+ }
+ usage, err := client.fetch(ctx, true)
+ if err != nil {
+ status, message, ok := commandCodeFetchFailure(err)
+ if !ok {
+ if isApplicationError(err) {
+ return nil, err
+ }
+ return nil, infraerrors.Newf(http.StatusBadGateway, "CN_QUOTA_REQUEST_FAILED", "%v", err)
+ }
+ result.StatusCode = status
+ result.Error = message
+ return result, nil
+ }
+
+ tiers := usage.tiers()
+ balance := usage.balance(now)
+ result.StatusCode = http.StatusOK
+ result.Tiers = tiers
+ result.PlanLevel = usage.planName()
+ result.Balance = balance
+ result.Success = true
+ result.CredentialValid = true
+
+ updates := commandCodeUsageExtraUpdates(usage, tiers, balance, now, true)
+ if err := s.accountRepo.UpdateExtra(ctx, account.ID, updates); err != nil {
+ slog.Warn("cn_quota_persist_failed", "account_id", account.ID, "provider", PlatformCommandCode, "error", err)
+ } else {
+ result.Persisted = true
+ balance.Persisted = true
+ }
+ clearCommandCodeWindowCooldown(ctx, s.accountRepo, account, usage, now)
+ return result, nil
+}
+
+// queryCommandCodeBalance 只查积分余额(whoami + credits),落余额快照。
+func (s *CNProviderBalanceService) queryCommandCodeBalance(ctx context.Context, account *Account) (*CNProviderBalanceResult, error) {
+ client := newCommandCodeUsageClient(s.cfg, s.httpUpstream, account, s.resolveProxyURL(ctx, account))
+ if client.apiKey == "" {
+ return nil, infraerrors.New(http.StatusBadRequest, "CN_BALANCE_NO_APIKEY", "account api_key is empty")
+ }
+ now := time.Now().UTC()
+ usage, err := client.fetch(ctx, false)
+ if err != nil {
+ status, message, ok := commandCodeFetchFailure(err)
+ if !ok {
+ if isApplicationError(err) {
+ return nil, err
+ }
+ return nil, infraerrors.Newf(http.StatusBadGateway, "CN_BALANCE_REQUEST_FAILED", "%v", err)
+ }
+ return &CNProviderBalanceResult{
+ Provider: PlatformCommandCode,
+ StatusCode: status,
+ FetchedAt: now.Unix(),
+ Available: true,
+ Error: message,
+ }, nil
+ }
+ result := usage.balance(now)
+ if err := s.accountRepo.UpdateExtra(ctx, account.ID, commandCodeUsageExtraUpdates(usage, nil, result, now, false)); err != nil {
+ slog.Warn("cn_balance_persist_failed", "account_id", account.ID, "provider", PlatformCommandCode, "error", err)
+ } else {
+ result.Persisted = true
+ }
+ clearCommandCodeWindowCooldown(ctx, s.accountRepo, account, usage, now)
+ return result, nil
+}
diff --git a/backend/internal/service/command_code_usage_test.go b/backend/internal/service/command_code_usage_test.go
new file mode 100644
index 000000000..a5b66c776
--- /dev/null
+++ b/backend/internal/service/command_code_usage_test.go
@@ -0,0 +1,694 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/tlsfingerprint"
+ "github.com/stretchr/testify/require"
+)
+
+// commandCodeAlphaUpstream 按路径返回 /alpha 接口响应,并记录请求。
+type commandCodeAlphaUpstream struct {
+ mu sync.Mutex
+ responses map[string]commandCodeAlphaResponse
+ requests []*http.Request
+}
+
+type commandCodeAlphaResponse struct {
+ status int
+ body string
+}
+
+func (u *commandCodeAlphaUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
+ u.mu.Lock()
+ u.requests = append(u.requests, req)
+ u.mu.Unlock()
+ resp, ok := u.responses[req.URL.Path]
+ if !ok {
+ resp = commandCodeAlphaResponse{status: http.StatusNotFound, body: `{"error":"not found"}`}
+ }
+ return &http.Response{
+ StatusCode: resp.status,
+ Body: io.NopCloser(strings.NewReader(resp.body)),
+ Header: make(http.Header),
+ Request: req,
+ }, nil
+}
+
+func (u *commandCodeAlphaUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
+ return u.Do(req, proxyURL, accountID, concurrency)
+}
+
+func (u *commandCodeAlphaUpstream) request(path string) *http.Request {
+ for _, req := range u.requests {
+ if req.URL.Path == path {
+ return req
+ }
+ }
+ return nil
+}
+
+const (
+ commandCodeTestCredits = `{
+ "credits": {"belowThreshold": false, "monthlyCredits": "34.9", "purchasedCredits": 0, "freeCredits": 0.1},
+ "windowLimits": {
+ "limited": true,
+ "fiveHour": {"used": 1.5, "cap": 14, "resetAt": 1790000000000},
+ "weekly": {"used": 35, "cap": 35, "resetAt": 1790400000000}
+ }
+ }`
+ commandCodeTestSubscription = `{"data": {"planId": "individual-goat", "status": "active",
+ "currentPeriodStart": "2026-09-01T00:00:00Z", "currentPeriodEnd": "2026-10-01T00:00:00Z"}}`
+ commandCodeTestSummary = `{"totalCost": 40, "totalMonthlyCredits": 35.1}`
+)
+
+func commandCodeUsageAccount() *Account {
+ account := commandCodeTestAccount(77)
+ account.Concurrency = 1
+ return account
+}
+
+func newCommandCodeAlphaUpstream(whoami string) *commandCodeAlphaUpstream {
+ return &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
+ "/alpha/whoami": {status: http.StatusOK, body: whoami},
+ "/alpha/billing/credits": {status: http.StatusOK, body: commandCodeTestCredits},
+ "/alpha/billing/subscriptions": {status: http.StatusOK, body: commandCodeTestSubscription},
+ "/alpha/usage/summary": {status: http.StatusOK, body: commandCodeTestSummary},
+ }}
+}
+
+func TestCommandCodeQuotaProbeParsesWindowsAndBalance(t *testing.T) {
+ account := commandCodeUsageAccount()
+ upstream := newCommandCodeAlphaUpstream(`{"user": {"userName": "alice"}, "org": null}`)
+ repo := &cnBalanceProbeRepo{account: account}
+ svc := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{})
+
+ result, err := svc.QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.True(t, result.Persisted)
+ require.Equal(t, PlatformCommandCode, result.Provider)
+ require.Equal(t, "GOAT", result.PlanLevel)
+ require.Equal(t, []CNQuotaTier{
+ {Window: "5h", UsedPercent: 10.71, ResetAt: time.UnixMilli(1790000000000).UTC().Format(time.RFC3339)},
+ {Window: "weekly", UsedPercent: 100, ResetAt: time.UnixMilli(1790400000000).UTC().Format(time.RFC3339)},
+ {Window: "monthly", UsedPercent: 50.14, ResetAt: "2026-10-01T00:00:00Z"},
+ }, result.Tiers)
+ require.NotNil(t, result.Balance)
+ require.InDelta(t, 35.0, result.Balance.Balance, 1e-9)
+ require.Equal(t, "USD", result.Balance.Currency)
+
+ // 个人账户不带 orgId;本周期用量从订阅周期起点统计。
+ for _, req := range upstream.requests {
+ require.Equal(t, "Bearer user_test_key", req.Header.Get("Authorization"))
+ require.Equal(t, "api.commandcode.ai", req.URL.Host)
+ require.False(t, req.URL.Query().Has("orgId"), req.URL.String())
+ }
+ require.Equal(t, "2026-09-01T00:00:00Z", upstream.request("/alpha/usage/summary").URL.Query().Get("since"))
+
+ require.Len(t, repo.extraWrites, 1)
+ extra := repo.extraWrites[0]
+ require.Equal(t, 10.71, extra["command_code_5h_used_percent"])
+ require.Equal(t, 100.0, extra["command_code_weekly_used_percent"])
+ require.Equal(t, 50.14, extra["command_code_monthly_used_percent"])
+ require.Equal(t, "2026-10-01T00:00:00Z", extra["command_code_monthly_reset_at"])
+ require.InDelta(t, 35.0, extra["command_code_balance"], 1e-9)
+ require.Equal(t, "USD", extra["command_code_balance_currency"])
+ require.Equal(t, 0.0, extra["command_code_purchased_credits"])
+ require.Equal(t, false, extra["command_code_balance_low"])
+}
+
+func TestCommandCodeQuotaProbePassesOrgID(t *testing.T) {
+ account := commandCodeUsageAccount()
+ upstream := newCommandCodeAlphaUpstream(`{"user": {"userName": "alice"}, "org": {"id": "9a0f5d0e-6d2c-4f36-9c55-0b8b0c0d1e2f", "login": "team"}}`)
+ svc := NewCNProviderQuotaService(&cnBalanceProbeRepo{account: account}, nil, upstream, &config.Config{})
+
+ _, err := svc.QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ for _, path := range []string{"/alpha/billing/credits", "/alpha/billing/subscriptions", "/alpha/usage/summary"} {
+ require.Equal(t, "9a0f5d0e-6d2c-4f36-9c55-0b8b0c0d1e2f", upstream.request(path).URL.Query().Get("orgId"), path)
+ }
+}
+
+func TestCommandCodeQuotaProbeUnlimitedPlanClearsRollingWindows(t *testing.T) {
+ account := commandCodeUsageAccount()
+ upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
+ upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: `{
+ "credits": {"monthlyCredits": 10, "purchasedCredits": 25, "freeCredits": 0},
+ "windowLimits": {"limited": false}
+ }`}
+ upstream.responses["/alpha/usage/summary"] = commandCodeAlphaResponse{status: http.StatusOK, body: `{"totalCost": 5}`}
+ repo := &cnBalanceProbeRepo{account: account}
+ svc := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{})
+
+ result, err := svc.QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.Equal(t, []CNQuotaTier{{Window: "monthly", UsedPercent: 33.33, ResetAt: "2026-10-01T00:00:00Z"}}, result.Tiers)
+ extra := repo.extraWrites[0]
+ for _, key := range []string{"command_code_5h_used_percent", "command_code_5h_reset_at", "command_code_weekly_used_percent", "command_code_weekly_reset_at"} {
+ value, ok := extra[key]
+ require.True(t, ok, key)
+ require.Nil(t, value, key)
+ }
+ require.Equal(t, 25.0, extra["command_code_purchased_credits"])
+ require.InDelta(t, 35.0, extra["command_code_balance"], 1e-9)
+}
+
+// 窗口尚未开始(resetAt 为空)时清掉上一个窗口的重置时间,不与新的用量配对。
+func TestCommandCodeQuotaProbeClearsResetOfUnstartedWindow(t *testing.T) {
+ account := commandCodeUsageAccount()
+ upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
+ upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: `{
+ "credits": {"monthlyCredits": 34.9, "purchasedCredits": 0, "freeCredits": 0},
+ "windowLimits": {
+ "limited": true,
+ "fiveHour": {"used": 0, "cap": 14, "resetAt": null},
+ "weekly": {"used": 35, "cap": 35, "resetAt": 1790400000000}
+ }
+ }`}
+ repo := &cnBalanceProbeRepo{account: account}
+
+ _, err := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{}).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ extra := repo.extraWrites[0]
+ require.Equal(t, 0.0, extra["command_code_5h_used_percent"])
+ value, written := extra["command_code_5h_reset_at"]
+ require.True(t, written)
+ require.Nil(t, value)
+ require.Equal(t, time.UnixMilli(1790400000000).UTC().Format(time.RFC3339), extra["command_code_weekly_reset_at"])
+ require.Equal(t, "2026-10-01T00:00:00Z", extra["command_code_monthly_reset_at"])
+}
+
+func TestCommandCodeQuotaProbeAuthFailureDoesNotPersist(t *testing.T) {
+ account := commandCodeUsageAccount()
+ upstream := newCommandCodeAlphaUpstream(`{}`)
+ upstream.responses["/alpha/whoami"] = commandCodeAlphaResponse{status: http.StatusUnauthorized, body: `{"error":"unauthorized"}`}
+ repo := &cnBalanceProbeRepo{account: account}
+ svc := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{})
+
+ result, err := svc.QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Equal(t, http.StatusUnauthorized, result.StatusCode)
+ require.Equal(t, "Authentication failed (HTTP 401)", result.Error)
+ require.Empty(t, repo.extraWrites)
+ require.Len(t, upstream.requests, 1)
+}
+
+// 订阅周期或本周期用量取数失败:滚动窗口照常更新,月度快照保留上一次的值(无从判断
+// 月度窗口是否还在);订阅确实没有周期时才清掉月度快照。
+// whoami 失败(非鉴权错误)时无从判断是否组织账户:探测整体失败,不按个人账户去查
+// credits,也不写快照。
+func TestCommandCodeProbeFailsWhenWhoamiFails(t *testing.T) {
+ for _, whoami := range []commandCodeAlphaResponse{
+ {status: http.StatusBadGateway, body: `bad gateway`},
+ {status: http.StatusOK, body: `not json`},
+ } {
+ account := commandCodeUsageAccount()
+ upstream := newCommandCodeAlphaUpstream(`{}`)
+ upstream.responses["/alpha/whoami"] = whoami
+ repo := &cnBalanceProbeRepo{account: account}
+
+ result, err := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{}).QueryUsage(context.Background(), account.ID)
+ require.NoError(t, err, whoami.body)
+ require.False(t, result.Success, whoami.body)
+ require.NotEmpty(t, result.Error, whoami.body)
+
+ balance, err := NewCNProviderBalanceService(repo, nil, upstream, &config.Config{}).QueryBalance(context.Background(), account.ID)
+ require.NoError(t, err, whoami.body)
+ require.False(t, balance.Success, whoami.body)
+
+ require.Nil(t, upstream.request("/alpha/billing/credits"), whoami.body)
+ require.Empty(t, repo.extraWrites, whoami.body)
+ }
+
+ // 请求本身失败(网络错误)同样整体失败。
+ account := commandCodeUsageAccount()
+ repo := &cnBalanceProbeRepo{account: account}
+ _, err := NewCNProviderQuotaService(repo, nil, failingCommandCodeUpstream{}, &config.Config{}).QueryUsage(context.Background(), account.ID)
+ require.Error(t, err)
+ require.Empty(t, repo.extraWrites)
+}
+
+// failingCommandCodeUpstream 让每个请求都在网络层失败。
+type failingCommandCodeUpstream struct{}
+
+func (failingCommandCodeUpstream) Do(*http.Request, string, int64, int) (*http.Response, error) {
+ return nil, errors.New("dial tcp: i/o timeout")
+}
+
+func (u failingCommandCodeUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
+ return u.Do(req, proxyURL, accountID, concurrency)
+}
+
+func TestCommandCodeQuotaProbeKeepsWindowsWhenPeriodEndpointsFail(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ path string
+ response commandCodeAlphaResponse
+ planLevel string
+ keepMonthly bool
+ }{
+ {"subscriptions failed", "/alpha/billing/subscriptions", commandCodeAlphaResponse{status: http.StatusInternalServerError, body: `oops`}, "", true},
+ {"summary failed", "/alpha/usage/summary", commandCodeAlphaResponse{status: http.StatusBadGateway, body: `oops`}, "GOAT", true},
+ {"no subscription period", "/alpha/billing/subscriptions", commandCodeAlphaResponse{status: http.StatusOK, body: `{"data":{}}`}, "", false},
+ } {
+ account := commandCodeUsageAccount()
+ upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
+ upstream.responses[tc.path] = tc.response
+ repo := &cnBalanceProbeRepo{account: account}
+
+ result, err := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{}).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err, tc.name)
+ require.True(t, result.Success, tc.name)
+ require.Len(t, result.Tiers, 2, tc.name)
+ require.Equal(t, tc.planLevel, result.PlanLevel, tc.name)
+ if tc.path == "/alpha/billing/subscriptions" {
+ require.Nil(t, upstream.request("/alpha/usage/summary"), tc.name)
+ }
+ extra := repo.extraWrites[0]
+ require.Equal(t, 10.71, extra["command_code_5h_used_percent"], tc.name)
+ for _, key := range []string{"command_code_monthly_used_percent", "command_code_monthly_reset_at"} {
+ value, written := extra[key]
+ require.Equal(t, !tc.keepMonthly, written, tc.name+": "+key)
+ require.Nil(t, value, tc.name+": "+key)
+ }
+ }
+}
+
+func TestCommandCodeUsageRequiresOfficialHost(t *testing.T) {
+ account := commandCodeUsageAccount()
+ require.Equal(t, PlatformCommandCode, account.GetCodingPlanProvider())
+ require.NoError(t, validateCodingPlanAccount(account))
+ require.NoError(t, validatePayGAccount(account))
+
+ account.Credentials["base_url"] = "https://relay.example.com/v1"
+ account.Credentials["api_protocol"] = APIProtocolChatCompletions
+ require.Empty(t, account.GetCodingPlanProvider())
+ require.Error(t, validateCodingPlanAccount(account))
+ require.Error(t, validatePayGAccount(account))
+}
+
+func TestCommandCodeBalanceProbeFetchesCreditsOnly(t *testing.T) {
+ account := commandCodeUsageAccount()
+ upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
+ repo := &cnBalanceProbeRepo{account: account}
+ svc := NewCNProviderBalanceService(repo, nil, upstream, &config.Config{})
+
+ result, err := svc.QueryBalance(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ require.True(t, result.Persisted)
+ require.InDelta(t, 35.0, result.Balance, 1e-9)
+ require.Len(t, upstream.requests, 2)
+ require.Len(t, repo.extraWrites, 1)
+ _, hasWindow := repo.extraWrites[0]["command_code_5h_used_percent"]
+ require.False(t, hasWindow)
+ require.InDelta(t, 35.0, repo.extraWrites[0]["command_code_balance"], 1e-9)
+}
+
+func TestCommandCodeWindowsIgnoredWithPurchasedCredits(t *testing.T) {
+ future := time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339)
+ account := commandCodeUsageAccount()
+ account.Extra = map[string]any{
+ "command_code_5h_used_percent": 100.0,
+ "command_code_5h_reset_at": future,
+ "command_code_purchased_credits": 0.0,
+ }
+ require.NotEmpty(t, cnProviderThresholdCandidates(account, PlatformCommandCode))
+ require.NotNil(t, cnProviderQuotaSnapshotReset(account, time.Now()))
+
+ account.Extra["command_code_purchased_credits"] = 12.5
+ require.Empty(t, cnProviderThresholdCandidates(account, PlatformCommandCode))
+ require.Nil(t, cnProviderQuotaSnapshotReset(account, time.Now()))
+}
+
+// commandCodeCheckRepo 按平台列出账号,并记录周期检测对账号的停调。
+type commandCodeCheckRepo struct {
+ AccountRepository
+ accounts []Account
+ mu sync.Mutex
+ paused []int64
+}
+
+func (r *commandCodeCheckRepo) ListByPlatform(_ context.Context, platform string) ([]Account, error) {
+ var accounts []Account
+ for _, account := range r.accounts {
+ if account.Platform == platform {
+ accounts = append(accounts, account)
+ }
+ }
+ return accounts, nil
+}
+
+func (r *commandCodeCheckRepo) SetTempUnschedulable(_ context.Context, id int64, _ time.Time, _ string) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.paused = append(r.paused, id)
+ return nil
+}
+
+type commandCodeBalanceProber struct {
+ mu sync.Mutex
+ probed []int64
+ balance float64
+}
+
+func (p *commandCodeBalanceProber) QueryUsage(_ context.Context, accountID int64) (*CNProviderQuotaProbeResult, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.probed = append(p.probed, accountID)
+ return &CNProviderQuotaProbeResult{
+ Success: true,
+ Balance: &CNProviderBalanceResult{Success: true, Balance: p.balance, Currency: "USD", Available: true},
+ }, nil
+}
+
+func TestCNProviderBalanceCheckRunOnceProbesCommandCode(t *testing.T) {
+ official := *commandCodeUsageAccount()
+ official.ID, official.Schedulable = 1, true
+ manualOff := *commandCodeUsageAccount()
+ manualOff.ID, manualOff.Schedulable = 2, false
+ relay := *commandCodeTestAccount(3)
+ relay.Schedulable = true
+ relay.Credentials = map[string]any{"api_key": "k", "api_protocol": APIProtocolChatCompletions, "base_url": "https://relay.example.com/v1"}
+ inactive := *commandCodeUsageAccount()
+ inactive.ID, inactive.Status = 4, StatusDisabled
+
+ repo := &commandCodeCheckRepo{accounts: []Account{official, manualOff, relay, inactive}}
+ prober := &commandCodeBalanceProber{balance: 0.2}
+ cfg := &config.Config{}
+ cfg.Gateway.CNProviders.BalanceThreshold = 0.5
+ svc := &CNProviderBalanceCheckService{accountRepo: repo, quotaService: prober, cfg: cfg}
+
+ svc.runOnce()
+
+ require.ElementsMatch(t, []int64{1, 2}, prober.probed)
+ require.Equal(t, []int64{1}, repo.paused)
+}
+
+// 积分不足(402)是可恢复状态:临时停调并标记 balance_low,不能永久置 error。
+func TestHandleUpstreamError_CommandCode402PausesInsteadOfError(t *testing.T) {
+ repo := &rateLimitAccountRepoStub{}
+ service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := commandCodeUsageAccount()
+
+ shouldDisable := service.HandleUpstreamError(context.Background(), account, http.StatusPaymentRequired,
+ http.Header{}, []byte(`{"error":{"message":"Insufficient credits"}}`))
+
+ require.True(t, shouldDisable)
+ require.Equal(t, 0, repo.setErrorCalls)
+ require.Equal(t, 1, repo.tempCalls)
+ require.Contains(t, repo.lastTempReason, cnBalanceLowReasonPrefix)
+ require.Equal(t, true, repo.lastExtraUpdates["command_code_balance_low"])
+}
+
+func TestHandleUpstreamError_CommandCode429InsufficientBalancePauses(t *testing.T) {
+ repo := &rateLimitAccountRepoStub{}
+ service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := commandCodeUsageAccount()
+
+ service.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests,
+ http.Header{}, []byte(`{"error":{"type":"insufficient_credits","message":"no credits left"}}`))
+
+ require.Equal(t, 0, repo.setErrorCalls)
+ require.Equal(t, 1, repo.tempCalls)
+ require.Contains(t, repo.lastTempReason, cnBalanceLowReasonPrefix)
+ require.Equal(t, 0, repo.rateLimitedCalls)
+}
+
+// commandCodeRateLimitRepo 记录 Command Code 响应式处理写入的临时停调与模型级限流。
+type commandCodeRateLimitRepo struct {
+ rateLimitAccountRepoStub
+ tempUntil time.Time
+ modelLimits map[string]time.Time
+ reasons map[string]string
+}
+
+func (r *commandCodeRateLimitRepo) SetTempUnschedulable(ctx context.Context, id int64, until time.Time, reason string) error {
+ r.tempUntil = until
+ return r.rateLimitAccountRepoStub.SetTempUnschedulable(ctx, id, until, reason)
+}
+
+func (r *commandCodeRateLimitRepo) SetModelRateLimit(_ context.Context, _ int64, scope string, resetAt time.Time, reason ...string) error {
+ if r.modelLimits == nil {
+ r.modelLimits = map[string]time.Time{}
+ r.reasons = map[string]string{}
+ }
+ r.modelLimits[scope] = resetAt
+ if len(reason) > 0 {
+ r.reasons[scope] = reason[0]
+ }
+ return nil
+}
+
+// 窗口用满:按文案中的重置时间写带原因的临时停调(充值后可据原因解除),不依赖额度快照。
+func TestHandleUpstreamError_CommandCodeWindowLimitCoolsDownToMessageReset(t *testing.T) {
+ for _, status := range []int{http.StatusTooManyRequests, http.StatusForbidden, http.StatusPaymentRequired} {
+ repo := &commandCodeRateLimitRepo{}
+ service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := commandCodeUsageAccount()
+
+ shouldDisable := service.HandleUpstreamError(context.Background(), account, status, http.Header{},
+ []byte(`{"error":{"type":"usage_exceeded","message":"You've reached your 5-hour usage limit. Resets in 2h 41m (3:00 PM)."}}`))
+
+ require.Equal(t, status != http.StatusTooManyRequests, shouldDisable, status)
+ require.Equal(t, 0, repo.setErrorCalls, status)
+ require.Equal(t, 0, repo.rateLimitedCalls, status)
+ require.Equal(t, 1, repo.tempCalls, status)
+ require.True(t, strings.HasPrefix(repo.lastTempReason, commandCodeUsageLimitReason+": "), repo.lastTempReason)
+ expected := time.Now().Add(2*time.Hour + 41*time.Minute)
+ require.WithinDuration(t, expected, repo.tempUntil, time.Minute, status)
+ }
+}
+
+// 文案没有重置时间时回落额度快照中最早的窗口重置点。
+func TestHandleUpstreamError_CommandCodeWindowLimitFallsBackToSnapshot(t *testing.T) {
+ repo := &commandCodeRateLimitRepo{}
+ service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := commandCodeUsageAccount()
+ account.Extra = map[string]any{
+ "command_code_5h_used_percent": 100.0,
+ "command_code_5h_reset_at": time.Now().Add(90 * time.Minute).UTC().Format(time.RFC3339),
+ "command_code_purchased_credits": 0.0,
+ }
+
+ service.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{},
+ []byte(`{"error":{"message":"You've reached your weekly usage limit."}}`))
+
+ require.Equal(t, 1, repo.tempCalls)
+ require.WithinDuration(t, time.Now().Add(90*time.Minute), repo.tempUntil, time.Minute)
+}
+
+// 普通频率限制很快恢复:即使快照里有窗口重置点,也不冷却到窗口重置。
+func TestHandleUpstreamError_CommandCodeRateLimitUsesDefaultCooldown(t *testing.T) {
+ repo := &commandCodeRateLimitRepo{}
+ service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := commandCodeUsageAccount()
+ account.Extra = map[string]any{
+ "command_code_5h_used_percent": 97.0,
+ "command_code_5h_reset_at": time.Now().Add(4 * time.Hour).UTC().Format(time.RFC3339),
+ "command_code_purchased_credits": 0.0,
+ }
+
+ service.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{},
+ []byte(`{"error":{"type":"rate_limit","message":"Rate limit exceeded. Please wait a moment and try again."}}`))
+
+ require.Equal(t, 0, repo.setErrorCalls)
+ require.Equal(t, 0, repo.tempCalls)
+ if repo.rateLimitedCalls > 0 {
+ require.True(t, repo.lastRateLimitedAt.Before(time.Now().Add(30*time.Minute)), "must not cool down to the 5h window reset")
+ }
+}
+
+const (
+ commandCodeSpendLimitBody = `{"error":{"type":"usage_exceeded","message":"You've reached the $10.00/mo spending limit your organization set for GLM-5. It resets in 3 days."}}`
+ commandCodeMemberSpendLimitBody = `{"error":{"type":"usage_exceeded","message":"You've reached the $50.00/mo spending limit your organization set. It resets in 12 days."}}`
+)
+
+// 组织为某个模型设的花费上限只限当前模型:写模型级限流到文案中的重置时间,不停整个账号。
+func TestHandleUpstreamError_CommandCodeSpendLimitIsModelScoped(t *testing.T) {
+ repo := &commandCodeRateLimitRepo{}
+ service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := commandCodeUsageAccount()
+ ctx := withTempUnschedulableModel(context.Background(), []string{"glm-5"})
+
+ shouldDisable := service.HandleUpstreamError(ctx, account, http.StatusForbidden, http.Header{}, []byte(commandCodeSpendLimitBody))
+
+ require.False(t, shouldDisable)
+ require.Equal(t, 0, repo.setErrorCalls)
+ require.Equal(t, 0, repo.tempCalls)
+ require.Equal(t, 0, repo.rateLimitedCalls)
+ require.Contains(t, repo.modelLimits, "glm-5")
+ require.WithinDuration(t, time.Now().Add(72*time.Hour), repo.modelLimits["glm-5"], time.Minute)
+ require.Equal(t, commandCodeSpendLimitReason, repo.reasons["glm-5"])
+}
+
+// 成员总额度耗尽:即使请求模型已知也按账号冷却,但最长一小时(管理员可能调高上限)。
+func TestHandleUpstreamError_CommandCodeMemberSpendLimitIsAccountScoped(t *testing.T) {
+ repo := &commandCodeRateLimitRepo{}
+ service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := commandCodeUsageAccount()
+ ctx := withTempUnschedulableModel(context.Background(), []string{"glm-5"})
+
+ shouldDisable := service.HandleUpstreamError(ctx, account, http.StatusForbidden, http.Header{}, []byte(commandCodeMemberSpendLimitBody))
+
+ require.True(t, shouldDisable)
+ require.Empty(t, repo.modelLimits)
+ require.Equal(t, 0, repo.setErrorCalls)
+ require.Equal(t, 1, repo.tempCalls)
+ require.Equal(t, commandCodeSpendLimitReason, repo.lastTempReason)
+ require.WithinDuration(t, time.Now().Add(commandCodeAccountSpendLimitRecheck), repo.tempUntil, time.Minute)
+
+ // 文案中的重置时间早于一小时时以文案为准。
+ soon := &commandCodeRateLimitRepo{}
+ NewRateLimitService(soon, nil, &config.Config{}, nil, nil).HandleUpstreamError(ctx, account, http.StatusTooManyRequests, http.Header{},
+ []byte(`{"error":{"message":"You've reached the $50.00/mo spending limit your organization set. It resets in 20 minutes."}}`))
+ require.WithinDuration(t, time.Now().Add(20*time.Minute), soon.tempUntil, time.Minute)
+}
+
+// 不知道模型时按账号冷却(最长一小时),不停账号数天,也不进入 403 累计禁用。
+func TestHandleUpstreamError_CommandCodeSpendLimitWithoutModelShortCooldown(t *testing.T) {
+ repo := &commandCodeRateLimitRepo{}
+ service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ account := commandCodeUsageAccount()
+
+ for i := 0; i < 5; i++ {
+ service.HandleUpstreamError(context.Background(), account, http.StatusForbidden, http.Header{}, []byte(commandCodeSpendLimitBody))
+ }
+
+ require.Equal(t, 0, repo.setErrorCalls)
+ require.Empty(t, repo.modelLimits)
+ require.Equal(t, 5, repo.tempCalls)
+ require.False(t, repo.tempUntil.After(time.Now().Add(commandCodeAccountSpendLimitRecheck)))
+}
+
+func TestCommandCodeSpendLimitScope(t *testing.T) {
+ require.True(t, commandCodeSpendLimitIsModelScoped([]byte(commandCodeSpendLimitBody)))
+ require.True(t, commandCodeSpendLimitIsModelScoped([]byte(`spending limit your organization set for gpt-5.5. It resets in 2 days.`)))
+ require.False(t, commandCodeSpendLimitIsModelScoped([]byte(commandCodeMemberSpendLimitBody)))
+ require.False(t, commandCodeSpendLimitIsModelScoped([]byte(`You've reached the $50.00/mo spending limit your organization set for you.`)))
+ require.False(t, commandCodeSpendLimitIsModelScoped([]byte(`spending limit reached`)))
+}
+
+// commandCodeStatefulRepo 把停调写回同一个账号对象,用于验证完整的状态转换。
+type commandCodeStatefulRepo struct {
+ AccountRepository
+ account *Account
+ clearCalls int
+}
+
+func (r *commandCodeStatefulRepo) GetByID(_ context.Context, _ int64) (*Account, error) {
+ clone := *r.account
+ return &clone, nil
+}
+
+func (r *commandCodeStatefulRepo) UpdateExtra(_ context.Context, _ int64, _ map[string]any) error {
+ return nil
+}
+
+func (r *commandCodeStatefulRepo) SetTempUnschedulable(_ context.Context, _ int64, until time.Time, reason string) error {
+ r.account.TempUnschedulableUntil = &until
+ r.account.TempUnschedulableReason = reason
+ return nil
+}
+
+func (r *commandCodeStatefulRepo) ClearTempUnschedulable(_ context.Context, _ int64) error {
+ r.clearCalls++
+ r.account.TempUnschedulableUntil = nil
+ r.account.TempUnschedulableReason = ""
+ return nil
+}
+
+func commandCodeCreditsBody(purchased float64) string {
+ return fmt.Sprintf(`{"credits":{"monthlyCredits":0,"purchasedCredits":%g,"freeCredits":0},
+ "windowLimits":{"limited":true,"fiveHour":{"used":14,"cap":14,"resetAt":1790000000000}}}`, purchased)
+}
+
+// 窗口用满进入冷却 → 充值 → 下一次额度探测发现充值积分 → 恢复可调度。
+func TestCommandCodeWindowCooldownClearedAfterTopUp(t *testing.T) {
+ account := commandCodeUsageAccount()
+ account.Schedulable = true
+ repo := &commandCodeStatefulRepo{account: account}
+ rateLimit := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+
+ rateLimit.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{},
+ []byte(`{"error":{"message":"You've reached your 5-hour usage limit. Resets in 3h 10m."}}`))
+ require.False(t, account.IsSchedulable())
+
+ // 未充值:探测不解除冷却。
+ upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
+ upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: commandCodeCreditsBody(0)}
+ quota := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{})
+ _, err := quota.QueryUsage(context.Background(), account.ID)
+ require.NoError(t, err)
+ require.Equal(t, 0, repo.clearCalls)
+ require.False(t, account.IsSchedulable())
+
+ // 充值后:额度探测与余额探测都能解除窗口冷却。
+ upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: commandCodeCreditsBody(20)}
+ _, err = quota.QueryUsage(context.Background(), account.ID)
+ require.NoError(t, err)
+ require.Equal(t, 1, repo.clearCalls)
+ require.True(t, account.IsSchedulable())
+
+ rateLimit.HandleUpstreamError(context.Background(), account, http.StatusTooManyRequests, http.Header{},
+ []byte(`{"error":{"message":"You've reached your weekly usage limit. Resets in 2 days."}}`))
+ require.False(t, account.IsSchedulable())
+ _, err = NewCNProviderBalanceService(repo, nil, upstream, &config.Config{}).QueryBalance(context.Background(), account.ID)
+ require.NoError(t, err)
+ require.True(t, account.IsSchedulable())
+}
+
+// 充值积分只解除窗口冷却:积分不足、花费上限等其他原因的停调保持不变。
+func TestCommandCodeTopUpKeepsOtherCooldowns(t *testing.T) {
+ for _, reason := range []string{cnBalanceLowReason("no credits"), commandCodeSpendLimitReason, "manual rule"} {
+ until := time.Now().Add(time.Hour)
+ account := commandCodeUsageAccount()
+ account.Schedulable = true
+ account.TempUnschedulableUntil = &until
+ account.TempUnschedulableReason = reason
+ repo := &commandCodeStatefulRepo{account: account}
+ upstream := newCommandCodeAlphaUpstream(`{"org": null}`)
+ upstream.responses["/alpha/billing/credits"] = commandCodeAlphaResponse{status: http.StatusOK, body: commandCodeCreditsBody(20)}
+
+ _, err := NewCNProviderQuotaService(repo, nil, upstream, &config.Config{}).QueryUsage(context.Background(), account.ID)
+
+ require.NoError(t, err)
+ require.Equal(t, 0, repo.clearCalls, reason)
+ require.False(t, account.IsSchedulable(), reason)
+ }
+}
+
+func TestClassifyCommandCodeUsageError(t *testing.T) {
+ cases := map[string]commandCodeUsageErrorKind{
+ `{"error":{"message":"You've reached your 5-hour usage limit. Resets in 2h 41m (3:00 PM)."}}`: commandCodeUsageWindowLimit,
+ `{"error":{"message":"You've reached your weekly usage limit."}}`: commandCodeUsageWindowLimit,
+ commandCodeSpendLimitBody: commandCodeUsageSpendLimit,
+ `{"error":{"type":"usage_exceeded","message":"Monthly credits spent."}}`: commandCodeUsageCreditsExhausted,
+ `{"error":{"message":"Insufficient credits"}}`: commandCodeUsageCreditsExhausted,
+ `{"error":{"type":"rate_limit","message":"Rate limit exceeded. Please wait a moment."}}`: commandCodeUsageErrorNone,
+ `{"error":{"message":"forbidden"}}`: commandCodeUsageErrorNone,
+ }
+ for body, want := range cases {
+ require.Equal(t, want, classifyCommandCodeUsageError([]byte(body)), body)
+ }
+}
diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go
index b1007a68b..66a246975 100644
--- a/backend/internal/service/composite_platform.go
+++ b/backend/internal/service/composite_platform.go
@@ -4,6 +4,7 @@ import (
"context"
"strings"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/ctxkey"
)
@@ -114,6 +115,8 @@ func DetectModelPlatform(model string) (string, bool) {
return PlatformDeepseek, true
case "minimax":
return PlatformMiniMax, true
+ case "typesafe", "jev":
+ return PlatformTypeSafe, true
}
if rest != "" {
normalized = strings.TrimPrefix(rest, "models/")
@@ -155,6 +158,8 @@ func DetectModelPlatform(model string) (string, bool) {
strings.HasPrefix(normalized, "abab6"),
strings.HasPrefix(normalized, "abab7"):
return PlatformMiniMax, true
+ case normalized == "jev-latest" || strings.HasPrefix(normalized, "jev-"):
+ return PlatformTypeSafe, true
default:
return "", false
}
@@ -200,11 +205,5 @@ func (s *GatewayService) resolveCompositeRouteDecision(ctx context.Context, grou
}
func isConcreteRequestPlatform(platform string) bool {
- switch platform {
- case PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
- PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS:
- return true
- default:
- return false
- }
+ return domain.IsConcretePlatform(platform)
}
diff --git a/backend/internal/service/composite_platform_test.go b/backend/internal/service/composite_platform_test.go
index 3c9e6ed04..8ac9e95f0 100644
--- a/backend/internal/service/composite_platform_test.go
+++ b/backend/internal/service/composite_platform_test.go
@@ -180,6 +180,8 @@ func TestDetectModelPlatform(t *testing.T) {
{name: "minimax prefix", model: "minimax/MiniMax-M2.5", platform: PlatformMiniMax, ok: true},
{name: "abab legacy", model: "abab6.5-chat", platform: PlatformMiniMax, ok: true},
{name: "abab7 legacy", model: "abab7-chat-preview", platform: PlatformMiniMax, ok: true},
+ {name: "jev", model: "jev-latest", platform: PlatformTypeSafe, ok: true},
+ {name: "typesafe prefix", model: "typesafe/jev-latest", platform: PlatformTypeSafe, ok: true},
{name: "abab unrelated namespace", model: "abab-other", ok: false},
{name: "unknown k3 alias", model: "k3-preview", ok: false},
{name: "unknown", model: "llama-4-maverick", ok: false},
@@ -216,13 +218,13 @@ func TestCompositeGroupSchedulerHasAllCanonicalPlatformBuckets(t *testing.T) {
platforms = append(platforms, platform)
}
require.ElementsMatch(t,
- []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS},
+ []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline, PlatformOpenAIBPS},
platforms,
)
}
func TestCompositeConcretePlatformsIncludeCNProviders(t *testing.T) {
- for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
+ for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, PlatformCommandCode, PlatformCline} {
require.True(t, isConcreteRequestPlatform(platform))
require.True(t, canCopyAccountsFromGroupPlatform(PlatformComposite, platform))
}
diff --git a/backend/internal/service/composite_route_resolver.go b/backend/internal/service/composite_route_resolver.go
index f2e1928ac..2eccbf853 100644
--- a/backend/internal/service/composite_route_resolver.go
+++ b/backend/internal/service/composite_route_resolver.go
@@ -22,6 +22,56 @@ func (r *CompositeRouteResolver) SetModelOwnershipResolver(resolver CompositeMod
}
}
+// ListExactPublicModels returns enabled, concrete route IDs suitable for a model catalog.
+func (r *CompositeRouteResolver) ListExactPublicModels(ctx context.Context, groupID int64, endpoint string, includeSystemOne bool) ([]string, error) {
+ if r == nil || r.repo == nil || groupID <= 0 {
+ return nil, nil
+ }
+ routes, err := r.repo.ListByGroup(ctx, groupID, false)
+ if err != nil {
+ return nil, err
+ }
+ models := make([]string, 0, len(routes))
+ for _, route := range routes {
+ // Sub4API: OpenAI BPS routes are listed by CompleteCompositeBPSModelCatalog, which checks account eligibility.
+ if route.TargetPlatform == PlatformOpenAIBPS {
+ continue
+ }
+ if route.Enabled && route.MatchType == CompositeRouteMatchExact &&
+ (endpoint == "" || normalizeCompositeRouteEndpoint(route.Endpoint) == CompositeRouteEndpointAny || normalizeCompositeRouteEndpoint(route.Endpoint) == endpoint) {
+ if model := strings.TrimSpace(route.PublicModel); model != "" {
+ models = append(models, model)
+ }
+ }
+ }
+ if !includeSystemOne {
+ models = filterSystemOneRouteModels(routes, models, endpoint)
+ }
+ return models, nil
+}
+
+func (r *CompositeRouteResolver) FilterCodexModels(ctx context.Context, groupID int64, models []string) ([]string, error) {
+ if r == nil || r.repo == nil || groupID <= 0 {
+ return models, nil
+ }
+ routes, err := r.repo.ListByGroup(ctx, groupID, false)
+ if err != nil {
+ return nil, err
+ }
+ return filterSystemOneRouteModels(routes, models, CompositeRouteEndpointResponses), nil
+}
+
+func filterSystemOneRouteModels(routes []CompositeModelRoute, models []string, endpoint string) []string {
+ filtered := make([]string, 0, len(models))
+ for _, model := range models {
+ route, matched := matchCompositeRoute(routes, model, normalizeCompositeRouteEndpoint(endpoint))
+ if !matched || route.TargetPlatform != PlatformTypeSafe {
+ filtered = append(filtered, model)
+ }
+ }
+ return filtered
+}
+
func (r *CompositeRouteResolver) Resolve(ctx context.Context, groupID int64, model, endpoint string) (CompositeRouteDecision, error) {
model = strings.TrimSpace(model)
endpoint = normalizeCompositeRouteEndpoint(endpoint)
diff --git a/backend/internal/service/composite_route_resolver_test.go b/backend/internal/service/composite_route_resolver_test.go
index 474b29387..92827ab65 100644
--- a/backend/internal/service/composite_route_resolver_test.go
+++ b/backend/internal/service/composite_route_resolver_test.go
@@ -12,6 +12,85 @@ type compositeRouteRepoStub struct {
routes []CompositeModelRoute
}
+func TestCompositeRouteResolverCodexFilteringMatchesProductionPriority(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ routes []CompositeModelRoute
+ want []string
+ }{
+ {
+ name: "endpoint beats priority",
+ routes: []CompositeModelRoute{
+ {ID: 1, PublicModel: "alias", MatchType: CompositeRouteMatchExact, Endpoint: CompositeRouteEndpointAny, TargetPlatform: PlatformOpenAI, Priority: 1},
+ {ID: 2, PublicModel: "alias", MatchType: CompositeRouteMatchExact, Endpoint: CompositeRouteEndpointResponses, TargetPlatform: PlatformTypeSafe, Priority: 100},
+ },
+ want: []string{"unrouted"},
+ },
+ {
+ name: "Responses OpenAI overrides any TypeSafe",
+ routes: []CompositeModelRoute{
+ {ID: 1, PublicModel: "alias", MatchType: CompositeRouteMatchExact, Endpoint: CompositeRouteEndpointAny, TargetPlatform: PlatformTypeSafe, Priority: 1},
+ {ID: 2, PublicModel: "alias", MatchType: CompositeRouteMatchExact, Endpoint: CompositeRouteEndpointResponses, TargetPlatform: PlatformOpenAI, Priority: 100},
+ },
+ want: []string{"alias", "unrouted"},
+ },
+ {
+ name: "longer prefix beats priority",
+ routes: []CompositeModelRoute{
+ {ID: 1, PublicModel: "a", MatchType: CompositeRouteMatchPrefix, TargetPlatform: PlatformOpenAI, Priority: 1},
+ {ID: 2, PublicModel: "ali", MatchType: CompositeRouteMatchPrefix, TargetPlatform: PlatformTypeSafe, Priority: 100},
+ },
+ want: []string{"unrouted"},
+ },
+ {
+ name: "exact beats endpoint prefix",
+ routes: []CompositeModelRoute{
+ {ID: 1, PublicModel: "alias", MatchType: CompositeRouteMatchPrefix, Endpoint: CompositeRouteEndpointResponses, TargetPlatform: PlatformTypeSafe},
+ {ID: 2, PublicModel: "alias", MatchType: CompositeRouteMatchExact, Endpoint: CompositeRouteEndpointAny, TargetPlatform: PlatformOpenAI},
+ },
+ want: []string{"alias", "unrouted"},
+ },
+ {
+ name: "lower priority wins",
+ routes: []CompositeModelRoute{
+ {ID: 1, PublicModel: "alias", MatchType: CompositeRouteMatchExact, TargetPlatform: PlatformTypeSafe, Priority: 100},
+ {ID: 2, PublicModel: "alias", MatchType: CompositeRouteMatchExact, TargetPlatform: PlatformOpenAI, Priority: 1},
+ },
+ want: []string{"alias", "unrouted"},
+ },
+ {
+ name: "lower ID breaks tie",
+ routes: []CompositeModelRoute{
+ {ID: 2, PublicModel: "alias", MatchType: CompositeRouteMatchExact, TargetPlatform: PlatformOpenAI},
+ {ID: 1, PublicModel: "alias", MatchType: CompositeRouteMatchExact, TargetPlatform: PlatformTypeSafe},
+ },
+ want: []string{"unrouted"},
+ },
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ for index := range scenario.routes {
+ scenario.routes[index].Enabled = true
+ scenario.routes[index].GroupID = 7
+ }
+ resolver := NewCompositeRouteResolver(compositeRouteRepoStub{routes: scenario.routes})
+ models, err := resolver.FilterCodexModels(context.Background(), 7, []string{"alias", "unrouted"})
+ require.NoError(t, err)
+ require.Equal(t, scenario.want, models)
+ decision, err := resolver.Resolve(context.Background(), 7, "alias", CompositeRouteEndpointResponses)
+ require.NoError(t, err)
+ require.True(t, decision.Matched)
+ require.Equal(t, decision.TargetPlatform != PlatformTypeSafe, len(models) == 2)
+ exactModels, err := resolver.ListExactPublicModels(context.Background(), 7, CompositeRouteEndpointResponses, false)
+ require.NoError(t, err)
+ if decision.TargetPlatform == PlatformTypeSafe {
+ require.Empty(t, exactModels)
+ } else {
+ require.Contains(t, exactModels, "alias")
+ }
+ })
+ }
+}
+
func (s compositeRouteRepoStub) ListByGroup(ctx context.Context, groupID int64, includeDisabled bool) ([]CompositeModelRoute, error) {
routes := make([]CompositeModelRoute, 0, len(s.routes))
for _, route := range s.routes {
diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go
index 7f514c59a..5c5d51598 100644
--- a/backend/internal/service/content_moderation.go
+++ b/backend/internal/service/content_moderation.go
@@ -56,6 +56,7 @@ const (
ContentModerationProtocolOpenAIChat = "openai_chat_completions"
ContentModerationProtocolGemini = "gemini"
ContentModerationProtocolOpenAIImages = "openai_images"
+ ContentModerationProtocolTypeSafeSystemOne = "typesafe_systemone"
defaultContentModerationBaseURL = "https://api.openai.com"
defaultContentModerationModel = "omni-moderation-latest"
diff --git a/backend/internal/service/content_moderation_input.go b/backend/internal/service/content_moderation_input.go
index 3886bfff8..b52adfaa2 100644
--- a/backend/internal/service/content_moderation_input.go
+++ b/backend/internal/service/content_moderation_input.go
@@ -46,6 +46,10 @@ func extractContentModerationInput(protocol string, body []byte, filterReminders
case ContentModerationProtocolOpenAIImages:
collector.addModerationText(&parts, gjson.GetBytes(body, "prompt").String())
collector.collectContentValue(gjson.GetBytes(body, "images"), &parts, &images)
+ case ContentModerationProtocolTypeSafeSystemOne:
+ // System One carries no client-harness reminder blocks, so a literal
+ // is ordinary user text and must never be skipped.
+ moderationTextCollector{}.collectSystemOneInput(body, &parts)
default:
collector.collectLastResponsesInput(gjson.GetBytes(body, "input"), &parts, &images)
collector.collectLastRoleMessage(gjson.GetBytes(body, "messages"), "user", &parts, &images)
@@ -61,6 +65,67 @@ func extractContentModerationInput(protocol string, body []byte, filterReminders
return out
}
+// collectSystemOneInput moderates every client-controlled text of a System One
+// request: question IDs, every question field except the validated type,
+// unknown top-level extension fields, and the evaluated state. Object keys are
+// sent to Jev as part of the JSON, so they are moderated like values.
+func (collector moderationTextCollector) collectSystemOneInput(body []byte, parts *[]string) {
+ root := gjson.ParseBytes(body)
+ questions := root.Get("questions")
+ if !questions.IsObject() {
+ collector.collectSystemOneText(questions, parts)
+ }
+ questions.ForEach(func(id, question gjson.Result) bool {
+ collector.addModerationText(parts, id.String())
+ if !question.IsObject() {
+ collector.collectSystemOneText(question, parts)
+ return true
+ }
+ question.ForEach(func(field, value gjson.Result) bool {
+ switch field.String() {
+ case "type":
+ return true
+ case "instructions", "criteria":
+ default:
+ collector.addModerationText(parts, field.String())
+ }
+ collector.collectSystemOneText(value, parts)
+ return true
+ })
+ return true
+ })
+ root.ForEach(func(field, value gjson.Result) bool {
+ switch field.String() {
+ case "model", "stream", "state", "questions":
+ return true
+ }
+ collector.addModerationText(parts, field.String())
+ collector.collectSystemOneText(value, parts)
+ return true
+ })
+ collector.collectSystemOneText(root.Get("state"), parts)
+}
+
+func (collector moderationTextCollector) collectSystemOneText(value gjson.Result, parts *[]string) {
+ switch {
+ case !value.Exists():
+ return
+ case value.Type == gjson.String:
+ collector.addModerationText(parts, value.String())
+ case value.IsArray():
+ value.ForEach(func(_, child gjson.Result) bool {
+ collector.collectSystemOneText(child, parts)
+ return true
+ })
+ case value.IsObject():
+ value.ForEach(func(key, child gjson.Result) bool {
+ collector.addModerationText(parts, key.String())
+ collector.collectSystemOneText(child, parts)
+ return true
+ })
+ }
+}
+
func (collector moderationTextCollector) collectLastRoleMessage(messages gjson.Result, role string, parts *[]string, images *[]string) {
if !messages.IsArray() {
return
diff --git a/backend/internal/service/content_moderation_systemone_test.go b/backend/internal/service/content_moderation_systemone_test.go
new file mode 100644
index 000000000..8f2eba816
--- /dev/null
+++ b/backend/internal/service/content_moderation_systemone_test.go
@@ -0,0 +1,34 @@
+package service
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestExtractContentModerationInputTypeSafeSystemOne(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ want string
+ }{
+ {"string", `{"state":"plain text"}`, "plain text"},
+ {"object", `{"state":{"title":"hello","nested":{"body":"world"}}}`, "title hello nested body world"},
+ {"array", `{"state":["first",{"text":"second"},3]}`, "first text second"},
+ {"questions", `{"state":"state text","questions":{"c":{"type":"choice","instructions":"pick one","criteria":{"label a":{"description":"desc a"},"label b":null}},"s":{"type":"score","criteria":["low",{"text":"high"}]},"n":{"type":"noul","instructions":["judge"],"criteria":{"true":"yes"},"ext":"extra"}},"top":{"k":"v"}}`, "c pick one label a description desc a label b s low text high n judge true yes ext extra top k v state text"},
+ {"key only payload", `{"state":{"hidden state key":1},"questions":{"hidden question id":{"type":"noul"}}}`, "hidden question id hidden state key"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ input := ExtractContentModerationInput(ContentModerationProtocolTypeSafeSystemOne, []byte(tc.body))
+ require.Equal(t, tc.want, input.Text)
+ require.Empty(t, input.Images)
+ })
+ }
+}
+
+func TestExtractContentModerationInputTypeSafeSystemOneKeepsReminderText(t *testing.T) {
+ body := `{"state":"hidden payload","questions":{"q":{"type":"noul","instructions":"hidden instructions"}}}`
+ input := ExtractContentModerationInput(ContentModerationProtocolTypeSafeSystemOne, []byte(body))
+ require.Contains(t, input.Text, "hidden payload")
+ require.Contains(t, input.Text, "hidden instructions")
+}
diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go
index 30ec42dfb..5f02a24fa 100644
--- a/backend/internal/service/domain_constants.go
+++ b/backend/internal/service/domain_constants.go
@@ -45,12 +45,15 @@ const (
PlatformAntigravity = domain.PlatformAntigravity
PlatformGrok = domain.PlatformGrok
// 国产 OpenAI 兼容供应商(与 grok 一样经 OpenAI 网关转发)。
- PlatformKimi = domain.PlatformKimi
- PlatformZhipu = domain.PlatformZhipu
- PlatformDeepseek = domain.PlatformDeepseek
- PlatformMiniMax = domain.PlatformMiniMax
- PlatformOpenCodeGo = domain.PlatformOpenCodeGo
- PlatformComposite = domain.PlatformComposite
+ PlatformKimi = domain.PlatformKimi
+ PlatformZhipu = domain.PlatformZhipu
+ PlatformDeepseek = domain.PlatformDeepseek
+ PlatformMiniMax = domain.PlatformMiniMax
+ PlatformOpenCodeGo = domain.PlatformOpenCodeGo
+ PlatformTypeSafe = domain.PlatformTypeSafe
+ PlatformCommandCode = domain.PlatformCommandCode
+ PlatformCline = domain.PlatformCline
+ PlatformComposite = domain.PlatformComposite
// PlatformKiro is retained for unsupported-platform threshold tests and legacy
// account rows. Scheduling-threshold evaluation never pauses kiro accounts.
PlatformKiro = "kiro"
@@ -86,6 +89,10 @@ const (
DefaultOpenCodeGoBaseURL = "https://opencode.ai/zen/go/v1"
// OpenCode Zen:按量付费网关,模型列表为 /zen/v1/models。
DefaultOpenCodeZenBaseURL = "https://opencode.ai/zen/v1"
+ // Command Code Provider API:Chat Completions / Responses / models 共用 /provider/v1 基址。
+ DefaultCommandCodeBaseURL = "https://api.commandcode.ai/provider/v1"
+ // Cline API:只提供 Chat Completions({base}/chat/completions)与模型列表。
+ DefaultClineBaseURL = "https://api.cline.bot/api/v1"
)
// 国产供应商 Anthropic 协议端点的默认 base_url(上游路径为 {base}/v1/messages)。
@@ -99,16 +106,14 @@ const (
// OpenCode Go Anthropic 基址不含 /v1:nativeAnthropicTargetURL 会再拼 /v1/messages。
DefaultOpenCodeGoAnthropicBaseURL = "https://opencode.ai/zen/go"
DefaultOpenCodeZenAnthropicBaseURL = "https://opencode.ai/zen"
+ // Command Code 的 Anthropic 端点为 /provider/v1/messages(Claude 系模型只在此端点提供)。
+ DefaultCommandCodeAnthropicBaseURL = "https://api.commandcode.ai/provider"
)
-// IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax)。
+// IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax),
+// 以平台清单(domain/platforms.go)为准。
func IsCNProvider(platform string) bool {
- switch platform {
- case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax:
- return true
- default:
- return false
- }
+ return domain.IsCNProviderPlatform(platform)
}
// IsOpenCodeGo 报告 platform 是否为 OpenCode Go 订阅网关。
@@ -118,30 +123,19 @@ func IsOpenCodeGo(platform string) bool {
// IsMultiProtocolAPIKeyProvider 报告 platform 是否为多协议 API Key 网关
// (国产供应商 + OpenCode):走 OpenAI 网关、支持 adaptive 协议分流。
+// 归属以 provider profile 登记为准(见 provider_profile.go)。
func IsMultiProtocolAPIKeyProvider(platform string) bool {
- return IsCNProvider(platform) || platform == PlatformOpenCodeGo
+ return LookupProviderProfile(platform) != nil
}
-// AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表(单一权威来源)。
-// ent/schema/user_platform_quota.go 的 Validate 函数独立维护(构建期约束),
-// 若新增平台需同步修改该 schema。
-var AllowedQuotaPlatforms = []string{
- PlatformOpenAIBPS,
- PlatformAnthropic,
- PlatformOpenAI,
- PlatformGemini,
- PlatformAntigravity,
- PlatformGrok,
- PlatformKimi,
- PlatformZhipu,
- PlatformDeepseek,
- PlatformMiniMax,
- PlatformOpenCodeGo,
-}
+// AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表:全部已登记的
+// 具体平台(domain/platforms.go),ent/schema/user_platform_quota.go 的校验同源。
+var AllowedQuotaPlatforms = domain.ConcretePlatformIDs()
// AllowedSchedulingThresholdPlatforms 是允许设置账号自动停调阈值的平台列表。
// openai/anthropic/grok 有原生用量窗口;kimi/zhipu/minimax 的 Coding Plan 同样暴露
// 5h/weekly 滚动窗口,纳入阈值评估。deepseek 为余额型,走余额检测而非阈值。
+// OpenCode Go 与 Command Code 的订阅套餐另有月度窗口。
var AllowedSchedulingThresholdPlatforms = []string{
PlatformOpenAI,
PlatformAnthropic,
@@ -150,6 +144,7 @@ var AllowedSchedulingThresholdPlatforms = []string{
PlatformZhipu,
PlatformMiniMax,
PlatformOpenCodeGo,
+ PlatformCommandCode,
}
// IsAllowedQuotaPlatform 报告 s 是否为合法的 quota platform 标识。
diff --git a/backend/internal/service/email_service.go b/backend/internal/service/email_service.go
index ee904d2fb..b05a4d5a5 100644
--- a/backend/internal/service/email_service.go
+++ b/backend/internal/service/email_service.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"crypto/rand"
+ "crypto/sha256"
"crypto/subtle"
"crypto/tls"
"crypto/x509"
@@ -37,16 +38,23 @@ type EmailCache interface {
GetVerificationCode(ctx context.Context, email string) (*VerificationCodeData, error)
SetVerificationCode(ctx context.Context, email string, data *VerificationCodeData, ttl time.Duration) error
DeleteVerificationCode(ctx context.Context, email string) error
+ // IncrVerificationCodeAttempts atomically increments the attempt counter of an
+ // existing code and returns the new count. Returns an error if the code is missing.
+ IncrVerificationCodeAttempts(ctx context.Context, email string) (int, error)
// Notify email verification code methods
GetNotifyVerifyCode(ctx context.Context, email string) (*VerificationCodeData, error)
SetNotifyVerifyCode(ctx context.Context, email string, data *VerificationCodeData, ttl time.Duration) error
DeleteNotifyVerifyCode(ctx context.Context, email string) error
+ IncrNotifyVerifyCodeAttempts(ctx context.Context, email string) (int, error)
// Password reset token methods
GetPasswordResetToken(ctx context.Context, email string) (*PasswordResetTokenData, error)
SetPasswordResetToken(ctx context.Context, email string, data *PasswordResetTokenData, ttl time.Duration) error
DeletePasswordResetToken(ctx context.Context, email string) error
+ // ConsumePasswordResetToken atomically compares the stored token hash with
+ // tokenHash and deletes it on match. Only one concurrent caller can succeed.
+ ConsumePasswordResetToken(ctx context.Context, email, tokenHash string) (bool, error)
// Password reset email cooldown methods
// Returns true if in cooldown period (email was sent recently)
@@ -68,6 +76,7 @@ type VerificationCodeData struct {
// PasswordResetTokenData represents password reset token data
type PasswordResetTokenData struct {
+ // Token holds the hex-encoded SHA-256 hash of the reset token (never the plaintext).
Token string
CreatedAt time.Time
}
@@ -376,35 +385,49 @@ func (s *EmailService) SendVerifyCode(ctx context.Context, email, siteName strin
// VerifyCode 验证验证码
func (s *EmailService) VerifyCode(ctx context.Context, email, code string) error {
- data, err := s.cache.GetVerificationCode(ctx, email)
+ return verifyCodeWithAttempts(ctx, email, code,
+ s.cache.GetVerificationCode, s.cache.IncrVerificationCodeAttempts,
+ func() {
+ if err := s.cache.DeleteVerificationCode(ctx, email); err != nil {
+ slog.Error("failed to delete verification code after success", "email", email, "error", err)
+ }
+ })
+}
+
+// verifyCodeWithAttempts checks a verification code while enforcing the attempt cap
+// atomically: each check first reserves an attempt via an atomic increment, so
+// concurrent guesses can never evaluate more than maxVerifyCodeAttempts codes.
+func verifyCodeWithAttempts(
+ ctx context.Context, email, code string,
+ get func(context.Context, string) (*VerificationCodeData, error),
+ incr func(context.Context, string) (int, error),
+ onSuccess func(),
+) error {
+ data, err := get(ctx, email)
if err != nil || data == nil {
return ErrInvalidVerifyCode
}
-
- // 检查是否已达到最大尝试次数
if data.Attempts >= maxVerifyCodeAttempts {
return ErrVerifyCodeMaxAttempts
}
+ attempts, err := incr(ctx, email)
+ if err != nil {
+ return ErrInvalidVerifyCode
+ }
+ if attempts > maxVerifyCodeAttempts {
+ return ErrVerifyCodeMaxAttempts
+ }
- // 验证码不匹配 (constant-time comparison to prevent timing attacks)
+ // constant-time comparison to prevent timing attacks
if subtle.ConstantTimeCompare([]byte(data.Code), []byte(code)) != 1 {
- data.Attempts++
- remaining := time.Until(data.ExpiresAt)
- if remaining <= 0 {
- return ErrInvalidVerifyCode
- }
- if err := s.cache.SetVerificationCode(ctx, email, data, remaining); err != nil {
- slog.Error("failed to update verification attempt count", "email", email, "error", err)
- }
- if data.Attempts >= maxVerifyCodeAttempts {
+ if attempts >= maxVerifyCodeAttempts {
return ErrVerifyCodeMaxAttempts
}
return ErrInvalidVerifyCode
}
- // 验证成功,删除验证码
- if err := s.cache.DeleteVerificationCode(ctx, email); err != nil {
- slog.Error("failed to delete verification code after success", "email", email, "error", err)
+ if onSuccess != nil {
+ onSuccess()
}
return nil
}
@@ -480,33 +503,18 @@ func (s *EmailService) GeneratePasswordResetToken() (string, error) {
// SendPasswordResetEmail sends a password reset email with a reset link
func (s *EmailService) SendPasswordResetEmail(ctx context.Context, email, siteName, resetURL string, locale ...string) error {
- var token string
- var needSaveToken bool
-
- // Check if token already exists
- existing, err := s.cache.GetPasswordResetToken(ctx, email)
- if err == nil && existing != nil {
- // Token exists, reuse it (allows resending email without generating new token)
- token = existing.Token
- needSaveToken = false
- } else {
- // Generate new token
- token, err = s.GeneratePasswordResetToken()
- if err != nil {
- return fmt.Errorf("generate token: %w", err)
- }
- needSaveToken = true
+ // Only the SHA-256 hash of the token is stored, so an existing token cannot be
+ // re-sent; always issue a fresh token (the email cooldown bounds resend frequency).
+ token, err := s.GeneratePasswordResetToken()
+ if err != nil {
+ return fmt.Errorf("generate token: %w", err)
}
-
- // Save token to Redis (only if new token generated)
- if needSaveToken {
- data := &PasswordResetTokenData{
- Token: token,
- CreatedAt: time.Now(),
- }
- if err := s.cache.SetPasswordResetToken(ctx, email, data, passwordResetTokenTTL); err != nil {
- return fmt.Errorf("save reset token: %w", err)
- }
+ data := &PasswordResetTokenData{
+ Token: hashPasswordResetToken(token),
+ CreatedAt: time.Now(),
+ }
+ if err := s.cache.SetPasswordResetToken(ctx, email, data, passwordResetTokenTTL); err != nil {
+ return fmt.Errorf("save reset token: %w", err)
}
// Build full reset URL with URL-encoded token and email
@@ -566,31 +574,40 @@ func (s *EmailService) SendPasswordResetEmailWithCooldown(ctx context.Context, e
return nil
}
+// hashPasswordResetToken returns the hex-encoded SHA-256 of a reset token.
+func hashPasswordResetToken(token string) string {
+ sum := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(sum[:])
+}
+
// VerifyPasswordResetToken verifies the password reset token without consuming it
func (s *EmailService) VerifyPasswordResetToken(ctx context.Context, email, token string) error {
data, err := s.cache.GetPasswordResetToken(ctx, email)
- if err != nil || data == nil {
+ if err != nil || data == nil || token == "" {
return ErrInvalidResetToken
}
// Use constant-time comparison to prevent timing attacks
- if subtle.ConstantTimeCompare([]byte(data.Token), []byte(token)) != 1 {
+ if subtle.ConstantTimeCompare([]byte(data.Token), []byte(hashPasswordResetToken(token))) != 1 {
return ErrInvalidResetToken
}
return nil
}
-// ConsumePasswordResetToken verifies and deletes the token (one-time use)
+// ConsumePasswordResetToken verifies and deletes the token atomically (one-time use).
func (s *EmailService) ConsumePasswordResetToken(ctx context.Context, email, token string) error {
- // Verify first
+ // Constant-time pre-check in Go; the atomic compare-and-delete below is authoritative.
if err := s.VerifyPasswordResetToken(ctx, email, token); err != nil {
return err
}
-
- // Delete after verification (one-time use)
- if err := s.cache.DeletePasswordResetToken(ctx, email); err != nil {
- slog.Error("failed to delete password reset token after consumption", "email", email, "error", err)
+ ok, err := s.cache.ConsumePasswordResetToken(ctx, email, hashPasswordResetToken(token))
+ if err != nil {
+ slog.Error("failed to consume password reset token", "email", email, "error", err)
+ return ErrInvalidResetToken
+ }
+ if !ok {
+ return ErrInvalidResetToken
}
return nil
}
diff --git a/backend/internal/service/email_service_reset_token_test.go b/backend/internal/service/email_service_reset_token_test.go
new file mode 100644
index 000000000..15efd50d6
--- /dev/null
+++ b/backend/internal/service/email_service_reset_token_test.go
@@ -0,0 +1,50 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+type resetTokenCacheStub struct {
+ emailCacheStub
+ stored *PasswordResetTokenData
+ consumedHash string
+}
+
+func (s *resetTokenCacheStub) GetPasswordResetToken(context.Context, string) (*PasswordResetTokenData, error) {
+ return s.stored, nil
+}
+
+func (s *resetTokenCacheStub) ConsumePasswordResetToken(_ context.Context, _ string, tokenHash string) (bool, error) {
+ s.consumedHash = tokenHash
+ if s.stored == nil || s.stored.Token != tokenHash {
+ return false, nil
+ }
+ s.stored = nil
+ return true, nil
+}
+
+func TestConsumePasswordResetToken_ComparesHashNotPlaintext(t *testing.T) {
+ token := "deadbeef"
+ sum := sha256.Sum256([]byte(token))
+ hash := hex.EncodeToString(sum[:])
+ require.Equal(t, hash, hashPasswordResetToken(token))
+ require.NotEqual(t, token, hashPasswordResetToken(token))
+
+ cache := &resetTokenCacheStub{stored: &PasswordResetTokenData{Token: hash}}
+ svc := NewEmailService(nil, cache)
+
+ require.NoError(t, svc.ConsumePasswordResetToken(context.Background(), "a@b.c", token))
+ require.Equal(t, hash, cache.consumedHash)
+ require.ErrorIs(t, svc.ConsumePasswordResetToken(context.Background(), "a@b.c", token), ErrInvalidResetToken)
+
+ // A legacy plaintext value (issued before upgrade) no longer validates.
+ cache.stored = &PasswordResetTokenData{Token: token}
+ require.ErrorIs(t, svc.ConsumePasswordResetToken(context.Background(), "a@b.c", token), ErrInvalidResetToken)
+}
diff --git a/backend/internal/service/gateway_cache_ttl_order_test.go b/backend/internal/service/gateway_cache_ttl_order_test.go
new file mode 100644
index 000000000..1fcc158d5
--- /dev/null
+++ b/backend/internal/service/gateway_cache_ttl_order_test.go
@@ -0,0 +1,156 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// requireCacheTTLOrderAccepted fails when a ttl=1h breakpoint follows a 5m one
+// in Anthropic's processing order (tools, system, messages). Anthropic rejects
+// such requests with HTTP 400.
+func requireCacheTTLOrderAccepted(t *testing.T, body []byte) {
+ t.Helper()
+ _, messagePaths, toolPaths, systemPaths := collectCacheControlPaths(body)
+ var paths []string
+ paths = append(paths, toolPaths...)
+ paths = append(paths, systemPaths...)
+ paths = append(paths, messagePaths...)
+ shortTTLPath := ""
+ for _, path := range paths {
+ if gjson.GetBytes(body, path+".ttl").String() == cacheTTLTarget1h {
+ require.Empty(t, shortTTLPath, "1h breakpoint %s follows 5m breakpoint %s in %s", path, shortTTLPath, body)
+ continue
+ }
+ if shortTTLPath == "" {
+ shortTTLPath = path
+ }
+ }
+}
+
+func TestNormalizeCacheControlTTLOrder_RaisesBreakpointsBeforeLast1h(t *testing.T) {
+ body := []byte(`{"tools":[{"name":"t","input_schema":{"type":"object"},"cache_control":{"type":"ephemeral"}}],` +
+ `"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"5m"}}],` +
+ `"messages":[{"role":"user","content":[` +
+ `{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}},` +
+ `{"type":"text","text":"b","cache_control":{"type":"ephemeral","ttl":"5m"}}]}]}`)
+
+ out := normalizeCacheControlTTLOrder(body)
+
+ require.Equal(t, "1h", gjson.GetBytes(out, "tools.0.cache_control.ttl").String(), "omitted ttl counts as 5m")
+ require.Equal(t, "1h", gjson.GetBytes(out, "system.0.cache_control.ttl").String())
+ require.Equal(t, "1h", gjson.GetBytes(out, "messages.0.content.0.cache_control.ttl").String())
+ require.Equal(t, "5m", gjson.GetBytes(out, "messages.0.content.1.cache_control.ttl").String(),
+ "a 5m breakpoint after the last 1h one is valid and must keep its ttl")
+ requireCacheTTLOrderAccepted(t, out)
+}
+
+func TestNormalizeCacheControlTTLOrder_TopLevelCacheControlIsLast(t *testing.T) {
+ body := []byte(`{"cache_control":{"type":"ephemeral","ttl":"1h"},` +
+ `"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"5m"}}],` +
+ `"messages":[{"role":"user","content":"hi"}]}`)
+
+ out := normalizeCacheControlTTLOrder(body)
+
+ require.Equal(t, "1h", gjson.GetBytes(out, "system.0.cache_control.ttl").String())
+}
+
+func TestNormalizeCacheControlTTLOrder_KeepsValidRequestsUnchanged(t *testing.T) {
+ cases := map[string]string{
+ "no breakpoints": `{"system":"s","messages":[{"role":"user","content":"hi"}]}`,
+ "all 5m": `{"tools":[{"name":"t","input_schema":{"type":"object"},"cache_control":{"type":"ephemeral"}}],` +
+ `"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"5m"}}],` +
+ `"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"5m"}}]}]}`,
+ "1h before 5m": `{"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"1h"}}],` +
+ `"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}}]}]}`,
+ }
+ for name, body := range cases {
+ t.Run(name, func(t *testing.T) {
+ require.Equal(t, body, string(normalizeCacheControlTTLOrder([]byte(body))))
+ })
+ }
+}
+
+// A non-Claude Code client sends one 1h breakpoint. The mimic path adds 5m
+// breakpoints to the injected system block and the last tool, which come first
+// in Anthropic's processing order. The outbound body must still be accepted.
+func TestEnforceCacheControlLimit_MimicPathKeepsClient1hBreakpointValid(t *testing.T) {
+ cases := map[string]string{
+ "message 1h": `{"model":"claude-sonnet-4-6","messages":[{"role":"user","content":[` +
+ `{"type":"text","text":"Reply OK.","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`,
+ "system 1h moved into messages": `{"model":"claude-sonnet-4-6",` +
+ `"system":[{"type":"text","text":"Be terse.","cache_control":{"type":"ephemeral","ttl":"1h"}}],` +
+ `"messages":[{"role":"user","content":"Reply OK."}]}`,
+ "tools and message 1h": `{"model":"claude-sonnet-4-6","tools":[{"name":"probe","input_schema":{"type":"object"}}],` +
+ `"messages":[{"role":"user","content":[` +
+ `{"type":"text","text":"Reply OK.","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`,
+ }
+ for name, raw := range cases {
+ t.Run(name, func(t *testing.T) {
+ body := []byte(raw)
+ var system any
+ if sys := gjson.GetBytes(body, "system"); sys.Exists() {
+ require.NoError(t, json.Unmarshal([]byte(sys.Raw), &system))
+ }
+ body = rewriteSystemForNonClaudeCode(body, system)
+ body = applyToolsLastCacheBreakpoint(body)
+
+ out := enforceCacheControlLimit(body)
+
+ requireCacheTTLOrderAccepted(t, out)
+ })
+ }
+}
+
+func TestForwardCountTokens_MimicPathKeepsClient1hBreakpointValid(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil)
+ c.Request.Header.Set("User-Agent", "third-party-client/1.0")
+
+ // The mimic path adds a 5m breakpoint to tools[-1], ahead of the client's 1h one.
+ body := []byte(`{"model":"claude-sonnet-4-6",` +
+ `"tools":[{"name":"probe","description":"d","input_schema":{"type":"object"}}],` +
+ `"messages":[{"role":"user","content":[{"type":"text","text":"Reply OK.","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`)
+ parsed := &ParsedRequest{Body: NewRequestBodyRef(body), Model: "claude-sonnet-4-6"}
+
+ upstream := &anthropicHTTPUpstreamRecorder{
+ resp: &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(`{"input_tokens":42}`)),
+ },
+ }
+ svc := &GatewayService{
+ cfg: &config.Config{Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize}},
+ httpUpstream: upstream,
+ rateLimitService: &RateLimitService{},
+ }
+ account := &Account{
+ ID: 402,
+ Name: "count-tokens-ttl-order-test",
+ Platform: PlatformAnthropic,
+ Type: AccountTypeSetupToken,
+ Concurrency: 1,
+ Credentials: map[string]any{"access_token": "test-oauth-token"},
+ Status: StatusActive,
+ Schedulable: true,
+ }
+
+ require.NoError(t, svc.ForwardCountTokens(context.Background(), c, account, parsed))
+
+ require.True(t, gjson.GetBytes(upstream.lastBody, "tools.0.cache_control").Exists(),
+ "the mimic tools breakpoint should still be present")
+ requireCacheTTLOrderAccepted(t, upstream.lastBody)
+}
diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go
index 37c30269c..b4f33b470 100644
--- a/backend/internal/service/gateway_claude_oauth_body.go
+++ b/backend/internal/service/gateway_claude_oauth_body.go
@@ -1052,9 +1052,15 @@ func collectCacheControlPaths(body []byte) (invalidThinking []cacheControlPath,
return invalidThinking, messagePaths, toolPaths, systemPaths
}
-// enforceCacheControlLimit 强制执行 cache_control 块数量限制(最多 4 个)
-// 超限时优先移除工具断点,再移除 messages 断点,最后才移除 system 断点。
+// enforceCacheControlLimit 让出站 cache_control 满足上游约束:
+// 先执行块数量限制,再修正 TTL 顺序。
func enforceCacheControlLimit(body []byte) []byte {
+ return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body))
+}
+
+// enforceCacheControlBlockLimit 强制执行 cache_control 块数量限制(最多 4 个)
+// 超限时优先移除工具断点,再移除 messages 断点,最后才移除 system 断点。
+func enforceCacheControlBlockLimit(body []byte) []byte {
if len(body) == 0 {
return body
}
@@ -1137,6 +1143,46 @@ func enforceCacheControlLimit(body []byte) []byte {
return body
}
+// normalizeCacheControlTTLOrder raises earlier ephemeral breakpoints to 1h when
+// a later breakpoint uses 1h. Anthropic processes tools, system, then messages,
+// and rejects a ttl=1h breakpoint that follows a 5m one; an omitted ttl means 5m.
+// The mimic path adds its own 5m breakpoints to tools and system, so a client
+// 1h breakpoint in messages would otherwise turn a valid request into a 400.
+//
+// Raising keeps the client's choice. Tokens before a 1h breakpoint are already
+// written at the 1h rate, so the earlier breakpoints add no cache write cost.
+// Requests with a valid order are returned unchanged.
+func normalizeCacheControlTTLOrder(body []byte) []byte {
+ _, messagePaths, toolPaths, systemPaths := collectCacheControlPaths(body)
+ paths := make([]string, 0, len(toolPaths)+len(systemPaths)+len(messagePaths)+1)
+ paths = append(paths, toolPaths...)
+ paths = append(paths, systemPaths...)
+ paths = append(paths, messagePaths...)
+ // A top-level cache_control applies to the last cacheable block.
+ if gjson.GetBytes(body, "cache_control").Exists() {
+ paths = append(paths, "cache_control")
+ }
+
+ last1h := -1
+ for i, path := range paths {
+ if gjson.GetBytes(body, path+".ttl").String() == cacheTTLTarget1h {
+ last1h = i
+ }
+ }
+
+ out := body
+ for _, path := range paths[:last1h+1] {
+ cc := gjson.GetBytes(out, path)
+ if cc.Get("type").String() != "ephemeral" || cc.Get("ttl").String() == cacheTTLTarget1h {
+ continue
+ }
+ if next, err := sjson.SetBytes(out, path+".ttl", cacheTTLTarget1h); err == nil {
+ out = next
+ }
+ }
+ return out
+}
+
// injectAnthropicCacheControlTTL1h 将已有 ephemeral cache_control 块的 ttl 强制写为 1h。
// 仅修改已经存在的 cache_control,不新增缓存断点。
func injectAnthropicCacheControlTTL1h(body []byte) []byte {
diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go
index bd02e1ba3..ed0716ae3 100644
--- a/backend/internal/service/gateway_forward_as_chat_completions.go
+++ b/backend/internal/service/gateway_forward_as_chat_completions.go
@@ -280,7 +280,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic(
}
if event.Type == "content_block_delta" && event.Delta != nil && finalResp != nil && event.Index != nil {
idx := *event.Index
- if idx < len(finalResp.Content) {
+ if idx >= 0 && idx < len(finalResp.Content) {
switch event.Delta.Type {
case "text_delta":
finalResp.Content[idx].Text += event.Delta.Text
@@ -421,10 +421,11 @@ func (s *GatewayService) handleCCStreamingFromAnthropic(
if event == nil {
return false
}
- // Drop Anthropic keepalive pings before OpenAI conversion:
- // leaking `event: ping` frames crashes OpenAI-stream clients.
- // Error events must still forward — they carry upstream failures.
if event.Type == "ping" {
+ if _, err := fmt.Fprint(c.Writer, ": ping\n\n"); err != nil {
+ return true
+ }
+ c.Writer.Flush()
return false
}
if firstChunk {
diff --git a/backend/internal/service/gateway_forward_as_chat_completions_ping_test.go b/backend/internal/service/gateway_forward_as_chat_completions_ping_test.go
new file mode 100644
index 000000000..e37e042e9
--- /dev/null
+++ b/backend/internal/service/gateway_forward_as_chat_completions_ping_test.go
@@ -0,0 +1,205 @@
+//go:build unit
+
+package service
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/apicompat"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type ccPingResponseWriter struct {
+ *httptest.ResponseRecorder
+ flushed chan string
+ failPing bool
+ failed bool
+ writesAfterError int
+ flushesAfterError int
+}
+
+func (writer *ccPingResponseWriter) Write(data []byte) (int, error) {
+ if writer.failed {
+ writer.writesAfterError++
+ }
+ if writer.failPing && string(data) == ": ping\n\n" {
+ writer.failed = true
+ return 0, errors.New("heartbeat write failed")
+ }
+ return writer.ResponseRecorder.Write(data)
+}
+
+func (writer *ccPingResponseWriter) Flush() {
+ if writer.failed {
+ writer.flushesAfterError++
+ }
+ writer.ResponseRecorder.Flush()
+ if writer.flushed != nil {
+ writer.flushed <- writer.Body.String()
+ }
+}
+
+func TestHandleCCStreamingFromAnthropic_PingFlushesImmediately(t *testing.T) {
+ writer := &ccPingResponseWriter{
+ ResponseRecorder: httptest.NewRecorder(),
+ flushed: make(chan string, 32),
+ }
+ context, _ := gin.CreateTestContext(writer)
+ reader, upstream := io.Pipe()
+ type outcome struct {
+ result *ForwardResult
+ err error
+ }
+ finished := make(chan outcome, 1)
+ go func() {
+ result, err := (&GatewayService{}).handleCCStreamingFromAnthropic(
+ &http.Response{Body: reader}, context, "gpt-5", "claude-sonnet-4.5", nil, time.Now(),
+ )
+ finished <- outcome{result: result, err: err}
+ }()
+ t.Cleanup(func() {
+ _ = upstream.Close()
+ _ = reader.Close()
+ })
+
+ awaitFlush := func() string {
+ t.Helper()
+ select {
+ case body := <-writer.flushed:
+ return body
+ case <-time.After(5 * time.Second):
+ t.Fatal("event did not flush before the next upstream event or EOF")
+ return ""
+ }
+ }
+ var body string
+ send := func(eventType, payload string) {
+ t.Helper()
+ _, err := io.WriteString(upstream, "event: "+eventType+"\ndata: "+payload+"\n\n")
+ require.NoError(t, err)
+ body = awaitFlush()
+ }
+ ping := func() {
+ t.Helper()
+ previous := body
+ send("ping", `{"type":"ping"}`)
+ require.Equal(t, previous+": ping\n\n", body)
+ }
+
+ ping()
+ ping()
+ send("message_start", `{"type":"message_start","message":{"id":"msg_ping","role":"assistant","content":[],"usage":{"input_tokens":10}}}`)
+ send("content_block_start", `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`)
+ send("content_block_delta", `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}`)
+ require.Contains(t, body, `"content":"hello"`)
+ ping()
+ send("content_block_delta", `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" world"}}`)
+ require.Contains(t, body, `"content":" world"`)
+ send("message_delta", `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}`)
+ send("message_stop", `{"type":"message_stop"}`)
+ ping()
+ require.NotContains(t, body, "[DONE]")
+ require.NoError(t, upstream.Close())
+
+ select {
+ case got := <-finished:
+ require.NoError(t, got.err)
+ require.Equal(t, 10, got.result.Usage.InputTokens)
+ require.Equal(t, 7, got.result.Usage.OutputTokens)
+ require.NotNil(t, got.result.FirstTokenMs)
+ case <-time.After(5 * time.Second):
+ t.Fatal("stream did not finish after EOF")
+ }
+ body = writer.Body.String()
+ require.NotContains(t, body, "event:")
+ require.NotContains(t, body, `"type":"ping"`)
+ require.Equal(t, 4, strings.Count(body, ": ping\n\n"))
+ require.Equal(t, 1, strings.Count(body, "data: [DONE]\n\n"))
+ require.True(t, strings.HasSuffix(body, "data: [DONE]\n\n"))
+ var content strings.Builder
+ var usage *apicompat.ChatUsage
+ var finishedChoice bool
+ for _, frame := range strings.Split(body, "\n\n") {
+ if frame == "" || frame == ": ping" || frame == "data: [DONE]" {
+ continue
+ }
+ require.True(t, strings.HasPrefix(frame, "data: "))
+ var chunk apicompat.ChatCompletionsChunk
+ require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(frame, "data: ")), &chunk))
+ require.Equal(t, "chat.completion.chunk", chunk.Object)
+ for _, choice := range chunk.Choices {
+ if choice.Delta.Content != nil {
+ content.WriteString(*choice.Delta.Content)
+ }
+ if choice.FinishReason != nil {
+ require.Equal(t, "stop", *choice.FinishReason)
+ finishedChoice = true
+ }
+ }
+ if chunk.Usage != nil {
+ usage = chunk.Usage
+ }
+ }
+ require.Equal(t, "hello world", content.String())
+ require.True(t, finishedChoice)
+ require.NotNil(t, usage)
+ require.Equal(t, 10, usage.PromptTokens)
+ require.Equal(t, 7, usage.CompletionTokens)
+ require.Equal(t, 17, usage.TotalTokens)
+}
+
+func TestHandleCCStreamingFromAnthropic_PingDoesNotSetFirstToken(t *testing.T) {
+ writer := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(writer)
+ result, err := (&GatewayService{}).handleCCStreamingFromAnthropic(
+ &http.Response{Body: io.NopCloser(strings.NewReader("event: ping\ndata: {\"type\":\"ping\"}\n\n"))},
+ context, "gpt-5", "claude-sonnet-4.5", nil, time.Now(),
+ )
+ require.NoError(t, err)
+ require.Nil(t, result.FirstTokenMs)
+ require.True(t, strings.HasPrefix(writer.Body.String(), ": ping\n\n"))
+}
+
+func TestHandleCCStreamingFromAnthropic_PingWriteFailureStopsDownstream(t *testing.T) {
+ for _, withUsage := range []bool{false, true} {
+ name := "before_message_start"
+ if withUsage {
+ name = "after_message_start"
+ }
+ t.Run(name, func(t *testing.T) {
+ writer := &ccPingResponseWriter{ResponseRecorder: httptest.NewRecorder(), failPing: true}
+ context, _ := gin.CreateTestContext(writer)
+ stream := ""
+ if withUsage {
+ stream += "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_failure\",\"usage\":{\"input_tokens\":10}}}\n\n"
+ }
+ stream += "event: ping\ndata: {\"type\":\"ping\"}\n\n" +
+ "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":7}}\n\n" +
+ "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
+ result, err := (&GatewayService{}).handleCCStreamingFromAnthropic(
+ &http.Response{Body: io.NopCloser(strings.NewReader(stream))},
+ context, "gpt-5", "claude-sonnet-4.5", nil, time.Now(),
+ )
+ require.NoError(t, err)
+ require.True(t, writer.failed)
+ require.Zero(t, writer.writesAfterError)
+ require.Zero(t, writer.flushesAfterError)
+ require.NotContains(t, writer.Body.String(), "[DONE]")
+ require.Zero(t, result.Usage.OutputTokens)
+ if withUsage {
+ require.Equal(t, 10, result.Usage.InputTokens)
+ } else {
+ require.Zero(t, result.Usage.InputTokens)
+ require.Nil(t, result.FirstTokenMs)
+ }
+ })
+ }
+}
diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go
index 77cf1eb24..78a4af4f6 100644
--- a/backend/internal/service/gateway_forward_as_responses.go
+++ b/backend/internal/service/gateway_forward_as_responses.go
@@ -438,7 +438,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse(
}
if event.Type == "content_block_delta" && event.Delta != nil && finalResp != nil && event.Index != nil {
idx := *event.Index
- if idx < len(finalResp.Content) {
+ if idx >= 0 && idx < len(finalResp.Content) {
switch event.Delta.Type {
case "text_delta":
finalResp.Content[idx].Text += event.Delta.Text
diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go
index e8436e0f9..316c6c13b 100644
--- a/backend/internal/service/gateway_service.go
+++ b/backend/internal/service/gateway_service.go
@@ -1535,6 +1535,21 @@ func explicitModelMappingClaims(account Account, model string) bool {
return ok && strings.TrimSpace(mapped) != ""
}
+// GetCompositeRouteModels returns public IDs from enabled exact composite routes.
+func (s *GatewayService) GetCompositeRouteModels(ctx context.Context, groupID *int64, endpoint string, includeSystemOne bool) ([]string, error) {
+ if s == nil || s.compositeResolver == nil || groupID == nil {
+ return nil, nil
+ }
+ return s.compositeResolver.ListExactPublicModels(ctx, *groupID, endpoint, includeSystemOne)
+}
+
+func (s *GatewayService) FilterCompositeCodexModels(ctx context.Context, groupID int64, models []string) ([]string, error) {
+ if s == nil || s.compositeResolver == nil {
+ return models, nil
+ }
+ return s.compositeResolver.FilterCodexModels(ctx, groupID, models)
+}
+
// GetSchedulablePlatforms returns the concrete platforms that currently have
// schedulable accounts in the target group.
func (s *GatewayService) GetSchedulablePlatforms(ctx context.Context, groupID *int64) map[string]struct{} {
diff --git a/backend/internal/service/gateway_systemone.go b/backend/internal/service/gateway_systemone.go
new file mode 100644
index 000000000..0eafb0677
--- /dev/null
+++ b/backend/internal/service/gateway_systemone.go
@@ -0,0 +1,182 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "mime"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
+ "github.com/gin-gonic/gin"
+)
+
+type SystemOneForwardResult struct {
+ ForwardResult
+ StatusCode int
+ Body []byte
+ ContentType string
+}
+
+type SystemOneUpstreamError struct {
+ StatusCode int
+}
+
+const TypeSafeCredentialRejectedReason GatewayFailureReason = "typesafe_api_key_rejected"
+
+func (e *SystemOneUpstreamError) Error() string {
+ return fmt.Sprintf("typesafe upstream rejected request with status %d", e.StatusCode)
+}
+
+func (s *GatewayService) ForwardSystemOne(ctx context.Context, c *gin.Context, account *Account, body []byte) (*SystemOneForwardResult, error) {
+ started := time.Now()
+ if account == nil || !account.IsTypeSafe() || account.Type != AccountTypeAPIKey {
+ return nil, errors.New("invalid typesafe account")
+ }
+ key := account.GetTypeSafeAPIKey()
+ if key == "" {
+ return nil, errors.New("typesafe api key is missing")
+ }
+ baseURL, err := s.validateUpstreamBaseURL(account.GetTypeSafeBaseURL())
+ if err != nil {
+ return nil, err
+ }
+ req, err := typesafe.NewSystemOneRequest(ctx, baseURL, key, body)
+ if err != nil {
+ return nil, err
+ }
+ upstreamURL := req.URL.Scheme + "://" + req.URL.Host + req.URL.Path
+ proxyURL := ""
+ if account.ProxyID != nil && account.Proxy != nil {
+ proxyURL = account.Proxy.URL()
+ }
+ resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, account.Concurrency)
+ if err != nil {
+ return nil, s.handleUpstreamTransportError(ctx, c, account, err, OpsUpstreamErrorEvent{
+ Passthrough: true,
+ UpstreamURL: upstreamURL,
+ })
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
+ return nil, s.handleSystemOneErrorResponse(ctx, c, account, resp, upstreamURL)
+ }
+
+ decoded, err := typesafe.DecodeSystemOneResponse(resp.Body)
+ if err != nil {
+ // The upstream accepted (and may have charged) this request but the
+ // gateway cannot relay it; keep an ops trail for reconciliation.
+ setOpsUpstreamError(c, resp.StatusCode, err.Error(), "")
+ appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
+ Passthrough: true,
+ ProxyID: opsUpstreamProxyID(account),
+ ProxyName: opsUpstreamProxyName(account),
+ Platform: account.Platform,
+ AccountID: account.ID,
+ AccountName: account.Name,
+ UpstreamStatusCode: resp.StatusCode,
+ UpstreamRequestID: resp.Header.Get("x-request-id"),
+ UpstreamURL: upstreamURL,
+ Kind: "response_error",
+ Message: err.Error(),
+ })
+ return nil, err
+ }
+ return &SystemOneForwardResult{
+ ForwardResult: ForwardResult{
+ RequestID: resp.Header.Get("x-request-id"),
+ UpstreamHeaders: resp.Header.Clone(),
+ Usage: ClaudeUsage{InputTokens: decoded.Usage.InputTokens, OutputTokens: decoded.Usage.OutputTokens},
+ Model: typesafe.JevLatestModel,
+ UpstreamResponseModel: decoded.Model,
+ Duration: time.Since(started),
+ },
+ StatusCode: resp.StatusCode,
+ Body: decoded.Body,
+ ContentType: systemOneResponseContentType(resp.Header.Get("Content-Type")),
+ }, nil
+}
+
+// IsSystemOneRequestErrorStatus reports upstream statuses that describe the
+// caller's own payload (malformed, unprocessable, or too large).
+func IsSystemOneRequestErrorStatus(status int) bool {
+ switch status {
+ case http.StatusBadRequest, http.StatusRequestEntityTooLarge, http.StatusUnprocessableEntity:
+ return true
+ default:
+ return false
+ }
+}
+
+// handleSystemOneErrorResponse applies the shared account error policy to a
+// non-2xx System One response. 400/413/422 describe the caller's own payload, so
+// they never touch account state (a tenant must not be able to disable an
+// account with bad input) and are not retried elsewhere. Every other status
+// goes through the account error policy (custom error codes, temporary
+// unschedulable rules, pool mode) and fails over when the status is retryable
+// or the policy took the account out of rotation.
+func (s *GatewayService) handleSystemOneErrorResponse(ctx context.Context, c *gin.Context, account *Account, resp *http.Response, upstreamURL string) error {
+ respBody, _ := s.readUpstreamErrorBody(resp)
+ upstreamMsg := sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody)))
+ setOpsUpstreamError(c, resp.StatusCode, upstreamMsg, "")
+ event := OpsUpstreamErrorEvent{
+ Passthrough: true,
+ ProxyID: opsUpstreamProxyID(account),
+ ProxyName: opsUpstreamProxyName(account),
+ Platform: account.Platform,
+ AccountID: account.ID,
+ AccountName: account.Name,
+ UpstreamStatusCode: resp.StatusCode,
+ UpstreamRequestID: resp.Header.Get("x-request-id"),
+ UpstreamURL: upstreamURL,
+ Kind: "http_error",
+ Message: upstreamMsg,
+ }
+
+ if IsSystemOneRequestErrorStatus(resp.StatusCode) {
+ appendOpsUpstreamError(c, event)
+ return &SystemOneUpstreamError{StatusCode: resp.StatusCode}
+ }
+
+ shouldDisable := false
+ if s.rateLimitService != nil {
+ shouldDisable = s.rateLimitService.HandleUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, typesafe.JevLatestModel)
+ }
+ if !shouldDisable && !s.shouldFailoverUpstreamError(resp.StatusCode) {
+ appendOpsUpstreamError(c, event)
+ return &SystemOneUpstreamError{StatusCode: resp.StatusCode}
+ }
+
+ event.Kind = "failover"
+ appendOpsUpstreamError(c, event)
+ failoverErr := &UpstreamFailoverError{
+ StatusCode: resp.StatusCode,
+ ResponseBody: respBody,
+ ResponseHeaders: resp.Header.Clone(),
+ RetryableOnSameAccount: !shouldDisable && account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode),
+ }
+ if resp.StatusCode == http.StatusUnauthorized {
+ failoverErr.Stage = GatewayFailureStageAccountAuth
+ failoverErr.Scope = GatewayFailureScopeAccount
+ failoverErr.Reason = TypeSafeCredentialRejectedReason
+ failoverErr.NextAccountAction = NextAccountRetry
+ }
+ return failoverErr
+}
+
+// systemOneResponseContentType keeps the upstream JSON media type (and its
+// charset) but never relays a non-JSON type for a body already validated as
+// JSON, so the gateway origin cannot be made to serve it as HTML.
+func systemOneResponseContentType(raw string) string {
+ mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(raw))
+ if err != nil {
+ return "application/json"
+ }
+ if mediaType == "application/json" || (strings.HasPrefix(mediaType, "application/") && strings.HasSuffix(mediaType, "+json")) {
+ return strings.TrimSpace(raw)
+ }
+ return "application/json"
+}
diff --git a/backend/internal/service/gateway_systemone_test.go b/backend/internal/service/gateway_systemone_test.go
new file mode 100644
index 000000000..7d974fc15
--- /dev/null
+++ b/backend/internal/service/gateway_systemone_test.go
@@ -0,0 +1,402 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/pkg/tlsfingerprint"
+ "github.com/MACOS-DO/sub4api/internal/pkg/typesafe"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type systemOneHTTPUpstream struct {
+ do func(*http.Request) (*http.Response, error)
+}
+
+type systemOnePolicyAccountRepo struct {
+ AccountRepository
+ account *Account
+ rateLimitedCalls int
+ overloadedCalls int
+ errorCalls int
+}
+
+func (r *systemOnePolicyAccountRepo) GetByID(context.Context, int64) (*Account, error) {
+ return r.account, nil
+}
+
+func (r *systemOnePolicyAccountRepo) SetRateLimited(context.Context, int64, time.Time) error {
+ r.rateLimitedCalls++
+ return nil
+}
+
+func (r *systemOnePolicyAccountRepo) SetOverloaded(context.Context, int64, time.Time) error {
+ r.overloadedCalls++
+ return nil
+}
+
+func (r *systemOnePolicyAccountRepo) SetError(context.Context, int64, string) error {
+ r.errorCalls++
+ return nil
+}
+
+func (u *systemOneHTTPUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
+ return u.do(req)
+}
+
+func (u *systemOneHTTPUpstream) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
+ return u.do(req)
+}
+
+func newSystemOneTestService(upstream HTTPUpstream) *GatewayService {
+ return &GatewayService{
+ cfg: &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{AllowInsecureHTTP: true}}},
+ httpUpstream: upstream,
+ }
+}
+
+func newSystemOneTestContext() *gin.Context {
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/systemone", nil)
+ return c
+}
+
+func TestForwardSystemOneForwardsNativeProtocolAndUsage(t *testing.T) {
+ requestBody := []byte(`{"model":"jev-latest","state":{"text":"sample"},"questions":{"q":{"type":"choice","instructions":"Pick","criteria":{"a":"A","b":"B"}}}}`)
+ responseBody := []byte(`{"model":"jev-1.13.0","answers":{"q":{"type":"choice","choice":"a"}},"usage":{"input_tokens":123,"output_tokens":7},"provider_extension":{"kept":true}}`)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, typesafeSystemOnePathForTest, r.URL.Path)
+ require.Equal(t, "Bearer ts-secret", r.Header.Get("Authorization"))
+ require.Equal(t, "application/json", r.Header.Get("Content-Type"))
+ got, err := io.ReadAll(r.Body)
+ require.NoError(t, err)
+ require.Equal(t, requestBody, got)
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.Header().Set("x-request-id", "req-jev")
+ _, err = w.Write(responseBody)
+ require.NoError(t, err)
+ }))
+ defer server.Close()
+
+ svc := newSystemOneTestService(&systemOneHTTPUpstream{do: server.Client().Do})
+ account := &Account{ID: 7, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": server.URL, "api_key": "ts-secret"}}
+ result, err := svc.ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, requestBody)
+ require.NoError(t, err)
+ require.Equal(t, responseBody, result.Body)
+ require.Equal(t, http.StatusOK, result.StatusCode)
+ require.Equal(t, "application/json; charset=utf-8", result.ContentType)
+ require.Equal(t, "req-jev", result.RequestID)
+ require.Equal(t, "jev-latest", result.Model)
+ require.Equal(t, "jev-1.13.0", result.UpstreamResponseModel)
+ require.Equal(t, 123, result.Usage.InputTokens)
+ require.Equal(t, 7, result.Usage.OutputTokens)
+}
+
+func TestForwardSystemOneAllowsSuccessfulResponseWithoutModel(t *testing.T) {
+ responseBody := []byte(`{"answers":{"q":{"type":"noul","answer":"ok"}},"usage":{"input_tokens":12}}`)
+ upstream := &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(responseBody)))}, nil
+ }}
+ svc := newSystemOneTestService(upstream)
+ account := &Account{ID: 11, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+
+ result, err := svc.ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, []byte(`{}`))
+ require.NoError(t, err)
+ require.Equal(t, responseBody, result.Body)
+ require.Empty(t, result.UpstreamResponseModel)
+ require.Equal(t, 12, result.Usage.InputTokens)
+}
+
+const typesafeSystemOnePathForTest = "/v1/systemone"
+
+func TestForwardSystemOneSchemaConformancePassthrough(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ }{
+ {"omitted noul instructions", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"noul","extension":{"kept":true}}}}`},
+ {"nullable noul fields", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"noul","instructions":null,"criteria":null}}}`},
+ {"structured noul descriptions", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"noul","criteria":{"true":{"reason":"Yes"},"false":["No",null]}}}}`},
+ {"object choice description", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"choice","criteria":{"a":{"description":"A","extra":null}}}}}`},
+ {"array choice description", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"choice","instructions":null,"criteria":{"a":["A",null],"b":null}}}}`},
+ {"empty choice criteria", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"choice","criteria":{}}}}`},
+ {"one-level score", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"score","criteria":["only"]}}}`},
+ {"object score level", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"score","instructions":null,"criteria":[{"description":"only","extra":null}]}}}`},
+ {"array score level", `{"model":"jev-latest","state":"sample","questions":{"q":{"type":"score","criteria":[["only",null]]}}}`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ requestBody := []byte(tc.body)
+ _, err := typesafe.ValidateSystemOneRequest(requestBody)
+ require.NoError(t, err)
+ responseBody := []byte(`{"answers":{},"usage":{"input_tokens":12}}`)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, "/v1/systemone", r.URL.Path)
+ require.Equal(t, "Bearer ts-mock-key", r.Header.Get("Authorization"))
+ got, err := io.ReadAll(r.Body)
+ require.NoError(t, err)
+ require.Equal(t, requestBody, got)
+ w.Header().Set("Content-Type", "application/json")
+ _, err = w.Write(responseBody)
+ require.NoError(t, err)
+ }))
+ defer server.Close()
+
+ svc := newSystemOneTestService(&systemOneHTTPUpstream{do: server.Client().Do})
+ account := &Account{ID: 12, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": server.URL, "api_key": "ts-mock-key"}}
+ result, err := svc.ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, requestBody)
+ require.NoError(t, err)
+ require.Equal(t, responseBody, result.Body)
+ require.Equal(t, 12, result.Usage.InputTokens)
+ })
+ }
+}
+
+func TestForwardSystemOneErrorPolicy(t *testing.T) {
+ for _, status := range []int{400, 422, 401, 429, 529, 500, 503} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ upstream := &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("private upstream body ts-secret"))}, nil
+ }}
+ svc := newSystemOneTestService(upstream)
+ account := &Account{ID: 8, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+ result, err := svc.ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, []byte(`{"private":"request"}`))
+ require.Nil(t, result)
+ require.Error(t, err)
+ require.NotContains(t, err.Error(), "private")
+ require.NotContains(t, err.Error(), "ts-secret")
+ if status == 400 || status == 422 {
+ var upstreamErr *SystemOneUpstreamError
+ require.ErrorAs(t, err, &upstreamErr)
+ require.Equal(t, status, upstreamErr.StatusCode)
+ return
+ }
+ var failoverErr *UpstreamFailoverError
+ require.ErrorAs(t, err, &failoverErr)
+ require.True(t, failoverErr.ShouldRetryNextAccount())
+ if status == http.StatusUnauthorized {
+ require.Equal(t, GatewayFailureStageAccountAuth, failoverErr.Stage)
+ require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope)
+ require.Equal(t, TypeSafeCredentialRejectedReason, failoverErr.Reason)
+ }
+ })
+ }
+}
+
+func TestForwardSystemOneAppliesExistingAccountStatePolicy(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status int
+ wantRateLimited int
+ wantOverloaded int
+ wantError int
+ }{
+ {name: "unauthorized", status: http.StatusUnauthorized, wantError: 1},
+ {name: "rate limited", status: http.StatusTooManyRequests, wantRateLimited: 1},
+ {name: "overloaded", status: 529, wantOverloaded: 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ account := &Account{ID: 10, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+ repo := &systemOnePolicyAccountRepo{account: account}
+ upstream := &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: tc.status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"error":"private"}`))}, nil
+ }}
+ svc := newSystemOneTestService(upstream)
+ svc.rateLimitService = NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+
+ _, err := svc.ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, []byte(`{}`))
+ require.Error(t, err)
+ require.Equal(t, tc.wantRateLimited, repo.rateLimitedCalls)
+ require.Equal(t, tc.wantOverloaded, repo.overloadedCalls)
+ require.Equal(t, tc.wantError, repo.errorCalls)
+ })
+ }
+}
+
+func TestForwardSystemOneTransportAndTimeoutFailOver(t *testing.T) {
+ for _, transportErr := range []error{errors.New("network unavailable"), context.DeadlineExceeded} {
+ upstream := &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) { return nil, transportErr }}
+ svc := newSystemOneTestService(upstream)
+ account := &Account{ID: 9, Name: "jev", Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+ _, err := svc.ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, []byte(`{}`))
+ var failoverErr *UpstreamFailoverError
+ require.ErrorAs(t, err, &failoverErr)
+ }
+}
+
+func newSystemOneStatusUpstream(status int, body string) *systemOneHTTPUpstream {
+ return &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: status, Header: http.Header{"X-Request-Id": []string{"req-err"}}, Body: io.NopCloser(strings.NewReader(body))}, nil
+ }}
+}
+
+func systemOneOpsEvents(t *testing.T, c *gin.Context) []*OpsUpstreamErrorEvent {
+ t.Helper()
+ raw, ok := c.Get(OpsUpstreamErrorsKey)
+ require.True(t, ok)
+ events, ok := raw.([]*OpsUpstreamErrorEvent)
+ require.True(t, ok)
+ return events
+}
+
+func TestForwardSystemOneRequestErrorsNeverTouchAccountState(t *testing.T) {
+ for _, status := range []int{http.StatusBadRequest, http.StatusRequestEntityTooLarge, http.StatusUnprocessableEntity} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ // Even a custom error-code rule must not let client input disable the account.
+ account := &Account{ID: 21, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "base_url": "http://typesafe.test", "api_key": "ts-secret",
+ "custom_error_codes_enabled": true, "custom_error_codes": []any{float64(status)},
+ }}
+ repo := &systemOnePolicyAccountRepo{account: account}
+ svc := newSystemOneTestService(newSystemOneStatusUpstream(status, `{"detail":"bad question"}`))
+ svc.rateLimitService = NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ c := newSystemOneTestContext()
+
+ _, err := svc.ForwardSystemOne(context.Background(), c, account, []byte(`{}`))
+ var upstreamErr *SystemOneUpstreamError
+ require.ErrorAs(t, err, &upstreamErr)
+ require.Equal(t, status, upstreamErr.StatusCode)
+ require.Zero(t, repo.errorCalls+repo.rateLimitedCalls+repo.overloadedCalls)
+ events := systemOneOpsEvents(t, c)
+ require.Len(t, events, 1)
+ require.Equal(t, "http_error", events[0].Kind)
+ require.Equal(t, status, events[0].UpstreamStatusCode)
+ require.Equal(t, "req-err", events[0].UpstreamRequestID)
+ })
+ }
+}
+
+func TestForwardSystemOneAccountLevelFailuresFailOver(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status int
+ wantError int
+ }{
+ {name: "payment required", status: http.StatusPaymentRequired, wantError: 1},
+ {name: "forbidden", status: http.StatusForbidden, wantError: 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ account := &Account{ID: 22, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+ repo := &systemOnePolicyAccountRepo{account: account}
+ svc := newSystemOneTestService(newSystemOneStatusUpstream(tc.status, `{"detail":"account problem"}`))
+ svc.rateLimitService = NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+ c := newSystemOneTestContext()
+
+ _, err := svc.ForwardSystemOne(context.Background(), c, account, []byte(`{}`))
+ var failoverErr *UpstreamFailoverError
+ require.ErrorAs(t, err, &failoverErr)
+ require.True(t, failoverErr.ShouldRetryNextAccount())
+ require.Equal(t, tc.status, failoverErr.StatusCode)
+ require.Equal(t, tc.wantError, repo.errorCalls)
+ require.Equal(t, "failover", systemOneOpsEvents(t, c)[0].Kind)
+ })
+ }
+}
+
+func TestForwardSystemOneHonorsCustomErrorCodes(t *testing.T) {
+ account := &Account{ID: 23, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "base_url": "http://typesafe.test", "api_key": "ts-secret",
+ "custom_error_codes_enabled": true, "custom_error_codes": []any{float64(http.StatusNotFound)},
+ }}
+ repo := &systemOnePolicyAccountRepo{account: account}
+ svc := newSystemOneTestService(newSystemOneStatusUpstream(http.StatusNotFound, `{"detail":"missing"}`))
+ svc.rateLimitService = NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+
+ _, err := svc.ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, []byte(`{}`))
+ var failoverErr *UpstreamFailoverError
+ require.ErrorAs(t, err, &failoverErr)
+ require.Equal(t, 1, repo.errorCalls)
+}
+
+func TestForwardSystemOneUnhandledStatusDoesNotFailOver(t *testing.T) {
+ account := &Account{ID: 24, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+ repo := &systemOnePolicyAccountRepo{account: account}
+ svc := newSystemOneTestService(newSystemOneStatusUpstream(http.StatusConflict, `{"detail":"conflict"}`))
+ svc.rateLimitService = NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
+
+ _, err := svc.ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, []byte(`{}`))
+ var upstreamErr *SystemOneUpstreamError
+ require.ErrorAs(t, err, &upstreamErr)
+ require.Equal(t, http.StatusConflict, upstreamErr.StatusCode)
+ require.Zero(t, repo.errorCalls)
+}
+
+func TestForwardSystemOneNormalizesResponseContentType(t *testing.T) {
+ for _, tc := range []struct{ upstream, want string }{
+ {"application/json; charset=utf-8", "application/json; charset=utf-8"},
+ {"application/problem+json", "application/problem+json"},
+ {"text/html; charset=utf-8", "application/json"},
+ {"", "application/json"},
+ {"not a media type;;", "application/json"},
+ } {
+ upstream := &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) {
+ header := make(http.Header)
+ if tc.upstream != "" {
+ header.Set("Content-Type", tc.upstream)
+ }
+ return &http.Response{StatusCode: http.StatusOK, Header: header, Body: io.NopCloser(strings.NewReader(`{"answers":{}}`))}, nil
+ }}
+ account := &Account{ID: 25, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+ result, err := newSystemOneTestService(upstream).ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, []byte(`{}`))
+ require.NoError(t, err)
+ require.Equal(t, tc.want, result.ContentType, tc.upstream)
+ }
+}
+
+func TestForwardSystemOneRejectsOversizedResponse(t *testing.T) {
+ oversized := `{"pad":"` + strings.Repeat("a", typesafe.MaxSystemOneResponseBytes) + `"}`
+ upstream := &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(oversized))}, nil
+ }}
+ account := &Account{ID: 26, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+ c := newSystemOneTestContext()
+ _, err := newSystemOneTestService(upstream).ForwardSystemOne(context.Background(), c, account, []byte(`{}`))
+ require.ErrorIs(t, err, typesafe.ErrSystemOneResponseTooLarge)
+ events := systemOneOpsEvents(t, c)
+ require.Len(t, events, 1)
+ require.Equal(t, "response_error", events[0].Kind)
+ require.Equal(t, http.StatusOK, events[0].UpstreamStatusCode)
+}
+
+func TestForwardSystemOneBillsLenientUsageShapes(t *testing.T) {
+ upstream := &systemOneHTTPUpstream{do: func(*http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"answers":{},"usage":{"input_tokens":"21","output_tokens":1.0}}`))}, nil
+ }}
+ account := &Account{ID: 27, Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": "http://typesafe.test", "api_key": "ts-secret"}}
+ result, err := newSystemOneTestService(upstream).ForwardSystemOne(context.Background(), newSystemOneTestContext(), account, []byte(`{}`))
+ require.NoError(t, err)
+ require.Equal(t, 21, result.Usage.InputTokens)
+ require.Equal(t, 1, result.Usage.OutputTokens)
+}
+
+func TestTypeSafeAccountBaseURLNeverFallsBackToAnthropic(t *testing.T) {
+ account := &Account{Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "ts-secret"}}
+ require.Equal(t, typesafe.DefaultBaseURL, account.GetBaseURL())
+ require.Equal(t, typesafe.DefaultBaseURL, account.GetTypeSafeBaseURL())
+ for raw, want := range map[string]string{
+ "https://api.typesafe.ai/v1": "https://api.typesafe.ai",
+ "https://api.typesafe.ai/V1/": "https://api.typesafe.ai",
+ "https://proxy.example/typesafe/": "https://proxy.example/typesafe",
+ "https://proxy.example/apiv1": "https://proxy.example/apiv1",
+ " https://proxy.example/x/v1/ ": "https://proxy.example/x",
+ "/v1": typesafe.DefaultBaseURL,
+ } {
+ withBase := &Account{Platform: PlatformTypeSafe, Type: AccountTypeAPIKey, Credentials: map[string]any{"base_url": raw}}
+ require.Equal(t, want, withBase.GetTypeSafeBaseURL(), raw)
+ }
+ anthropic := &Account{Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "sk"}}
+ require.Equal(t, "https://api.anthropic.com", anthropic.GetBaseURL())
+}
+
+func TestTypeSafeModelsListCandidates(t *testing.T) {
+ require.Equal(t, []string{typesafe.JevLatestModel}, defaultModelsListCandidateIDs(PlatformTypeSafe))
+ require.NotContains(t, compositeDefaultModelsListCandidateIDs(), typesafe.JevLatestModel)
+}
diff --git a/backend/internal/service/gateway_tool_changes_beta_test.go b/backend/internal/service/gateway_tool_changes_beta_test.go
new file mode 100644
index 000000000..aa114b7a2
--- /dev/null
+++ b/backend/internal/service/gateway_tool_changes_beta_test.go
@@ -0,0 +1,63 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func TestBuildUpstreamRequestToolChangeBetas(t *testing.T) {
+ const mid = "mid-conversation-tool-changes-2026-07-01"
+ const inline = "inline-tools-2026-09-15"
+ for _, tc := range []struct {
+ name, header string
+ drop map[string]struct{}
+ wantMid, wantInline bool
+ }{
+ {"both", mid + "," + inline, nil, true, true},
+ {"mid only", mid, nil, true, false},
+ {"inline only", inline, nil, false, true},
+ {"absent", "", nil, false, false},
+ {"unknown", inline + "-other", nil, false, false},
+ {"duplicate", inline + ", " + inline + "," + mid, nil, true, true},
+ {"filter inline", mid + "," + inline, map[string]struct{}{inline: {}}, true, false},
+ {"filter mid", mid + "," + inline, map[string]struct{}{mid: {}}, false, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
+ c.Request.Header.Set("anthropic-beta", tc.header+",unrelated-beta")
+ if tc.drop != nil {
+ c.Set(betaPolicyFilterSetKey, tc.drop)
+ }
+ account := &Account{ID: 701, Platform: PlatformAnthropic, Type: AccountTypeOAuth,
+ Credentials: map[string]any{"access_token": "test-token"}, Status: StatusActive, Schedulable: true}
+ body := []byte(`{"model":"claude-opus-5-5","max_tokens":1024,"messages":[{"role":"user","content":[{"type":"tool_addition","tool":{"type":"tool_reference","tool_name":"lookup"}},{"type":"text","text":"Use lookup"}]}]}`)
+ svc := &GatewayService{cfg: &config.Config{}}
+ req, _, err := svc.buildUpstreamRequest(context.Background(), c, account, body,
+ "test-token", "oauth", "claude-opus-5-5", false, true)
+ require.NoError(t, err)
+ out := readUpstreamBodyForTest(t, req)
+ require.JSONEq(t, gjson.GetBytes(body, "messages").Raw, gjson.GetBytes(out, "messages").Raw)
+ header := getHeaderRaw(req.Header, "anthropic-beta")
+ require.Equal(t, tc.wantMid, containsBetaToken(header, mid))
+ require.Equal(t, tc.wantInline, containsBetaToken(header, inline))
+ require.False(t, containsBetaToken(header, "unrelated-beta"))
+ require.False(t, containsBetaToken(header, inline+"-other"))
+ require.True(t, containsBetaToken(header, "oauth-2025-04-20"))
+ if tc.wantInline {
+ require.Equal(t, 1, strings.Count(header, inline))
+ }
+ })
+ }
+}
diff --git a/backend/internal/service/gateway_upstream_request.go b/backend/internal/service/gateway_upstream_request.go
index 589c7844e..1430506a3 100644
--- a/backend/internal/service/gateway_upstream_request.go
+++ b/backend/internal/service/gateway_upstream_request.go
@@ -545,14 +545,20 @@ func (s *GatewayService) computeFinalAnthropicBeta(
if tokenType == "oauth" {
if mimicClaudeCode {
- // Keep the default beta set, with a narrow opt-in for legacy structured
- // output requests. Unknown client betas remain excluded and policy drops
- // still take precedence over this compatibility token.
- incomingBeta := ""
- if containsBetaToken(clientBeta, claude.BetaStructuredOutputs) {
- incomingBeta = claude.BetaStructuredOutputs
+ // Preserve explicitly requested compatibility tokens so the forwarded
+ // body and headers agree. Unknown betas remain excluded; policy drops
+ // still take precedence. Missing companion tokens are not inferred.
+ var incomingBetas []string
+ for _, token := range []string{
+ claude.BetaStructuredOutputs,
+ claude.BetaMidConversationToolChanges,
+ claude.BetaInlineTools,
+ } {
+ if containsBetaToken(clientBeta, token) {
+ incomingBetas = append(incomingBetas, token)
+ }
}
- return mergeAnthropicBetaDropping(claude.FullClaudeCodeMimicryBetas(), incomingBeta, effectiveDropSet), true
+ return mergeAnthropicBetaDropping(claude.FullClaudeCodeMimicryBetas(), strings.Join(incomingBetas, ","), effectiveDropSet), true
}
// 真 Claude Code 客户端透传路径
return stripBetaTokensWithSet(s.getBetaHeader(modelID, clientBeta), effectiveDropSet), true
diff --git a/backend/internal/service/grok_upstream_headers.go b/backend/internal/service/grok_upstream_headers.go
index c3a05dfdb..d057f5813 100644
--- a/backend/internal/service/grok_upstream_headers.go
+++ b/backend/internal/service/grok_upstream_headers.go
@@ -17,7 +17,7 @@ const (
grokClientModeHeader = xai.CLIClientMode
)
-// defaultGrokUpstreamUserAgent is the pinned Grok CLI / workspace UA.
+// defaultGrokUpstreamUserAgent 使用固定版本的官方交互式 CLI UA。
// Grok upstream must not forward Claude Code / Codex / browser client UAs.
func defaultGrokUpstreamUserAgent() string {
return xai.CLIUserAgent(xai.ResolveCLIVersion())
diff --git a/backend/internal/service/grok_upstream_headers_test.go b/backend/internal/service/grok_upstream_headers_test.go
index 6c4be0b8c..742d0be44 100644
--- a/backend/internal/service/grok_upstream_headers_test.go
+++ b/backend/internal/service/grok_upstream_headers_test.go
@@ -28,7 +28,7 @@ func TestApplyDefaultGrokUpstreamHeadersUsesCLIUserAgent(t *testing.T) {
}
func TestApplyDefaultGrokUpstreamHeadersHonorsCLIVersionOverride(t *testing.T) {
- t.Setenv(xai.CLIVersionEnv, "0.2.95")
+ t.Setenv(xai.CLIVersionEnv, "1.0.14")
req, err := http.NewRequest(http.MethodGet, "https://api.x.ai/v1/responses", nil)
require.NoError(t, err)
@@ -36,9 +36,9 @@ func TestApplyDefaultGrokUpstreamHeadersHonorsCLIVersionOverride(t *testing.T) {
applyDefaultGrokUpstreamHeaders(req)
- require.Equal(t, "0.2.95", req.Header.Get("x-grok-client-version"))
- require.Equal(t, xai.CLIUserAgent("0.2.95"), req.Header.Get("User-Agent"))
- require.Equal(t, "grok-shell", req.Header.Get("x-grok-client-identifier"))
+ require.Equal(t, "1.0.14", req.Header.Get("x-grok-client-version"))
+ require.Equal(t, xai.CLIUserAgent("1.0.14"), req.Header.Get("User-Agent"))
+ require.Equal(t, "grok-pager", req.Header.Get("x-grok-client-identifier"))
}
func TestResolveGrokUpstreamUserAgentNeverPassthrough(t *testing.T) {
diff --git a/backend/internal/service/model_protocol_catalog.go b/backend/internal/service/model_protocol_catalog.go
new file mode 100644
index 000000000..3a7d0c75c
--- /dev/null
+++ b/backend/internal/service/model_protocol_catalog.go
@@ -0,0 +1,263 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/tidwall/gjson"
+)
+
+// 上游模型目录中的协议能力。部分聚合平台(Command Code)在 {Chat Completions 基址}/models
+// 的每个模型上给出 supported_endpoints,例如:
+//
+// {"id":"deepseek/deepseek-v4-flash","supported_endpoints":["/chat/completions","/responses"]}
+// {"id":"claude-sonnet-4-6","supported_endpoints":["/messages"]}
+//
+// 按模型分流时据此判断模型是否支持入站协议:支持就同协议直通,省去一次协议转换
+// (见 modelProtocolSet)。
+//
+// 缓存范围:所有目录均按账号和地址隔离,包括官方默认地址。目录可能随 Key、租户
+// 或请求头不同,鉴权失败的刷新退避也不能影响其他账号(见 modelProtocolCatalogKey)。
+//
+// 刷新在后台进行:过期时继续使用旧目录。目录从未加载成功时,首批请求最多等待
+// modelProtocolCatalogFirstLoadWait,各请求共用本轮刷新开始时的截止时间,并响应请求
+// 取消。超时后同一轮刷新中的后续请求立即回落内置规则,失败退避期内不再等待。
+
+const (
+ modelProtocolCatalogTTL = 30 * time.Minute
+ modelProtocolCatalogRetryBackoff = 5 * time.Minute
+ modelProtocolCatalogTimeout = 15 * time.Second
+ modelProtocolCatalogFirstLoadWait = 2 * time.Second
+ modelProtocolCatalogMaxBodyBytes = 2 << 20
+)
+
+type modelProtocolCatalogEntry struct {
+ // models 以小写模型 ID 为键,值为上游声明的协议(保持上游顺序)。
+ models map[string][]string
+ fetchedAt time.Time
+ retryAt time.Time
+ refreshing bool
+ // done 在进行中的刷新结束时关闭。
+ done chan struct{}
+ // firstLoadDeadline 是本轮冷启动刷新共享的等待截止时间。
+ firstLoadDeadline time.Time
+}
+
+type modelProtocolCatalog struct {
+ mu sync.Mutex
+ entries map[string]*modelProtocolCatalogEntry
+}
+
+// upstreamModelProtocols 是全进程共享的模型协议目录。
+var upstreamModelProtocols modelProtocolCatalog
+
+func (c *modelProtocolCatalog) entryLocked(key string) *modelProtocolCatalogEntry {
+ if c.entries == nil {
+ c.entries = make(map[string]*modelProtocolCatalogEntry)
+ }
+ entry := c.entries[key]
+ if entry == nil {
+ entry = &modelProtocolCatalogEntry{}
+ c.entries[key] = entry
+ }
+ return entry
+}
+
+// lookup 返回 key 目录中 model 支持的协议;目录尚未就绪或模型不在目录中时返回 nil。
+// 目录缺失或过期、且不在刷新中也不在失败退避期时,异步调用 refresh(由其调用 store);
+// 目录从未加载成功且刷新进行中时,只等待本轮冷启动窗口的剩余时间。
+func (c *modelProtocolCatalog) lookup(ctx context.Context, key, model string, now time.Time, refresh func()) []string {
+ if ctx.Err() != nil {
+ return nil
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ entry := c.entryLocked(key)
+ stale := entry.models == nil || now.Sub(entry.fetchedAt) >= modelProtocolCatalogTTL
+ if stale && !entry.refreshing && !now.Before(entry.retryAt) && refresh != nil {
+ entry.refreshing = true
+ entry.done = make(chan struct{})
+ if entry.models == nil {
+ entry.firstLoadDeadline = now.Add(modelProtocolCatalogFirstLoadWait)
+ }
+ go refresh()
+ }
+ if entry.models == nil && entry.refreshing && now.Before(entry.firstLoadDeadline) {
+ done := entry.done
+ deadline := entry.firstLoadDeadline
+ c.mu.Unlock()
+ timer := time.NewTimer(time.Until(deadline))
+ select {
+ case <-done:
+ case <-timer.C:
+ case <-ctx.Done():
+ }
+ timer.Stop()
+ c.mu.Lock()
+ }
+ if entry.models == nil || ctx.Err() != nil {
+ return nil
+ }
+ return entry.models[strings.ToLower(strings.TrimSpace(model))]
+}
+
+// store 写入一次刷新的结果;失败时保留旧目录并进入退避。
+func (c *modelProtocolCatalog) store(key string, models map[string][]string, err error, now time.Time) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ entry := c.entryLocked(key)
+ entry.refreshing = false
+ if entry.done != nil {
+ close(entry.done)
+ entry.done = nil
+ }
+ if err != nil {
+ entry.retryAt = now.Add(modelProtocolCatalogRetryBackoff)
+ return
+ }
+ entry.models = models
+ entry.fetchedAt = now
+ entry.retryAt = time.Time{}
+}
+
+// modelEndpointProtocol 把 supported_endpoints 中的端点路径映射为上游协议。
+func modelEndpointProtocol(endpoint string) string {
+ endpoint = strings.ToLower(strings.TrimRight(strings.TrimSpace(endpoint), "/"))
+ switch {
+ case strings.HasSuffix(endpoint, "/chat/completions"):
+ return APIProtocolChatCompletions
+ case strings.HasSuffix(endpoint, "/responses"):
+ return APIProtocolResponses
+ case strings.HasSuffix(endpoint, "/messages"):
+ return APIProtocolAnthropic
+ default:
+ return ""
+ }
+}
+
+// parseModelProtocolCatalog 解析 /models 响应;没有任何模型带可识别的 supported_endpoints
+// 时返回错误(上游不提供该字段,或是中转站的普通 /models)。
+func parseModelProtocolCatalog(body []byte) (map[string][]string, error) {
+ entries, err := extractUpstreamModelRawEntries(body)
+ if err != nil {
+ return nil, err
+ }
+ models := make(map[string][]string)
+ for _, raw := range entries {
+ id := strings.ToLower(strings.TrimSpace(gjson.GetBytes(raw, "id").String()))
+ if id == "" {
+ continue
+ }
+ var protocols []string
+ for _, endpoint := range gjson.GetBytes(raw, "supported_endpoints").Array() {
+ protocol := modelEndpointProtocol(endpoint.String())
+ if protocol != "" && !slices.Contains(protocols, protocol) {
+ protocols = append(protocols, protocol)
+ }
+ }
+ if len(protocols) > 0 {
+ models[id] = protocols
+ }
+ }
+ if len(models) == 0 {
+ return nil, fmt.Errorf("model list has no supported_endpoints")
+ }
+ return models, nil
+}
+
+// modelCatalogProtocols 返回上游模型目录中 model 支持的协议;平台不提供目录、账号固定了
+// 上游协议或目录尚未就绪时返回 nil。
+func (s *OpenAIGatewayService) modelCatalogProtocols(ctx context.Context, account *Account, model string) []string {
+ if s == nil || s.httpUpstream == nil || strings.TrimSpace(model) == "" || !account.routesByModel() {
+ return nil
+ }
+ if profile := account.providerProfile(); profile == nil || !profile.ModelCatalog {
+ return nil
+ }
+ if account.GetAPIProtocol() != APIProtocolAdaptive {
+ return nil
+ }
+ base := strings.TrimSpace(account.GetCNProtocolBaseURL(APIProtocolChatCompletions))
+ if base == "" {
+ return nil
+ }
+ url := buildOpenAIModelsURL(base)
+ key := modelProtocolCatalogKey(account, url)
+ headers := modelProtocolCatalogHeaders(account, url)
+ proxyURL := ""
+ if account.ProxyID != nil && account.Proxy != nil {
+ proxyURL = account.Proxy.URL()
+ }
+ accountID, concurrency := account.ID, account.Concurrency
+ return upstreamModelProtocols.lookup(ctx, key, model, time.Now(), func() {
+ ctx, cancel := context.WithTimeout(context.Background(), modelProtocolCatalogTimeout)
+ defer cancel()
+ models, err := s.fetchModelProtocolCatalog(ctx, url, headers, proxyURL, accountID, concurrency)
+ if err != nil {
+ slog.Warn("model_protocol_catalog_refresh_failed", "account_id", accountID, "url", url, "error", err)
+ } else {
+ slog.Info("model_protocol_catalog_refreshed", "account_id", accountID, "url", url, "models", len(models))
+ }
+ upstreamModelProtocols.store(key, models, err, time.Now())
+ })
+}
+
+// modelProtocolCatalogKey 按账号和地址隔离目录及刷新退避,避免一个账号的目录或
+// 鉴权失败影响同地址的其他账号。
+func modelProtocolCatalogKey(account *Account, url string) string {
+ return fmt.Sprintf("%s#account=%d", url, account.ID)
+}
+
+// modelProtocolCatalogHeaders 构造目录请求头,UA 收敛与账号请求头覆写与转发一致
+// (见 buildUpstreamRequest)。在请求时构造,后台刷新不再读取账号。
+func modelProtocolCatalogHeaders(account *Account, url string) http.Header {
+ headers := http.Header{}
+ headers.Set("Accept", "application/json")
+ if apiKey := strings.TrimSpace(account.GetOpenAIProtocolAPIKey()); apiKey != "" {
+ headers.Set("Authorization", "Bearer "+apiKey)
+ }
+ applyOpenCodeUpstreamUserAgent(account, url, headers)
+ account.ApplyHeaderOverrides(headers)
+ return headers
+}
+
+func (s *OpenAIGatewayService) fetchModelProtocolCatalog(ctx context.Context, url string, headers http.Header, proxyURL string, accountID int64, concurrency int) (map[string][]string, error) {
+ validatedURL, err := s.validateUpstreamBaseURL(url)
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequestWithContext(WithHTTPUpstreamRedirectsDisabled(ctx), http.MethodGet, validatedURL, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header = headers.Clone()
+ resp, err := s.httpUpstream.Do(req, proxyURL, accountID, maxInt(concurrency, 1))
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
+ return nil, fmt.Errorf("model list returned HTTP %d", resp.StatusCode)
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, modelProtocolCatalogMaxBodyBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if len(body) > modelProtocolCatalogMaxBodyBytes {
+ return nil, fmt.Errorf("model list exceeds %d bytes", modelProtocolCatalogMaxBodyBytes)
+ }
+ return parseModelProtocolCatalog(body)
+}
+
+// resolveUpstreamProtocolFor 是网关入口使用的 resolveUpstreamProtocol:按模型分流且平台
+// 提供模型目录时,带上目录中该模型支持的协议。
+func (s *OpenAIGatewayService) resolveUpstreamProtocolFor(ctx context.Context, account *Account, inbound, model string) string {
+ return resolveUpstreamProtocol(account, inbound, model, s.modelCatalogProtocols(ctx, account, model))
+}
diff --git a/backend/internal/service/model_protocol_catalog_test.go b/backend/internal/service/model_protocol_catalog_test.go
new file mode 100644
index 000000000..f8918eedf
--- /dev/null
+++ b/backend/internal/service/model_protocol_catalog_test.go
@@ -0,0 +1,420 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "testing/synctest"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// 取自 https://api.commandcode.ai/provider/v1/models 的片段(2026-09-26)。
+const commandCodeModelsSample = `{"object":"list","data":[
+ {"id":"claude-sonnet-4-6","supported_endpoints":["/messages"]},
+ {"id":"gpt-5.5","supported_endpoints":["/chat/completions","/responses"]},
+ {"id":"deepseek/deepseek-v4-flash","supported_endpoints":["/chat/completions","/responses"]},
+ {"id":"deepseek/deepseek-v4-flash-fast","supported_endpoints":["/chat/completions"]},
+ {"id":"zai-org/GLM-5.3","supported_endpoints":["/chat/completions","/responses"]},
+ {"id":"typesafe/jev","supported_endpoints":["/systemone"]},
+ {"id":"no-endpoints"}
+]}`
+
+func TestParseModelProtocolCatalog(t *testing.T) {
+ models, err := parseModelProtocolCatalog([]byte(commandCodeModelsSample))
+ require.NoError(t, err)
+ require.Equal(t, map[string][]string{
+ "claude-sonnet-4-6": {APIProtocolAnthropic},
+ "gpt-5.5": {APIProtocolChatCompletions, APIProtocolResponses},
+ "deepseek/deepseek-v4-flash": {APIProtocolChatCompletions, APIProtocolResponses},
+ "deepseek/deepseek-v4-flash-fast": {APIProtocolChatCompletions},
+ "zai-org/glm-5.3": {APIProtocolChatCompletions, APIProtocolResponses},
+ }, models)
+
+ _, err = parseModelProtocolCatalog([]byte(`{"data":[{"id":"gpt-5"},{"id":"glm-5"}]}`))
+ require.Error(t, err, "a plain /models without supported_endpoints is not a protocol catalog")
+}
+
+func TestModelProtocolCatalogLookupRefreshesInBackground(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ var catalog modelProtocolCatalog
+ const key = "https://catalog.example/v1/models"
+ now := time.Now()
+ models, err := parseModelProtocolCatalog([]byte(commandCodeModelsSample))
+ require.NoError(t, err)
+ catalog.store(key, models, nil, now)
+ var refreshes atomic.Int32
+ refresh := func() { refreshes.Add(1) }
+
+ require.Equal(t, []string{APIProtocolChatCompletions, APIProtocolResponses}, catalog.lookup(t.Context(), key, "ZAI-ORG/GLM-5.3", now, refresh))
+ require.Nil(t, catalog.lookup(t.Context(), key, "unknown-model", now, refresh))
+ require.Zero(t, refreshes.Load())
+
+ // A stale catalog is returned immediately while one refresh runs in the background.
+ time.Sleep(modelProtocolCatalogTTL) // synctest advances virtual time.
+ later := time.Now()
+ require.NotNil(t, catalog.lookup(t.Context(), key, "gpt-5.5", later, refresh))
+ require.Equal(t, later, time.Now(), "a stale result must not wait for refresh")
+ synctest.Wait()
+ require.EqualValues(t, 1, refreshes.Load())
+ require.NotNil(t, catalog.lookup(t.Context(), key, "gpt-5.5", later, refresh))
+ require.EqualValues(t, 1, refreshes.Load(), "concurrent stale reads share one refresh")
+ catalog.store(key, nil, errors.New("boom"), later)
+ require.NotNil(t, catalog.lookup(t.Context(), key, "gpt-5.5", later.Add(time.Minute), refresh))
+ require.EqualValues(t, 1, refreshes.Load(), "failure backoff preserves the old catalog")
+ require.NotNil(t, catalog.lookup(t.Context(), key, "gpt-5.5", later.Add(modelProtocolCatalogRetryBackoff), refresh))
+ synctest.Wait()
+ require.EqualValues(t, 2, refreshes.Load())
+ })
+}
+
+func TestModelProtocolCatalogFirstLoadSharesWaitDeadline(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ var catalog modelProtocolCatalog
+ const key = "https://catalog.example/v1/models"
+ models := map[string][]string{"gpt-5.5": {APIProtocolResponses}}
+ release := make(chan struct{})
+ var refreshes atomic.Int32
+ refresh := func() {
+ refreshes.Add(1)
+ <-release
+ catalog.store(key, models, nil, time.Now())
+ }
+ type result struct {
+ protocols []string
+ elapsed time.Duration
+ }
+ first, second := make(chan result, 1), make(chan result, 1)
+ lookup := func(done chan<- result) {
+ start := time.Now()
+ protocols := catalog.lookup(t.Context(), key, "gpt-5.5", start, refresh)
+ done <- result{protocols, time.Since(start)}
+ }
+ start := time.Now()
+ go lookup(first)
+ synctest.Wait()
+ time.Sleep(modelProtocolCatalogFirstLoadWait / 2) // Virtual time only.
+ go lookup(second)
+ synctest.Wait()
+ time.Sleep(modelProtocolCatalogFirstLoadWait / 2)
+ synctest.Wait()
+
+ r1, r2 := <-first, <-second
+ require.Nil(t, r1.protocols)
+ require.Nil(t, r2.protocols)
+ require.Equal(t, modelProtocolCatalogFirstLoadWait, r1.elapsed)
+ require.Equal(t, modelProtocolCatalogFirstLoadWait/2, r2.elapsed, "a later caller waits only for the remaining shared window")
+ require.Equal(t, modelProtocolCatalogFirstLoadWait, time.Since(start))
+ require.Nil(t, catalog.lookup(t.Context(), key, "gpt-5.5", time.Now(), refresh))
+ require.Equal(t, modelProtocolCatalogFirstLoadWait, time.Since(start), "later calls fall back immediately while the same refresh continues")
+ require.EqualValues(t, 1, refreshes.Load())
+
+ close(release)
+ synctest.Wait()
+ require.Equal(t, models["gpt-5.5"], catalog.lookup(t.Context(), key, "gpt-5.5", time.Now(), refresh), "a late successful refresh still populates the cache")
+ })
+}
+
+func TestModelProtocolCatalogFirstLoadWaitsForRefresh(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ const key = "https://catalog.example/v1/models"
+ models, err := parseModelProtocolCatalog([]byte(commandCodeModelsSample))
+ require.NoError(t, err)
+ var loaded modelProtocolCatalog
+ release := make(chan struct{})
+ result := make(chan []string, 1)
+ go func() {
+ result <- loaded.lookup(t.Context(), key, "gpt-5.5", time.Now(), func() {
+ <-release
+ loaded.store(key, models, nil, time.Now())
+ })
+ }()
+ synctest.Wait()
+ close(release)
+ synctest.Wait()
+ require.Equal(t, []string{APIProtocolChatCompletions, APIProtocolResponses}, <-result)
+
+ var failing modelProtocolCatalog
+ var refreshes atomic.Int32
+ refresh := func() {
+ refreshes.Add(1)
+ failing.store(key, nil, errors.New("boom"), time.Now())
+ }
+ start := time.Now()
+ require.Nil(t, failing.lookup(t.Context(), key, "gpt-5.5", start, refresh))
+ require.Nil(t, failing.lookup(t.Context(), key, "gpt-5.5", start.Add(time.Minute), refresh))
+ require.Equal(t, start, time.Now(), "a failed first load and its backoff must not hold requests")
+ require.EqualValues(t, 1, refreshes.Load())
+ })
+}
+
+func TestModelProtocolCatalogFirstLoadWaitRespondsToCancellation(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ var catalog modelProtocolCatalog
+ const key = "https://catalog.example/v1/models"
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ release := make(chan struct{})
+ models := map[string][]string{"gpt-5.5": {APIProtocolResponses}}
+ result := make(chan []string, 1)
+ start := time.Now()
+ go func() {
+ result <- catalog.lookup(ctx, key, "gpt-5.5", start, func() {
+ <-release
+ catalog.store(key, models, nil, time.Now())
+ })
+ }()
+ synctest.Wait()
+ cancel()
+ synctest.Wait()
+ require.Nil(t, <-result)
+ require.Equal(t, start, time.Now(), "cancellation releases the caller without waiting for the cold-start deadline")
+
+ // The caller's cancellation must not cancel the background refresh for future requests.
+ close(release)
+ synctest.Wait()
+ require.Equal(t, models["gpt-5.5"], catalog.lookup(t.Context(), key, "gpt-5.5", time.Now(), nil))
+ })
+}
+
+// 官方默认地址和自定义上游均按账号隔离;请求头与转发一致。
+func TestModelProtocolCatalogKeyAndHeaders(t *testing.T) {
+ official := commandCodeTestAccount(21)
+ base := official.GetCNProtocolBaseURL(APIProtocolChatCompletions)
+ url := buildOpenAIModelsURL(base)
+ require.Equal(t, "https://api.commandcode.ai/provider/v1/models", url)
+ require.Equal(t, url+"#account=21", modelProtocolCatalogKey(official, url))
+ require.Equal(t, url+"#account=22", modelProtocolCatalogKey(commandCodeTestAccount(22), url))
+
+ headers := modelProtocolCatalogHeaders(official, url)
+ require.Equal(t, "Bearer user_test_key", headers.Get("Authorization"))
+ require.Equal(t, CodexCanonicalUserAgent(), headers.Get("User-Agent"), "official host gets the canonical UA like forwarding")
+
+ custom := commandCodeTestAccount(23)
+ custom.Credentials["api_base_urls"] = map[string]any{APIProtocolChatCompletions: "https://relay.example/v1"}
+ custom.Credentials["header_override_enabled"] = true
+ custom.Credentials["header_overrides"] = map[string]any{"X-Tenant": "t-1"}
+ customBase := custom.GetCNProtocolBaseURL(APIProtocolChatCompletions)
+ customURL := buildOpenAIModelsURL(customBase)
+ require.Equal(t, customURL+"#account=23", modelProtocolCatalogKey(custom, customURL))
+ headers = modelProtocolCatalogHeaders(custom, customURL)
+ require.Equal(t, "t-1", getHeaderRaw(headers, "x-tenant"))
+ require.Empty(t, headers.Get("User-Agent"))
+}
+
+type modelCatalogAccountUpstream struct {
+ HTTPUpstream
+ mu sync.Mutex
+ requests []*http.Request
+ failureStatus int
+ failureErr error
+}
+
+func (u *modelCatalogAccountUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
+ u.mu.Lock()
+ u.requests = append(u.requests, req)
+ u.mu.Unlock()
+ if req.Header.Get("Authorization") == "Bearer invalid-key" {
+ if u.failureErr != nil {
+ return nil, u.failureErr
+ }
+ return newJSONResponse(u.failureStatus, `{"error":"invalid credentials"}`), nil
+ }
+ endpoint := "/chat/completions"
+ if getHeaderRaw(req.Header, "x-tenant") == "responses-tenant" {
+ endpoint = "/responses"
+ }
+ return newJSONResponse(http.StatusOK, fmt.Sprintf(`{"data":[{"id":"vendor/model","supported_endpoints":[%q]}]}`, endpoint)), nil
+}
+
+func TestModelProtocolCatalogOfficialAccountsAreIsolated(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status int
+ err error
+ }{
+ {name: "unauthorized", status: http.StatusUnauthorized},
+ {name: "forbidden", status: http.StatusForbidden},
+ {name: "transport", err: errors.New("upstream connection failed")},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ upstream := &modelCatalogAccountUpstream{failureStatus: tc.status, failureErr: tc.err}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+ id := time.Now().UnixNano()
+ bad, chat, responses := commandCodeTestAccount(id), commandCodeTestAccount(id+1), commandCodeTestAccount(id+2)
+ bad.Credentials["api_key"] = "invalid-key"
+ responses.Credentials["header_override_enabled"] = true
+ responses.Credentials["header_overrides"] = map[string]any{"X-Tenant": "responses-tenant"}
+ url := buildOpenAIModelsURL(bad.GetCNProtocolBaseURL(APIProtocolChatCompletions))
+ t.Cleanup(func() {
+ upstreamModelProtocols.mu.Lock()
+ defer upstreamModelProtocols.mu.Unlock()
+ for _, account := range []*Account{bad, chat, responses} {
+ delete(upstreamModelProtocols.entries, modelProtocolCatalogKey(account, url))
+ }
+ })
+
+ require.Nil(t, svc.modelCatalogProtocols(t.Context(), bad, "vendor/model"))
+ require.Equal(t, APIProtocolChatCompletions, svc.resolveUpstreamProtocolFor(t.Context(), chat, APIProtocolResponses, "vendor/model"), "a healthy account fetches its own catalog despite another account's backoff")
+ require.Equal(t, APIProtocolResponses, svc.resolveUpstreamProtocolFor(t.Context(), responses, APIProtocolChatCompletions, "vendor/model"), "successful catalogs stay isolated when headers select different tenants")
+ require.Equal(t, []string{APIProtocolChatCompletions}, svc.modelCatalogProtocols(t.Context(), chat, "vendor/model"))
+ require.Nil(t, svc.modelCatalogProtocols(t.Context(), bad, "vendor/model"))
+ upstream.mu.Lock()
+ defer upstream.mu.Unlock()
+ require.Len(t, upstream.requests, 3, "each healthy account fetches once; the failed account remains in its own backoff")
+ for _, req := range upstream.requests {
+ require.Equal(t, url, req.URL.String(), "all accounts use the same official model-list URL")
+ }
+ })
+ }
+}
+
+func TestCommandCodeModelProtocolSetUsesCatalog(t *testing.T) {
+ account := commandCodeTestAccount(11)
+ both := []string{APIProtocolChatCompletions, APIProtocolResponses}
+
+ // 目录声明两种协议:入站同协议直通;Anthropic 入站走首选(内置规则没有命中时为 Chat Completions)。
+ require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolResponses, "deepseek/deepseek-v4-flash", both))
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolChatCompletions, "deepseek/deepseek-v4-flash", both))
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolAnthropic, "deepseek/deepseek-v4-flash", both))
+ // GPT 的首选沿用内置规则(Responses)。
+ require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolAnthropic, "gpt-5.5", both))
+ // 目录只声明 Chat Completions:Responses 入站也转换到 Chat Completions。
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolResponses, "deepseek/deepseek-v4-flash-fast", []string{APIProtocolChatCompletions}))
+ require.Equal(t, APIProtocolAnthropic, resolveUpstreamProtocol(account, APIProtocolResponses, "claude-sonnet-4-6", []string{APIProtocolAnthropic}))
+
+ // 账号规则命中时优先于目录;已配置但未命中时仍使用目录。
+ account.Credentials["protocol_rules"] = []any{map[string]any{"pattern": "deepseek/*", "protocol": APIProtocolChatCompletions}}
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolResponses, "deepseek/deepseek-v4-flash", both))
+ require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(account, APIProtocolResponses, "zai-org/glm-5.3", both))
+
+ // 显式协议优先于一切。
+ account.Credentials["api_protocol"] = APIProtocolChatCompletions
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(account, APIProtocolResponses, "zai-org/glm-5.3", both))
+}
+
+func TestProtocolRulesWithProtocolSets(t *testing.T) {
+ credentials := map[string]any{"protocol_rules": []any{
+ map[string]any{"pattern": " GPT-* ", "protocol": APIProtocolResponses, "protocols": []any{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolChatCompletions}},
+ map[string]any{"pattern": "qwen*", "protocols": []any{APIProtocolAnthropic}},
+ map[string]any{"pattern": "glm-*", "protocol": APIProtocolChatCompletions},
+ }}
+ require.NoError(t, NormalizeProtocolRulesCredentials(credentials))
+ require.Equal(t, []any{
+ map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses, "protocols": []any{APIProtocolResponses, APIProtocolChatCompletions}},
+ map[string]any{"pattern": "qwen*", "protocol": APIProtocolAnthropic},
+ map[string]any{"pattern": "glm-*", "protocol": APIProtocolChatCompletions},
+ }, credentials["protocol_rules"])
+
+ bad := map[string]any{"protocol_rules": []any{map[string]any{"pattern": "gpt-*", "protocols": []any{"responses", "bogus"}}}}
+ require.Error(t, NormalizeProtocolRulesCredentials(bad))
+
+ // 单一协议规则(OpenCode)不受影响:与入站无关。
+ openCode := &Account{Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey, Credentials: map[string]any{"api_key": "k"}}
+ for _, inbound := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic} {
+ require.Equal(t, APIProtocolResponses, resolveUpstreamProtocol(openCode, inbound, "gpt-5.5", nil), inbound)
+ require.Equal(t, APIProtocolChatCompletions, resolveUpstreamProtocol(openCode, inbound, "glm-5.3", nil), inbound)
+ }
+}
+
+// 经真实入口验证:目录声明模型支持入站协议时原样直通,不做协议转换。
+func TestCommandCodeGatewayPassesThroughCatalogProtocols(t *testing.T) {
+ type observation struct {
+ url string
+ body []byte
+ }
+ forward := func(t *testing.T, ingress routingMatrixIngress, model string, catalog map[string][]string) observation {
+ t.Helper()
+ base := fmt.Sprintf("http://cc-%s-%d.example", strings.ReplaceAll(t.Name(), "/", "-"), time.Now().UnixNano())
+ account := commandCodeTestAccount(12)
+ account.Credentials["api_base_urls"] = map[string]any{
+ APIProtocolChatCompletions: base + "/provider/v1",
+ APIProtocolResponses: base + "/provider/v1",
+ APIProtocolAnthropic: base + "/provider",
+ }
+ url := buildOpenAIModelsURL(base + "/provider/v1")
+ key := modelProtocolCatalogKey(account, url)
+ if catalog != nil {
+ upstreamModelProtocols.store(key, catalog, nil, time.Now())
+ } else {
+ // 目录不可用(退避中):不触发刷新,回落内置规则。
+ upstreamModelProtocols.store(key, nil, errors.New("unavailable"), time.Now())
+ }
+ upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+ body := routingMatrixCase{ingress: ingress, model: model}.body()
+ _ = ingress.forward(svc, adaptiveProtocolTestContext(ingress.path, body), account, body)
+ require.NotEmpty(t, upstream.requests)
+ return observation{url: upstream.requests[len(upstream.requests)-1].URL.String(), body: upstream.lastBody}
+ }
+ ingresses := map[string]routingMatrixIngress{}
+ for _, ingress := range routingMatrixIngresses() {
+ ingresses[ingress.name] = ingress
+ }
+ catalog := map[string][]string{
+ "deepseek/deepseek-v4-flash": {APIProtocolChatCompletions, APIProtocolResponses},
+ "deepseek/deepseek-v4-flash-fast": {APIProtocolChatCompletions},
+ "gpt-5.5": {APIProtocolChatCompletions, APIProtocolResponses},
+ }
+
+ obs := forward(t, ingresses["responses"], "deepseek/deepseek-v4-flash", catalog)
+ require.True(t, strings.HasSuffix(obs.url, "/provider/v1/responses"), obs.url)
+ require.True(t, gjson.GetBytes(obs.body, "input").Exists(), "Responses body passes through unconverted")
+
+ obs = forward(t, ingresses["responses"], "deepseek/deepseek-v4-flash", nil)
+ require.True(t, strings.HasSuffix(obs.url, "/provider/v1/chat/completions"), obs.url)
+ require.True(t, gjson.GetBytes(obs.body, "messages").Exists())
+
+ obs = forward(t, ingresses["responses"], "deepseek/deepseek-v4-flash-fast", catalog)
+ require.True(t, strings.HasSuffix(obs.url, "/provider/v1/chat/completions"), obs.url)
+
+ obs = forward(t, ingresses["chat"], "gpt-5.5", catalog)
+ require.True(t, strings.HasSuffix(obs.url, "/provider/v1/chat/completions"), obs.url)
+ require.True(t, gjson.GetBytes(obs.body, "messages").Exists(), "Chat body passes through unconverted")
+}
+
+// 目录缺失时网关拉取目录,首个请求即按目录分流;自定义上游按账号各自拉取,并带上
+// 账号的请求头覆写。
+func TestCommandCodeGatewayFetchesModelCatalog(t *testing.T) {
+ base := fmt.Sprintf("http://cc-fetch-%d.example/provider/v1", time.Now().UnixNano())
+ newAccount := func(id int64) *Account {
+ account := commandCodeTestAccount(id)
+ account.Credentials["api_base_urls"] = map[string]any{
+ APIProtocolChatCompletions: base,
+ APIProtocolResponses: base,
+ APIProtocolAnthropic: strings.TrimSuffix(base, "/v1"),
+ }
+ account.Credentials["header_override_enabled"] = true
+ account.Credentials["header_overrides"] = map[string]any{"X-Tenant": fmt.Sprintf("t-%d", id)}
+ return account
+ }
+ upstream := &commandCodeAlphaUpstream{responses: map[string]commandCodeAlphaResponse{
+ "/provider/v1/models": {status: 200, body: commandCodeModelsSample},
+ }}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+ both := []string{APIProtocolChatCompletions, APIProtocolResponses}
+
+ first, second := newAccount(13), newAccount(14)
+ require.Equal(t, both, svc.modelCatalogProtocols(t.Context(), first, "deepseek/deepseek-v4-flash"))
+ require.Equal(t, both, svc.modelCatalogProtocols(t.Context(), first, "deepseek/deepseek-v4-flash"))
+ require.Equal(t, both, svc.modelCatalogProtocols(t.Context(), second, "deepseek/deepseek-v4-flash"))
+
+ upstream.mu.Lock()
+ defer upstream.mu.Unlock()
+ require.Len(t, upstream.requests, 2, "one fetch per account on a custom upstream")
+ for i, account := range []*Account{first, second} {
+ req := upstream.requests[i]
+ require.Equal(t, "/provider/v1/models", req.URL.Path)
+ require.Equal(t, "Bearer user_test_key", req.Header.Get("Authorization"))
+ require.Equal(t, fmt.Sprintf("t-%d", account.ID), getHeaderRaw(req.Header, "x-tenant"))
+ }
+}
diff --git a/backend/internal/service/model_rate_limit.go b/backend/internal/service/model_rate_limit.go
index 935f11ec8..970139a58 100644
--- a/backend/internal/service/model_rate_limit.go
+++ b/backend/internal/service/model_rate_limit.go
@@ -90,6 +90,10 @@ func (a *Account) modelRateLimitKeysForRequest(ctx context.Context, requestedMod
if isAnthropicFableModel(modelKey) && modelKey != anthropicFableRateLimitKey {
keys = append(keys, anthropicFableRateLimitKey)
}
+ case PlatformCline:
+ if walletKey := clineWalletRateLimitKey(modelKey); walletKey != "" {
+ keys = append(keys, walletKey)
+ }
}
return keys
}
@@ -189,6 +193,17 @@ func (a *Account) modelRateLimitResetAt(scope string) *time.Time {
return &resetAt
}
+// modelRateLimitReason 返回指定 scope 冷却记录中的原因;没有记录时为空。
+func (a *Account) modelRateLimitReason(scope string) string {
+ if a == nil || a.Extra == nil {
+ return ""
+ }
+ rawLimits, _ := a.Extra[modelRateLimitsKey].(map[string]any)
+ rawLimit, _ := rawLimits[scope].(map[string]any)
+ reason, _ := rawLimit["reason"].(string)
+ return reason
+}
+
func setAccountModelRateLimitSnapshot(account *Account, scope string, resetAt time.Time, reason string, now time.Time) {
if account == nil || strings.TrimSpace(scope) == "" {
return
diff --git a/backend/internal/service/openai_apikey_responses_probe.go b/backend/internal/service/openai_apikey_responses_probe.go
index 4adf1003f..2f2f95e86 100644
--- a/backend/internal/service/openai_apikey_responses_probe.go
+++ b/backend/internal/service/openai_apikey_responses_probe.go
@@ -130,8 +130,8 @@ func (s *AccountTestService) ProbeOpenAIAPIKeyResponsesSupport(ctx context.Conte
if account.Type != AccountTypeAPIKey {
return
}
- if account.IsCNProvider() {
- // 国产 OpenAI 兼容上游默认仅支持 /v1/chat/completions。直接落标 false
+ if account.RoutesProtocolByInbound() {
+ // 按入站协议分流的供应商(国产厂商等)默认仅支持 /v1/chat/completions。直接落标 false
// 走 Chat Completions 直转,跳过网络探测。
// 例外:deepseek / kimi 的固定 responses 和 adaptive 账号使用官方原生
// Responses 端点,落标 force_responses;其余协议显式重置为 auto,避免
diff --git a/backend/internal/service/openai_bps_composite_catalog.go b/backend/internal/service/openai_bps_composite_catalog.go
index e7eb162d0..d3b4d6d99 100644
--- a/backend/internal/service/openai_bps_composite_catalog.go
+++ b/backend/internal/service/openai_bps_composite_catalog.go
@@ -54,6 +54,13 @@ func (s *GatewayService) CompleteCompositeBPSModelCatalog(ctx context.Context, g
if s.compositeResolver != nil && s.compositeResolver.repo != nil {
all, err := s.compositeResolver.repo.ListByGroup(ctx, *groupID, true)
if err != nil {
+ if !configured {
+ // No BPS account: keep the account-derived catalog, as for other route lookup failures.
+ if len(existing) == 0 {
+ return nil, nil
+ }
+ return existing, nil
+ }
return nil, fmt.Errorf("load composite catalog routes: %w", err)
}
for _, route := range all {
diff --git a/backend/internal/service/openai_codex_model_metadata.go b/backend/internal/service/openai_codex_model_metadata.go
index b692bf5d0..16b56724e 100644
--- a/backend/internal/service/openai_codex_model_metadata.go
+++ b/backend/internal/service/openai_codex_model_metadata.go
@@ -21,6 +21,9 @@ func applyCodexToolCapabilities(dst, src map[string]json.RawMessage, overwrite b
if len(value) == 0 {
continue
}
+ if field == "service_tiers" && bytes.Equal(value, []byte("null")) {
+ value = []byte("[]")
+ }
// These Codex fields are nullable booleans or strings, never arbitrary objects.
if !bytes.Equal(value, []byte("null")) {
if field == "service_tiers" {
@@ -278,8 +281,11 @@ func intersectUpstreamModelMetadata(modelID string, candidates []UpstreamModelMe
result.CodexToolCapabilities[field] = value
} else if declared {
fallback := json.RawMessage("null")
- if field == "supports_search_tool" || field == "use_responses_lite" {
+ switch field {
+ case "supports_search_tool", "use_responses_lite":
fallback = json.RawMessage("false")
+ case "service_tiers":
+ fallback = json.RawMessage("[]")
}
result.CodexToolCapabilities[field] = fallback
}
diff --git a/backend/internal/service/openai_codex_model_metadata_test.go b/backend/internal/service/openai_codex_model_metadata_test.go
index f0d35b56c..16ed878e9 100644
--- a/backend/internal/service/openai_codex_model_metadata_test.go
+++ b/backend/internal/service/openai_codex_model_metadata_test.go
@@ -108,6 +108,41 @@ func TestAstraCodexToolCapabilitiesUseAccountScopeAndSharedDeclarations(t *testi
require.Equal(t, "3000", model["comp_hash"])
}
+func TestCodexToolCapabilitiesNeverAdvertiseNullServiceTiers(t *testing.T) {
+ newAccount := func(id int64, tiers string) Account {
+ account := Account{ID: id, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "base_url": "https://relay.example/v1", "model_mapping": map[string]any{"gpt-6-sol": "gpt-6-sol"},
+ }}
+ if tiers != "" {
+ account.SetUpstreamModelMetadataSnapshot(UpstreamModelMetadataSnapshot{Models: map[string]UpstreamModelMetadata{
+ "gpt-6-sol": {CodexToolCapabilities: map[string]json.RawMessage{"service_tiers": json.RawMessage(tiers)}},
+ }})
+ }
+ return account
+ }
+ for _, tt := range []struct {
+ name string
+ accounts []Account
+ }{
+ {"conflicting peer tiers", []Account{newAccount(1, `[{"id":"priority"}]`), newAccount(2, `[]`)}},
+ {"undeclared peer tiers", []Account{newAccount(1, `[{"id":"priority"}]`), newAccount(2, "")}},
+ {"explicit null tiers", []Account{newAccount(1, "null")}},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ body, err := buildCodexModelsManifestForAccounts(PlatformOpenAI, []string{"gpt-6-sol"}, tt.accounts, nil, nil, true)
+ require.NoError(t, err)
+ model := decodeCodexManifestModels(t, body)[0]
+ require.Equal(t, []any{}, model["service_tiers"])
+ })
+ }
+
+ merged := intersectUpstreamModelMetadata("gpt-6-sol", []UpstreamModelMetadata{
+ {CodexToolCapabilities: map[string]json.RawMessage{"service_tiers": json.RawMessage(`[{"id":"priority"}]`)}},
+ {CodexToolCapabilities: map[string]json.RawMessage{"service_tiers": json.RawMessage(`[]`)}},
+ })
+ require.JSONEq(t, `[]`, string(merged.CodexToolCapabilities["service_tiers"]))
+}
+
func TestAstraCodexToolCapabilitiesPreserveLiveNullAndFalse(t *testing.T) {
account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
Credentials: map[string]any{"base_url": "https://api.openai.com/v1"}}
diff --git a/backend/internal/service/openai_codex_models_pinned.go b/backend/internal/service/openai_codex_models_pinned.go
index e8090d557..2953c33c4 100644
--- a/backend/internal/service/openai_codex_models_pinned.go
+++ b/backend/internal/service/openai_codex_models_pinned.go
@@ -8,6 +8,7 @@ import (
"fmt"
"log/slog"
"net/http"
+ "slices"
"strings"
"sync"
"time"
@@ -91,6 +92,13 @@ func mergeCodexModelsManifestBodies(bodies [][]byte) ([]byte, error) {
}
}
+ if len(bodies) == 1 {
+ _, original, err := modelCatalogEntries(bodies[0], "models")
+ if err == nil && slices.EqualFunc(original, mergedModels, func(a, b json.RawMessage) bool { return bytes.Equal(a, b) }) {
+ return bodies[0], nil
+ }
+ }
+
encodedModels, err := json.Marshal(mergedModels)
if err != nil {
return nil, fmt.Errorf("encode merged codex models: %w", err)
@@ -139,6 +147,9 @@ func (s *OpenAIGatewayService) FetchPinnedCodexModelsManifest(ctx context.Contex
if err != nil {
return nil, nil, fmt.Errorf("merge pinned codex models manifests: %w", err)
}
+ if len(results) == 1 && bytes.Equal(merged, results[0].response.Body) {
+ return results[0].response, results[0].account, nil
+ }
return &OpenAIModelsResponse{Body: merged, ETag: codexModelsManifestBodyETag(merged)}, results[0].account, nil
}
diff --git a/backend/internal/service/openai_codex_models_pinned_test.go b/backend/internal/service/openai_codex_models_pinned_test.go
index eee3100c7..3c389402f 100644
--- a/backend/internal/service/openai_codex_models_pinned_test.go
+++ b/backend/internal/service/openai_codex_models_pinned_test.go
@@ -63,11 +63,11 @@ func TestMergeCodexModelsManifestBodiesHandlesSluglessEntries(t *testing.T) {
}
func TestMergeCodexModelsManifestBodiesSingleBody(t *testing.T) {
- body := `{"models":[{"slug":"model-a"}]}`
+ body := `{ "unknown": true, "models": [ { "slug": "model-a" } ] }`
merged, err := mergeCodexModelsManifestBodies([][]byte{[]byte(body)})
require.NoError(t, err)
- require.JSONEq(t, body, string(merged))
+ require.Equal(t, body, string(merged))
}
func TestMergeCodexModelsManifestBodiesRejectsInvalidInput(t *testing.T) {
@@ -80,3 +80,9 @@ func TestMergeCodexModelsManifestBodiesRejectsInvalidInput(t *testing.T) {
_, err = mergeCodexModelsManifestBodies([][]byte{[]byte(`{}`), []byte(`{"models":{}`)})
require.Error(t, err, "models 非数组必须报错")
}
+
+func TestMergeCodexModelsManifestBodiesSingleBodyDeduplicates(t *testing.T) {
+ merged, err := mergeCodexModelsManifestBodies([][]byte{[]byte(`{"models":[{"slug":"a"},{"slug":"a","extra":true}]}`)})
+ require.NoError(t, err)
+ require.JSONEq(t, `{"models":[{"slug":"a"}]}`, string(merged))
+}
diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go
index d029524aa..a7e0f1889 100644
--- a/backend/internal/service/openai_codex_transform.go
+++ b/backend/internal/service/openai_codex_transform.go
@@ -93,6 +93,8 @@ type codexOAuthTransformOptions struct {
SkipDefaultInstructions bool
PreserveToolCallIDs bool
OmitPromotedSystemMessagesFromInput bool
+ // ResponsesLite selects where an injected hosted tool is declared.
+ ResponsesLite bool
}
const (
@@ -347,6 +349,12 @@ func applyCodexOAuthTransformWithOptions(reqBody map[string]any, opts codexOAuth
result.Modified = true
}
+ // Runs after input filtering so it sees the final replayed history. The
+ // compact endpoint has its own wire shape and is left untouched.
+ if !opts.IsCompact && ensureOpenAIOAuthWebSearchToolForHistory(reqBody, opts.ResponsesLite) {
+ result.Modified = true
+ }
+
return result
}
diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go
index b230353d4..54b5dd67d 100644
--- a/backend/internal/service/openai_gateway_chat_completions.go
+++ b/backend/internal/service/openai_gateway_chat_completions.go
@@ -110,85 +110,43 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
}
// Cursor compatibility: some clients send a Responses-shaped body to the
- // /v1/chat/completions URL. Detect it before adaptive routing so adaptive
+ // /v1/chat/completions URL. Detect it before protocol routing so adaptive
// accounts never forward the body unchanged to a Chat Completions endpoint.
isResponsesShape := !gjson.GetBytes(body, "messages").Exists() && gjson.GetBytes(body, "input").Exists()
-
- // OpenCode Go:按模型原生协议分流(与 inbound 协议正交)。
- // 规则未命中一律兜底 Chat Completions,只有显式 Responses 才走下方转换链。
- if account.IsOpenCodeGo() {
- mapped := resolveOpenCodeGoMappedModel(account, body, defaultMappedModel)
- proto := openCodeGoNativeProtocol(account, mapped)
- if proto != APIProtocolResponses {
- if isResponsesShape {
- if proto == APIProtocolAnthropic {
- return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "")
- }
- var responsesReq apicompat.ResponsesRequest
- if err := json.Unmarshal(body, &responsesReq); err != nil {
- return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err)
- }
- chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions(
- &responsesReq,
- &apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID},
- )
- if err != nil {
- return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err)
- }
- chatBody, err := json.Marshal(chatReq)
- if err != nil {
- return nil, fmt.Errorf("marshal converted chat completions request: %w", err)
- }
- return s.forwardAsRawChatCompletions(ctx, c, account, chatBody, defaultMappedModel)
- }
- if proto == APIProtocolAnthropic {
- return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel)
- }
- return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel)
- }
- }
-
- // 自适应账号的标准 Chat Completions 入站使用供应商原生 CC 端点。
- // Responses 形状下,DeepSeek / Kimi 继续走下方原生 Responses 链;GLM
- // 没有 Responses 端点,先转换成 Chat Completions 再直转。
- if account.IsAdaptiveAPIProtocol() && !account.IsOpenCodeGo() {
- if !isResponsesShape {
- return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel)
+ inbound := APIProtocolChatCompletions
+ if isResponsesShape {
+ inbound = APIProtocolResponses
+ }
+ // 按模型分流与 adaptive 账号按请求体形状处理 Responses 形状入站;其余账号
+ // 维持原样把请求体交给所选路径。
+ convertResponsesShape := isResponsesShape && (account.routesByModel() || account.IsAdaptiveAPIProtocol())
+
+ // 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。Anthropic 分流必须先于
+ // ShouldUseResponsesAPI:Anthropic 协议账号经 probe 落标
+ // openai_responses_supported=false,否则会命中 CC 直转。
+ routingModel := upstreamRoutingModel(account, body, defaultMappedModel)
+ if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) {
+ return nil, writeOpenCodeUnsupportedModelError(c, false, routingModel)
+ }
+ switch s.resolveUpstreamProtocolFor(ctx, account, inbound, routingModel) {
+ case APIProtocolAnthropic:
+ if convertResponsesShape {
+ return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "")
}
- if !account.SupportsNativeCNResponses() {
- var responsesReq apicompat.ResponsesRequest
- if err := json.Unmarshal(body, &responsesReq); err != nil {
- return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err)
- }
- chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions(
- &responsesReq,
- &apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID},
- )
- if err != nil {
- return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err)
- }
- chatBody, err := json.Marshal(chatReq)
+ // CC 入站经 CC→Responses→Anthropic 转换链直通供应商原生 Anthropic 端点。
+ return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel)
+ case APIProtocolChatCompletions:
+ if convertResponsesShape {
+ chatBody, err := s.convertResponsesShapedChatBody(body)
if err != nil {
- return nil, fmt.Errorf("marshal converted chat completions request: %w", err)
+ return nil, err
}
return s.forwardAsRawChatCompletions(ctx, c, account, chatBody, defaultMappedModel)
}
- // DeepSeek / Kimi 原生 Responses 请求继续走下方 Responses→Chat 回程转换。
- }
-
- // 入口分流(国产供应商 Anthropic 协议):上游为供应商原生 Anthropic 端点,
- // CC 入站请求经 CC→Responses→Anthropic 转换链直通该端点。必须先于
- // ShouldUseResponsesAPI 分流:该类账号经 probe 落标
- // openai_responses_supported=false,会先命中下方的 CC 直转分支。
- if account.IsAnthropicProtocol() {
- return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel)
- }
-
- // 固定 chat_completions 的 CN 账号,以及强制或已探测确认不支持 Responses
- // 的其他 APIKey 账号,均走 CC 直转。
- if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel)
}
+ // 上游为 Responses(含 adaptive 下 Responses 形状入站且供应商有原生
+ // Responses 端点):走下方 Chat Completions ↔ Responses 转换链。
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
startTime := time.Now()
@@ -421,7 +379,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
return s.forwardAsChatCompletions(markAgentIdentityTaskRecoveryTried(ctx), c, account, body, promptCacheKey, defaultMappedModel, compatPromptCacheTenantIsolated)
}
if account.Type == AccountTypeAPIKey &&
- !account.IsOpenCodeGo() &&
+ !account.routesByModel() &&
openai_compat.ResolveResponsesSupport(account.Extra) == openai_compat.ResponsesSupportUnknown &&
!isResponsesEndpointSupportedByStatus(resp.StatusCode) {
logger.L().Info("openai chat_completions: /responses unsupported, falling back to raw chat completions",
diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go
index d15688666..df2884807 100644
--- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go
+++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go
@@ -241,7 +241,7 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic(
}
if event.Type == "content_block_delta" && event.Delta != nil && finalResp != nil && event.Index != nil {
idx := *event.Index
- if idx < len(finalResp.Content) {
+ if idx >= 0 && idx < len(finalResp.Content) {
switch event.Delta.Type {
case "text_delta":
finalResp.Content[idx].Text += event.Delta.Text
diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go
index 4ae903cb3..c582cd966 100644
--- a/backend/internal/service/openai_gateway_count_tokens.go
+++ b/backend/internal/service/openai_gateway_count_tokens.go
@@ -150,7 +150,7 @@ func prepareNativeOpenAIInputTokensCountRequest(body []byte, account *Account) (
}
func shouldEstimateOpenAIInputTokensLocally(account *Account) bool {
- if account == nil || account.IsGrok() || account.IsCNProvider() || account.Type == AccountTypeUpstream {
+ if account == nil || account.IsGrok() || account.RoutesProtocolByInbound() || account.Type == AccountTypeUpstream {
return true
}
if account.Type != AccountTypeAPIKey {
@@ -264,14 +264,14 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic(
return fmt.Errorf("count_tokens: missing account")
}
- // 国产供应商与 OpenCode(全部协议,含 anthropic):一律本地估算,不发上游请求。
+ // 多协议 API Key 供应商(国产厂商与聚合平台,全部协议,含 anthropic):一律本地估算,不发上游请求。
// 依据(2026-08 核实):三家的 Anthropic 兼容层均未提供
// /v1/messages/count_tokens——DeepSeek 官方 anthropic_api 文档无此端点
// (且注明 anthropic-version 头被忽略),聚合网关 OpenModel 明确标注
// count_tokens 为 "Anthropic only",Kimi/智谱亦无任何文档承诺。转发上游
// 只会常态 404,且错误还会流入账号处置逻辑误伤整账号调度;Claude Code
// 高频调用此端点,本地 tiktoken 估算是与 Grok 一致的既有方案。
- if account.IsCNProvider() || account.IsOpenCodeGo() {
+ if account.IsMultiProtocolAPIKey() {
estimated, err := estimateAnthropicCountTokensLocally(body)
if err != nil {
writeAnthropicCountTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go
index 771125d33..751716a6c 100644
--- a/backend/internal/service/openai_gateway_forward.go
+++ b/backend/internal/service/openai_gateway_forward.go
@@ -163,24 +163,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
return s.forwardGrokResponses(ctx, c, account, body, originalModel, reqStream, startTime)
}
- if account.IsOpenCodeGo() {
- mapped := resolveOpenCodeGoMappedModel(account, body, "")
- switch openCodeGoNativeProtocol(account, mapped) {
- case APIProtocolAnthropic:
- return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "")
- case APIProtocolResponses:
- break
- default:
- return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body)
- }
- }
-
- // CN 供应商 anthropic 协议账号:/v1/responses 入站是交叉协议组合
- // (Responses 客户端 × Anthropic 上游),转成 Anthropic 请求走原生端点。
- // 不能落到下面的 raw-CC 分支——其 URL 构造会把 anthropic base 当 CC base 用。
- if account.IsAnthropicProtocol() {
- return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel)
- }
if account.IsOpenAIApiKey() {
if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil {
return nil, normalizeErr
@@ -199,7 +181,19 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
originalModel = reqModel
}
- if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
+ // 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。OpenAI API Key 账号只会落到
+ // Responses / Chat Completions,上面的归一化对两条路径都生效。
+ routingModel := upstreamRoutingModel(account, body, "")
+ if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) {
+ return nil, writeOpenCodeUnsupportedModelError(c, false, routingModel)
+ }
+ switch s.resolveUpstreamProtocolFor(ctx, account, APIProtocolResponses, routingModel) {
+ case APIProtocolAnthropic:
+ // Responses 客户端 × Anthropic 上游:转成 Anthropic 请求走原生端点。不能落到
+ // raw-CC 分支——其 URL 构造会把 anthropic base 当 CC base 用。
+ // 账号映射未命中时以去除首尾空白的请求模型兜底,计费名与上游模型名一致。
+ return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel)
+ case APIProtocolChatCompletions:
return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body)
}
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
@@ -518,6 +512,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
SkipDefaultInstructions: true,
PreserveToolCallIDs: true,
OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages,
+ ResponsesLite: responsesLite,
})
ensureCodexOAuthInstructionsField(decoded)
markDecodedModified()
@@ -526,6 +521,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
IsCodexCLI: isCodexCLI,
IsCompact: isCompactRequest,
OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages,
+ ResponsesLite: responsesLite,
})
}
if codexResult.Error != nil {
@@ -1117,7 +1113,12 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
}
respBody = s.redactAgentIdentitySensitiveBody(ctx, account, respBody)
resp.Body = io.NopCloser(bytes.NewReader(respBody))
- if !httpInvalidEncryptedContentRetryTried && resp.StatusCode == http.StatusBadRequest && upstreamCode == "invalid_encrypted_content" {
+ invalidEncryptedContentError := upstreamCode == "invalid_encrypted_content" ||
+ (upstreamCode == "thinking_signature_invalid" &&
+ strings.Contains(upstreamMsg, "The encrypted content") &&
+ strings.Contains(upstreamMsg, "could not be verified") &&
+ strings.Contains(upstreamMsg, "could not be decrypted or parsed"))
+ if !httpInvalidEncryptedContentRetryTried && resp.StatusCode == http.StatusBadRequest && invalidEncryptedContentError {
decoded, decodeErr := ensureReqBody()
if decodeErr != nil {
return nil, decodeErr
@@ -1351,14 +1352,15 @@ func shouldForwardOpenAIResponsesViaRawChatCompletions(account *Account) bool {
if account == nil || account.Type != AccountTypeAPIKey {
return false
}
- if account.IsOpenCodeGo() {
+ if account.routesByModel() {
// Model protocol_rules are the authority. Probe Extra must not collapse
// Grok/GPT/Muse into Chat Completions.
return false
}
- if account.IsCNProvider() {
- // CN 的显式协议配置优先于异步探针 Extra;adaptive 仅 DeepSeek / Kimi
- // 有原生 Responses,GLM 回退 Chat Completions。
+ if account.RoutesProtocolByInbound() {
+ // 按入站协议分流的供应商(国产厂商等):显式协议配置优先于异步探针
+ // Extra;adaptive 仅在供应商有原生 Responses 端点时直转,否则回退
+ // Chat Completions(如 GLM)。
switch account.GetAPIProtocol() {
case APIProtocolChatCompletions:
return true
diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go
index 5cd50dee0..b3baec5e9 100644
--- a/backend/internal/service/openai_gateway_grok.go
+++ b/backend/internal/service/openai_gateway_grok.go
@@ -1613,8 +1613,8 @@ func applyGrokCLIHeaders(headers http.Header) {
headers.Set("X-Grok-Client-Version", version)
headers.Set("x-grok-client-version", version)
headers.Set("x-grok-client-identifier", xai.CLIClientIdentifier)
- // Historical mode value expected by some unit tests / older CLI probes.
- headers.Set("X-Grok-Client-Mode", "interactive")
+ // 对齐官方 CLI 交互模式,网关请求与额度探测共用身份。
+ headers.Set("X-Grok-Client-Mode", xai.CLIClientMode)
}
func (s *OpenAIGatewayService) updateGrokUsageSnapshot(ctx context.Context, account *Account, snapshot *xai.QuotaSnapshot) {
diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go
index 030b38bab..48dc7b328 100644
--- a/backend/internal/service/openai_gateway_messages.go
+++ b/backend/internal/service/openai_gateway_messages.go
@@ -53,29 +53,21 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic(
return nil, err
}
- // OpenCode Go:按模型原生协议分流。规则未命中兜底 Chat Completions。
- if account.IsOpenCodeGo() {
- mapped := resolveOpenCodeGoMappedModel(account, body, defaultMappedModel)
- switch openCodeGoNativeProtocol(account, mapped) {
- case APIProtocolAnthropic:
- return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel)
- case APIProtocolResponses:
- break
- default:
- return s.forwardAnthropicViaRawChatCompletions(ctx, c, account, body, defaultMappedModel)
- }
- } else if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() {
- // 入口分流(国产供应商 Anthropic 协议):上游为供应商原生 Anthropic 端点时,
- // /v1/messages 请求零转换直通(仅模型名映射 + 少量 body 清洗),完整保留
- // thinking / tool_use / cache 语义,适配 Claude Code 等原生客户端。
- // 必须先于 ShouldUseResponsesAPI 分流:Anthropic 协议账号经 probe 落标
- // openai_responses_supported=false,会先命中下方的 CC 直转分支。
+ // 上游协议统一由 resolveUpstreamProtocol 判定(按模型分流时带上游模型目录)。Anthropic 分流必须先于
+ // ShouldUseResponsesAPI:Anthropic 协议账号经 probe 落标
+ // openai_responses_supported=false,否则会命中 CC 直转。
+ routingModel := upstreamRoutingModel(account, body, defaultMappedModel)
+ if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) {
+ return nil, writeOpenCodeUnsupportedModelError(c, true, routingModel)
+ }
+ switch s.resolveUpstreamProtocolFor(ctx, account, APIProtocolAnthropic, routingModel) {
+ case APIProtocolAnthropic:
+ // 上游为供应商原生 Anthropic 端点:/v1/messages 零转换直通(仅模型名映射 +
+ // 少量 body 清洗),完整保留 thinking / tool_use / cache 语义。
return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel)
- }
-
- // 固定 chat_completions 的 CN 账号,以及不支持 Responses 的其他 APIKey
- // 账号,均将 Messages 转为 CC;固定 responses 的 CN 账号不受探针旧值覆盖。
- if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
+ case APIProtocolChatCompletions:
+ // 固定 chat_completions 的多协议账号、规则命中 CC 的按模型分流账号,以及
+ // 不支持 Responses 的其他 APIKey 账号,均将 Messages 转为 CC。
return s.forwardAnthropicViaRawChatCompletions(ctx, c, account, body, defaultMappedModel)
}
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go
index 5270cc9c4..6caddacb4 100644
--- a/backend/internal/service/openai_gateway_messages_anthropic_native.go
+++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go
@@ -133,14 +133,20 @@ func (s *OpenAIGatewayService) nativeAnthropicTargetURL(account *Account) (strin
if err != nil {
return "", fmt.Errorf("invalid base_url: %w", err)
}
- if account.IsOpenCodeGo() {
- // OpenCode Go 的 Chat Completions base 带 /v1;用版本感知拼接避免 /v1/v1/messages。
- return buildOpenAIEndpointURL(validatedURL, "/v1/messages"), nil
+ return nativeAnthropicMessagesURL(account, validatedURL), nil
+}
+
+// nativeAnthropicMessagesURL 由已校验的 Anthropic 协议基址拼出 messages 端点,转发与
+// 连接测试共用。按模型分流的聚合平台(OpenCode、Command Code 等)的基址可能沿用带 /v1
+// 的 Chat Completions 基址,用版本感知拼接避免 /v1/v1/messages;其余供应商朴素拼接。
+func nativeAnthropicMessagesURL(account *Account, validatedBaseURL string) string {
+ if account.routesByModel() {
+ return buildOpenAIEndpointURL(validatedBaseURL, "/v1/messages")
}
- return strings.TrimRight(validatedURL, "/") + "/v1/messages", nil
+ return strings.TrimRight(validatedBaseURL, "/") + "/v1/messages"
}
-func resolveOpenCodeGoMappedModel(account *Account, body []byte, defaultMappedModel string) string {
+func resolveMappedUpstreamModel(account *Account, body []byte, defaultMappedModel string) string {
original := strings.TrimSpace(gjson.GetBytes(body, "model").String())
billing := resolveOpenAIForwardModel(account, original, defaultMappedModel)
return normalizeOpenAIModelForUpstream(account, billing)
diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go
index f345dc6f9..7217f633d 100644
--- a/backend/internal/service/openai_gateway_passthrough.go
+++ b/backend/internal/service/openai_gateway_passthrough.go
@@ -213,7 +213,10 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough(
}
if account != nil && account.IsOpenAI() {
responsesLite := isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) || isOpenAIResponsesLiteWebSocketPayload(body)
- normalizedBody, normalized, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBody(body, account, responsesLite)
+ normalizedBody, normalized, normalizeErr := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{
+ ResponsesLite: responsesLite,
+ Compact: isOpenAIResponsesCompactPath(c),
+ })
if normalizeErr != nil {
return nil, fmt.Errorf("normalize passthrough Responses compatibility: %w", normalizeErr)
}
diff --git a/backend/internal/service/openai_gateway_provider_claude_billing_test.go b/backend/internal/service/openai_gateway_provider_claude_billing_test.go
new file mode 100644
index 000000000..84f11bd3d
--- /dev/null
+++ b/backend/internal/service/openai_gateway_provider_claude_billing_test.go
@@ -0,0 +1,120 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestOpenAIGatewayServiceRecordUsage_AggregatorClaudeUsesDefaultPricing(t *testing.T) {
+ for _, platform := range []string{PlatformCommandCode, PlatformCline} {
+ for _, model := range []string{"claude-sonnet-4-6", "anthropic/claude-sonnet-4-6"} {
+ t.Run(platform+"/"+model, func(t *testing.T) {
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ userRepo := &openAIRecordUsageUserRepoStub{}
+ svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
+ svc.resolver = NewModelPricingResolver(nil, svc.billingService)
+ group := &Group{ID: 1, Platform: platform, RateMultiplier: 1.1}
+ usage := OpenAIUsage{InputTokens: 1000, OutputTokens: 200}
+ expected := expectedOpenAICost(t, svc, model, usage, group.RateMultiplier)
+ require.Greater(t, expected.ActualCost, 0.0)
+
+ err := svc.RecordUsage(context.Background(), providerClaudeRecordUsageInput(platform, model, group, usage))
+
+ require.NoError(t, err)
+ require.Equal(t, 1, usageRepo.calls)
+ require.NotNil(t, usageRepo.lastLog)
+ require.Equal(t, usage.InputTokens, usageRepo.lastLog.InputTokens)
+ require.Equal(t, usage.OutputTokens, usageRepo.lastLog.OutputTokens)
+ require.InDelta(t, expected.TotalCost, usageRepo.lastLog.TotalCost, 1e-12)
+ require.InDelta(t, expected.ActualCost, usageRepo.lastLog.ActualCost, 1e-12)
+ require.Equal(t, 1, userRepo.deductCalls)
+ require.InDelta(t, expected.ActualCost, userRepo.lastAmount, 1e-12)
+ })
+ }
+ }
+}
+
+func TestOpenAIGatewayServiceRecordUsage_CNAndOpenCodeClaudeRequireExplicitPricing(t *testing.T) {
+ for _, platform := range []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
+ t.Run(platform, func(t *testing.T) {
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ userRepo := &openAIRecordUsageUserRepoStub{}
+ svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
+ svc.resolver = NewModelPricingResolver(nil, svc.billingService)
+ group := &Group{ID: 1, Platform: platform, RateMultiplier: 1.1}
+ usage := OpenAIUsage{InputTokens: 1000, OutputTokens: 200}
+
+ err := svc.RecordUsage(context.Background(), providerClaudeRecordUsageInput(platform, "claude-sonnet-4-6", group, usage))
+
+ require.NoError(t, err)
+ require.Equal(t, 1, usageRepo.calls)
+ require.NotNil(t, usageRepo.lastLog)
+ require.Equal(t, usage.InputTokens, usageRepo.lastLog.InputTokens)
+ require.Equal(t, usage.OutputTokens, usageRepo.lastLog.OutputTokens)
+ require.Zero(t, usageRepo.lastLog.TotalCost)
+ require.Zero(t, usageRepo.lastLog.ActualCost)
+ require.Zero(t, userRepo.deductCalls)
+ })
+ }
+}
+
+func TestOpenAIGatewayServiceRecordUsage_CNAndOpenCodeClaudeHonorExplicitPricing(t *testing.T) {
+ const model = "claude-sonnet-4-6"
+ for _, platform := range []string{PlatformKimi, PlatformOpenCodeGo} {
+ for _, source := range []string{PricingSourceGroup, PricingSourceChannel} {
+ t.Run(platform+"/"+source, func(t *testing.T) {
+ usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
+ userRepo := &openAIRecordUsageUserRepoStub{}
+ svc := newOpenAIRecordUsageServiceForTest(usageRepo, userRepo, &openAIRecordUsageSubRepoStub{}, nil)
+ group := &Group{ID: 1, Platform: platform, RateMultiplier: 1.25}
+ inputPrice, outputPrice := 1e-6, 2e-6
+ pricing := ChannelModelPricing{
+ Models: []string{model}, BillingMode: BillingModeToken,
+ InputPrice: &inputPrice, OutputPrice: &outputPrice,
+ }
+ if source == PricingSourceGroup {
+ group.ModelPricing = []ChannelModelPricing{pricing}
+ } else {
+ cache := newEmptyChannelCache()
+ cache.pricingByGroupModel[channelModelKey{groupID: group.ID, platform: platform, model: model}] = &pricing
+ cache.channelByGroupID[group.ID] = &Channel{ID: 1, Status: StatusActive}
+ cache.groupPlatform[group.ID] = platform
+ cache.loadedAt = time.Now()
+ svc.channelService = &ChannelService{}
+ svc.channelService.cache.Store(cache)
+ }
+ svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService)
+ usage := OpenAIUsage{InputTokens: 1000, OutputTokens: 200}
+ expectedTotal := float64(usage.InputTokens)*inputPrice + float64(usage.OutputTokens)*outputPrice
+ expectedActual := expectedTotal * group.RateMultiplier
+
+ err := svc.RecordUsage(context.Background(), providerClaudeRecordUsageInput(platform, model, group, usage))
+
+ require.NoError(t, err)
+ require.NotNil(t, usageRepo.lastLog)
+ require.InDelta(t, expectedTotal, usageRepo.lastLog.TotalCost, 1e-12)
+ require.InDelta(t, expectedActual, usageRepo.lastLog.ActualCost, 1e-12)
+ require.Equal(t, 1, userRepo.deductCalls)
+ require.InDelta(t, expectedActual, userRepo.lastAmount, 1e-12)
+ })
+ }
+ }
+}
+
+func providerClaudeRecordUsageInput(platform, model string, group *Group, usage OpenAIUsage) *OpenAIRecordUsageInput {
+ return &OpenAIRecordUsageInput{
+ Result: &OpenAIForwardResult{
+ RequestID: "provider_claude_" + platform,
+ Model: model, BillingModel: model, UpstreamModel: model,
+ Usage: usage, Duration: time.Second,
+ },
+ APIKey: &APIKey{ID: 10, GroupID: &group.ID, Group: group},
+ User: &User{ID: 20},
+ Account: &Account{ID: 30, Platform: platform, Type: AccountTypeAPIKey},
+ }
+}
diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go
index 5f3ebeeef..cb0173442 100644
--- a/backend/internal/service/openai_gateway_request_body.go
+++ b/backend/internal/service/openai_gateway_request_body.go
@@ -53,11 +53,11 @@ func buildOpenAIResponsesURL(base string) string {
}
// buildOpenAIResponsesURLForPlatform 组装 Responses 端点(平台感知)。
-// DeepSeek 官方 Responses 端点为 /responses(无 /v1 前缀,适配 Codex);
-// 其余平台维持 /v1/responses。
+// 供应商 profile 声明了 ResponsesPath 时按其拼接(如 DeepSeek 为无 /v1 前缀的
+// /responses);其余平台维持 /v1/responses。
func buildOpenAIResponsesURLForPlatform(platform string, base string) string {
- if platform == PlatformDeepseek {
- return buildOpenAIEndpointURL(base, "/responses")
+ if profile := LookupProviderProfile(platform); profile != nil && profile.ResponsesPath != "" {
+ return buildOpenAIEndpointURL(base, profile.ResponsesPath)
}
return buildOpenAIResponsesURL(base)
}
@@ -1430,6 +1430,18 @@ func normalizeOpenAIResponseFormatSchemasBody(body []byte) ([]byte, bool, error)
}
func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Account, responsesLite bool) ([]byte, bool, error) {
+ return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{ResponsesLite: responsesLite})
+}
+
+type openAIResponsesCompatibilityOptions struct {
+ ResponsesLite bool
+ // Compact marks the /responses/compact wire shape, which is left as-is
+ // by request-shape compatibility rewrites such as web_search history.
+ Compact bool
+}
+
+func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account *Account, opts openAIResponsesCompatibilityOptions) ([]byte, bool, error) {
+ responsesLite := opts.ResponsesLite
if account == nil || !account.IsOpenAI() {
return body, false, nil
}
@@ -1494,6 +1506,14 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac
normalized = next
changed = true
}
+ if !opts.Compact {
+ webSearchBody, webSearchChanged, err := ensureOpenAIOAuthWebSearchToolForHistoryBody(normalized, responsesLite)
+ if err != nil {
+ return body, false, fmt.Errorf("normalize websocket body: %w", err)
+ }
+ normalized = webSearchBody
+ changed = changed || webSearchChanged
+ }
}
needsOrphanCleanup := account != nil && account.IsOpenAIOAuthLike() &&
gjson.GetBytes(normalized, "input").IsArray()
diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go
index 55382a492..c14793611 100644
--- a/backend/internal/service/openai_gateway_response_handling.go
+++ b/backend/internal/service/openai_gateway_response_handling.go
@@ -687,8 +687,12 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.
// OpenAI Responses streams that terminate with an empty
// response.completed (no output, no usage, no error, nothing sent
// to the client) are silent upstream refusals: fail over instead of
- // recording a successful 0/0 usage turn (issue #5009).
- if account != nil && account.Platform == PlatformOpenAI &&
+ // recording a successful 0/0 usage turn (issue #5009). Grok
+ // subscriptions behind vendor gateways show the same silent-refusal
+ // shape on /v1/responses (forwardGrokResponses reaches this same
+ // handler), so cover PlatformGrok too — the passthrough-path guard
+ // is already unconditional.
+ if account != nil && (account.Platform == PlatformOpenAI || account.Platform == PlatformGrok) &&
(eventType == "response.completed" || eventType == "response.done") &&
!sawFailedEvent && !responsesSemanticOutputSeen && !clientOutputStarted &&
openAIResponsesCompletedEventIsEmpty(dataBytes, usage) {
diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go
index 179b8d70a..dbb906ef8 100644
--- a/backend/internal/service/openai_gateway_responses_anthropic_native.go
+++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go
@@ -242,7 +242,7 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic(
}
if event.Type == "content_block_delta" && event.Delta != nil && finalResp != nil && event.Index != nil {
idx := *event.Index
- if idx < len(finalResp.Content) {
+ if idx >= 0 && idx < len(finalResp.Content) {
switch event.Delta.Type {
case "text_delta":
finalResp.Content[idx].Text += event.Delta.Text
diff --git a/backend/internal/service/openai_gateway_responses_empty_completed_test.go b/backend/internal/service/openai_gateway_responses_empty_completed_test.go
index 55bfda089..c5989136c 100644
--- a/backend/internal/service/openai_gateway_responses_empty_completed_test.go
+++ b/backend/internal/service/openai_gateway_responses_empty_completed_test.go
@@ -166,3 +166,71 @@ func TestOpenAIResponsesCompletedEventIsEmpty(t *testing.T) {
})
}
}
+
+// TestOpenAIResponsesEmptyCompletedFailsOverGrok verifies that Grok platform
+// accounts — which reach the stream relay through forwardGrokResponses instead
+// of the passthrough path — get the same #5009 silent-refusal failover for an
+// empty response.completed (issue #7774).
+func TestOpenAIResponsesEmptyCompletedFailsOverGrok(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ upstream := &httpUpstreamRecorder{resp: &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(
+ "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_grok\",\"object\":\"response\",\"status\":\"in_progress\"}}\n\n" +
+ "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_grok\",\"object\":\"response\",\"status\":\"completed\",\"output\":[]}}\n\n",
+ )),
+ }}
+ svc := newOpenAIImageGenerationControlTestService(upstream)
+ c, recorder := newOpenAIImageGenerationControlTestContext(true, "codex_cli_rs/0.144.1")
+ account := newOpenAIImageGenerationControlTestAccount()
+ account.Platform = PlatformGrok
+
+ body := []byte(`{
+ "model":"grok-4.7",
+ "stream":true,
+ "input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}]
+ }`)
+
+ _, err := svc.Forward(context.Background(), c, account, body)
+ require.Error(t, err)
+ var failoverErr *UpstreamFailoverError
+ require.True(t, errors.As(err, &failoverErr), "empty completed must produce UpstreamFailoverError, got: %v", err)
+ require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode)
+ require.Empty(t, recorder.Body.String(), "no empty success stream may reach the client")
+}
+
+// TestOpenAIResponsesEmptyCompletedWithOutputSucceedsGrok ensures normal Grok
+// streams with real semantic output still succeed.
+func TestOpenAIResponsesEmptyCompletedWithOutputSucceedsGrok(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ upstream := &httpUpstreamRecorder{resp: &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(
+ "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_grok_ok\",\"object\":\"response\",\"status\":\"in_progress\"}}\n\n" +
+ "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hello grok\"}\n\n" +
+ "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_grok_ok\",\"object\":\"response\",\"status\":\"completed\",\"usage\":{\"input_tokens\":11,\"output_tokens\":4,\"total_tokens\":15}}}\n\n",
+ )),
+ }}
+ svc := newOpenAIImageGenerationControlTestService(upstream)
+ c, recorder := newOpenAIImageGenerationControlTestContext(true, "codex_cli_rs/0.144.1")
+ account := newOpenAIImageGenerationControlTestAccount()
+ account.Platform = PlatformGrok
+
+ body := []byte(`{
+ "model":"grok-4.7",
+ "stream":true,
+ "input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}]
+ }`)
+
+ result, err := svc.Forward(context.Background(), c, account, body)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.Contains(t, recorder.Body.String(), "hello grok")
+ require.NotNil(t, result.Usage)
+ require.Equal(t, 11, result.Usage.InputTokens)
+ require.Equal(t, 4, result.Usage.OutputTokens)
+}
diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go
index 9b9ec2f2b..380186ddd 100644
--- a/backend/internal/service/openai_gateway_scheduling.go
+++ b/backend/internal/service/openai_gateway_scheduling.go
@@ -14,6 +14,7 @@ import (
"time"
"github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/openai"
"github.com/MACOS-DO/sub4api/internal/pkg/xai"
"github.com/gin-gonic/gin"
@@ -285,18 +286,16 @@ func (s *OpenAIGatewayService) SelectAccountForTokenCount(
)
}
-// NormalizeOpenAICompatiblePlatform 保留 grok 与国产 OpenAI 兼容供应商(kimi/zhipu/
-// deepseek)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配:
+// NormalizeOpenAICompatiblePlatform 保留走 OpenAI 网关的平台(openai、grok 与多协议
+// API Key 供应商,见平台清单)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配:
// kimi 分组请求只命中 kimi 账号,语义与 openai/grok 一致。
// (upstream 曾将本函数改为未导出 normalizeOpenAICompatiblePlatform,本分支的
// handler 调度入口仍需导出,保持导出名。)
func NormalizeOpenAICompatiblePlatform(platform string) string {
- switch platform {
- case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS:
+ if domain.UsesOpenAIGateway(platform) {
return platform
- default:
- return PlatformOpenAI
}
+ return PlatformOpenAI
}
// noAvailableOpenAISelectionError builds the standard "no account available" error
diff --git a/backend/internal/service/openai_gateway_service_hotpath_test.go b/backend/internal/service/openai_gateway_service_hotpath_test.go
index f4ac89f1b..48a3927ee 100644
--- a/backend/internal/service/openai_gateway_service_hotpath_test.go
+++ b/backend/internal/service/openai_gateway_service_hotpath_test.go
@@ -637,6 +637,70 @@ func TestOpenAIGatewayService_Forward_HTTPRetryRecoveryDropsCompaction(t *testin
require.False(t, gjson.GetBytes(upstream.bodies[1], "input.1").Exists())
}
+func TestOpenAIGatewayService_Forward_HTTPThinkingSignatureRecoveryAndLineage(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ response := func(status int, body string) *http.Response {
+ return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body))}
+ }
+ upstream := &httpUpstreamRecorder{responses: []*http.Response{
+ response(http.StatusBadRequest, `{"error":{"code":"thinking_signature_invalid","message":"The encrypted content abc could not be verified. Reason: Encrypted content could not be decrypted or parsed."}}`),
+ response(http.StatusOK, `{"id":"resp_recovered","usage":{"input_tokens":1,"output_tokens":2}}`),
+ response(http.StatusOK, `{"id":"resp_next","usage":{"input_tokens":1,"output_tokens":2}}`),
+ }}
+ cfg := &config.Config{}
+ cfg.Security.URLAllowlist.Enabled = false
+ svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream}
+ account := &Account{ID: 10, Name: "openai-apikey", Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
+ Concurrency: 1, Credentials: map[string]any{"api_key": "sk-test", "base_url": "https://example.com"},
+ Extra: map[string]any{"use_responses_api": true}}
+ newContext := func() *gin.Context {
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil)
+ SetOpenAIClientTransport(c, OpenAIClientTransportHTTP)
+ return c
+ }
+ input := `{"model":"gpt-5","stream":false,"prompt_cache_key":"issue-7700","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}],"input":[{"type":"reasoning","encrypted_content":"stale","summary":[{"type":"summary_text","text":"keep"}]},{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"}]},{"type":"function_call_output","call_id":"call_1","output":"result"}]}`
+ first, err := svc.Forward(context.Background(), newContext(), account, []byte(input))
+ require.NoError(t, err)
+ require.NotNil(t, first)
+ require.Len(t, upstream.bodies, 2)
+ require.Equal(t, "stale", gjson.GetBytes(upstream.bodies[0], "input.0.encrypted_content").String())
+ require.False(t, gjson.GetBytes(upstream.bodies[1], "input.0.encrypted_content").Exists())
+ require.Equal(t, "keep", gjson.GetBytes(upstream.bodies[1], "input.0.summary.0.text").String())
+ require.Equal(t, "hello", gjson.GetBytes(upstream.bodies[1], "input.1.content.0.text").String())
+ require.Equal(t, "result", gjson.GetBytes(upstream.bodies[1], "input.2.output").String())
+ require.Equal(t, "lookup", gjson.GetBytes(upstream.bodies[1], "tools.0.name").String())
+
+ second, err := svc.Forward(context.Background(), newContext(), account, []byte(input))
+ require.NoError(t, err)
+ require.NotNil(t, second)
+ require.Len(t, upstream.bodies, 3, "later turn should be stripped before its first upstream request")
+ require.False(t, gjson.GetBytes(upstream.bodies[2], "input.0.encrypted_content").Exists())
+ require.Equal(t, "result", gjson.GetBytes(upstream.bodies[2], "input.2.output").String())
+}
+
+func TestOpenAIGatewayService_Forward_HTTPThinkingSignatureDoesNotRetryUnrelatedErrors(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, tc := range []struct{ name, code, message, input string }{
+ {"no encrypted reasoning", "thinking_signature_invalid", "The encrypted content could not be verified. Reason: Encrypted content could not be decrypted or parsed.", `[{"type":"message","role":"user","content":"hello"}]`},
+ {"ordinary 400", "invalid_request_error", "bad request", `[{"type":"reasoning","encrypted_content":"stale"},{"type":"message","content":"hello"}]`},
+ {"unrelated signature error", "thinking_signature_invalid", "Invalid signature", `[{"type":"reasoning","encrypted_content":"stale"},{"type":"message","content":"hello"}]`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"` + tc.code + `","message":"` + tc.message + `"}}`))}}
+ cfg := &config.Config{}
+ cfg.Security.URLAllowlist.Enabled = false
+ svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream}
+ account := &Account{ID: 10, Name: "openai-apikey", Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Concurrency: 1, Credentials: map[string]any{"api_key": "sk-test", "base_url": "https://example.com"}, Extra: map[string]any{"use_responses_api": true}}
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil)
+ SetOpenAIClientTransport(c, OpenAIClientTransportHTTP)
+ _, _ = svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5","stream":false,"input":`+tc.input+`}`))
+ require.Len(t, upstream.bodies, 1)
+ })
+ }
+}
+
func TestOpenAIGatewayService_Forward_CodexSparkRejectsEscapedInputImage(t *testing.T) {
gin.SetMode(gin.TestMode)
upstream := &httpUpstreamRecorder{
diff --git a/backend/internal/service/openai_models_list.go b/backend/internal/service/openai_models_list.go
index baf398768..634d65937 100644
--- a/backend/internal/service/openai_models_list.go
+++ b/backend/internal/service/openai_models_list.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"net/http"
+ "slices"
"sort"
"strings"
@@ -229,6 +230,10 @@ func projectAccountModelsBody(body []byte, account *Account, group *Group, codex
continue
}
seen[id] = struct{}{}
+ if id == target {
+ projected = append(projected, raw)
+ continue
+ }
var entry map[string]json.RawMessage
if err := json.Unmarshal(raw, &entry); err != nil {
return nil, err
@@ -243,6 +248,9 @@ func projectAccountModelsBody(body []byte, account *Account, group *Group, codex
}
projected = append(projected, encoded)
}
+ if slices.EqualFunc(entries, projected, func(a, b json.RawMessage) bool { return bytes.Equal(a, b) }) {
+ return body, nil
+ }
envelope[field], err = json.Marshal(projected)
if err != nil {
return nil, err
@@ -250,18 +258,21 @@ func projectAccountModelsBody(body []byte, account *Account, group *Group, codex
return json.Marshal(envelope)
}
-// ApplyPinnedCodexModelsMapping is used by pinned discovery and its scheduler
-// fallback. The ordinary (non-pinned) Codex path retains its local catalog policy.
+// ApplyPinnedCodexModelsMapping projects all remotely discovered Codex catalogs,
+// including ordinary discovery and pinned scheduler fallback. Locally generated
+// catalogs retain their existing policy and do not pass through this function.
func ApplyPinnedCodexModelsMapping(response *OpenAIModelsResponse, account *Account, group *Group) error {
- if group == nil || group.Platform != PlatformOpenAI || !group.CodexModelsManifestConfig.Enabled {
+ if group == nil || group.Platform != PlatformOpenAI {
return nil
}
body, err := projectAccountModelsBody(response.Body, account, group, true)
if err != nil {
return err
}
- response.Body = body
- response.ETag = codexModelsManifestBodyETag(body)
+ if !bytes.Equal(response.Body, body) {
+ response.Body = body
+ response.ETag = codexModelsManifestBodyETag(body)
+ }
return nil
}
diff --git a/backend/internal/service/openai_models_list_test.go b/backend/internal/service/openai_models_list_test.go
index bbf046e5d..9fe1d706c 100644
--- a/backend/internal/service/openai_models_list_test.go
+++ b/backend/internal/service/openai_models_list_test.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"encoding/json"
+ "fmt"
"io"
"net/http"
"strings"
@@ -346,3 +347,18 @@ func TestOpenAIModelsCacheSeparatesRepresentationsForIdenticalRequests(t *testin
require.JSONEq(t, manifestBody, string(manifest.Body))
require.EqualValues(t, 2, calls.Load())
}
+
+func TestApplyCodexModelsMappingPreservesUnchangedBodyAndETag(t *testing.T) {
+ for _, pinned := range []bool{false, true} {
+ t.Run(fmt.Sprint(pinned), func(t *testing.T) {
+ account := newCodexModelsAPIKeyTestAccount("https://models.example/v1")
+ account.Credentials["model_mapping"] = map[string]any{"gpt-5.4": "gpt-5.4"}
+ body := []byte(`{ "unknown": { "keep": true }, "models": [ { "slug": "gpt-5.4", "custom": 123 } ] }`)
+ response := &OpenAIModelsResponse{Body: body, ETag: `W/"upstream-validator"`}
+ group := &Group{Platform: PlatformOpenAI, CodexModelsManifestConfig: GroupCodexModelsManifestConfig{Enabled: pinned}}
+ require.NoError(t, ApplyPinnedCodexModelsMapping(response, account, group))
+ require.Equal(t, body, response.Body)
+ require.Equal(t, `W/"upstream-validator"`, response.ETag)
+ })
+ }
+}
diff --git a/backend/internal/service/openai_oauth_web_search_history.go b/backend/internal/service/openai_oauth_web_search_history.go
new file mode 100644
index 000000000..6a68eb719
--- /dev/null
+++ b/backend/internal/service/openai_oauth_web_search_history.go
@@ -0,0 +1,264 @@
+package service
+
+import (
+ "bytes"
+ "fmt"
+ "strings"
+
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+// The ChatGPT internal Codex endpoint rejects a request whose input replays a
+// hosted web_search_call item unless the request also declares the web_search
+// tool; the stream then fails with "response protection is unavailable".
+// Codex's local context compaction sends the full history with tools:[], so
+// every compaction after a web search fails (#7927).
+//
+// Declare a cached-only web_search tool for such requests. Responses Lite
+// rejects hosted tools at the top level, so Lite requests carry it in an
+// input additional_tools item instead. When the caller declared no tools at
+// all, also pin tool_choice to "none" so the injected tool cannot be invoked
+// and the request keeps its no-tools semantics.
+
+const (
+ openAIWebSearchCallItemType = "web_search_call"
+ openAIAdditionalToolsItemType = "additional_tools"
+ openAICompactionTriggerItemType = "compaction_trigger"
+ openAIAdditionalToolsDefaultRole = "developer"
+)
+
+var openAIWebSearchHistoryTool = map[string]any{
+ "type": "web_search",
+ "external_web_access": false,
+}
+
+func isOpenAIWebSearchToolType(toolType string) bool {
+ return strings.HasPrefix(strings.TrimSpace(toolType), "web_search")
+}
+
+func openAIToolsContainWebSearch(rawTools any) bool {
+ tools, ok := rawTools.([]any)
+ if !ok {
+ return false
+ }
+ for _, rawTool := range tools {
+ tool, ok := rawTool.(map[string]any)
+ if ok && isOpenAIWebSearchToolType(firstNonEmptyString(tool["type"])) {
+ return true
+ }
+ }
+ return false
+}
+
+// shouldPinOpenAIWebSearchHistoryToolChoice reports whether tool_choice may be
+// forced to "none": only when the caller offered no tools, so the choice
+// cannot meaningfully be anything else.
+func shouldPinOpenAIWebSearchHistoryToolChoice(choice any) bool {
+ switch typed := choice.(type) {
+ case nil:
+ return true
+ case string:
+ normalized := strings.ToLower(strings.TrimSpace(typed))
+ return normalized == "" || normalized == "auto" || normalized == "none"
+ default:
+ return false
+ }
+}
+
+// openAIAdditionalToolsInsertIndex keeps a trailing compaction trigger last,
+// as required by the remote compaction v2 wire format.
+func openAIAdditionalToolsInsertIndex(itemTypes []string) int {
+ if n := len(itemTypes); n > 0 && itemTypes[n-1] == openAICompactionTriggerItemType {
+ return n - 1
+ }
+ return len(itemTypes)
+}
+
+// ensureOpenAIOAuthWebSearchToolForHistory is the map variant used by the
+// Codex OAuth transform.
+func ensureOpenAIOAuthWebSearchToolForHistory(reqBody map[string]any, responsesLite bool) bool {
+ if reqBody == nil {
+ return false
+ }
+ input, ok := reqBody["input"].([]any)
+ if !ok {
+ return false
+ }
+ hasWebSearchCall := false
+ callerDeclaredTools := false
+ additionalToolsIndex := -1
+ itemTypes := make([]string, len(input))
+ for i, rawItem := range input {
+ item, ok := rawItem.(map[string]any)
+ if !ok {
+ continue
+ }
+ itemTypes[i] = strings.TrimSpace(firstNonEmptyString(item["type"]))
+ switch itemTypes[i] {
+ case openAIWebSearchCallItemType:
+ hasWebSearchCall = true
+ case openAIAdditionalToolsItemType:
+ if openAIToolsContainWebSearch(item["tools"]) {
+ return false
+ }
+ if tools, _ := item["tools"].([]any); len(tools) > 0 {
+ callerDeclaredTools = true
+ }
+ if additionalToolsIndex < 0 {
+ additionalToolsIndex = i
+ }
+ }
+ }
+ if !hasWebSearchCall || openAIToolsContainWebSearch(reqBody["tools"]) {
+ return false
+ }
+ tools, _ := reqBody["tools"].([]any)
+ callerDeclaredTools = callerDeclaredTools || len(tools) > 0
+
+ switch {
+ case !responsesLite:
+ reqBody["tools"] = append(tools, cloneOpenAIWebSearchHistoryTool())
+ case additionalToolsIndex >= 0:
+ // additionalToolsIndex is only recorded for map items.
+ item, _ := input[additionalToolsIndex].(map[string]any)
+ existing, _ := item["tools"].([]any)
+ item["tools"] = append(existing, cloneOpenAIWebSearchHistoryTool())
+ default:
+ at := openAIAdditionalToolsInsertIndex(itemTypes)
+ additional := map[string]any{
+ "type": openAIAdditionalToolsItemType,
+ "role": openAIAdditionalToolsDefaultRole,
+ "tools": []any{cloneOpenAIWebSearchHistoryTool()},
+ }
+ next := make([]any, 0, len(input)+1)
+ next = append(next, input[:at]...)
+ next = append(next, additional)
+ next = append(next, input[at:]...)
+ reqBody["input"] = next
+ }
+ if !callerDeclaredTools {
+ if choice, exists := reqBody["tool_choice"]; !exists || shouldPinOpenAIWebSearchHistoryToolChoice(choice) {
+ reqBody["tool_choice"] = "none"
+ }
+ }
+ return true
+}
+
+// ensureOpenAIOAuthWebSearchToolForHistoryBody is the raw-body variant used by
+// the passthrough and WebSocket paths; it avoids decoding the whole body.
+func ensureOpenAIOAuthWebSearchToolForHistoryBody(body []byte, responsesLite bool) ([]byte, bool, error) {
+ if len(body) == 0 || !bytes.Contains(body, []byte(openAIWebSearchCallItemType)) {
+ return body, false, nil
+ }
+ input := gjson.GetBytes(body, "input")
+ if !input.IsArray() {
+ return body, false, nil
+ }
+ items := input.Array()
+ hasWebSearchCall := false
+ callerDeclaredTools := false
+ additionalToolsIndex := -1
+ itemTypes := make([]string, len(items))
+ for i, item := range items {
+ itemTypes[i] = strings.TrimSpace(item.Get("type").String())
+ switch itemTypes[i] {
+ case openAIWebSearchCallItemType:
+ hasWebSearchCall = true
+ case openAIAdditionalToolsItemType:
+ itemTools := item.Get("tools")
+ if gjsonToolsContainWebSearch(itemTools) {
+ return body, false, nil
+ }
+ if itemTools.IsArray() && len(itemTools.Array()) > 0 {
+ callerDeclaredTools = true
+ }
+ if additionalToolsIndex < 0 {
+ additionalToolsIndex = i
+ }
+ }
+ }
+ if !hasWebSearchCall {
+ return body, false, nil
+ }
+ tools := gjson.GetBytes(body, "tools")
+ if gjsonToolsContainWebSearch(tools) {
+ return body, false, nil
+ }
+ topLevelTools := tools.IsArray() && len(tools.Array()) > 0
+ callerDeclaredTools = callerDeclaredTools || topLevelTools
+
+ var (
+ next []byte
+ err error
+ )
+ switch {
+ case !responsesLite && topLevelTools:
+ next, err = sjson.SetBytes(body, "tools.-1", cloneOpenAIWebSearchHistoryTool())
+ case !responsesLite:
+ next, err = sjson.SetBytes(body, "tools", []any{cloneOpenAIWebSearchHistoryTool()})
+ case additionalToolsIndex >= 0 && items[additionalToolsIndex].Get("tools").IsArray():
+ next, err = sjson.SetBytes(body, fmt.Sprintf("input.%d.tools.-1", additionalToolsIndex), cloneOpenAIWebSearchHistoryTool())
+ case additionalToolsIndex >= 0:
+ next, err = sjson.SetBytes(body, fmt.Sprintf("input.%d.tools", additionalToolsIndex), []any{cloneOpenAIWebSearchHistoryTool()})
+ default:
+ next, err = insertOpenAIAdditionalToolsItemRaw(body, items, openAIAdditionalToolsInsertIndex(itemTypes))
+ }
+ if err != nil {
+ return body, false, fmt.Errorf("declare web_search tool for web_search_call history: %w", err)
+ }
+ if !callerDeclaredTools {
+ choice := gjson.GetBytes(next, "tool_choice")
+ if !choice.Exists() || choice.Type == gjson.Null || (choice.Type == gjson.String && shouldPinOpenAIWebSearchHistoryToolChoice(choice.String())) {
+ next, err = sjson.SetBytes(next, "tool_choice", "none")
+ if err != nil {
+ return body, false, fmt.Errorf("pin tool_choice for web_search_call history: %w", err)
+ }
+ }
+ }
+ return next, true, nil
+}
+
+func insertOpenAIAdditionalToolsItemRaw(body []byte, items []gjson.Result, at int) ([]byte, error) {
+ additional, err := marshalOpenAIUpstreamJSON(map[string]any{
+ "type": openAIAdditionalToolsItemType,
+ "role": openAIAdditionalToolsDefaultRole,
+ "tools": []any{cloneOpenAIWebSearchHistoryTool()},
+ })
+ if err != nil {
+ return nil, err
+ }
+ rawItems := make([][]byte, 0, len(items)+1)
+ for i, item := range items {
+ if i == at {
+ rawItems = append(rawItems, additional)
+ }
+ rawItems = append(rawItems, []byte(item.Raw))
+ }
+ if at >= len(items) {
+ rawItems = append(rawItems, additional)
+ }
+ raw := append([]byte{'['}, bytes.Join(rawItems, []byte{','})...)
+ raw = append(raw, ']')
+ return sjson.SetRawBytes(body, "input", raw)
+}
+
+func gjsonToolsContainWebSearch(tools gjson.Result) bool {
+ if !tools.IsArray() {
+ return false
+ }
+ for _, tool := range tools.Array() {
+ if isOpenAIWebSearchToolType(tool.Get("type").String()) {
+ return true
+ }
+ }
+ return false
+}
+
+func cloneOpenAIWebSearchHistoryTool() map[string]any {
+ tool := make(map[string]any, len(openAIWebSearchHistoryTool))
+ for key, value := range openAIWebSearchHistoryTool {
+ tool[key] = value
+ }
+ return tool
+}
diff --git a/backend/internal/service/openai_oauth_web_search_history_forward_test.go b/backend/internal/service/openai_oauth_web_search_history_forward_test.go
new file mode 100644
index 000000000..9735f179c
--- /dev/null
+++ b/backend/internal/service/openai_oauth_web_search_history_forward_test.go
@@ -0,0 +1,71 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+// TestForward_OAuthWebSearchHistoryDeclaresTool drives the Codex compaction
+// shape (web_search_call history, tools:[]) through Forward and asserts the
+// body reaching chatgpt.com declares web_search (#7927): top-level for the
+// standard wire, input additional_tools for Responses Lite.
+func TestForward_OAuthWebSearchHistoryDeclaresTool(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ passthrough bool
+ lite bool
+ }{
+ {"transform", false, false},
+ {"passthrough", true, false},
+ {"transform lite", false, true},
+ {"passthrough lite", true, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ s := newAstraOAuthSetup(t, tc.passthrough)
+ if tc.lite {
+ s.c.Request.Header.Set(responsesLiteHeader, "true")
+ }
+ inner := `{"id":"resp_test","model":"gpt-5.5","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}`
+ s.upstream.resp = &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader(codexCompletedSSE(inner))),
+ }
+ body, err := sjson.SetRawBytes([]byte(openAIWebSearchHistoryCompactionBody), "input.-1", []byte(`{"type":"compaction_trigger"}`))
+ require.NoError(t, err)
+
+ result, err := s.svc.Forward(context.Background(), s.c, s.account, body)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.NotNil(t, s.upstream.lastReq)
+ require.Equal(t, astraProCodexResponsesURL, s.upstream.lastReq.URL.String())
+
+ forwarded := s.upstream.lastBody
+ require.Equal(t, "web_search_call", gjson.GetBytes(forwarded, "input.1.type").String())
+ require.Equal(t, "none", gjson.GetBytes(forwarded, "tool_choice").String())
+ items := gjson.GetBytes(forwarded, "input").Array()
+ require.Equal(t, "compaction_trigger", items[len(items)-1].Get("type").String())
+ if !tc.lite {
+ tools := gjson.GetBytes(forwarded, "tools").Array()
+ require.Len(t, tools, 1)
+ require.Equal(t, "web_search", tools[0].Get("type").String())
+ return
+ }
+ require.False(t, gjsonToolsContainWebSearch(gjson.GetBytes(forwarded, "tools")))
+ additional := items[len(items)-2]
+ require.Equal(t, "additional_tools", additional.Get("type").String())
+ require.Equal(t, "web_search", additional.Get("tools.0.type").String())
+ })
+ }
+}
diff --git a/backend/internal/service/openai_oauth_web_search_history_test.go b/backend/internal/service/openai_oauth_web_search_history_test.go
new file mode 100644
index 000000000..19b7ef0cf
--- /dev/null
+++ b/backend/internal/service/openai_oauth_web_search_history_test.go
@@ -0,0 +1,152 @@
+package service
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// Codex local compaction replays hosted web_search_call history with tools:[];
+// ChatGPT then fails with "response protection is unavailable" (#7927).
+const openAIWebSearchHistoryCompactionBody = `{"model":"gpt-5.5","instructions":"x","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"look it up"}]},{"type":"web_search_call","id":"ws_123","status":"completed","action":{"type":"search","query":"kwin inputmethod"}},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"found"}]},{"type":"message","role":"user","content":[{"type":"input_text","text":"summarize"}]}],"tools":[],"tool_choice":"auto","parallel_tool_calls":false,"stream":true,"store":false}`
+
+func TestOAuthWebSearchHistoryToolAcrossPaths(t *testing.T) {
+ oauth := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}
+ transform := func(compact bool) func([]byte) ([]byte, bool, error) {
+ return func(b []byte) ([]byte, bool, error) {
+ var req map[string]any
+ if err := json.Unmarshal(b, &req); err != nil {
+ return nil, false, err
+ }
+ result := applyCodexOAuthTransform(req, true, compact)
+ out, err := json.Marshal(req)
+ return out, result.Modified, err
+ }
+ }
+ tests := []struct {
+ name string
+ normalize func([]byte) ([]byte, bool, error)
+ inject bool
+ }{
+ {"transformed OAuth", transform(false), true},
+ {"transformed OAuth compact", transform(true), false},
+ {"OAuth websocket", func(b []byte) ([]byte, bool, error) {
+ return normalizeOpenAIResponsesWebSocketCompatibilityBody(b, oauth, false)
+ }, true},
+ {"OAuth passthrough compact", func(b []byte) ([]byte, bool, error) {
+ return normalizeOpenAIResponsesCompatibilityBodyWithOptions(b, oauth, openAIResponsesCompatibilityOptions{Compact: true})
+ }, false},
+ {"API key websocket", func(b []byte) ([]byte, bool, error) {
+ return normalizeOpenAIResponsesWebSocketCompatibilityBody(b, &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, false)
+ }, false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ out, _, err := tt.normalize([]byte(openAIWebSearchHistoryCompactionBody))
+ require.NoError(t, err)
+ require.Equal(t, "web_search_call", gjson.GetBytes(out, "input.1.type").String())
+ if !tt.inject {
+ require.False(t, gjsonToolsContainWebSearch(gjson.GetBytes(out, "tools")))
+ return
+ }
+ tools := gjson.GetBytes(out, "tools").Array()
+ require.Len(t, tools, 1)
+ require.Equal(t, "web_search", tools[0].Get("type").String())
+ require.False(t, tools[0].Get("external_web_access").Bool())
+ require.True(t, tools[0].Get("external_web_access").Exists())
+ require.Equal(t, "none", gjson.GetBytes(out, "tool_choice").String())
+ })
+ }
+}
+
+func TestEnsureOpenAIOAuthWebSearchToolForHistory(t *testing.T) {
+ const (
+ user = `{"type":"message","role":"user","content":[{"type":"input_text","text":"q"}]}`
+ search = `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q"}}`
+ trigger = `{"type":"compaction_trigger"}`
+ history = `[` + user + `,` + search + `]`
+ )
+ tests := []struct {
+ name string
+ body string
+ lite bool
+ changed bool
+ toolsPath string
+ toolCount int
+ toolChoice string
+ itemTypes []string
+ }{
+ {"tools absent", `{"input":` + history + `}`, false, true, "tools", 1, "none", nil},
+ {"tools null", `{"input":` + history + `,"tools":null,"tool_choice":null}`, false, true, "tools", 1, "none", nil},
+ {"explicit none kept", `{"input":` + history + `,"tools":[],"tool_choice":"none"}`, false, true, "tools", 1, "none", nil},
+ {"required not rewritten", `{"input":` + history + `,"tools":[],"tool_choice":"required"}`, false, true, "tools", 1, "required", nil},
+ {"caller tools keep choice", `{"input":` + history + `,"tools":[{"type":"function","name":"echo"}],"tool_choice":"auto"}`, false, true, "tools", 2, "auto", nil},
+ {"web_search already declared", `{"input":` + history + `,"tools":[{"type":"web_search"}]}`, false, false, "", 0, "", nil},
+ {"web_search_preview declared", `{"input":` + history + `,"tools":[{"type":"web_search_preview"}]}`, false, false, "", 0, "", nil},
+ {"declared via additional_tools", `{"input":[{"type":"additional_tools","tools":[{"type":"web_search"}]},` + search + `]}`, false, false, "", 0, "", nil},
+ {"no web_search_call item", `{"input":[{"type":"message","role":"user","content":"web_search_call"}],"tools":[]}`, false, false, "", 0, "", nil},
+ {"string input", `{"input":"web_search_call"}`, false, false, "", 0, "", nil},
+ {"lite inserts before compaction trigger", `{"input":[` + user + `,` + search + `,` + trigger + `]}`, true, true, "input.2.tools", 1, "none",
+ []string{"message", "web_search_call", "additional_tools", "compaction_trigger"}},
+ {"lite appends without trigger", `{"input":` + history + `,"tool_choice":"auto"}`, true, true, "input.2.tools", 1, "none",
+ []string{"message", "web_search_call", "additional_tools"}},
+ {"lite extends caller additional_tools", `{"input":[{"type":"additional_tools","role":"developer","tools":[{"type":"function","name":"echo"}]},` + search + `,` + trigger + `],"tool_choice":"auto"}`, true, true, "input.0.tools", 2, "auto",
+ []string{"additional_tools", "web_search_call", "compaction_trigger"}},
+ {"lite fills empty additional_tools", `{"input":[{"type":"additional_tools","role":"developer"},` + search + `]}`, true, true, "input.0.tools", 1, "none",
+ []string{"additional_tools", "web_search_call"}},
+ {"lite keeps top-level tools untouched", `{"input":` + history + `,"tools":[{"type":"function","name":"echo"}]}`, true, true, "input.2.tools", 1, "",
+ []string{"message", "web_search_call", "additional_tools"}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ out, changed, err := ensureOpenAIOAuthWebSearchToolForHistoryBody([]byte(tt.body), tt.lite)
+ require.NoError(t, err)
+ require.Equal(t, tt.changed, changed)
+ var req map[string]any
+ require.NoError(t, json.Unmarshal([]byte(tt.body), &req))
+ require.Equal(t, tt.changed, ensureOpenAIOAuthWebSearchToolForHistory(req, tt.lite))
+ if !tt.changed {
+ require.JSONEq(t, tt.body, string(out))
+ return
+ }
+ require.True(t, gjson.ValidBytes(out))
+ tools := gjson.GetBytes(out, tt.toolsPath).Array()
+ require.Len(t, tools, tt.toolCount)
+ require.Equal(t, "web_search", tools[len(tools)-1].Get("type").String())
+ require.Equal(t, tt.toolChoice, gjson.GetBytes(out, "tool_choice").String())
+ if tt.lite {
+ require.False(t, gjsonToolsContainWebSearch(gjson.GetBytes(out, "tools")), "Lite rejects top-level hosted tools")
+ var types []string
+ for _, item := range gjson.GetBytes(out, "input").Array() {
+ types = append(types, item.Get("type").String())
+ }
+ require.Equal(t, tt.itemTypes, types)
+ }
+
+ // The map variant used by the Codex transform must agree.
+ mapOut, err := json.Marshal(req)
+ require.NoError(t, err)
+ require.JSONEq(t, string(out), string(mapOut))
+ })
+ }
+}
+
+func TestEnsureOpenAIOAuthWebSearchToolForHistoryDoesNotShareToolMap(t *testing.T) {
+ first := map[string]any{"input": []any{map[string]any{"type": "web_search_call"}}}
+ second := map[string]any{"input": []any{map[string]any{"type": "web_search_call"}}}
+ require.True(t, ensureOpenAIOAuthWebSearchToolForHistory(first, false))
+ require.True(t, ensureOpenAIOAuthWebSearchToolForHistory(second, false))
+ firstTools, ok := first["tools"].([]any)
+ require.True(t, ok)
+ firstTool, ok := firstTools[0].(map[string]any)
+ require.True(t, ok)
+ firstTool["external_web_access"] = true
+ secondTools, ok := second["tools"].([]any)
+ require.True(t, ok)
+ secondTool, ok := secondTools[0].(map[string]any)
+ require.True(t, ok)
+ require.Equal(t, false, secondTool["external_web_access"])
+ require.Equal(t, false, openAIWebSearchHistoryTool["external_web_access"])
+}
diff --git a/backend/internal/service/openai_responses_namespace.go b/backend/internal/service/openai_responses_namespace.go
index 2cf2a18ab..1b32cb81b 100644
--- a/backend/internal/service/openai_responses_namespace.go
+++ b/backend/internal/service/openai_responses_namespace.go
@@ -202,37 +202,39 @@ func stripOpenAIResponsesInputNamespaces(body []byte, keepToolCallNamespaces boo
}
var rebuilt bytes.Buffer
- rebuilt.Grow(len(input.Raw))
- _ = rebuilt.WriteByte('[')
changed := false
- first := true
+ // Offsets below are relative to input.Raw, not the full request body.
+ copyFrom := 0
var stripErr error
input.ForEach(func(_, item gjson.Result) bool {
- if !first {
- _ = rebuilt.WriteByte(',')
+ if !item.IsObject() || !item.Get("namespace").Exists() ||
+ (keepToolCallNamespaces && isOpenAIResponsesToolCallItemType(item.Get("type").String())) {
+ return true
}
- first = false
- itemBody := []byte(item.Raw)
- // 先判存在再判类型:长历史里绝大多数是 message/reasoning 等不带 namespace
- // 的项,这样它们无需再扫一次 type。
- if item.IsObject() && item.Get("namespace").Exists() &&
- (!keepToolCallNamespaces || !isOpenAIResponsesToolCallItemType(item.Get("type").String())) {
- itemBody, stripErr = sjson.DeleteBytes(itemBody, "namespace")
- if stripErr != nil {
- return false
- }
+ itemBody, err := sjson.DeleteBytes([]byte(item.Raw), "namespace")
+ if err != nil {
+ stripErr = err
+ return false
+ }
+ if !changed {
+ // Allocate only on the first change; copy unchanged spans without
+ // traversing their items again or converting them to byte slices.
+ rebuilt.Grow(len(input.Raw))
changed = true
}
+ itemStart := item.Index - input.Index
+ _, _ = rebuilt.WriteString(input.Raw[copyFrom:itemStart])
_, _ = rebuilt.Write(itemBody)
+ copyFrom = itemStart + len(item.Raw)
return true
})
- _ = rebuilt.WriteByte(']')
if stripErr != nil {
return body, fmt.Errorf("delete OpenAI input namespace: %w", stripErr)
}
if !changed {
return body, nil
}
+ _, _ = rebuilt.WriteString(input.Raw[copyFrom:])
stripped, err := sjson.SetRawBytes(body, "input", rebuilt.Bytes())
if err != nil {
return body, fmt.Errorf("replace OpenAI input after namespace deletion: %w", err)
diff --git a/backend/internal/service/openai_responses_namespace_benchmark_test.go b/backend/internal/service/openai_responses_namespace_benchmark_test.go
new file mode 100644
index 000000000..9297354b0
--- /dev/null
+++ b/backend/internal/service/openai_responses_namespace_benchmark_test.go
@@ -0,0 +1,55 @@
+package service
+
+import (
+ "bytes"
+ "fmt"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/tidwall/gjson"
+)
+
+func BenchmarkStripOpenAIResponsesInputNamespaces(b *testing.B) {
+ for _, size := range []int{1 << 20, 8 << 20} {
+ message := `{"type":"message","content":"` + strings.Repeat("x", size) + `"}`
+ call := `{"type":"function_call","namespace":"files","name":"search"}`
+ for _, tc := range []struct {
+ name string
+ input string
+ keep bool
+ stripIndex int
+ }{
+ {"tools_only", message, false, -1},
+ {"nested_only", `{"content":{"namespace":"nested"}},` + message, false, -1},
+ {"keep_calls", call + "," + message, true, -1},
+ {"strip_first", call + "," + message, false, 0},
+ {"strip_last", message + "," + call, false, 1},
+ } {
+ b.Run(fmt.Sprintf("%s/%dMiB", tc.name, size>>20), func(b *testing.B) {
+ body := []byte(`{"tools":[{"type":"namespace","name":"files","tools":[]}],"input":[` + tc.input + `]}`)
+ out, err := stripOpenAIResponsesInputNamespaces(body, tc.keep)
+ if err != nil {
+ b.Fatal(err)
+ }
+ if tc.stripIndex < 0 {
+ if !bytes.Equal(body, out) {
+ b.Fatal("no-op changed body")
+ }
+ } else if !gjson.ValidBytes(out) || gjson.GetBytes(out, fmt.Sprintf("input.%d.namespace", tc.stripIndex)).Exists() {
+ b.Fatal("namespace was not removed")
+ }
+ b.ReportAllocs()
+ b.SetBytes(int64(len(body)))
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ out, err = stripOpenAIResponsesInputNamespaces(body, tc.keep)
+ if err != nil {
+ b.Fatal(err)
+ }
+ runtime.KeepAlive(out)
+ }
+ })
+ }
+ }
+}
diff --git a/backend/internal/service/openai_responses_namespace_test.go b/backend/internal/service/openai_responses_namespace_test.go
index 5d847981b..22364c626 100644
--- a/backend/internal/service/openai_responses_namespace_test.go
+++ b/backend/internal/service/openai_responses_namespace_test.go
@@ -2,6 +2,7 @@ package service
import (
"strconv"
+ "strings"
"testing"
"github.com/stretchr/testify/require"
@@ -179,6 +180,8 @@ func TestStripOpenAIResponsesInputNamespaces(t *testing.T) {
func TestStripOpenAIResponsesInputNamespacesLeavesOtherShapesByteExact(t *testing.T) {
tests := [][]byte{
+ []byte(`{"input":[],"tools":[{"type":"namespace"}]}`),
+ []byte(`{"input":[null,42,"namespace",{"content":{"namespace":"nested"}}]}`),
[]byte(`{"input":"text","namespace":"top-level"}`),
[]byte(`{"input":{"namespace":"single-object"}}`),
[]byte(`{"input":[{"content":{"namespace":"nested-only"}}],"tools":[{"namespace":"keep"}]}`),
@@ -192,6 +195,42 @@ func TestStripOpenAIResponsesInputNamespacesLeavesOtherShapesByteExact(t *testin
}
}
+func TestStripOpenAIResponsesInputNamespacesPreservesUnchangedSpans(t *testing.T) {
+ for _, input := range []string{
+ `[ {"namespace":"drop","type":"message"} ]`,
+ `[ null, 9007199254740993, {"namespace":"drop","type":"message"} ]`,
+ `[ {"namespace":"drop","type":"message"}, "tail", {"content":{"namespace":"nested"}} ]`,
+ `[ {"namespace":"drop","type":"message"}, {"type":"function_call","namespace":"keep"}, {"namespace":"drop","type":"message"} ]`,
+ } {
+ t.Run(input, func(t *testing.T) {
+ body := []byte(" \n{\"prefix\":9007199254740993,\"input\":" + input + ",\"tail\":true} \n")
+ original := append([]byte(nil), body...)
+ out, err := stripOpenAIResponsesInputNamespaces(body, true)
+ require.NoError(t, err)
+ require.True(t, gjson.ValidBytes(out))
+ require.Equal(t, strings.ReplaceAll(string(body), `"namespace":"drop",`, ""), string(out))
+ require.Equal(t, original, body, "must not mutate the input body")
+ })
+ }
+}
+
+func TestStripOpenAIResponsesInputNamespacesNullAndKeptPrefix(t *testing.T) {
+ for _, keep := range []bool{false, true} {
+ body := []byte(`{"input":[null,42,"keep",{"type":"function_call","namespace":"files"},{"type":"message","namespace":null,"content":"keep"}]}`)
+ out, err := stripOpenAIResponsesInputNamespaces(body, keep)
+ require.NoError(t, err)
+ require.True(t, gjson.ValidBytes(out))
+ require.Equal(t, 5, len(gjson.GetBytes(out, "input").Array()))
+ for index := 0; index < 3; index++ {
+ path := "input." + strconv.Itoa(index)
+ require.Equal(t, gjson.GetBytes(body, path).Raw, gjson.GetBytes(out, path).Raw)
+ }
+ require.Equal(t, keep, gjson.GetBytes(out, "input.3.namespace").Exists())
+ require.False(t, gjson.GetBytes(out, "input.4.namespace").Exists())
+ require.Equal(t, "keep", gjson.GetBytes(out, "input.4.content").String())
+ }
+}
+
// 保留模式下只有工具调用项留住 namespace:上游按 namespace 解析历史调用,
// 而 message / reasoning / 输出项带该字段会被 schema 拒绝。
func TestStripOpenAIResponsesInputNamespacesKeepsToolCallNamespaces(t *testing.T) {
diff --git a/backend/internal/service/openai_ws_v2/passthrough_relay.go b/backend/internal/service/openai_ws_v2/passthrough_relay.go
index bc850cdfd..4979e65bf 100644
--- a/backend/internal/service/openai_ws_v2/passthrough_relay.go
+++ b/backend/internal/service/openai_ws_v2/passthrough_relay.go
@@ -26,6 +26,7 @@ type FrameConn interface {
type Usage struct {
InputTokens int
+ ImageInputTokens int
OutputTokens int
CacheCreationInputTokens int
CacheReadInputTokens int
@@ -1117,6 +1118,21 @@ func parseUsageAndAccumulate(
if imageTokens == 0 {
imageTokens = usageResult.Get("completion_tokens_details.image_tokens").Int()
}
+ imageInputTokens := usageResult.Get("input_tokens_details.image_tokens").Int()
+ if imageInputTokens <= 0 {
+ imageInputTokens = usageResult.Get("prompt_tokens_details.image_tokens").Int()
+ }
+ // 与 HTTP Responses 同口径:usage 缺图片计数时由托管工具 tool_usage.image_gen 回填。
+ imageGen := gjson.GetBytes(message, "response.tool_usage.image_gen")
+ if !imageGen.Exists() {
+ imageGen = gjson.GetBytes(message, "tool_usage.image_gen")
+ }
+ if imageTokens <= 0 {
+ imageTokens = max(imageGen.Get("output_tokens_details.image_tokens").Int(), 0)
+ }
+ if imageInputTokens <= 0 {
+ imageInputTokens = max(imageGen.Get("input_tokens_details.image_tokens").Int(), 0)
+ }
requireTotals := isTerminalEvent(strings.TrimSpace(eventType))
inputTokens, inputOK := parseUsageIntField(inputResult, requireTotals)
@@ -1141,6 +1157,7 @@ func parseUsageAndAccumulate(
}
parsedUsage := Usage{
InputTokens: inputTokens,
+ ImageInputTokens: int(imageInputTokens),
OutputTokens: outputTokens,
CacheCreationInputTokens: openAICacheCreationTokensFromUsage(usageResult),
CacheReadInputTokens: cachedTokens,
@@ -1161,7 +1178,7 @@ func parseUsageAndAccumulate(
func relayUsageHasTokens(usage Usage) bool {
return usage.InputTokens > 0 || usage.OutputTokens > 0 ||
usage.CacheCreationInputTokens > 0 || usage.CacheReadInputTokens > 0 ||
- usage.ImageOutputTokens > 0
+ usage.ImageInputTokens > 0 || usage.ImageOutputTokens > 0
}
func mergeRelayUsageNonZero(dst *Usage, src Usage) {
@@ -1180,6 +1197,9 @@ func mergeRelayUsageNonZero(dst *Usage, src Usage) {
if src.CacheReadInputTokens > 0 {
dst.CacheReadInputTokens = src.CacheReadInputTokens
}
+ if src.ImageInputTokens > 0 {
+ dst.ImageInputTokens = src.ImageInputTokens
+ }
if src.ImageOutputTokens > 0 {
dst.ImageOutputTokens = src.ImageOutputTokens
}
@@ -1191,6 +1211,7 @@ func finalizeRelayTurnUsage(state *relayState) Usage {
}
turnUsage := state.turnUsage
state.usage.InputTokens += turnUsage.InputTokens
+ state.usage.ImageInputTokens += turnUsage.ImageInputTokens
state.usage.OutputTokens += turnUsage.OutputTokens
state.usage.CacheCreationInputTokens += turnUsage.CacheCreationInputTokens
state.usage.CacheReadInputTokens += turnUsage.CacheReadInputTokens
diff --git a/backend/internal/service/openai_ws_v2/passthrough_relay_image_usage_test.go b/backend/internal/service/openai_ws_v2/passthrough_relay_image_usage_test.go
new file mode 100644
index 000000000..74beacd6c
--- /dev/null
+++ b/backend/internal/service/openai_ws_v2/passthrough_relay_image_usage_test.go
@@ -0,0 +1,47 @@
+package openai_ws_v2
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ coderws "github.com/coder/websocket"
+ "github.com/stretchr/testify/require"
+)
+
+// WS passthrough must account image tokens the way the HTTP Responses path
+// does: image input from input/prompt_tokens_details, and the hosted
+// tool_usage.image_gen breakdown filling counters the usage object omits.
+func TestRelay_ImageUsageMatchesHTTPResponsesAccounting(t *testing.T) {
+ t.Parallel()
+
+ clientConn := newPassthroughTestFrameConn(nil, false)
+ upstreamConn := newPassthroughTestFrameConn([]passthroughTestFrame{
+ {msgType: coderws.MessageText, payload: []byte(`{"type":"response.completed","response":{"id":"resp_tool_image","usage":{"input_tokens":100,"output_tokens":60},"tool_usage":{"image_gen":{"input_tokens_details":{"image_tokens":80},"output_tokens_details":{"image_tokens":50}}}}}`)},
+ {msgType: coderws.MessageText, payload: []byte(`{"type":"response.completed","response":{"id":"resp_explicit_image","usage":{"input_tokens":30,"output_tokens":15,"input_tokens_details":{"image_tokens":20},"output_tokens_details":{"image_tokens":10}},"tool_usage":{"image_gen":{"input_tokens_details":{"image_tokens":800},"output_tokens_details":{"image_tokens":500}}}}}`)},
+ {msgType: coderws.MessageText, payload: []byte(`{"type":"response.completed","response":{"id":"resp_prompt_details","usage":{"prompt_tokens":12,"completion_tokens":2,"prompt_tokens_details":{"image_tokens":7}}}}`)},
+ {msgType: coderws.MessageText, payload: []byte(`{"type":"response.completed","response":{"id":"resp_text","usage":{"input_tokens":3,"output_tokens":4}}}`)},
+ }, true)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ var turns []RelayTurnResult
+ result, relayExit := Relay(ctx, clientConn, upstreamConn,
+ []byte(`{"type":"response.create","model":"gpt-5.4","tools":[{"type":"image_generation"}],"input":[]}`),
+ RelayOptions{OnTurnComplete: func(turn RelayTurnResult) { turns = append(turns, turn) }})
+ require.Nil(t, relayExit)
+ require.Len(t, turns, 4)
+
+ require.Equal(t, 80, turns[0].Usage.ImageInputTokens, "tool_usage.image_gen fills a missing image input counter")
+ require.Equal(t, 50, turns[0].Usage.ImageOutputTokens, "tool_usage.image_gen fills a missing image output counter")
+ require.Equal(t, 20, turns[1].Usage.ImageInputTokens, "response usage takes precedence over the hosted tool breakdown")
+ require.Equal(t, 10, turns[1].Usage.ImageOutputTokens, "response usage takes precedence over the hosted tool breakdown")
+ require.Equal(t, 7, turns[2].Usage.ImageInputTokens)
+ require.Zero(t, turns[3].Usage.ImageInputTokens, "a text turn must not reuse earlier image usage")
+ require.Zero(t, turns[3].Usage.ImageOutputTokens, "a text turn must not reuse earlier image usage")
+
+ require.Equal(t, 107, result.Usage.ImageInputTokens)
+ require.Equal(t, 60, result.Usage.ImageOutputTokens)
+ require.Equal(t, 145, result.Usage.InputTokens)
+ require.Equal(t, 81, result.Usage.OutputTokens)
+}
diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go
index 886c67f3f..da24f4970 100644
--- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go
+++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go
@@ -1214,6 +1214,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough(
RequestID: turn.RequestID,
Usage: OpenAIUsage{
InputTokens: turn.Usage.InputTokens,
+ ImageInputTokens: turn.Usage.ImageInputTokens,
OutputTokens: turn.Usage.OutputTokens,
CacheCreationInputTokens: turn.Usage.CacheCreationInputTokens,
CacheReadInputTokens: turn.Usage.CacheReadInputTokens,
@@ -1355,6 +1356,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough(
RequestID: relayResult.RequestID,
Usage: OpenAIUsage{
InputTokens: relayResult.Usage.InputTokens,
+ ImageInputTokens: relayResult.Usage.ImageInputTokens,
OutputTokens: relayResult.Usage.OutputTokens,
CacheCreationInputTokens: relayResult.Usage.CacheCreationInputTokens,
CacheReadInputTokens: relayResult.Usage.CacheReadInputTokens,
diff --git a/backend/internal/service/openai_ws_v2_passthrough_image_usage_test.go b/backend/internal/service/openai_ws_v2_passthrough_image_usage_test.go
new file mode 100644
index 000000000..b7e06261b
--- /dev/null
+++ b/backend/internal/service/openai_ws_v2_passthrough_image_usage_test.go
@@ -0,0 +1,103 @@
+package service
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ coderws "github.com/coder/websocket"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+// The billed turn result of a WS passthrough image generation must carry the
+// image input tokens and the tool_usage.image_gen backfill, as HTTP does.
+func TestOpenAIWSPassthroughTurnResultCarriesImageUsage(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ cfg := &config.Config{}
+ cfg.Security.URLAllowlist.Enabled = false
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ cfg.Gateway.OpenAIWS.Enabled = true
+ cfg.Gateway.OpenAIWS.APIKeyEnabled = true
+ cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
+ cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
+ cfg.Gateway.OpenAIWS.IngressModeDefault = OpenAIWSIngressModeCtxPool
+ cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
+ cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
+ cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
+
+ upstreamConn := &openAIWSCaptureConn{
+ events: [][]byte{
+ []byte(`{"type":"response.completed","response":{"id":"resp_ws_image","model":"gpt-5.4","output":[{"id":"ig_ws_1","type":"image_generation_call","status":"completed","result":"final-image"}],"usage":{"input_tokens":120,"output_tokens":70,"input_tokens_details":{"image_tokens":40}},"tool_usage":{"image_gen":{"input_tokens_details":{"image_tokens":900},"output_tokens_details":{"image_tokens":55}}}}}`),
+ },
+ }
+ svc := &OpenAIGatewayService{
+ cfg: cfg,
+ httpUpstream: &httpUpstreamRecorder{},
+ cache: &stubGatewayCache{},
+ openaiWSResolver: NewOpenAIWSProtocolResolver(cfg),
+ toolCorrector: NewCodexToolCorrector(),
+ openaiWSPassthroughDialer: &openAIWSCaptureDialer{conn: upstreamConn},
+ }
+ account := &Account{
+ ID: 453, Name: "openai-ws-image-usage", Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
+ Status: StatusActive, Schedulable: true, Concurrency: 1,
+ Credentials: map[string]any{"api_key": "sk-test"},
+ Extra: map[string]any{"openai_apikey_responses_websockets_v2_mode": OpenAIWSIngressModePassthrough},
+ }
+
+ resultCh := make(chan *OpenAIForwardResult, 1)
+ hooks := &OpenAIWSIngressHooks{
+ AfterTurn: func(_ int, result *OpenAIForwardResult, turnErr error) {
+ if turnErr == nil && result != nil {
+ resultCh <- result
+ }
+ },
+ }
+ wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, err := coderws.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer func() { _ = conn.CloseNow() }()
+ ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder())
+ ginCtx.Request = r.Clone(r.Context())
+ readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
+ _, firstMessage, readErr := conn.Read(readCtx)
+ cancel()
+ if readErr != nil {
+ return
+ }
+ _ = svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "sk-test", firstMessage, hooks)
+ }))
+ defer wsServer.Close()
+
+ dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
+ clientConn, _, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil)
+ cancelDial()
+ require.NoError(t, err)
+ defer func() { _ = clientConn.CloseNow() }()
+
+ writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
+ require.NoError(t, clientConn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.4","tools":[{"type":"image_generation"}],"input":"draw"}`)))
+ cancelWrite()
+ readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
+ _, _, readErr := clientConn.Read(readCtx)
+ cancelRead()
+ require.NoError(t, readErr)
+ _ = clientConn.Close(coderws.StatusNormalClosure, "done")
+
+ select {
+ case result := <-resultCh:
+ require.Equal(t, 120, result.Usage.InputTokens)
+ require.Equal(t, 40, result.Usage.ImageInputTokens, "usage image input wins over the hosted tool breakdown")
+ require.Equal(t, 55, result.Usage.ImageOutputTokens, "tool_usage.image_gen fills the missing image output counter")
+ case <-time.After(5 * time.Second):
+ t.Fatal("passthrough turn result was not reported")
+ }
+}
diff --git a/backend/internal/service/opencode_go.go b/backend/internal/service/opencode_go.go
index 6057be030..2defd3851 100644
--- a/backend/internal/service/opencode_go.go
+++ b/backend/internal/service/opencode_go.go
@@ -3,9 +3,11 @@ package service
import (
"fmt"
"net/http"
+ "slices"
"strings"
infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+ "github.com/gin-gonic/gin"
)
// OpenCode Go 是 OpenCode Zen 的订阅网关:同一 API Key 下按模型分流到
@@ -18,9 +20,9 @@ const (
// the UI does not pick a model. glm-5.3 is a Chat Completions catalog ID.
DefaultOpenCodeGoTestModel = "glm-5.3"
- openCodeGoProtocolRulesKey = "protocol_rules"
- maxOpenCodeGoProtocolRules = 64
- maxOpenCodeGoProtocolPatternLength = 128
+ protocolRulesCredentialKey = "protocol_rules"
+ maxProtocolRules = 64
+ maxProtocolRulePatternLength = 128
)
// DefaultOpenCodeGoModelIDs 是官方文档当前公开的模型 ID 目录,
@@ -67,16 +69,64 @@ func normalizeOpenCodeGoModelID(model string) string {
return model
}
-// OpenCodeGoProtocolRule is one model-pattern → native protocol mapping.
+// IsOpenCodeUnsupportedModel 判断请求的模型是否属于 OpenCode 专有协议端点模型。
+// 官方 Zen 上 gemini-* 仅走 Google SDK 专属端点 /zen/v1/models/,
+// jev-* 仅走 SystemOne 专属端点 /zen/v1/systemone,
+// 在通用 Chat Completions / Anthropic Messages / Responses 网关端点上不可用。
+func IsOpenCodeUnsupportedModel(model string) bool {
+ normalized := normalizeOpenCodeGoModelID(model)
+ return strings.HasPrefix(normalized, "gemini-") || strings.HasPrefix(normalized, "jev-")
+}
+
+func writeOpenCodeUnsupportedModelError(c *gin.Context, isAnthropic bool, model string) error {
+ msg := fmt.Sprintf("Model '%s' is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)", model)
+ if c != nil {
+ if isAnthropic {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "type": "error",
+ "error": gin.H{
+ "type": "invalid_request_error",
+ "message": msg,
+ },
+ })
+ } else {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "error": gin.H{
+ "type": "invalid_request_error",
+ "code": "model_not_supported",
+ "message": msg,
+ },
+ })
+ }
+ }
+ return fmt.Errorf("opencode unsupported model: %s", model)
+}
+
+// ProtocolRule is one model-pattern → native protocol mapping.
// Pattern is an exact ID or a suffix glob (foo* / *). First match wins.
-type OpenCodeGoProtocolRule struct {
+type ProtocolRule struct {
Pattern string `json:"pattern"`
Protocol string `json:"protocol"`
+ // Protocols 是命中模型支持的全部原生协议,首项即 Protocol(首选);为空表示只支持
+ // Protocol。入站协议在其中时同协议直通,否则走首选协议(见 resolveModelRoutedProtocolFor)。
+ Protocols []string `json:"protocols,omitempty"`
+}
+
+// normalizeProtocolSet 返回以 preferred 开头、去重且只含原生协议的协议集合。
+func normalizeProtocolSet(preferred string, protocols []string) []string {
+ set := []string{preferred}
+ for _, protocol := range protocols {
+ if !isNativeUpstreamProtocol(protocol) || slices.Contains(set, protocol) {
+ continue
+ }
+ set = append(set, protocol)
+ }
+ return set
}
// DefaultOpenCodeGoProtocolRules is the built-in adaptive routing table for Go.
-func DefaultOpenCodeGoProtocolRules() []OpenCodeGoProtocolRule {
- return []OpenCodeGoProtocolRule{
+func DefaultOpenCodeGoProtocolRules() []ProtocolRule {
+ return []ProtocolRule{
{Pattern: "grok-*", Protocol: APIProtocolResponses},
{Pattern: "gpt-*", Protocol: APIProtocolResponses},
{Pattern: "muse-spark-*", Protocol: APIProtocolResponses},
@@ -86,25 +136,20 @@ func DefaultOpenCodeGoProtocolRules() []OpenCodeGoProtocolRule {
}
// DefaultOpenCodeZenProtocolRules 对齐 https://opencode.ai/docs/zen/ 端点表:
-// GPT/Grok/Muse Spark → Responses,Claude/Qwen → Anthropic,其余 Chat Completions。
-func DefaultOpenCodeZenProtocolRules() []OpenCodeGoProtocolRule {
- return []OpenCodeGoProtocolRule{
+// GPT/Grok/Muse Spark → Responses,Claude/Qwen(除 qwen3.8-max) → Anthropic,
+// qwen3.8-max 及其余模型 → Chat Completions。
+func DefaultOpenCodeZenProtocolRules() []ProtocolRule {
+ return []ProtocolRule{
{Pattern: "grok-*", Protocol: APIProtocolResponses},
{Pattern: "gpt-*", Protocol: APIProtocolResponses},
{Pattern: "muse-spark-*", Protocol: APIProtocolResponses},
{Pattern: "claude-*", Protocol: APIProtocolAnthropic},
+ {Pattern: "qwen3.8-max", Protocol: APIProtocolChatCompletions},
{Pattern: "qwen*", Protocol: APIProtocolAnthropic},
}
}
-func defaultOpenCodeProtocolRules(mode string) []OpenCodeGoProtocolRule {
- if mode == AccountModeZen {
- return DefaultOpenCodeZenProtocolRules()
- }
- return DefaultOpenCodeGoProtocolRules()
-}
-
-func isNativeOpenCodeGoProtocol(protocol string) bool {
+func isNativeUpstreamProtocol(protocol string) bool {
switch protocol {
case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses:
return true
@@ -113,7 +158,7 @@ func isNativeOpenCodeGoProtocol(protocol string) bool {
}
}
-func openCodeGoPatternMatches(pattern, model string) bool {
+func protocolRulePatternMatches(pattern, model string) bool {
pattern = strings.ToLower(strings.TrimSpace(pattern))
model = normalizeOpenCodeGoModelID(model)
if pattern == "" || model == "" {
@@ -128,49 +173,51 @@ func openCodeGoPatternMatches(pattern, model string) bool {
return model == pattern
}
-func matchOpenCodeGoProtocolRules(model string, rules []OpenCodeGoProtocolRule) string {
+// matchProtocolRules 返回首条命中规则的首选协议;未命中时为 Chat Completions。
+func matchProtocolRules(model string, rules []ProtocolRule) string {
+ if set, ok := matchProtocolRuleSet(model, rules); ok {
+ return set[0]
+ }
+ return APIProtocolChatCompletions
+}
+
+// matchProtocolRuleSet 返回首条命中规则支持的协议集合(首项为首选);未命中时 ok=false。
+func matchProtocolRuleSet(model string, rules []ProtocolRule) ([]string, bool) {
for _, rule := range rules {
- if !isNativeOpenCodeGoProtocol(rule.Protocol) {
+ if !isNativeUpstreamProtocol(rule.Protocol) {
continue
}
- if openCodeGoPatternMatches(rule.Pattern, model) {
- return rule.Protocol
+ if protocolRulePatternMatches(rule.Pattern, model) {
+ return normalizeProtocolSet(rule.Protocol, rule.Protocols), true
}
}
- return APIProtocolChatCompletions
+ return nil, false
}
-// OpenCodeGoModelProtocol 返回内置默认表下模型对应的原生上游协议。
-// 未命中时为 Chat Completions。账号自定义 protocol_rules 见
-// ResolveOpenCodeGoUpstreamProtocol。
-func OpenCodeGoModelProtocol(model string) string {
- return matchOpenCodeGoProtocolRules(model, DefaultOpenCodeGoProtocolRules())
-}
-
-func (a *Account) openCodeGoProtocolRules() ([]OpenCodeGoProtocolRule, bool) {
+func (a *Account) configuredProtocolRules() ([]ProtocolRule, bool) {
if a == nil || a.Credentials == nil {
return nil, false
}
- raw, ok := a.Credentials[openCodeGoProtocolRulesKey]
+ raw, ok := a.Credentials[protocolRulesCredentialKey]
if !ok || raw == nil {
return nil, false
}
- rules, err := parseOpenCodeGoProtocolRules(raw)
+ rules, err := parseProtocolRules(raw)
if err != nil {
return nil, false
}
return rules, true
}
-func parseOpenCodeGoProtocolRules(raw any) ([]OpenCodeGoProtocolRule, error) {
- items, err := openCodeGoProtocolRuleItems(raw)
+func parseProtocolRules(raw any) ([]ProtocolRule, error) {
+ items, err := protocolRuleItems(raw)
if err != nil {
return nil, err
}
- if len(items) > maxOpenCodeGoProtocolRules {
- return nil, fmt.Errorf("protocol_rules supports at most %d entries", maxOpenCodeGoProtocolRules)
+ if len(items) > maxProtocolRules {
+ return nil, fmt.Errorf("protocol_rules supports at most %d entries", maxProtocolRules)
}
- rules := make([]OpenCodeGoProtocolRule, 0, len(items))
+ rules := make([]ProtocolRule, 0, len(items))
for i, item := range items {
entry, ok := item.(map[string]any)
if !ok {
@@ -178,20 +225,59 @@ func parseOpenCodeGoProtocolRules(raw any) ([]OpenCodeGoProtocolRule, error) {
}
pattern, _ := entry["pattern"].(string)
protocol, _ := entry["protocol"].(string)
- pattern, err := normalizeOpenCodeGoProtocolPattern(pattern)
+ pattern, err := normalizeProtocolRulePattern(pattern)
+ if err != nil {
+ return nil, fmt.Errorf("protocol_rules[%d]: %w", i, err)
+ }
+ protocols, err := protocolRuleProtocols(entry["protocols"])
if err != nil {
return nil, fmt.Errorf("protocol_rules[%d]: %w", i, err)
}
protocol = strings.TrimSpace(protocol)
- if !isNativeOpenCodeGoProtocol(protocol) {
+ if protocol == "" && len(protocols) > 0 {
+ protocol = protocols[0]
+ }
+ if !isNativeUpstreamProtocol(protocol) {
return nil, fmt.Errorf("protocol_rules[%d]: protocol must be chat_completions, anthropic, or responses", i)
}
- rules = append(rules, OpenCodeGoProtocolRule{Pattern: pattern, Protocol: protocol})
+ rule := ProtocolRule{Pattern: pattern, Protocol: protocol}
+ if set := normalizeProtocolSet(protocol, protocols); len(set) > 1 {
+ rule.Protocols = set
+ }
+ rules = append(rules, rule)
}
return rules, nil
}
-func openCodeGoProtocolRuleItems(raw any) ([]any, error) {
+// protocolRuleProtocols 解析规则的 protocols 列表(可缺省);其中每一项都须为原生协议。
+func protocolRuleProtocols(raw any) ([]string, error) {
+ if raw == nil {
+ return nil, nil
+ }
+ var items []any
+ switch values := raw.(type) {
+ case []any:
+ items = values
+ case []string:
+ for _, value := range values {
+ items = append(items, value)
+ }
+ default:
+ return nil, fmt.Errorf("protocols must be an array")
+ }
+ out := make([]string, 0, len(items))
+ for _, item := range items {
+ protocol, _ := item.(string)
+ protocol = strings.TrimSpace(protocol)
+ if !isNativeUpstreamProtocol(protocol) {
+ return nil, fmt.Errorf("protocols must only contain chat_completions, anthropic, or responses")
+ }
+ out = append(out, protocol)
+ }
+ return out, nil
+}
+
+func protocolRuleItems(raw any) ([]any, error) {
switch items := raw.(type) {
case []any:
return items, nil
@@ -206,12 +292,12 @@ func openCodeGoProtocolRuleItems(raw any) ([]any, error) {
}
}
-func normalizeOpenCodeGoProtocolPattern(pattern string) (string, error) {
+func normalizeProtocolRulePattern(pattern string) (string, error) {
pattern = strings.ToLower(strings.TrimSpace(pattern))
if pattern == "" {
return "", fmt.Errorf("pattern is required")
}
- if len(pattern) > maxOpenCodeGoProtocolPatternLength {
+ if len(pattern) > maxProtocolRulePatternLength {
return "", fmt.Errorf("pattern is too long")
}
if strings.ContainsAny(pattern, " \t") {
@@ -224,28 +310,36 @@ func normalizeOpenCodeGoProtocolPattern(pattern string) (string, error) {
return pattern, nil
}
-// NormalizeOpenCodeGoProtocolRulesCredentials 校验并原地规范化 credentials.protocol_rules。
+// NormalizeProtocolRulesCredentials 校验并原地规范化 credentials.protocol_rules。
// 未携带该字段时为 no-op,使旧账号继续使用内置默认表。
-func NormalizeOpenCodeGoProtocolRulesCredentials(credentials map[string]any) error {
+func NormalizeProtocolRulesCredentials(credentials map[string]any) error {
if credentials == nil {
return nil
}
- raw, ok := credentials[openCodeGoProtocolRulesKey]
+ raw, ok := credentials[protocolRulesCredentialKey]
if !ok || raw == nil {
return nil
}
- rules, err := parseOpenCodeGoProtocolRules(raw)
+ rules, err := parseProtocolRules(raw)
if err != nil {
return infraerrors.New(http.StatusBadRequest, "INVALID_OPENCODE_GO_PROTOCOL_RULES", err.Error())
}
encoded := make([]any, 0, len(rules))
for _, rule := range rules {
- encoded = append(encoded, map[string]any{
+ item := map[string]any{
"pattern": rule.Pattern,
"protocol": rule.Protocol,
- })
+ }
+ if len(rule.Protocols) > 1 {
+ protocols := make([]any, 0, len(rule.Protocols))
+ for _, protocol := range rule.Protocols {
+ protocols = append(protocols, protocol)
+ }
+ item["protocols"] = protocols
+ }
+ encoded = append(encoded, item)
}
- credentials[openCodeGoProtocolRulesKey] = encoded
+ credentials[protocolRulesCredentialKey] = encoded
return nil
}
@@ -272,56 +366,10 @@ func (a *Account) IsOpenCodeGoPlan() bool {
return a.GetOpenCodeAccountMode() == AccountModeGo
}
-func (a *Account) openCodeDefaultChatBaseURL() string {
- if a.IsOpenCodeZen() {
- return DefaultOpenCodeZenBaseURL
- }
- return DefaultOpenCodeGoBaseURL
-}
-
-func (a *Account) openCodeDefaultAnthropicBaseURL() string {
- if a.IsOpenCodeZen() {
- return DefaultOpenCodeZenAnthropicBaseURL
- }
- return DefaultOpenCodeGoAnthropicBaseURL
-}
-
func (a *Account) IsMultiProtocolAPIKey() bool {
return a != nil && IsMultiProtocolAPIKeyProvider(a.Platform)
}
-// openCodeGoNativeProtocol 返回 OpenCode Go 实际上游协议。
-// 规则未命中、空值或未知协议一律兜底 Chat Completions,避免落入 Responses 转换链。
-func openCodeGoNativeProtocol(account *Account, model string) string {
- if account == nil {
- return APIProtocolChatCompletions
- }
- switch proto := account.ResolveOpenCodeGoUpstreamProtocol(model); proto {
- case APIProtocolAnthropic, APIProtocolResponses:
- return proto
- default:
- return APIProtocolChatCompletions
- }
-}
-
-// ResolveOpenCodeGoUpstreamProtocol 按账号协议配置与模型规则决定上游协议。
-// 显式 pinned 协议优先;adaptive(默认)先走 credentials.protocol_rules,
-// 未配置时回落内置默认表;已配置但未命中则走 Chat Completions。
-func (a *Account) ResolveOpenCodeGoUpstreamProtocol(model string) string {
- if a == nil || !a.IsOpenCodeGo() {
- return ""
- }
- switch a.GetAPIProtocol() {
- case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses:
- return a.GetAPIProtocol()
- default:
- if rules, present := a.openCodeGoProtocolRules(); present {
- return matchOpenCodeGoProtocolRules(model, rules)
- }
- return matchOpenCodeGoProtocolRules(model, defaultOpenCodeProtocolRules(a.GetOpenCodeAccountMode()))
- }
-}
-
// openCodeGoQuotaURL 根据 base_url 解析 OpenCode Go 额度端点。
// /zen/go/v1(Chat 协议默认,DefaultOpenCodeGoBaseURL)与 /zen/go
// (Anthropic 协议默认,DefaultOpenCodeGoAnthropicBaseURL)两种 base 统一
diff --git a/backend/internal/service/opencode_go_test.go b/backend/internal/service/opencode_go_test.go
index 796487c95..c3bbc2558 100644
--- a/backend/internal/service/opencode_go_test.go
+++ b/backend/internal/service/opencode_go_test.go
@@ -6,7 +6,7 @@ import (
"github.com/stretchr/testify/require"
)
-func TestOpenCodeGoModelProtocol(t *testing.T) {
+func TestOpenCodeGoDefaultProtocolRules(t *testing.T) {
t.Parallel()
cases := []struct {
model string
@@ -28,114 +28,119 @@ func TestOpenCodeGoModelProtocol(t *testing.T) {
{"unknown-model", APIProtocolChatCompletions},
}
for _, tc := range cases {
- require.Equal(t, tc.want, OpenCodeGoModelProtocol(tc.model), "model=%s", tc.model)
+ require.Equal(t, tc.want, matchProtocolRules(tc.model, DefaultOpenCodeGoProtocolRules()), "model=%s", tc.model)
}
}
-func TestResolveOpenCodeGoUpstreamProtocol(t *testing.T) {
+func TestOpenCodeGoModelRoutedProtocol(t *testing.T) {
t.Parallel()
adaptive := &Account{Platform: PlatformOpenCodeGo, Credentials: map[string]any{"api_protocol": APIProtocolAdaptive}}
- require.Equal(t, APIProtocolAnthropic, adaptive.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
- require.Equal(t, APIProtocolResponses, adaptive.ResolveOpenCodeGoUpstreamProtocol("grok-4.6"))
- require.Equal(t, APIProtocolChatCompletions, adaptive.ResolveOpenCodeGoUpstreamProtocol("glm-5.3"))
+ require.Equal(t, APIProtocolAnthropic, adaptive.resolveModelRoutedProtocol("minimax-m3"))
+ require.Equal(t, APIProtocolResponses, adaptive.resolveModelRoutedProtocol("grok-4.6"))
+ require.Equal(t, APIProtocolChatCompletions, adaptive.resolveModelRoutedProtocol("glm-5.3"))
pinned := &Account{Platform: PlatformOpenCodeGo, Credentials: map[string]any{"api_protocol": APIProtocolChatCompletions}}
- require.Equal(t, APIProtocolChatCompletions, pinned.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
+ require.Equal(t, APIProtocolChatCompletions, pinned.resolveModelRoutedProtocol("minimax-m3"))
empty := &Account{Platform: PlatformOpenCodeGo}
- require.Equal(t, APIProtocolResponses, empty.ResolveOpenCodeGoUpstreamProtocol("gpt-5.6-luna"))
+ require.Equal(t, APIProtocolResponses, empty.resolveModelRoutedProtocol("gpt-5.6-luna"))
require.Equal(t, AccountModeGo, empty.GetOpenCodeAccountMode())
require.True(t, empty.IsOpenCodeGoPlan())
zen := &Account{Platform: PlatformOpenCodeGo, Credentials: map[string]any{"account_mode": AccountModeZen, "api_protocol": APIProtocolAdaptive}}
- require.Equal(t, APIProtocolChatCompletions, zen.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
- require.Equal(t, APIProtocolAnthropic, zen.ResolveOpenCodeGoUpstreamProtocol("claude-opus-4-6"))
+ require.Equal(t, APIProtocolChatCompletions, zen.resolveModelRoutedProtocol("minimax-m3"))
+ require.Equal(t, APIProtocolAnthropic, zen.resolveModelRoutedProtocol("claude-opus-4-6"))
+ require.Equal(t, APIProtocolChatCompletions, zen.resolveModelRoutedProtocol("qwen3.8-max"))
+ require.Equal(t, APIProtocolAnthropic, zen.resolveModelRoutedProtocol("qwen3.8-flash"))
+ require.Equal(t, APIProtocolAnthropic, zen.resolveModelRoutedProtocol("qwen3.7-max"))
require.Equal(t, DefaultOpenCodeZenBaseURL, zen.GetOpenAIBaseURL())
- require.Equal(t, "", (&Account{Platform: PlatformKimi}).ResolveOpenCodeGoUpstreamProtocol("glm-5.3"))
+ goAccount := &Account{Platform: PlatformOpenCodeGo, Credentials: map[string]any{"account_mode": AccountModeGo, "api_protocol": APIProtocolAdaptive}}
+ require.Equal(t, APIProtocolAnthropic, goAccount.resolveModelRoutedProtocol("qwen3.8-max"))
+
+ require.False(t, (&Account{Platform: PlatformKimi}).routesByModel())
}
-func TestResolveOpenCodeGoUpstreamProtocolUsesAccountRules(t *testing.T) {
+func TestOpenCodeGoModelRoutedProtocolUsesAccountRules(t *testing.T) {
t.Parallel()
account := &Account{
Platform: PlatformOpenCodeGo,
Credentials: map[string]any{
"api_protocol": APIProtocolAdaptive,
- openCodeGoProtocolRulesKey: []any{
+ protocolRulesCredentialKey: []any{
map[string]any{"pattern": "grok-*", "protocol": APIProtocolChatCompletions},
map[string]any{"pattern": "deepseek-v4-flash", "protocol": APIProtocolResponses},
map[string]any{"pattern": "qwen*", "protocol": APIProtocolAnthropic},
},
},
}
- require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("grok-4.6"))
- require.Equal(t, APIProtocolResponses, account.ResolveOpenCodeGoUpstreamProtocol("deepseek-v4-flash"))
- require.Equal(t, APIProtocolAnthropic, account.ResolveOpenCodeGoUpstreamProtocol("qwen3.8-max"))
- require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("glm-5.3"))
- require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
+ require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("grok-4.6"))
+ require.Equal(t, APIProtocolResponses, account.resolveModelRoutedProtocol("deepseek-v4-flash"))
+ require.Equal(t, APIProtocolAnthropic, account.resolveModelRoutedProtocol("qwen3.8-max"))
+ require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("glm-5.3"))
+ require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("minimax-m3"))
}
-func TestResolveOpenCodeGoUpstreamProtocolEmptyRulesAreAllChatCompletions(t *testing.T) {
+func TestOpenCodeGoModelRoutedProtocolEmptyRulesAreAllChatCompletions(t *testing.T) {
t.Parallel()
account := &Account{
Platform: PlatformOpenCodeGo,
Credentials: map[string]any{
- openCodeGoProtocolRulesKey: []any{},
+ protocolRulesCredentialKey: []any{},
},
}
- require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("grok-4.6"))
- require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("minimax-m3"))
+ require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("grok-4.6"))
+ require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("minimax-m3"))
}
-func TestResolveOpenCodeGoUpstreamProtocolFirstMatchWins(t *testing.T) {
+func TestOpenCodeGoModelRoutedProtocolFirstMatchWins(t *testing.T) {
t.Parallel()
account := &Account{
Platform: PlatformOpenCodeGo,
Credentials: map[string]any{
- openCodeGoProtocolRulesKey: []any{
+ protocolRulesCredentialKey: []any{
map[string]any{"pattern": "gpt-5.6-luna", "protocol": APIProtocolChatCompletions},
map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses},
},
},
}
- require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("gpt-5.6-luna"))
- require.Equal(t, APIProtocolResponses, account.ResolveOpenCodeGoUpstreamProtocol("gpt-5.4"))
+ require.Equal(t, APIProtocolChatCompletions, account.resolveModelRoutedProtocol("gpt-5.6-luna"))
+ require.Equal(t, APIProtocolResponses, account.resolveModelRoutedProtocol("gpt-5.4"))
}
-func TestOpenCodeGoNativeProtocolUnmatchedFallsBackToChatCompletions(t *testing.T) {
+func TestOpenCodeGoUnmatchedFallsBackToChatCompletions(t *testing.T) {
t.Parallel()
withRules := &Account{
Platform: PlatformOpenCodeGo,
Credentials: map[string]any{
"api_protocol": APIProtocolAdaptive,
- openCodeGoProtocolRulesKey: []any{
+ protocolRulesCredentialKey: []any{
map[string]any{"pattern": "grok-*", "protocol": APIProtocolResponses},
map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses},
map[string]any{"pattern": "qwen*", "protocol": APIProtocolAnthropic},
},
},
}
- require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "deepseek-v4-flash"))
- require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "glm-5.3"))
- require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "omen-alpha"))
- require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "kimi-k3"))
- require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(withRules, "unknown-model"))
- require.Equal(t, APIProtocolResponses, openCodeGoNativeProtocol(withRules, "grok-4.6"))
- require.Equal(t, APIProtocolAnthropic, openCodeGoNativeProtocol(withRules, "qwen3.8-flash"))
+ require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("deepseek-v4-flash"))
+ require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("glm-5.3"))
+ require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("omen-alpha"))
+ require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("kimi-k3"))
+ require.Equal(t, APIProtocolChatCompletions, withRules.resolveModelRoutedProtocol("unknown-model"))
+ require.Equal(t, APIProtocolResponses, withRules.resolveModelRoutedProtocol("grok-4.6"))
+ require.Equal(t, APIProtocolAnthropic, withRules.resolveModelRoutedProtocol("qwen3.8-flash"))
defaults := &Account{Platform: PlatformOpenCodeGo}
- require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(defaults, "deepseek-v4-flash"))
- require.Equal(t, APIProtocolChatCompletions, openCodeGoNativeProtocol(nil, "grok-4.6"))
+ require.Equal(t, APIProtocolChatCompletions, defaults.resolveModelRoutedProtocol("deepseek-v4-flash"))
}
func TestParseOpenCodeGoProtocolRulesAcceptsTypedMaps(t *testing.T) {
t.Parallel()
- rules, err := parseOpenCodeGoProtocolRules([]map[string]any{
+ rules, err := parseProtocolRules([]map[string]any{
{"pattern": "grok-*", "protocol": APIProtocolResponses},
{"pattern": "qwen*", "protocol": APIProtocolAnthropic},
})
require.NoError(t, err)
- require.Equal(t, []OpenCodeGoProtocolRule{
+ require.Equal(t, []ProtocolRule{
{Pattern: "grok-*", Protocol: APIProtocolResponses},
{Pattern: "qwen*", Protocol: APIProtocolAnthropic},
}, rules)
@@ -154,9 +159,9 @@ func TestShouldForwardOpenAIResponsesViaRawChatCompletions_OpenCodeGoIgnoresProb
},
}
require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(account))
- require.Equal(t, APIProtocolResponses, account.ResolveOpenCodeGoUpstreamProtocol("grok-4.6"))
- require.Equal(t, APIProtocolResponses, account.ResolveOpenCodeGoUpstreamProtocol("gpt-5.6-luna"))
- require.Equal(t, APIProtocolAnthropic, account.ResolveOpenCodeGoUpstreamProtocol("qwen3.8-flash"))
+ require.Equal(t, APIProtocolResponses, account.resolveModelRoutedProtocol("grok-4.6"))
+ require.Equal(t, APIProtocolResponses, account.resolveModelRoutedProtocol("gpt-5.6-luna"))
+ require.Equal(t, APIProtocolAnthropic, account.resolveModelRoutedProtocol("qwen3.8-flash"))
}
func TestStampOpenAIResponsesUpstreamEndpoint(t *testing.T) {
@@ -172,31 +177,31 @@ func TestStampOpenAIResponsesUpstreamEndpoint(t *testing.T) {
func TestNormalizeOpenCodeGoProtocolRulesCredentials(t *testing.T) {
t.Parallel()
- require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(nil))
- require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{}))
+ require.NoError(t, NormalizeProtocolRulesCredentials(nil))
+ require.NoError(t, NormalizeProtocolRulesCredentials(map[string]any{}))
creds := map[string]any{
- openCodeGoProtocolRulesKey: []any{
+ protocolRulesCredentialKey: []any{
map[string]any{"pattern": " Grok-* ", "protocol": APIProtocolResponses},
},
}
- require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(creds))
- rules, ok := creds[openCodeGoProtocolRulesKey].([]any)
+ require.NoError(t, NormalizeProtocolRulesCredentials(creds))
+ rules, ok := creds[protocolRulesCredentialKey].([]any)
require.True(t, ok)
require.NotEmpty(t, rules)
entry, ok := rules[0].(map[string]any)
require.True(t, ok)
require.Equal(t, "grok-*", entry["pattern"])
- err := NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{
- openCodeGoProtocolRulesKey: []any{
+ err := NormalizeProtocolRulesCredentials(map[string]any{
+ protocolRulesCredentialKey: []any{
map[string]any{"pattern": "*grok", "protocol": APIProtocolResponses},
},
})
require.Error(t, err)
- err = NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{
- openCodeGoProtocolRulesKey: []any{
+ err = NormalizeProtocolRulesCredentials(map[string]any{
+ protocolRulesCredentialKey: []any{
map[string]any{"pattern": "grok-*", "protocol": "adaptive"},
},
})
@@ -235,3 +240,29 @@ func TestDefaultOpenCodeGoModelIDsCoverDocumentedCatalog(t *testing.T) {
require.Contains(t, ids, "glm-5.3")
require.NotEmpty(t, ids)
}
+
+func TestIsOpenCodeUnsupportedModel(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ model string
+ want bool
+ }{
+ {"gemini-3.8-flash", true},
+ {"gemini-3.7-flash", true},
+ {"opencode/gemini-3.8-flash", true},
+ {"opencode-go/gemini-3.1-pro", true},
+ {"jev-1.13", true},
+ {"jev-1.13-free", true},
+ {"opencode/jev-1.13", true},
+ {"qwen3.8-max", false},
+ {"qwen3.8-flash", false},
+ {"gpt-5.6-luna", false},
+ {"grok-4.6", false},
+ {"minimax-m3", false},
+ {"glm-5.3", false},
+ {"", false},
+ }
+ for _, tc := range cases {
+ require.Equal(t, tc.want, IsOpenCodeUnsupportedModel(tc.model), "model=%s", tc.model)
+ }
+}
diff --git a/backend/internal/service/opencode_go_usage.go b/backend/internal/service/opencode_go_usage.go
index f46be4204..11d01f858 100644
--- a/backend/internal/service/opencode_go_usage.go
+++ b/backend/internal/service/opencode_go_usage.go
@@ -779,7 +779,7 @@ func (s *OpenCodeGoUsageService) refreshLoadedAccount(ctx context.Context, accou
return s.persistFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "unauthorized", retryAfter(resp.Header, now), true)
}
if resp.StatusCode == http.StatusForbidden {
- return s.persistFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "OpenCode Go subscription required (403)", retryAfter(resp.Header, now), false)
+ return s.persistFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "forbidden", retryAfter(resp.Header, now), false)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return s.persistFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "http_error", retryAfter(resp.Header, now), false)
@@ -1000,8 +1000,17 @@ func decodeOpenCodeGoUsageSnapshot(extra map[string]any) *OpenCodeGoUsageSnapsho
// nextOpenCodeGoUsageDelay computes the not-before delay for the next refresh:
// interval * 2^min(failureCount-1, 6) capped at 24h, ±10% jitter capped at 5min,
-// never below a Retry-After hint or one minute.
+// never below a Retry-After hint or one minute. The hint is honored over the
+// local backoff but clamped to the same 24h ceiling: it arrives over a network
+// path we do not control (upstream CDN, account proxy), and an unbounded value
+// would freeze a group's auto refresh indefinitely.
func nextOpenCodeGoUsageDelay(intervalMinutes, failureCount int, retryAfterDuration time.Duration) time.Duration {
+ if retryAfterDuration < 0 {
+ retryAfterDuration = 0
+ }
+ if retryAfterDuration > opencodeGoUsageMaxDelay {
+ retryAfterDuration = opencodeGoUsageMaxDelay
+ }
minimumDelay := retryAfterDuration
base := time.Duration(intervalMinutes) * time.Minute
if base < opencodeGoUsageMinIntervalMinutes*time.Minute {
diff --git a/backend/internal/service/opencode_go_usage_test.go b/backend/internal/service/opencode_go_usage_test.go
index e6cb63516..fac4cf237 100644
--- a/backend/internal/service/opencode_go_usage_test.go
+++ b/backend/internal/service/opencode_go_usage_test.go
@@ -320,7 +320,7 @@ func TestOpenCodeGoUsageRefresh401Unauthorized(t *testing.T) {
require.True(t, openCodeGoUsageAutoRefreshEnabled(account))
}
-func TestOpenCodeGoUsageRefresh403SubscriptionRequired(t *testing.T) {
+func TestOpenCodeGoUsageRefresh403Forbidden(t *testing.T) {
account := openCodeGoUsageAccount(7)
repo := &openCodeGoUsageTestRepo{accounts: map[int64]*Account{7: account}}
stub := &openCodeGoUsageHTTPStub{status: http.StatusForbidden}
@@ -330,7 +330,7 @@ func TestOpenCodeGoUsageRefresh403SubscriptionRequired(t *testing.T) {
require.NoError(t, err)
require.Equal(t, OpenCodeGoUsageStatusFailed, state.Snapshot.Status)
require.Equal(t, http.StatusForbidden, state.Snapshot.HTTPStatus)
- require.Equal(t, "OpenCode Go subscription required (403)", state.Snapshot.LastError)
+ require.Equal(t, "forbidden", state.Snapshot.LastError)
require.Equal(t, 1, state.Snapshot.FailureCount)
}
@@ -403,11 +403,39 @@ func TestNextOpenCodeGoUsageDelayBackoff(t *testing.T) {
delay = nextOpenCodeGoUsageDelay(15, 0, 2*time.Hour)
require.GreaterOrEqual(t, delay, 2*time.Hour)
+ // a hint beyond the 24h ceiling is clamped, never adopted verbatim
+ delay = nextOpenCodeGoUsageDelay(15, 0, 48*time.Hour)
+ require.GreaterOrEqual(t, delay, 23*time.Hour+55*time.Minute)
+ require.LessOrEqual(t, delay, 24*time.Hour+5*time.Minute)
+
// floor of one minute
delay = nextOpenCodeGoUsageDelay(5, 0, 0)
require.GreaterOrEqual(t, delay, time.Minute)
}
+func TestOpenCodeGoUsageRefreshClampsHugeRetryAfter(t *testing.T) {
+ now := time.Now().UTC()
+ account := openCodeGoUsageAccount(7)
+ repo := &openCodeGoUsageTestRepo{accounts: map[int64]*Account{7: account}}
+ stub := &openCodeGoUsageHTTPStub{
+ status: http.StatusTooManyRequests,
+ header: http.Header{"Retry-After": []string{"99999999"}},
+ }
+ svc := newOpenCodeGoUsageTestService(t, repo, stub, &upstreamBillingProbeSettingRepo{})
+ svc.now = func() time.Time { return now }
+
+ state, err := svc.Refresh(context.Background(), 7)
+ require.NoError(t, err)
+ require.Equal(t, OpenCodeGoUsageStatusFailed, state.Snapshot.Status)
+ require.Equal(t, http.StatusTooManyRequests, state.Snapshot.HTTPStatus)
+ require.Equal(t, "http_error", state.Snapshot.LastError)
+
+ maxExpected := now.Add(24*time.Hour + 5*time.Minute)
+ minExpected := now.Add(23*time.Hour + 55*time.Minute)
+ require.True(t, state.Snapshot.NextRefreshAt.Before(maxExpected.Add(time.Second)))
+ require.True(t, state.Snapshot.NextRefreshAt.After(minExpected.Add(-time.Second)))
+}
+
func TestOpenCodeGoUsageManualRefreshThrottle(t *testing.T) {
now := time.Now().UTC()
account := openCodeGoUsageAccount(7)
diff --git a/backend/internal/service/opencode_unsupported_models_routing_test.go b/backend/internal/service/opencode_unsupported_models_routing_test.go
new file mode 100644
index 000000000..3e1b514e2
--- /dev/null
+++ b/backend/internal/service/opencode_unsupported_models_routing_test.go
@@ -0,0 +1,86 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+func TestOpenCodeUnsupportedModelsRejectMappedAliasesBeforeProtocolSelection(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, ingress := range routingMatrixIngresses() {
+ for _, protocol := range []string{APIProtocolAdaptive, APIProtocolResponses, APIProtocolChatCompletions, APIProtocolAnthropic} {
+ for _, mode := range []string{AccountModeGo, AccountModeZen} {
+ t.Run(ingress.name+"/"+protocol+"/"+mode, func(t *testing.T) {
+ account := &Account{ID: 105, Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "test-key", "api_protocol": protocol, "account_mode": mode,
+ "model_mapping": map[string]any{"public-model": "gemini-3.8-flash"},
+ "protocol_rules": []any{map[string]any{"pattern": "*", "protocol": APIProtocolChatCompletions}},
+ }}
+ body := (routingMatrixCase{ingress: ingress, model: "public-model"}).body()
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, ingress.path, bytes.NewReader(body))
+ upstream := &httpUpstreamRecorder{err: errors.New("unexpected upstream request")}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+
+ err := ingress.forward(svc, c, account, body)
+
+ require.ErrorContains(t, err, "opencode unsupported model: gemini-3.8-flash")
+ require.Equal(t, http.StatusBadRequest, recorder.Code)
+ require.Empty(t, upstream.requests)
+ })
+ }
+ }
+ }
+}
+
+func TestCommandCodeGeminiModelReachesUpstream(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, ingress := range routingMatrixIngresses() {
+ t.Run(ingress.name, func(t *testing.T) {
+ account := commandCodeTestAccount(106)
+ account.Credentials["api_protocol"] = APIProtocolChatCompletions
+ body := (routingMatrixCase{ingress: ingress, model: "gemini-3.8-flash"}).body()
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, ingress.path, bytes.NewReader(body))
+ upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+
+ err := ingress.forward(svc, c, account, body)
+
+ require.Error(t, err)
+ require.NotContains(t, err.Error(), "opencode unsupported model")
+ require.Len(t, upstream.requests, 1)
+ require.Equal(t, "https://api.commandcode.ai/provider/v1/chat/completions", upstream.requests[0].URL.String())
+ })
+ }
+ account := commandCodeTestAccount(107)
+ svc, upstream := adaptiveCNAccountTestService(account, adaptiveCNChatTestResponse())
+ c, _ := newTestContext()
+ require.NoError(t, svc.testModelRoutedAccountConnection(c, account, "gemini-3.8-flash", "hi"))
+ require.Len(t, upstream.requests, 1)
+}
+
+func TestOpenCodeConnectionTestRejectsMappedUnsupportedModel(t *testing.T) {
+ account := &Account{Platform: PlatformOpenCodeGo, Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_protocol": APIProtocolChatCompletions,
+ "model_mapping": map[string]any{"public-model": "jev-1.13"},
+ }}
+ c, _ := newTestContext()
+ c.Request = httptest.NewRequest(http.MethodPost, "/test", nil).WithContext(context.Background())
+ err := (&AccountTestService{}).testModelRoutedAccountConnection(c, account, "public-model", "hi")
+ require.ErrorContains(t, err, "not supported on OpenCode standard gateway")
+ require.ErrorContains(t, err, "jev-1.13")
+}
diff --git a/backend/internal/service/opencode_unsupported_models_test.go b/backend/internal/service/opencode_unsupported_models_test.go
new file mode 100644
index 000000000..060c83494
--- /dev/null
+++ b/backend/internal/service/opencode_unsupported_models_test.go
@@ -0,0 +1,138 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func TestForwardOpenCodeUnsupportedModels_ChatCompletionsReturns400(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ account := &Account{
+ ID: 101,
+ Platform: PlatformOpenCodeGo,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "test-key",
+ "account_mode": AccountModeZen,
+ },
+ }
+
+ svc := &OpenAIGatewayService{
+ cfg: &config.Config{},
+ }
+
+ for _, model := range []string{"gemini-3.8-flash", "jev-1.13", "opencode/gemini-3.7-flash", "opencode-go/jev-1.13-free"} {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ body := []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"hello"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body))
+
+ result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
+ require.Nil(t, result)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "opencode unsupported model")
+
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ respBody := rec.Body.String()
+ require.Equal(t, "invalid_request_error", gjson.Get(respBody, "error.type").String())
+ require.Equal(t, "model_not_supported", gjson.Get(respBody, "error.code").String())
+ require.Contains(t, gjson.Get(respBody, "error.message").String(), "not supported on OpenCode standard gateway")
+ }
+}
+
+func TestForwardOpenCodeUnsupportedModels_ResponsesReturns400(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ account := &Account{
+ ID: 102,
+ Platform: PlatformOpenCodeGo,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "test-key",
+ "account_mode": AccountModeZen,
+ },
+ }
+
+ svc := &OpenAIGatewayService{
+ cfg: &config.Config{},
+ }
+
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ body := []byte(`{"model":"gemini-3.8-flash","input":[{"role":"user","content":"hello"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
+
+ result, err := svc.Forward(context.Background(), c, account, body)
+ require.Nil(t, result)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "opencode unsupported model")
+
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ respBody := rec.Body.String()
+ require.Equal(t, "invalid_request_error", gjson.Get(respBody, "error.type").String())
+ require.Equal(t, "model_not_supported", gjson.Get(respBody, "error.code").String())
+}
+
+func TestForwardOpenCodeUnsupportedModels_MessagesReturns400(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ account := &Account{
+ ID: 103,
+ Platform: PlatformOpenCodeGo,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "test-key",
+ "account_mode": AccountModeZen,
+ },
+ }
+
+ svc := &OpenAIGatewayService{
+ cfg: &config.Config{},
+ }
+
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ body := []byte(`{"model":"gemini-3.8-flash","messages":[{"role":"user","content":"hello"}]}`)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body))
+
+ result, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "")
+ require.Nil(t, result)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "opencode unsupported model")
+
+ require.Equal(t, http.StatusBadRequest, rec.Code)
+ respBody := rec.Body.String()
+ require.Equal(t, "invalid_request_error", gjson.Get(respBody, "error.type").String())
+ require.Contains(t, gjson.Get(respBody, "error.message").String(), "not supported on OpenCode standard gateway")
+}
+
+func TestAccountTestService_OpenCodeUnsupportedModelReturnsError(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/test", nil)
+
+ account := &Account{
+ ID: 104,
+ Platform: PlatformOpenCodeGo,
+ Type: AccountTypeAPIKey,
+ }
+
+ svc := &AccountTestService{}
+ err := svc.testModelRoutedAccountConnection(c, account, "gemini-3.8-flash", "hi")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "not supported on OpenCode standard gateway")
+
+ err = svc.testModelRoutedAccountConnection(c, account, "jev-1.13", "hi")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "not supported on OpenCode standard gateway")
+}
diff --git a/backend/internal/service/ops_dashboard_models.go b/backend/internal/service/ops_dashboard_models.go
index f189031bd..7ab9e69bc 100644
--- a/backend/internal/service/ops_dashboard_models.go
+++ b/backend/internal/service/ops_dashboard_models.go
@@ -29,6 +29,15 @@ type OpsPercentiles struct {
Max *int `json:"max_ms"`
}
+// OpsOutputTPS describes per-request output rates, not aggregate token throughput.
+type OpsOutputTPS struct {
+ P5 *float64 `json:"p5"`
+ P10 *float64 `json:"p10"`
+ P50 *float64 `json:"p50"`
+ Avg *float64 `json:"avg"`
+ SampleCount int64 `json:"sample_count"`
+}
+
type OpsDashboardOverview struct {
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
@@ -62,8 +71,9 @@ type OpsDashboardOverview struct {
Upstream429Count int64 `json:"upstream_429_count"`
Upstream529Count int64 `json:"upstream_529_count"`
- QPS OpsRateSummary `json:"qps"`
- TPS OpsRateSummary `json:"tps"`
+ QPS OpsRateSummary `json:"qps"`
+ TPS OpsRateSummary `json:"tps"`
+ OutputTPS *OpsOutputTPS `json:"output_tps"`
Duration OpsPercentiles `json:"duration"`
TTFT OpsPercentiles `json:"ttft"`
diff --git a/backend/internal/service/payment_config_service.go b/backend/internal/service/payment_config_service.go
index 880ae8ea5..449033daf 100644
--- a/backend/internal/service/payment_config_service.go
+++ b/backend/internal/service/payment_config_service.go
@@ -62,12 +62,18 @@ type PaymentConfig struct {
// SubscriptionUSDToCNYRate 为 0 时订阅换算关闭(兼容存量行为)。
SubscriptionUSDToCNYRate float64 `json:"subscription_usd_to_cny_rate"`
RechargeFeeRate float64 `json:"recharge_fee_rate"`
- LoadBalanceStrategy string `json:"load_balance_strategy"`
- ProductNamePrefix string `json:"product_name_prefix"`
- ProductNameSuffix string `json:"product_name_suffix"`
- HelpImageURL string `json:"help_image_url"`
- HelpText string `json:"help_text"`
- StripePublishableKey string `json:"stripe_publishable_key,omitempty"`
+ // RechargeBonusTiers 余额充值优惠阶梯(按 MinAmount 升序);空表示无优惠。
+ RechargeBonusTiers []RechargeBonusTier `json:"recharge_bonus_tiers"`
+ // RechargeBonusMode 阶梯模式:bonus(赠金)/ discount(折扣),已归一化。
+ RechargeBonusMode string `json:"recharge_bonus_mode"`
+ // RechargeBonusNotice 充值页展示的 Markdown 活动文案;空表示不展示。
+ RechargeBonusNotice string `json:"recharge_bonus_notice"`
+ LoadBalanceStrategy string `json:"load_balance_strategy"`
+ ProductNamePrefix string `json:"product_name_prefix"`
+ ProductNameSuffix string `json:"product_name_suffix"`
+ HelpImageURL string `json:"help_image_url"`
+ HelpText string `json:"help_text"`
+ StripePublishableKey string `json:"stripe_publishable_key,omitempty"`
// Cancel rate limit settings
CancelRateLimitEnabled bool `json:"cancel_rate_limit_enabled"`
@@ -95,11 +101,15 @@ type UpdatePaymentConfigRequest struct {
BalanceRechargeMultiplier *float64 `json:"balance_recharge_multiplier"`
SubscriptionUSDToCNYRate *float64 `json:"subscription_usd_to_cny_rate"`
RechargeFeeRate *float64 `json:"recharge_fee_rate"`
- LoadBalanceStrategy *string `json:"load_balance_strategy"`
- ProductNamePrefix *string `json:"product_name_prefix"`
- ProductNameSuffix *string `json:"product_name_suffix"`
- HelpImageURL *string `json:"help_image_url"`
- HelpText *string `json:"help_text"`
+ // RechargeBonusTiers nil 表示不更新;空切片表示清空阶梯。
+ RechargeBonusTiers *[]RechargeBonusTier `json:"recharge_bonus_tiers"`
+ RechargeBonusMode *string `json:"recharge_bonus_mode"`
+ RechargeBonusNotice *string `json:"recharge_bonus_notice"`
+ LoadBalanceStrategy *string `json:"load_balance_strategy"`
+ ProductNamePrefix *string `json:"product_name_prefix"`
+ ProductNameSuffix *string `json:"product_name_suffix"`
+ HelpImageURL *string `json:"help_image_url"`
+ HelpText *string `json:"help_text"`
// Cancel rate limit settings
CancelRateLimitEnabled *bool `json:"cancel_rate_limit_enabled"`
@@ -220,6 +230,7 @@ func (s *PaymentConfigService) GetPaymentConfig(ctx context.Context) (*PaymentCo
SettingPaymentEnabled, SettingMinRechargeAmount, SettingMaxRechargeAmount,
SettingDailyRechargeLimit, SettingOrderTimeoutMinutes, SettingMaxPendingOrders,
SettingEnabledPaymentTypes, SettingBalancePayDisabled, SettingBalanceRechargeMult, SettingSubscriptionUSDToCNYRate, SettingRechargeFeeRate, SettingLoadBalanceStrategy,
+ SettingRechargeBonusTiers, SettingRechargeBonusMode, SettingRechargeBonusNotice,
SettingProductNamePrefix, SettingProductNameSuffix,
SettingHelpImageURL, SettingHelpText,
SettingCancelRateLimitOn, SettingCancelRateLimitMax,
@@ -250,6 +261,8 @@ func (s *PaymentConfigService) parsePaymentConfig(vals map[string]string) *Payme
BalanceRechargeMultiplier: normalizeBalanceRechargeMultiplier(pcParseFloat(vals[SettingBalanceRechargeMult], defaultBalanceRechargeMultiplier)),
SubscriptionUSDToCNYRate: normalizeSubscriptionUSDToCNYRate(pcParseFloat(vals[SettingSubscriptionUSDToCNYRate], 0)),
RechargeFeeRate: pcParseFloat(vals[SettingRechargeFeeRate], 0),
+ RechargeBonusTiers: parseRechargeBonusTiers(vals[SettingRechargeBonusTiers]),
+ RechargeBonusNotice: vals[SettingRechargeBonusNotice],
LoadBalanceStrategy: vals[SettingLoadBalanceStrategy],
ProductNamePrefix: vals[SettingProductNamePrefix],
ProductNameSuffix: vals[SettingProductNameSuffix],
@@ -265,6 +278,7 @@ func (s *PaymentConfigService) parsePaymentConfig(vals map[string]string) *Payme
AlipayForceQRCode: vals[SettingAlipayForceQRCode] == "true",
AlipayMobilePrecreateDeepLink: vals[SettingAlipayMobilePrecreateDeepLink] == "true",
}
+ cfg.RechargeBonusMode, _ = NormalizeRechargeBonusMode(vals[SettingRechargeBonusMode])
cfg.AlipayMobilePrecreateDeepLink = pcEnvBoolOverride(
SettingAlipayMobilePrecreateDeepLink,
cfg.AlipayMobilePrecreateDeepLink,
@@ -343,6 +357,15 @@ func (s *PaymentConfigService) UpdatePaymentConfig(ctx context.Context, req Upda
return infraerrors.BadRequest("INVALID_RECHARGE_FEE_RATE", "recharge fee rate allows at most 2 decimal places")
}
}
+ rechargeBonusTiersValue, rechargeBonusModeValue, err := s.resolveRechargeBonusUpdate(ctx, req)
+ if err != nil {
+ return err
+ }
+ if req.RechargeBonusNotice != nil {
+ if err := validateRechargeBonusNotice(*req.RechargeBonusNotice); err != nil {
+ return infraerrors.BadRequest("INVALID_RECHARGE_BONUS_NOTICE", err.Error())
+ }
+ }
m := make(map[string]string)
if req.Enabled != nil {
m[SettingPaymentEnabled] = formatBoolOrEmpty(req.Enabled)
@@ -377,6 +400,15 @@ func (s *PaymentConfigService) UpdatePaymentConfig(ctx context.Context, req Upda
if req.RechargeFeeRate != nil {
m[SettingRechargeFeeRate] = formatNonNegativeFloat(req.RechargeFeeRate)
}
+ if req.RechargeBonusTiers != nil {
+ m[SettingRechargeBonusTiers] = rechargeBonusTiersValue
+ }
+ if req.RechargeBonusMode != nil {
+ m[SettingRechargeBonusMode] = rechargeBonusModeValue
+ }
+ if req.RechargeBonusNotice != nil {
+ m[SettingRechargeBonusNotice] = strings.TrimSpace(*req.RechargeBonusNotice)
+ }
if req.LoadBalanceStrategy != nil {
m[SettingLoadBalanceStrategy] = derefStr(req.LoadBalanceStrategy)
}
diff --git a/backend/internal/service/payment_fulfillment.go b/backend/internal/service/payment_fulfillment.go
index aa1000995..14ff8963f 100644
--- a/backend/internal/service/payment_fulfillment.go
+++ b/backend/internal/service/payment_fulfillment.go
@@ -741,7 +741,10 @@ func affiliateRebateBaseAmount(o *dbent.PaymentOrder) float64 {
return 0
}
switch o.OrderType {
- case payment.OrderTypeBalance, payment.OrderTypeSubscription:
+ case payment.OrderTypeBalance:
+ // 返利只按实充部分计算,赠送额度不参与
+ return paymentOrderAmountWithoutBonus(o)
+ case payment.OrderTypeSubscription:
return o.Amount
default:
return 0
diff --git a/backend/internal/service/payment_order.go b/backend/internal/service/payment_order.go
index abbc2b55d..a4948f060 100644
--- a/backend/internal/service/payment_order.go
+++ b/backend/internal/service/payment_order.go
@@ -53,14 +53,6 @@ func (s *PaymentService) CreateOrder(ctx context.Context, req CreateOrderRequest
if s.notificationEmailService != nil {
s.notificationEmailService.RememberRecipientLocale(ctx, req.UserID, user.Email, req.Locale)
}
- orderAmount := req.Amount
- limitAmount := req.Amount
- if plan != nil {
- orderAmount = plan.Price
- limitAmount = plan.Price
- } else if req.OrderType == payment.OrderTypeBalance {
- orderAmount = calculateCreditedBalance(req.Amount, cfg.BalanceRechargeMultiplier)
- }
feeRate := cfg.RechargeFeeRate
methodCurrency := payment.DefaultPaymentCurrency
if s.configService != nil {
@@ -69,6 +61,19 @@ func (s *PaymentService) CreateOrder(ctx context.Context, req CreateOrderRequest
return nil, err
}
}
+ orderAmount := req.Amount
+ limitAmount := req.Amount
+ bonusAmount := 0.0
+ if plan != nil {
+ orderAmount = plan.Price
+ limitAmount = plan.Price
+ } else if req.OrderType == payment.OrderTypeBalance {
+ // 阈值按支付金额命中。赠金模式:到账 = 基数 + 赠送;折扣模式:到账 = 基数,实付基数按折扣减少。
+ quote := quoteRechargeBonus(cfg, req.Amount, methodCurrency)
+ limitAmount = quote.PayBase
+ bonusAmount = quote.Bonus
+ orderAmount = quote.Credited
+ }
payAmountStr, payAmount, err := calculateCreateOrderPayAmountForOrderType(limitAmount, feeRate, methodCurrency, req.OrderType, cfg.SubscriptionUSDToCNYRate)
if err != nil {
return nil, err
@@ -100,7 +105,7 @@ func (s *PaymentService) CreateOrder(ctx context.Context, req CreateOrderRequest
if oauthResp != nil {
return oauthResp, nil
}
- order, err := s.createOrderInTx(ctx, req, user, plan, cfg, orderAmount, limitAmount, feeRate, payAmount, sel)
+ order, err := s.createOrderInTx(ctx, req, user, plan, cfg, orderAmount, limitAmount, feeRate, payAmount, bonusAmount, sel)
if err != nil {
return nil, err
}
@@ -149,7 +154,7 @@ func (s *PaymentService) validateSubOrder(ctx context.Context, req CreateOrderRe
return plan, nil
}
-func (s *PaymentService) createOrderInTx(ctx context.Context, req CreateOrderRequest, user *User, plan *dbent.SubscriptionPlan, cfg *PaymentConfig, orderAmount, limitAmount, feeRate, payAmount float64, sel *payment.InstanceSelection) (*dbent.PaymentOrder, error) {
+func (s *PaymentService) createOrderInTx(ctx context.Context, req CreateOrderRequest, user *User, plan *dbent.SubscriptionPlan, cfg *PaymentConfig, orderAmount, limitAmount, feeRate, payAmount, bonusAmount float64, sel *payment.InstanceSelection) (*dbent.PaymentOrder, error) {
tx, err := s.entClient.Tx(ctx)
if err != nil {
return nil, fmt.Errorf("begin transaction: %w", err)
@@ -185,6 +190,7 @@ func (s *PaymentService) createOrderInTx(ctx context.Context, req CreateOrderReq
SetAmount(orderAmount).
SetPayAmount(payAmount).
SetFeeRate(feeRate).
+ SetBonusAmount(bonusAmount).
SetRechargeCode("").
SetOutTradeNo(outTradeNo).
SetPaymentType(req.PaymentType).
@@ -471,6 +477,7 @@ func (s *PaymentService) invokeProvider(ctx context.Context, order *dbent.Paymen
s.writeAuditLog(ctx, order.ID, "ORDER_CREATED", fmt.Sprintf("user:%d", req.UserID), map[string]any{
"paymentAmount": req.Amount,
"creditedAmount": order.Amount,
+ "bonusAmount": order.BonusAmount,
"payAmount": order.PayAmount,
"paymentType": req.PaymentType,
"orderType": req.OrderType,
@@ -735,6 +742,7 @@ func buildCreateOrderResponse(order *dbent.PaymentOrder, req CreateOrderRequest,
Amount: order.Amount,
PayAmount: payAmount,
FeeRate: order.FeeRate,
+ BonusAmount: order.BonusAmount,
Status: OrderStatusPending,
ResultType: resultType,
PaymentType: req.PaymentType,
diff --git a/backend/internal/service/payment_order_provider_snapshot_test.go b/backend/internal/service/payment_order_provider_snapshot_test.go
index d82e2f0d8..5add7c04f 100644
--- a/backend/internal/service/payment_order_provider_snapshot_test.go
+++ b/backend/internal/service/payment_order_provider_snapshot_test.go
@@ -88,6 +88,7 @@ func TestCreateOrderInTx_WritesProviderSnapshot(t *testing.T) {
88,
0,
88,
+ 0,
&payment.InstanceSelection{
InstanceID: strconv.FormatInt(instance.ID, 10),
ProviderKey: payment.TypeAlipay,
diff --git a/backend/internal/service/payment_recharge_bonus.go b/backend/internal/service/payment_recharge_bonus.go
new file mode 100644
index 000000000..f5405b7b6
--- /dev/null
+++ b/backend/internal/service/payment_recharge_bonus.go
@@ -0,0 +1,337 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "math"
+ "sort"
+ "strings"
+ "unicode/utf8"
+
+ dbent "github.com/MACOS-DO/sub4api/ent"
+ "github.com/MACOS-DO/sub4api/internal/payment"
+ infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
+ "github.com/shopspring/decimal"
+)
+
+// 充值优惠阶梯:余额充值订单按用户输入的支付金额命中阶梯(取不超过该金额的最大 MinAmount),
+// 整条阶梯只有一种模式(RECHARGE_BONUS_MODE):
+// - bonus(赠金):实付不变,在到账基数(输入 × 充值倍率)之上额外赠送 BonusPercent% 的 USD 余额;
+// - discount(折扣):到账不变(输入 × 倍率),实付基数按 BonusPercent% 打折。
+//
+// 两种模式落库形态相同:amount 为到账总额,bonus_amount 为其中「免费」的 USD 部分,pay_amount 为实收。
+// 订阅订单不参与。优惠在下单时按当时配置计算并落库,后续改配置不影响已建订单。
+const (
+ // SettingRechargeBonusTiers 存 JSON 数组(RechargeBonusTier 列表),空/缺失表示未启用优惠。
+ SettingRechargeBonusTiers = "RECHARGE_BONUS_TIERS"
+ // SettingRechargeBonusNotice 充值页金额卡顶部展示的 Markdown 活动文案,空表示不展示。
+ SettingRechargeBonusNotice = "RECHARGE_BONUS_NOTICE"
+ // SettingRechargeBonusMode 阶梯模式:bonus / discount;空/非法按 bonus 解析(兼容早期配置)。
+ SettingRechargeBonusMode = "RECHARGE_BONUS_MODE"
+)
+
+const (
+ RechargeBonusModeBonus = "bonus"
+ RechargeBonusModeDiscount = "discount"
+)
+
+const (
+ maxRechargeBonusTiers = 20
+ maxRechargeBonusPercent = 1000
+ maxRechargeBonusNoticeRunes = 10000
+ rechargeBonusAmountEpsilon = 1e-9
+)
+
+// RechargeBonusTier 一个优惠档位:支付金额 ≥ MinAmount 时按 BonusPercent% 赠送(bonus)或打折(discount)。
+type RechargeBonusTier struct {
+ MinAmount float64 `json:"min_amount"`
+ BonusPercent float64 `json:"bonus_percent"`
+}
+
+// NormalizeRechargeBonusMode 归一化模式;空按 bonus。第二个返回值表示输入是否合法。
+func NormalizeRechargeBonusMode(raw string) (string, bool) {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case "", RechargeBonusModeBonus:
+ return RechargeBonusModeBonus, true
+ case RechargeBonusModeDiscount:
+ return RechargeBonusModeDiscount, true
+ default:
+ return RechargeBonusModeBonus, false
+ }
+}
+
+// ValidateRechargeBonusTiersForMode 折扣模式下百分比必须 < 100,否则实付为 0 或负数。
+func ValidateRechargeBonusTiersForMode(mode string, tiers []RechargeBonusTier) error {
+ if mode != RechargeBonusModeDiscount {
+ return nil
+ }
+ for _, tier := range tiers {
+ if tier.BonusPercent >= 100 {
+ return fmt.Errorf("discount percent must be less than 100 (tier with min amount %s)",
+ decimal.NewFromFloat(tier.MinAmount).Round(2).String())
+ }
+ }
+ return nil
+}
+
+func rechargeBonusValueValid(v float64, max float64) bool {
+ if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > max {
+ return false
+ }
+ d := decimal.NewFromFloat(v)
+ return d.Equal(d.Round(2))
+}
+
+// NormalizeRechargeBonusTiers 严格归一化(写路径):任何非法项直接报错;
+// 成功时返回按 MinAmount 升序排序的副本。
+func NormalizeRechargeBonusTiers(raw []RechargeBonusTier) ([]RechargeBonusTier, error) {
+ if len(raw) == 0 {
+ return []RechargeBonusTier{}, nil
+ }
+ if len(raw) > maxRechargeBonusTiers {
+ return nil, fmt.Errorf("recharge bonus tiers exceed limit of %d", maxRechargeBonusTiers)
+ }
+ out := make([]RechargeBonusTier, 0, len(raw))
+ seen := make(map[string]struct{}, len(raw))
+ for _, tier := range raw {
+ if !rechargeBonusValueValid(tier.MinAmount, math.MaxFloat64) {
+ return nil, fmt.Errorf("recharge bonus tier min amount must be a non-negative number with at most 2 decimals")
+ }
+ if !rechargeBonusValueValid(tier.BonusPercent, maxRechargeBonusPercent) {
+ return nil, fmt.Errorf("recharge bonus tier percent must be between 0 and %d with at most 2 decimals", maxRechargeBonusPercent)
+ }
+ key := decimal.NewFromFloat(tier.MinAmount).Round(2).String()
+ if _, dup := seen[key]; dup {
+ return nil, fmt.Errorf("duplicate recharge bonus tier min amount: %s", key)
+ }
+ seen[key] = struct{}{}
+ out = append(out, RechargeBonusTier{MinAmount: tier.MinAmount, BonusPercent: tier.BonusPercent})
+ }
+ sortRechargeBonusTiers(out)
+ return out, nil
+}
+
+func sortRechargeBonusTiers(tiers []RechargeBonusTier) {
+ sort.SliceStable(tiers, func(i, j int) bool {
+ return tiers[i].MinAmount < tiers[j].MinAmount
+ })
+}
+
+// encodeRechargeBonusTiers 序列化为设置值;空列表存空串,与「未配置」保持同一形态。
+func encodeRechargeBonusTiers(tiers []RechargeBonusTier) (string, error) {
+ if len(tiers) == 0 {
+ return "", nil
+ }
+ raw, err := json.Marshal(tiers)
+ if err != nil {
+ return "", fmt.Errorf("marshal recharge bonus tiers: %w", err)
+ }
+ return string(raw), nil
+}
+
+// parseRechargeBonusTiers 宽松解析(读路径):非法条目丢弃而非报错,避免历史错配置阻断下单。
+// 同一 MinAmount 重复时保留先出现的档位。始终返回非 nil 切片,便于 JSON 输出为 []。
+func parseRechargeBonusTiers(raw string) []RechargeBonusTier {
+ out := make([]RechargeBonusTier, 0)
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return out
+ }
+ var items []RechargeBonusTier
+ if err := json.Unmarshal([]byte(raw), &items); err != nil {
+ slog.Warn("[Payment] parseRechargeBonusTiers: unmarshal failed", "error", err)
+ return out
+ }
+ seen := make(map[string]struct{}, len(items))
+ for _, tier := range items {
+ if !rechargeBonusValueValid(tier.MinAmount, math.MaxFloat64) || !rechargeBonusValueValid(tier.BonusPercent, maxRechargeBonusPercent) {
+ continue
+ }
+ key := decimal.NewFromFloat(tier.MinAmount).Round(2).String()
+ if _, dup := seen[key]; dup {
+ continue
+ }
+ seen[key] = struct{}{}
+ out = append(out, tier)
+ }
+ sortRechargeBonusTiers(out)
+ return out
+}
+
+func validateRechargeBonusNotice(notice string) error {
+ if utf8.RuneCountInString(notice) > maxRechargeBonusNoticeRunes {
+ return fmt.Errorf("recharge bonus notice exceeds %d characters", maxRechargeBonusNoticeRunes)
+ }
+ return nil
+}
+
+// resolveRechargeBonusUpdate 校验并归一化阶梯/模式更新。任一字段缺省时读取现值做交叉校验
+// (折扣模式下所有档位百分比必须 < 100)。返回值仅在对应请求字段非 nil 时有意义。
+func (s *PaymentConfigService) resolveRechargeBonusUpdate(ctx context.Context, req UpdatePaymentConfigRequest) (tiersValue string, modeValue string, err error) {
+ if req.RechargeBonusTiers == nil && req.RechargeBonusMode == nil {
+ return "", "", nil
+ }
+ stored := map[string]string{}
+ if (req.RechargeBonusTiers == nil || req.RechargeBonusMode == nil) && s != nil && s.settingRepo != nil {
+ stored, err = s.settingRepo.GetMultiple(ctx, []string{SettingRechargeBonusTiers, SettingRechargeBonusMode})
+ if err != nil {
+ return "", "", fmt.Errorf("get recharge bonus settings: %w", err)
+ }
+ }
+
+ var tiers []RechargeBonusTier
+ if req.RechargeBonusTiers != nil {
+ tiers, err = NormalizeRechargeBonusTiers(*req.RechargeBonusTiers)
+ if err != nil {
+ return "", "", infraerrors.BadRequest("INVALID_RECHARGE_BONUS_TIERS", err.Error())
+ }
+ } else {
+ tiers = parseRechargeBonusTiers(stored[SettingRechargeBonusTiers])
+ }
+
+ var mode string
+ if req.RechargeBonusMode != nil {
+ normalized, ok := NormalizeRechargeBonusMode(*req.RechargeBonusMode)
+ if !ok {
+ return "", "", infraerrors.BadRequest("INVALID_RECHARGE_BONUS_MODE", "recharge bonus mode must be bonus or discount")
+ }
+ mode = normalized
+ } else {
+ mode, _ = NormalizeRechargeBonusMode(stored[SettingRechargeBonusMode])
+ }
+
+ if err := ValidateRechargeBonusTiersForMode(mode, tiers); err != nil {
+ return "", "", infraerrors.BadRequest("INVALID_RECHARGE_BONUS_TIERS", err.Error())
+ }
+ tiersValue, err = encodeRechargeBonusTiers(tiers)
+ if err != nil {
+ return "", "", err
+ }
+ return tiersValue, mode, nil
+}
+
+// matchRechargeBonusTier 返回不超过 paymentAmount 的最大档位;tiers 需已按 MinAmount 升序。
+func matchRechargeBonusTier(tiers []RechargeBonusTier, paymentAmount float64) (RechargeBonusTier, bool) {
+ if math.IsNaN(paymentAmount) || math.IsInf(paymentAmount, 0) || paymentAmount <= 0 {
+ return RechargeBonusTier{}, false
+ }
+ var matched RechargeBonusTier
+ found := false
+ for _, tier := range tiers {
+ if paymentAmount+rechargeBonusAmountEpsilon < tier.MinAmount {
+ break
+ }
+ matched = tier
+ found = true
+ }
+ return matched, found
+}
+
+// calculateRechargeBonus 赠送金额 = 到账基数 × 百分比,保留两位小数(四舍五入)。
+func calculateRechargeBonus(baseCredited, bonusPercent float64) float64 {
+ if baseCredited <= 0 || bonusPercent <= 0 || math.IsNaN(baseCredited) || math.IsNaN(bonusPercent) {
+ return 0
+ }
+ return decimal.NewFromFloat(baseCredited).
+ Mul(decimal.NewFromFloat(bonusPercent)).
+ Div(decimal.NewFromInt(100)).
+ Round(2).
+ InexactFloat64()
+}
+
+// addRechargeBonus 到账总额 = 基数 + 赠送,两位小数。
+func addRechargeBonus(baseCredited, bonus float64) float64 {
+ return decimal.NewFromFloat(baseCredited).
+ Add(decimal.NewFromFloat(bonus)).
+ Round(2).
+ InexactFloat64()
+}
+
+// calculateDiscountedPayBase 折扣模式实付基数 = 支付金额 × (1 − 百分比),按币种精度四舍五入。
+func calculateDiscountedPayBase(paymentAmount, discountPercent float64, currency string) float64 {
+ digits := int32(payment.CurrencyMaxFractionDigits(currency))
+ return decimal.NewFromFloat(paymentAmount).
+ Mul(decimal.NewFromInt(100).Sub(decimal.NewFromFloat(discountPercent))).
+ Div(decimal.NewFromInt(100)).
+ Round(digits).
+ InexactFloat64()
+}
+
+// rechargeBonusQuote 一笔余额充值的报价结果。
+type rechargeBonusQuote struct {
+ // PayBase 网关收款基数(支付币种,不含手续费);赠金模式等于支付金额,折扣模式为折后金额。
+ PayBase float64
+ // Credited 到账总额(USD),含 Bonus。
+ Credited float64
+ // Bonus 免费额度(USD):赠金模式为额外赠送,折扣模式为未付费却到账的部分。
+ Bonus float64
+ // Percent 命中档位的百分比;未命中或未产生优惠时为 0。
+ Percent float64
+}
+
+// quoteRechargeBonus 按配置模式报价。currency 用于折扣模式实付基数的精度。
+// 未配置阶梯、未命中、或折扣百分比 ≥ 100(非法历史数据,fail-safe)时按无优惠处理。
+func quoteRechargeBonus(cfg *PaymentConfig, paymentAmount float64, currency string) rechargeBonusQuote {
+ multiplier := defaultBalanceRechargeMultiplier
+ var tiers []RechargeBonusTier
+ mode := RechargeBonusModeBonus
+ if cfg != nil {
+ multiplier = cfg.BalanceRechargeMultiplier
+ tiers = cfg.RechargeBonusTiers
+ mode, _ = NormalizeRechargeBonusMode(cfg.RechargeBonusMode)
+ }
+ base := calculateCreditedBalance(paymentAmount, multiplier)
+ quote := rechargeBonusQuote{PayBase: paymentAmount, Credited: base}
+
+ tier, ok := matchRechargeBonusTier(tiers, paymentAmount)
+ if !ok || tier.BonusPercent <= 0 {
+ return quote
+ }
+ switch mode {
+ case RechargeBonusModeDiscount:
+ if tier.BonusPercent >= 100 {
+ return quote
+ }
+ payBase := calculateDiscountedPayBase(paymentAmount, tier.BonusPercent, currency)
+ if payBase <= 0 || payBase >= paymentAmount {
+ return quote
+ }
+ paidCredit := calculateCreditedBalance(payBase, multiplier)
+ bonus := decimal.NewFromFloat(base).Sub(decimal.NewFromFloat(paidCredit)).Round(2).InexactFloat64()
+ if bonus < 0 {
+ bonus = 0
+ }
+ quote.PayBase = payBase
+ quote.Bonus = bonus
+ quote.Percent = tier.BonusPercent
+ default:
+ bonus := calculateRechargeBonus(base, tier.BonusPercent)
+ if bonus <= 0 {
+ return quote
+ }
+ quote.Bonus = bonus
+ quote.Credited = addRechargeBonus(base, bonus)
+ quote.Percent = tier.BonusPercent
+ }
+ return quote
+}
+
+// paymentOrderAmountWithoutBonus 订单到账金额剔除免费额度后的实付部分(USD),用于推广返利基数。
+func paymentOrderAmountWithoutBonus(o *dbent.PaymentOrder) float64 {
+ if o == nil {
+ return 0
+ }
+ if o.OrderType != payment.OrderTypeBalance || o.BonusAmount <= 0 {
+ return o.Amount
+ }
+ base := decimal.NewFromFloat(o.Amount).
+ Sub(decimal.NewFromFloat(o.BonusAmount)).
+ Round(2).
+ InexactFloat64()
+ if base < 0 {
+ return 0
+ }
+ return base
+}
diff --git a/backend/internal/service/payment_recharge_bonus_test.go b/backend/internal/service/payment_recharge_bonus_test.go
new file mode 100644
index 000000000..ffaad3074
--- /dev/null
+++ b/backend/internal/service/payment_recharge_bonus_test.go
@@ -0,0 +1,349 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "testing"
+
+ dbent "github.com/MACOS-DO/sub4api/ent"
+ "github.com/MACOS-DO/sub4api/internal/payment"
+ "github.com/stretchr/testify/require"
+)
+
+func TestNormalizeRechargeBonusTiers(t *testing.T) {
+ t.Run("sorts ascending by min amount", func(t *testing.T) {
+ out, err := NormalizeRechargeBonusTiers([]RechargeBonusTier{
+ {MinAmount: 1000, BonusPercent: 35},
+ {MinAmount: 100, BonusPercent: 20},
+ {MinAmount: 500, BonusPercent: 30},
+ })
+ require.NoError(t, err)
+ require.Equal(t, []RechargeBonusTier{
+ {MinAmount: 100, BonusPercent: 20},
+ {MinAmount: 500, BonusPercent: 30},
+ {MinAmount: 1000, BonusPercent: 35},
+ }, out)
+ })
+
+ t.Run("empty input yields empty non-nil slice", func(t *testing.T) {
+ out, err := NormalizeRechargeBonusTiers(nil)
+ require.NoError(t, err)
+ require.NotNil(t, out)
+ require.Len(t, out, 0)
+ })
+
+ t.Run("allows zero threshold and zero percent", func(t *testing.T) {
+ out, err := NormalizeRechargeBonusTiers([]RechargeBonusTier{{MinAmount: 0, BonusPercent: 0}})
+ require.NoError(t, err)
+ require.Len(t, out, 1)
+ })
+
+ t.Run("rejects invalid values", func(t *testing.T) {
+ cases := map[string][]RechargeBonusTier{
+ "negative min": {{MinAmount: -1, BonusPercent: 10}},
+ "min three decimals": {{MinAmount: 100.123, BonusPercent: 10}},
+ "negative percent": {{MinAmount: 100, BonusPercent: -5}},
+ "percent over limit": {{MinAmount: 100, BonusPercent: 1000.01}},
+ "percent 3 decimals": {{MinAmount: 100, BonusPercent: 12.345}},
+ "duplicate min": {{MinAmount: 100, BonusPercent: 10}, {MinAmount: 100, BonusPercent: 20}},
+ "duplicate min 2 dec": {{MinAmount: 100, BonusPercent: 10}, {MinAmount: 100.00, BonusPercent: 20}},
+ }
+ for name, tiers := range cases {
+ _, err := NormalizeRechargeBonusTiers(tiers)
+ require.Error(t, err, name)
+ }
+ })
+
+ t.Run("rejects too many tiers", func(t *testing.T) {
+ tiers := make([]RechargeBonusTier, 0, maxRechargeBonusTiers+1)
+ for i := 0; i <= maxRechargeBonusTiers; i++ {
+ tiers = append(tiers, RechargeBonusTier{MinAmount: float64(i + 1), BonusPercent: 1})
+ }
+ _, err := NormalizeRechargeBonusTiers(tiers)
+ require.Error(t, err)
+ })
+}
+
+func TestParseRechargeBonusTiers(t *testing.T) {
+ t.Run("empty or invalid json yields empty slice", func(t *testing.T) {
+ require.NotNil(t, parseRechargeBonusTiers(""))
+ require.Len(t, parseRechargeBonusTiers(""), 0)
+ require.Len(t, parseRechargeBonusTiers("not json"), 0)
+ })
+
+ t.Run("drops invalid entries keeps first duplicate and sorts", func(t *testing.T) {
+ raw := `[{"min_amount":500,"bonus_percent":30},{"min_amount":-1,"bonus_percent":5},` +
+ `{"min_amount":100,"bonus_percent":20},{"min_amount":100,"bonus_percent":99},` +
+ `{"min_amount":50,"bonus_percent":5000}]`
+ out := parseRechargeBonusTiers(raw)
+ require.Equal(t, []RechargeBonusTier{
+ {MinAmount: 100, BonusPercent: 20},
+ {MinAmount: 500, BonusPercent: 30},
+ }, out)
+ })
+
+ t.Run("round trips encode", func(t *testing.T) {
+ tiers := []RechargeBonusTier{{MinAmount: 100, BonusPercent: 20}, {MinAmount: 500, BonusPercent: 30}}
+ encoded, err := encodeRechargeBonusTiers(tiers)
+ require.NoError(t, err)
+ require.Equal(t, tiers, parseRechargeBonusTiers(encoded))
+
+ empty, err := encodeRechargeBonusTiers(nil)
+ require.NoError(t, err)
+ require.Equal(t, "", empty)
+ })
+}
+
+func TestMatchRechargeBonusTier(t *testing.T) {
+ tiers := []RechargeBonusTier{
+ {MinAmount: 100, BonusPercent: 20},
+ {MinAmount: 500, BonusPercent: 30},
+ {MinAmount: 1000, BonusPercent: 35},
+ }
+ cases := []struct {
+ amount float64
+ percent float64
+ ok bool
+ }{
+ {amount: 0, ok: false},
+ {amount: 99.99, ok: false},
+ {amount: 100, percent: 20, ok: true},
+ {amount: 499.99, percent: 20, ok: true},
+ {amount: 500, percent: 30, ok: true},
+ {amount: 1000, percent: 35, ok: true},
+ {amount: 1000000, percent: 35, ok: true},
+ }
+ for _, tc := range cases {
+ tier, ok := matchRechargeBonusTier(tiers, tc.amount)
+ require.Equal(t, tc.ok, ok, "amount %v", tc.amount)
+ if ok {
+ require.Equal(t, tc.percent, tier.BonusPercent, "amount %v", tc.amount)
+ }
+ }
+
+ t.Run("float boundary 0.1+0.2 still matches 0.3 threshold", func(t *testing.T) {
+ _, ok := matchRechargeBonusTier([]RechargeBonusTier{{MinAmount: 0.3, BonusPercent: 1}}, 0.1+0.2)
+ require.True(t, ok)
+ })
+
+ t.Run("no tiers never matches", func(t *testing.T) {
+ _, ok := matchRechargeBonusTier(nil, 100)
+ require.False(t, ok)
+ })
+}
+
+func TestCalculateRechargeBonusRounding(t *testing.T) {
+ require.Equal(t, 20.0, calculateRechargeBonus(100, 20))
+ require.Equal(t, 120.0, addRechargeBonus(100, 20))
+ // 33.33 * 15% = 4.9995 → 5.00
+ require.Equal(t, 5.0, calculateRechargeBonus(33.33, 15))
+ require.Zero(t, calculateRechargeBonus(100, 0))
+ require.Zero(t, calculateRechargeBonus(0, 20))
+
+ // 阈值按支付金额命中,赠送按到账基数计算:1000 CNY × 0.14 = 140 USD,命中 1000 档 30% → 42
+ cfg := &PaymentConfig{
+ BalanceRechargeMultiplier: 0.14,
+ RechargeBonusTiers: []RechargeBonusTier{{MinAmount: 100, BonusPercent: 20}, {MinAmount: 500, BonusPercent: 30}},
+ }
+ require.Equal(t, rechargeBonusQuote{PayBase: 1000, Credited: 182, Bonus: 42, Percent: 30}, quoteRechargeBonus(cfg, 1000, "CNY"))
+ // 命中 0% 档位视为无优惠
+ cfg.RechargeBonusTiers = []RechargeBonusTier{{MinAmount: 10, BonusPercent: 0}}
+ require.Equal(t, rechargeBonusQuote{PayBase: 50, Credited: 7}, quoteRechargeBonus(cfg, 50, "CNY"))
+}
+
+func TestParsePaymentConfigRechargeBonus(t *testing.T) {
+ svc := &PaymentConfigService{}
+
+ t.Run("defaults", func(t *testing.T) {
+ cfg := svc.parsePaymentConfig(map[string]string{})
+ require.NotNil(t, cfg.RechargeBonusTiers)
+ require.Len(t, cfg.RechargeBonusTiers, 0)
+ require.Equal(t, "", cfg.RechargeBonusNotice)
+ })
+
+ t.Run("reads tiers and notice", func(t *testing.T) {
+ cfg := svc.parsePaymentConfig(map[string]string{
+ SettingRechargeBonusTiers: `[{"min_amount":500,"bonus_percent":30},{"min_amount":100,"bonus_percent":20}]`,
+ SettingRechargeBonusNotice: "**满 100 送 20%**",
+ })
+ require.Equal(t, []RechargeBonusTier{{MinAmount: 100, BonusPercent: 20}, {MinAmount: 500, BonusPercent: 30}}, cfg.RechargeBonusTiers)
+ require.Equal(t, "**满 100 送 20%**", cfg.RechargeBonusNotice)
+ })
+}
+
+func TestUpdatePaymentConfigRechargeBonus(t *testing.T) {
+ ctx := context.Background()
+
+ t.Run("persists normalized tiers and trimmed notice", func(t *testing.T) {
+ repo := &paymentConfigSettingRepoStub{values: map[string]string{}}
+ svc := &PaymentConfigService{settingRepo: repo}
+ tiers := []RechargeBonusTier{{MinAmount: 500, BonusPercent: 30}, {MinAmount: 100, BonusPercent: 20}}
+ notice := " 活动文案 "
+ require.NoError(t, svc.UpdatePaymentConfig(ctx, UpdatePaymentConfigRequest{
+ RechargeBonusTiers: &tiers,
+ RechargeBonusNotice: ¬ice,
+ }))
+ require.Equal(t, `[{"min_amount":100,"bonus_percent":20},{"min_amount":500,"bonus_percent":30}]`, repo.updates[SettingRechargeBonusTiers])
+ require.Equal(t, "活动文案", repo.updates[SettingRechargeBonusNotice])
+
+ cfg, err := svc.GetPaymentConfig(ctx)
+ require.NoError(t, err)
+ require.Equal(t, []RechargeBonusTier{{MinAmount: 100, BonusPercent: 20}, {MinAmount: 500, BonusPercent: 30}}, cfg.RechargeBonusTiers)
+ })
+
+ t.Run("empty tiers clears setting and omitted fields are untouched", func(t *testing.T) {
+ repo := &paymentConfigSettingRepoStub{values: map[string]string{
+ SettingRechargeBonusTiers: `[{"min_amount":100,"bonus_percent":20}]`,
+ SettingRechargeBonusNotice: "keep me",
+ }}
+ svc := &PaymentConfigService{settingRepo: repo}
+ empty := []RechargeBonusTier{}
+ require.NoError(t, svc.UpdatePaymentConfig(ctx, UpdatePaymentConfigRequest{RechargeBonusTiers: &empty}))
+ value, ok := repo.updates[SettingRechargeBonusTiers]
+ require.True(t, ok)
+ require.Equal(t, "", value)
+ _, touched := repo.updates[SettingRechargeBonusNotice]
+ require.False(t, touched)
+ require.Equal(t, "keep me", repo.values[SettingRechargeBonusNotice])
+ })
+
+ t.Run("rejects invalid tiers", func(t *testing.T) {
+ repo := &paymentConfigSettingRepoStub{values: map[string]string{}}
+ svc := &PaymentConfigService{settingRepo: repo}
+ bad := []RechargeBonusTier{{MinAmount: 100, BonusPercent: 20}, {MinAmount: 100, BonusPercent: 30}}
+ err := svc.UpdatePaymentConfig(ctx, UpdatePaymentConfigRequest{RechargeBonusTiers: &bad})
+ require.Error(t, err)
+ require.Nil(t, repo.updates)
+ })
+}
+
+func TestAffiliateRebateBaseAmountExcludesRechargeBonus(t *testing.T) {
+ require.Equal(t, 100.0, affiliateRebateBaseAmount(&dbent.PaymentOrder{
+ OrderType: payment.OrderTypeBalance, Amount: 130, BonusAmount: 30,
+ }))
+ require.Equal(t, 130.0, affiliateRebateBaseAmount(&dbent.PaymentOrder{
+ OrderType: payment.OrderTypeBalance, Amount: 130,
+ }))
+ // 订阅订单不受 bonus 字段影响
+ require.Equal(t, 50.0, affiliateRebateBaseAmount(&dbent.PaymentOrder{
+ OrderType: payment.OrderTypeSubscription, Amount: 50, BonusAmount: 30,
+ }))
+ // 异常数据:赠送大于总额时钳到 0
+ require.Equal(t, 0.0, affiliateRebateBaseAmount(&dbent.PaymentOrder{
+ OrderType: payment.OrderTypeBalance, Amount: 10, BonusAmount: 30,
+ }))
+}
+
+func TestNormalizeRechargeBonusMode(t *testing.T) {
+ for raw, want := range map[string]string{"": RechargeBonusModeBonus, "bonus": RechargeBonusModeBonus, " Discount ": RechargeBonusModeDiscount} {
+ mode, ok := NormalizeRechargeBonusMode(raw)
+ require.True(t, ok, raw)
+ require.Equal(t, want, mode, raw)
+ }
+ mode, ok := NormalizeRechargeBonusMode("cashback")
+ require.False(t, ok)
+ require.Equal(t, RechargeBonusModeBonus, mode)
+}
+
+func TestValidateRechargeBonusTiersForMode(t *testing.T) {
+ tiers := []RechargeBonusTier{{MinAmount: 100, BonusPercent: 20}, {MinAmount: 500, BonusPercent: 100}}
+ require.NoError(t, ValidateRechargeBonusTiersForMode(RechargeBonusModeBonus, tiers))
+ require.Error(t, ValidateRechargeBonusTiersForMode(RechargeBonusModeDiscount, tiers))
+ require.NoError(t, ValidateRechargeBonusTiersForMode(RechargeBonusModeDiscount, tiers[:1]))
+}
+
+func TestQuoteRechargeBonus(t *testing.T) {
+ tiers := []RechargeBonusTier{{MinAmount: 100, BonusPercent: 20}, {MinAmount: 500, BonusPercent: 50}}
+
+ t.Run("bonus mode keeps pay base and inflates credit", func(t *testing.T) {
+ cfg := &PaymentConfig{BalanceRechargeMultiplier: 1, RechargeBonusTiers: tiers, RechargeBonusMode: RechargeBonusModeBonus}
+ q := quoteRechargeBonus(cfg, 100, "USD")
+ require.Equal(t, rechargeBonusQuote{PayBase: 100, Credited: 120, Bonus: 20, Percent: 20}, q)
+
+ // 未命中:无优惠
+ q = quoteRechargeBonus(cfg, 50, "USD")
+ require.Equal(t, rechargeBonusQuote{PayBase: 50, Credited: 50}, q)
+ })
+
+ t.Run("discount mode keeps credit and reduces pay base", func(t *testing.T) {
+ cfg := &PaymentConfig{BalanceRechargeMultiplier: 1, RechargeBonusTiers: tiers, RechargeBonusMode: RechargeBonusModeDiscount}
+ q := quoteRechargeBonus(cfg, 500, "USD")
+ require.Equal(t, rechargeBonusQuote{PayBase: 250, Credited: 500, Bonus: 250, Percent: 50}, q)
+
+ // 倍率 0.14:1000 CNY 到账 140 USD;20% off 实付 800 CNY,免费部分 = 140 − 112 = 28 USD
+ cfg.BalanceRechargeMultiplier = 0.14
+ q = quoteRechargeBonus(cfg, 1000, "CNY")
+ require.Equal(t, rechargeBonusQuote{PayBase: 500, Credited: 140, Bonus: 70, Percent: 50}, q)
+ q = quoteRechargeBonus(cfg, 200, "CNY")
+ require.Equal(t, rechargeBonusQuote{PayBase: 160, Credited: 28, Bonus: 5.6, Percent: 20}, q)
+ })
+
+ t.Run("discount rounds pay base to currency precision", func(t *testing.T) {
+ cfg := &PaymentConfig{BalanceRechargeMultiplier: 1, RechargeBonusTiers: []RechargeBonusTier{{MinAmount: 1, BonusPercent: 15}}, RechargeBonusMode: RechargeBonusModeDiscount}
+ require.Equal(t, 85.85, quoteRechargeBonus(cfg, 101, "USD").PayBase)
+ require.Equal(t, 86.0, quoteRechargeBonus(cfg, 101, "JPY").PayBase)
+ })
+
+ t.Run("discount percent at or above 100 is ignored fail-safe", func(t *testing.T) {
+ cfg := &PaymentConfig{BalanceRechargeMultiplier: 1, RechargeBonusTiers: []RechargeBonusTier{{MinAmount: 1, BonusPercent: 100}}, RechargeBonusMode: RechargeBonusModeDiscount}
+ require.Equal(t, rechargeBonusQuote{PayBase: 100, Credited: 100}, quoteRechargeBonus(cfg, 100, "USD"))
+ })
+
+ t.Run("nil config and empty tiers yield plain conversion", func(t *testing.T) {
+ require.Equal(t, rechargeBonusQuote{PayBase: 100, Credited: 100}, quoteRechargeBonus(nil, 100, "USD"))
+ require.Equal(t, rechargeBonusQuote{PayBase: 100, Credited: 14}, quoteRechargeBonus(&PaymentConfig{BalanceRechargeMultiplier: 0.14}, 100, "CNY"))
+ })
+}
+
+func TestParsePaymentConfigRechargeBonusMode(t *testing.T) {
+ svc := &PaymentConfigService{}
+ require.Equal(t, RechargeBonusModeBonus, svc.parsePaymentConfig(map[string]string{}).RechargeBonusMode)
+ require.Equal(t, RechargeBonusModeDiscount, svc.parsePaymentConfig(map[string]string{SettingRechargeBonusMode: "discount"}).RechargeBonusMode)
+ require.Equal(t, RechargeBonusModeBonus, svc.parsePaymentConfig(map[string]string{SettingRechargeBonusMode: "junk"}).RechargeBonusMode)
+}
+
+func TestUpdatePaymentConfigRechargeBonusMode(t *testing.T) {
+ ctx := context.Background()
+
+ t.Run("persists discount mode with valid tiers", func(t *testing.T) {
+ repo := &paymentConfigSettingRepoStub{values: map[string]string{}}
+ svc := &PaymentConfigService{settingRepo: repo}
+ mode := "discount"
+ tiers := []RechargeBonusTier{{MinAmount: 100, BonusPercent: 20}}
+ require.NoError(t, svc.UpdatePaymentConfig(ctx, UpdatePaymentConfigRequest{RechargeBonusTiers: &tiers, RechargeBonusMode: &mode}))
+ require.Equal(t, "discount", repo.updates[SettingRechargeBonusMode])
+ cfg, err := svc.GetPaymentConfig(ctx)
+ require.NoError(t, err)
+ require.Equal(t, RechargeBonusModeDiscount, cfg.RechargeBonusMode)
+ })
+
+ t.Run("rejects unknown mode", func(t *testing.T) {
+ repo := &paymentConfigSettingRepoStub{values: map[string]string{}}
+ svc := &PaymentConfigService{settingRepo: repo}
+ mode := "cashback"
+ require.Error(t, svc.UpdatePaymentConfig(ctx, UpdatePaymentConfigRequest{RechargeBonusMode: &mode}))
+ require.Nil(t, repo.updates)
+ })
+
+ t.Run("switching to discount with stored tiers at 100 percent is rejected", func(t *testing.T) {
+ repo := &paymentConfigSettingRepoStub{values: map[string]string{
+ SettingRechargeBonusTiers: `[{"min_amount":100,"bonus_percent":100}]`,
+ }}
+ svc := &PaymentConfigService{settingRepo: repo}
+ mode := "discount"
+ require.Error(t, svc.UpdatePaymentConfig(ctx, UpdatePaymentConfigRequest{RechargeBonusMode: &mode}))
+ require.Nil(t, repo.updates)
+ })
+
+ t.Run("saving tiers at 100 percent while stored mode is discount is rejected", func(t *testing.T) {
+ repo := &paymentConfigSettingRepoStub{values: map[string]string{SettingRechargeBonusMode: "discount"}}
+ svc := &PaymentConfigService{settingRepo: repo}
+ tiers := []RechargeBonusTier{{MinAmount: 100, BonusPercent: 100}}
+ require.Error(t, svc.UpdatePaymentConfig(ctx, UpdatePaymentConfigRequest{RechargeBonusTiers: &tiers}))
+ require.Nil(t, repo.updates)
+ // 同样的档位在赠金模式下合法
+ repo.values[SettingRechargeBonusMode] = "bonus"
+ require.NoError(t, svc.UpdatePaymentConfig(ctx, UpdatePaymentConfigRequest{RechargeBonusTiers: &tiers}))
+ })
+}
diff --git a/backend/internal/service/payment_resume_service.go b/backend/internal/service/payment_resume_service.go
index 02ee7cda0..92366c631 100644
--- a/backend/internal/service/payment_resume_service.go
+++ b/backend/internal/service/payment_resume_service.go
@@ -245,6 +245,13 @@ func CanonicalizeReturnURL(raw string, srcHost string, srcURL string) (string, e
return "", infraerrors.BadRequest("INVALID_RETURN_URL", "return_url must use http or https")
}
parsed.Fragment = ""
+ // Client-supplied query parameters are dropped: buildPaymentReturnURL adds
+ // its own signed set, and user-controlled pairs such as
+ // "trade_status=TRADE_SUCCESS" inside the signed return_url value can be
+ // smuggled into EasyPay-style sign base strings (values are concatenated
+ // unescaped), letting an order-creation signature be replayed as a forged
+ // payment-success callback. See issue #7881.
+ parsed.RawQuery = ""
if parsed.Path == "" {
parsed.Path = "/"
}
diff --git a/backend/internal/service/payment_resume_service_test.go b/backend/internal/service/payment_resume_service_test.go
index 47987aad7..0e81ba9a8 100644
--- a/backend/internal/service/payment_resume_service_test.go
+++ b/backend/internal/service/payment_resume_service_test.go
@@ -10,6 +10,7 @@ import (
"encoding/json"
"net/url"
"strconv"
+ "strings"
"testing"
"time"
@@ -81,12 +82,30 @@ func TestNormalizePaymentSource(t *testing.T) {
func TestCanonicalizeReturnURL(t *testing.T) {
t.Parallel()
+ // Client-supplied query and fragment are both dropped: user-controlled
+ // pairs inside the signed return_url value could be smuggled into
+ // EasyPay-style sign base strings (issue #7881).
got, err := CanonicalizeReturnURL("https://example.com/payment/result?b=2#a", "example.com", "")
if err != nil {
t.Fatalf("CanonicalizeReturnURL returned error: %v", err)
}
- if got != "https://example.com/payment/result?b=2" {
- t.Fatalf("CanonicalizeReturnURL = %q, want %q", got, "https://example.com/payment/result?b=2")
+ if got != "https://example.com/payment/result" {
+ t.Fatalf("CanonicalizeReturnURL = %q, want %q", got, "https://example.com/payment/result")
+ }
+}
+
+func TestCanonicalizeReturnURLStripsSmuggledTradeStatus(t *testing.T) {
+ t.Parallel()
+
+ got, err := CanonicalizeReturnURL(
+ "https://example.com/payment/result?trade_status=TRADE_SUCCESS",
+ "example.com", "",
+ )
+ if err != nil {
+ t.Fatalf("CanonicalizeReturnURL returned error: %v", err)
+ }
+ if strings.Contains(got, "trade_status") {
+ t.Fatalf("CanonicalizeReturnURL kept smuggled trade_status: %q", got)
}
}
@@ -117,8 +136,10 @@ func TestCanonicalizeReturnURLAllowsConfiguredFrontendHost(t *testing.T) {
if err != nil {
t.Fatalf("CanonicalizeReturnURL returned error: %v", err)
}
- if got != "https://app.example.com/payment/result?from=checkout" {
- t.Fatalf("CanonicalizeReturnURL = %q, want %q", got, "https://app.example.com/payment/result?from=checkout")
+ // The host allowlist still applies, but client query parameters are
+ // always dropped (issue #7881: signed-value parameter smuggling).
+ if got != "https://app.example.com/payment/result" {
+ t.Fatalf("CanonicalizeReturnURL = %q, want %q", got, "https://app.example.com/payment/result")
}
}
diff --git a/backend/internal/service/payment_service.go b/backend/internal/service/payment_service.go
index 3f2c3fce6..21379c7c5 100644
--- a/backend/internal/service/payment_service.go
+++ b/backend/internal/service/payment_service.go
@@ -92,6 +92,7 @@ type CreateOrderResponse struct {
Amount float64 `json:"amount"`
PayAmount float64 `json:"pay_amount"`
FeeRate float64 `json:"fee_rate"`
+ BonusAmount float64 `json:"bonus_amount"`
Status string `json:"status"`
ResultType payment.CreatePaymentResultType `json:"result_type,omitempty"`
PaymentType string `json:"payment_type"`
diff --git a/backend/internal/service/platform_catalog.go b/backend/internal/service/platform_catalog.go
new file mode 100644
index 000000000..5ef702fda
--- /dev/null
+++ b/backend/internal/service/platform_catalog.go
@@ -0,0 +1,110 @@
+package service
+
+import (
+ "sort"
+
+ "github.com/MACOS-DO/sub4api/internal/domain"
+)
+
+// PlatformCatalog 是前端使用的平台清单:domain 平台清单加上多协议供应商的
+// profile(接入模式、各协议默认基址、内置分流规则)。它被写成前端内置清单
+// frontend/src/constants/platformCatalog.builtin.json(见
+// TestFrontendBuiltinPlatformCatalogInSync),前端据此生成平台选项、展示名与
+// 多协议账号表单,新登记的平台只需重新生成该文件,无需修改前端代码。
+type PlatformCatalog struct {
+ Platforms []PlatformCatalogEntry `json:"platforms"`
+ // CompositePrecedence 是组合分组逐平台回退的顺序(先命中者生效)。
+ CompositePrecedence []string `json:"composite_precedence"`
+}
+
+// PlatformCatalogEntry 描述一个具体平台;MultiProtocol 仅多协议 API Key 供应商有值。
+type PlatformCatalogEntry struct {
+ domain.PlatformSpec
+ MultiProtocol *ProviderProfileInfo `json:"multi_protocol,omitempty"`
+}
+
+// ProviderProfileInfo 是 ProviderProfile 的对外形状。
+type ProviderProfileInfo struct {
+ DefaultMode string `json:"default_mode"`
+ Routing ProviderRouting `json:"routing"`
+ ResponsesPath string `json:"responses_path,omitempty"`
+ // ModelCatalog 表示模型支持的协议由上游 /models 自动获取(账号规则仍优先)。
+ ModelCatalog bool `json:"model_catalog,omitempty"`
+ // Modes 以默认模式开头,其余按模式名排序。
+ Modes []ProviderModeInfo `json:"modes"`
+}
+
+// ProviderModeInfo 是某接入模式的默认端点;BaseURLs 缺少某协议即该模式不提供该原生端点。
+type ProviderModeInfo struct {
+ Mode string `json:"mode"`
+ BaseURLs map[string]string `json:"base_urls"`
+ ProtocolRules []ProtocolRule `json:"protocol_rules,omitempty"`
+}
+
+// BuildPlatformCatalog 按展示顺序返回全部具体平台(不含 composite)。
+func BuildPlatformCatalog() PlatformCatalog {
+ specs := domain.Platforms()
+ catalog := PlatformCatalog{
+ Platforms: make([]PlatformCatalogEntry, 0, len(specs)),
+ CompositePrecedence: domain.CompositePrecedencePlatformIDs(),
+ }
+ for _, spec := range specs {
+ catalog.Platforms = append(catalog.Platforms, PlatformCatalogEntry{
+ PlatformSpec: spec,
+ MultiProtocol: providerProfileInfo(LookupProviderProfile(spec.ID)),
+ })
+ }
+ return catalog
+}
+
+func providerProfileInfo(profile *ProviderProfile) *ProviderProfileInfo {
+ if profile == nil {
+ return nil
+ }
+ routing := profile.Routing
+ if routing == "" {
+ routing = ProviderRoutingByInbound
+ }
+ modes := make([]string, 0, len(profile.Modes))
+ for mode := range profile.Modes {
+ if mode != profile.DefaultMode {
+ modes = append(modes, mode)
+ }
+ }
+ sort.Strings(modes)
+ if _, ok := profile.Modes[profile.DefaultMode]; ok {
+ modes = append([]string{profile.DefaultMode}, modes...)
+ }
+ info := &ProviderProfileInfo{
+ DefaultMode: profile.DefaultMode,
+ Routing: routing,
+ ResponsesPath: profile.ResponsesPath,
+ ModelCatalog: profile.ModelCatalog,
+ Modes: make([]ProviderModeInfo, 0, len(modes)),
+ }
+ for _, mode := range modes {
+ endpoints := profile.Modes[mode]
+ baseURLs := make(map[string]string, len(endpoints.BaseURLs))
+ for protocol, baseURL := range endpoints.BaseURLs {
+ baseURLs[protocol] = baseURL
+ }
+ info.Modes = append(info.Modes, ProviderModeInfo{
+ Mode: mode,
+ BaseURLs: baseURLs,
+ ProtocolRules: cloneProtocolRules(endpoints.ProtocolRules),
+ })
+ }
+ return info
+}
+
+func cloneProtocolRules(rules []ProtocolRule) []ProtocolRule {
+ if rules == nil {
+ return nil
+ }
+ out := make([]ProtocolRule, len(rules))
+ for i, rule := range rules {
+ out[i] = rule
+ out[i].Protocols = append([]string(nil), rule.Protocols...)
+ }
+ return out
+}
diff --git a/backend/internal/service/platform_catalog_test.go b/backend/internal/service/platform_catalog_test.go
new file mode 100644
index 000000000..209e99dfc
--- /dev/null
+++ b/backend/internal/service/platform_catalog_test.go
@@ -0,0 +1,140 @@
+//go:build unit
+
+package service
+
+import (
+ "encoding/json"
+ "errors"
+ "os"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/domain"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildPlatformCatalogMirrorsPlatformListAndProfiles(t *testing.T) {
+ catalog := BuildPlatformCatalog()
+ require.Equal(t, domain.CompositePrecedencePlatformIDs(), catalog.CompositePrecedence)
+ require.Len(t, catalog.Platforms, len(domain.ConcretePlatformIDs()))
+
+ for i, entry := range catalog.Platforms {
+ require.Equal(t, domain.ConcretePlatformIDs()[i], entry.ID)
+ profile := LookupProviderProfile(entry.ID)
+ if profile == nil {
+ require.Nil(t, entry.MultiProtocol, entry.ID)
+ continue
+ }
+ require.NotNil(t, entry.MultiProtocol, entry.ID)
+ require.Equal(t, profile.DefaultMode, entry.MultiProtocol.DefaultMode, entry.ID)
+ require.Equal(t, profile.DefaultMode, entry.MultiProtocol.Modes[0].Mode, entry.ID)
+ require.Equal(t, profile.ResponsesPath, entry.MultiProtocol.ResponsesPath, entry.ID)
+ require.Len(t, entry.MultiProtocol.Modes, len(profile.Modes), entry.ID)
+ for _, mode := range entry.MultiProtocol.Modes {
+ endpoints := profile.Modes[mode.Mode]
+ require.Equal(t, endpoints.BaseURLs, mode.BaseURLs, "%s/%s", entry.ID, mode.Mode)
+ require.Equal(t, len(endpoints.ProtocolRules), len(mode.ProtocolRules), "%s/%s", entry.ID, mode.Mode)
+ for j, rule := range endpoints.ProtocolRules {
+ require.Equal(t, rule, mode.ProtocolRules[j])
+ }
+ }
+ }
+}
+
+func TestBuildPlatformCatalogJSONShape(t *testing.T) {
+ raw, err := json.Marshal(BuildPlatformCatalog())
+ require.NoError(t, err)
+
+ type modeJSON struct {
+ Mode string `json:"mode"`
+ BaseURLs map[string]string `json:"base_urls"`
+ ProtocolRules []ProtocolRule `json:"protocol_rules"`
+ }
+ type platformJSON struct {
+ ID string `json:"id"`
+ DisplayName string `json:"display_name"`
+ Gateway string `json:"gateway"`
+ CNProvider *bool `json:"cn_provider"`
+ MultiProtocol *struct {
+ DefaultMode string `json:"default_mode"`
+ Routing string `json:"routing"`
+ ResponsesPath string `json:"responses_path"`
+ Modes []modeJSON `json:"modes"`
+ } `json:"multi_protocol"`
+ }
+ var decoded struct {
+ Platforms []platformJSON `json:"platforms"`
+ CompositePrecedence []string `json:"composite_precedence"`
+ }
+ require.NoError(t, json.Unmarshal(raw, &decoded))
+ require.Equal(t, domain.CompositePrecedencePlatformIDs(), decoded.CompositePrecedence)
+ byID := map[string]platformJSON{}
+ for _, p := range decoded.Platforms {
+ byID[p.ID] = p
+ }
+
+ anthropic := byID[PlatformAnthropic]
+ require.Equal(t, "Anthropic", anthropic.DisplayName)
+ require.Equal(t, "anthropic", anthropic.Gateway)
+ require.NotNil(t, anthropic.CNProvider)
+ require.False(t, *anthropic.CNProvider)
+ require.Nil(t, anthropic.MultiProtocol)
+ require.NotContains(t, string(raw), `"multi_protocol":null`)
+
+ deepseek := byID[PlatformDeepseek].MultiProtocol
+ require.NotNil(t, deepseek)
+ require.Equal(t, "by_inbound", deepseek.Routing)
+ require.Equal(t, "/responses", deepseek.ResponsesPath)
+
+ openCode := byID[PlatformOpenCodeGo].MultiProtocol
+ require.NotNil(t, openCode)
+ require.Equal(t, "by_model", openCode.Routing)
+ require.Equal(t, AccountModeGo, openCode.DefaultMode)
+ require.Len(t, openCode.Modes, 2)
+ require.Equal(t, AccountModeGo, openCode.Modes[0].Mode)
+ require.Equal(t, DefaultOpenCodeGoBaseURL, openCode.Modes[0].BaseURLs[APIProtocolChatCompletions])
+ require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Modes[0].ProtocolRules)
+ require.Equal(t, AccountModeZen, openCode.Modes[1].Mode)
+}
+
+// 下发的是副本:调用方修改结果不影响内置 profile。
+func TestBuildPlatformCatalogReturnsCopies(t *testing.T) {
+ catalog := BuildPlatformCatalog()
+ for _, entry := range catalog.Platforms {
+ if entry.MultiProtocol == nil {
+ continue
+ }
+ for _, mode := range entry.MultiProtocol.Modes {
+ for protocol := range mode.BaseURLs {
+ mode.BaseURLs[protocol] = "mutated"
+ }
+ for i := range mode.ProtocolRules {
+ mode.ProtocolRules[i].Protocol = "mutated"
+ }
+ }
+ }
+ require.Equal(t, DefaultOpenCodeGoBaseURL, LookupProviderProfile(PlatformOpenCodeGo).DefaultBaseURL(AccountModeGo, APIProtocolChatCompletions))
+ require.NotEqual(t, "mutated", LookupProviderProfile(PlatformOpenCodeGo).Modes[AccountModeGo].ProtocolRules[0].Protocol)
+}
+
+// 前端内置的平台清单(接口加载前与加载失败时使用)必须与后端一致。
+// 更新平台清单或 profile 后运行:
+//
+// UPDATE_PLATFORM_CATALOG=1 go test -tags unit ./internal/service/ -run TestFrontendBuiltinPlatformCatalogInSync
+func TestFrontendBuiltinPlatformCatalogInSync(t *testing.T) {
+ const path = "../../../frontend/src/constants/platformCatalog.builtin.json"
+ want, err := json.MarshalIndent(BuildPlatformCatalog(), "", " ")
+ require.NoError(t, err)
+ want = append(want, '\n')
+
+ if os.Getenv("UPDATE_PLATFORM_CATALOG") == "1" {
+ require.NoError(t, os.WriteFile(path, want, 0o644))
+ return
+ }
+ got, err := os.ReadFile(path)
+ if errors.Is(err, os.ErrNotExist) {
+ t.Skip("frontend sources not available")
+ }
+ require.NoError(t, err)
+ require.JSONEq(t, string(want), string(got),
+ "frontend/src/constants/platformCatalog.builtin.json 与后端平台清单不一致,按测试注释重新生成")
+}
diff --git a/backend/internal/service/platform_list_test.go b/backend/internal/service/platform_list_test.go
new file mode 100644
index 000000000..2a718056b
--- /dev/null
+++ b/backend/internal/service/platform_list_test.go
@@ -0,0 +1,182 @@
+//go:build unit
+
+package service
+
+import (
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/domain"
+ "github.com/stretchr/testify/require"
+)
+
+// 以下为重构前各处手写的平台列表 / switch,作为平台清单派生结果的等价基准;
+// 重构后新登记的平台(Command Code、Cline)按同类平台(OpenCode)的位置补入;
+// Sub4API 的 OpenAI BPS 按合并前的位置补入(展示紧随 OpenAI,组合回退最后)。
+var (
+ legacyAllPlatforms = []string{
+ PlatformAnthropic, PlatformOpenAI, PlatformOpenAIBPS, PlatformGemini, PlatformAntigravity, PlatformGrok,
+ PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
+ PlatformCommandCode,
+ PlatformCline,
+ }
+ legacySchedulerSnapshotPlatforms = []string{
+ PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok,
+ PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
+ PlatformCommandCode,
+ PlatformCline,
+ PlatformOpenAIBPS,
+ }
+ legacyCompositeMatchingPlatforms = legacySchedulerSnapshotPlatforms
+ legacyMultiProtocolProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline}
+ platformProbeValues = append(append([]string{}, legacyAllPlatforms...), PlatformComposite, "", "moonshot", "Kimi", "openai ", "glm", "bogus")
+ platformProbeAccountTypes = []string{AccountTypeAPIKey, AccountTypeOAuth, AccountTypeSetupToken, AccountTypeUpstream, ""}
+)
+
+func legacyIsCNProvider(platform string) bool {
+ switch platform {
+ case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax:
+ return true
+ }
+ return false
+}
+
+func legacyIsOpenAICompatible(platform string) bool {
+ return platform == PlatformOpenAI || platform == PlatformOpenAIBPS || platform == PlatformGrok || legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo || platform == PlatformCommandCode || platform == PlatformCline
+}
+
+func legacyNormalizeOpenAICompatiblePlatform(platform string) string {
+ switch platform {
+ case PlatformOpenAIBPS, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline:
+ return platform
+ }
+ return PlatformOpenAI
+}
+
+func legacyIsUpstreamBillingProbeIdentity(platform, accountType string) bool {
+ if accountType != AccountTypeAPIKey {
+ return false
+ }
+ switch platform {
+ case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok,
+ PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
+ PlatformTypeSafe, PlatformCommandCode, PlatformCline:
+ return true
+ }
+ return false
+}
+
+func legacyIsHeaderOverrideEligible(platform, accountType string) bool {
+ switch platform {
+ case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformCommandCode, PlatformCline:
+ return accountType == AccountTypeAPIKey
+ case PlatformGrok:
+ return accountType == AccountTypeAPIKey || accountType == AccountTypeOAuth
+ }
+ return false
+}
+
+func legacyIsConcreteRequestPlatform(platform string) bool {
+ for _, p := range legacyAllPlatforms {
+ if p == platform {
+ return true
+ }
+ }
+ return false
+}
+
+func TestPlatformListDerivedListsMatchLegacy(t *testing.T) {
+ require.Equal(t, legacyAllPlatforms, AllowedQuotaPlatforms)
+ require.Equal(t, legacySchedulerSnapshotPlatforms, schedulerSnapshotPlatforms())
+ require.Equal(t, legacyCompositeMatchingPlatforms, matchingPlatforms(PlatformComposite))
+ require.Equal(t, []string{PlatformKimi}, matchingPlatforms(PlatformKimi))
+
+ var multiProtocol []string
+ for _, platform := range legacyAllPlatforms {
+ if IsMultiProtocolAPIKeyProvider(platform) {
+ multiProtocol = append(multiProtocol, platform)
+ }
+ }
+ require.Equal(t, legacyMultiProtocolProviders, multiProtocol)
+}
+
+func TestPlatformListDerivedPredicatesMatchLegacy(t *testing.T) {
+ for _, platform := range platformProbeValues {
+ require.Equal(t, legacyIsCNProvider(platform), IsCNProvider(platform), platform)
+ require.Equal(t, legacyIsConcreteRequestPlatform(platform), isConcreteRequestPlatform(platform), platform)
+ require.Equal(t, legacyNormalizeOpenAICompatiblePlatform(platform), NormalizeOpenAICompatiblePlatform(platform), platform)
+ require.Equal(t, legacyIsOpenAICompatible(platform), (&Account{Platform: platform}).IsOpenAICompatible(), platform)
+ for _, accountType := range platformProbeAccountTypes {
+ require.Equal(t, legacyIsUpstreamBillingProbeIdentity(platform, accountType),
+ IsUpstreamBillingProbeIdentity(platform, accountType), "%s/%s", platform, accountType)
+ require.Equal(t, legacyIsHeaderOverrideEligible(platform, accountType),
+ (&Account{Platform: platform, Type: accountType}).IsHeaderOverrideEligible(), "%s/%s", platform, accountType)
+ }
+ }
+}
+
+// 多协议 API Key 供应商经 OpenAI 网关转发(NormalizeOpenAICompatiblePlatform、
+// countTokens 路由等依赖此约束),ProviderProfile 登记的平台必须在平台清单中声明 openai 网关。
+func TestProviderProfilesUseOpenAIGateway(t *testing.T) {
+ for platform := range providerProfiles {
+ spec, ok := domain.LookupPlatform(platform)
+ require.True(t, ok, platform)
+ require.Equal(t, domain.PlatformGatewayOpenAI, spec.Gateway, platform)
+ }
+}
+
+// 转发、探测与计费中"多协议供应商"类判断改为查 profile:现有平台上与改动前的
+// 国产厂商 / 国产厂商 ∪ OpenCode 判断逐一相同。
+func TestProviderProfileAccountPredicatesMatchLegacy(t *testing.T) {
+ for _, platform := range platformProbeValues {
+ account := &Account{Platform: platform, Type: AccountTypeAPIKey}
+ // Cline 只有 Chat Completions 一个端点,按入站协议分流(其余入站转换)。
+ require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformCline, account.RoutesProtocolByInbound(), platform)
+ require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo || platform == PlatformCommandCode || platform == PlatformCline, account.IsMultiProtocolAPIKey(), platform)
+ }
+ var nilAccount *Account
+ require.False(t, nilAccount.RoutesProtocolByInbound())
+}
+
+// 仅在 providerProfiles 中登记的新供应商按分流方式自动获得对应行为:按入站协议
+// 分流的与国产厂商一致,按模型分流的与 OpenCode 一致。
+func TestNewlyRegisteredProviderInheritsRoutingBehaviour(t *testing.T) {
+ const byInbound, byModel = "test_inbound_provider", "test_model_provider"
+ providerProfiles[byInbound] = &ProviderProfile{
+ Platform: byInbound, DefaultMode: AccountModePayG, Routing: ProviderRoutingByInbound,
+ Modes: map[string]ProviderEndpoints{AccountModePayG: {BaseURLs: map[string]string{
+ APIProtocolChatCompletions: "https://inbound.example.com/v1",
+ APIProtocolAnthropic: "https://inbound.example.com/anthropic",
+ }}},
+ }
+ providerProfiles[byModel] = &ProviderProfile{
+ Platform: byModel, DefaultMode: AccountModePayG, Routing: ProviderRoutingByModel,
+ Modes: map[string]ProviderEndpoints{AccountModePayG: {BaseURLs: map[string]string{
+ APIProtocolChatCompletions: "https://model.example.com/v1",
+ }}},
+ }
+ t.Cleanup(func() {
+ delete(providerProfiles, byInbound)
+ delete(providerProfiles, byModel)
+ })
+
+ inbound := &Account{Platform: byInbound, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "api_key": "sk-test", "api_protocol": APIProtocolAdaptive,
+ "base_url": "https://inbound.example.com/v1",
+ }}
+ require.True(t, inbound.IsMultiProtocolAPIKey())
+ require.True(t, inbound.RoutesProtocolByInbound())
+ // 无原生 Responses 端点的 adaptive 账号回退 Chat Completions(与 GLM 相同)。
+ require.True(t, shouldForwardOpenAIResponsesViaRawChatCompletions(inbound))
+ require.True(t, shouldEstimateOpenAIInputTokensLocally(inbound))
+ require.Equal(t, "https://inbound.example.com/v1", upstreamModelRegistryBaseURL(inbound))
+
+ model := &Account{Platform: byModel, Type: AccountTypeAPIKey, Credentials: map[string]any{
+ "api_key": "sk-test", "api_protocol": APIProtocolAdaptive,
+ "base_url": "https://model.example.com/v1",
+ }}
+ require.True(t, model.IsMultiProtocolAPIKey())
+ require.False(t, model.RoutesProtocolByInbound())
+ // 按模型分流:protocol_rules 决定协议,不按 Responses 能力标记回退(与 OpenCode 相同)。
+ require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(model))
+ require.Equal(t, "https://model.example.com/v1", upstreamModelRegistryBaseURL(model))
+}
diff --git a/backend/internal/service/provider_profile.go b/backend/internal/service/provider_profile.go
new file mode 100644
index 000000000..37841403a
--- /dev/null
+++ b/backend/internal/service/provider_profile.go
@@ -0,0 +1,267 @@
+package service
+
+import "strings"
+
+// ProviderEndpoints 是多协议 API Key 供应商在某个接入模式下的官方默认端点与
+// 内置分流规则。账号凭证里的 base_url / api_base_urls / protocol_rules 仍优先于这里。
+type ProviderEndpoints struct {
+ // BaseURLs 以上游协议(chat_completions / responses / anthropic)为键,
+ // 值为该协议的官方默认基址。缺少某协议的条目即表示该模式不提供该原生端点。
+ // Anthropic 基址的上游路径为 {base}/v1/messages。
+ BaseURLs map[string]string
+ // ProtocolRules 是按模型分流的内置默认表(首条命中生效);为空表示该模式
+ // 不按模型分流,由账号 api_protocol 决定上游协议。
+ ProtocolRules []ProtocolRule
+}
+
+// ProviderRouting 决定多协议供应商账号如何选择上游协议。
+type ProviderRouting string
+
+const (
+ // ProviderRoutingByInbound 适用于单一厂商:模型在各原生端点都可用,adaptive 账号
+ // 按入站协议选同协议端点,供应商不提供该协议时回落 Chat Completions。
+ ProviderRoutingByInbound ProviderRouting = "by_inbound"
+ // ProviderRoutingByModel 适用于多模型聚合平台:每个模型只在某一协议端点提供,
+ // 按 protocol_rules 以模型名选协议,与入站协议无关。
+ ProviderRoutingByModel ProviderRouting = "by_model"
+)
+
+// ProviderProfile 描述一个多协议 API Key 供应商(国产厂商或多模型聚合平台)的
+// 静态数据:各接入模式的默认端点、内置分流规则与端点路径约定。
+// 额度解析、会话头等行为差异不在这里,仍由各自的代码路径处理。
+type ProviderProfile struct {
+ Platform string
+ // DefaultMode 在 credentials.account_mode 缺失或不在 Modes 中时使用。
+ DefaultMode string
+ Modes map[string]ProviderEndpoints
+ // Routing 为空时按 ProviderRoutingByInbound 处理。
+ Routing ProviderRouting
+ // ResponsesPath 覆盖 Responses 端点路径(按 buildOpenAIEndpointURL 的版本感知
+ // 规则拼接),空值为 /v1/responses。对自定义 base_url 的账号同样生效。
+ ResponsesPath string
+ // DefaultTestModel 是管理端连接测试未指定模型时使用的模型;空值时按各协议的
+ // 通用默认模型。
+ DefaultTestModel string
+ // ModelCatalog 表示上游 {Chat Completions 基址}/models 为每个模型给出
+ // supported_endpoints;按模型分流时据此判断模型支持哪些协议(见 model_protocol_catalog.go)。
+ ModelCatalog bool
+}
+
+// providerDefaultTestModel 返回账号连接测试未指定模型时的默认模型;非多协议供应商或
+// 未设置时为空。
+func (a *Account) providerDefaultTestModel() string {
+ profile := a.providerProfile()
+ if profile == nil {
+ return ""
+ }
+ // Cline 订阅了 ClinePass 的账号用订阅模型测试,不消耗积分;ClinePass 钱包冷却中
+ // (窗口用满等)时改用按量模型,否则测试必然失败,而积分模型照常可用。
+ if a.IsCline() && a.clinePassSubscribed() && !a.isRateLimitActiveForKey(clinePassRateLimitKey) {
+ return DefaultClinePassTestModel
+ }
+ return profile.DefaultTestModel
+}
+
+// Endpoints 返回指定接入模式的端点;未知模式回落 DefaultMode。
+func (p *ProviderProfile) Endpoints(mode string) ProviderEndpoints {
+ if p == nil {
+ return ProviderEndpoints{}
+ }
+ if endpoints, ok := p.Modes[strings.TrimSpace(mode)]; ok {
+ return endpoints
+ }
+ return p.Modes[p.DefaultMode]
+}
+
+// DefaultBaseURL 返回指定接入模式与上游协议的官方默认基址;该模式不提供此协议时为空串。
+func (p *ProviderProfile) DefaultBaseURL(mode, protocol string) string {
+ return p.Endpoints(mode).BaseURLs[protocol]
+}
+
+// SupportsProtocol 报告指定接入模式是否提供该协议的原生端点。
+func (p *ProviderProfile) SupportsProtocol(mode, protocol string) bool {
+ return p.DefaultBaseURL(mode, protocol) != ""
+}
+
+// providerProfiles 是多协议 API Key 供应商的单一数据来源。新增同类供应商时在此
+// 登记一条即可获得默认端点、原生 Responses 能力判定(有 responses 条目即支持)、
+// 上游协议分流方式、Responses 路径约定与 IsMultiProtocolAPIKeyProvider 归属。
+// 默认端点需与前端 credentialsBuilder.ts 的预设保持一致。
+var providerProfiles = map[string]*ProviderProfile{
+ PlatformKimi: {
+ Platform: PlatformKimi,
+ DefaultMode: AccountModePayG,
+ Routing: ProviderRoutingByInbound,
+ Modes: map[string]ProviderEndpoints{
+ AccountModePayG: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultKimiPayGBaseURL,
+ APIProtocolResponses: DefaultKimiPayGBaseURL,
+ APIProtocolAnthropic: DefaultKimiPayGAnthropicBaseURL,
+ },
+ },
+ AccountModeCoding: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultKimiCodingBaseURL,
+ APIProtocolResponses: DefaultKimiCodingBaseURL,
+ APIProtocolAnthropic: DefaultKimiCodingAnthropicBaseURL,
+ },
+ },
+ },
+ },
+ PlatformZhipu: {
+ Platform: PlatformZhipu,
+ DefaultMode: AccountModePayG,
+ Routing: ProviderRoutingByInbound,
+ // 智谱没有原生 Responses 端点,故不登记 responses 条目。
+ Modes: map[string]ProviderEndpoints{
+ AccountModePayG: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultZhipuPayGBaseURL,
+ APIProtocolAnthropic: DefaultZhipuAnthropicBaseURL,
+ },
+ },
+ AccountModeCoding: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultZhipuCodingBaseURL,
+ APIProtocolAnthropic: DefaultZhipuAnthropicBaseURL,
+ },
+ },
+ },
+ },
+ PlatformDeepseek: {
+ Platform: PlatformDeepseek,
+ DefaultMode: AccountModePayG,
+ Routing: ProviderRoutingByInbound,
+ // DeepSeek 官方 Responses 端点为 /responses(无 /v1 前缀,适配 Codex)。
+ ResponsesPath: "/responses",
+ Modes: map[string]ProviderEndpoints{
+ AccountModePayG: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultDeepseekBaseURL,
+ APIProtocolResponses: DefaultDeepseekBaseURL,
+ APIProtocolAnthropic: DefaultDeepseekAnthropicBaseURL,
+ },
+ },
+ },
+ },
+ PlatformMiniMax: {
+ Platform: PlatformMiniMax,
+ DefaultMode: AccountModePayG,
+ Routing: ProviderRoutingByInbound,
+ Modes: map[string]ProviderEndpoints{
+ // 按量付费与 Coding/Token Plan 共用推理域名,靠 API Key 区分套餐。
+ AccountModePayG: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultMiniMaxBaseURL,
+ APIProtocolResponses: DefaultMiniMaxBaseURL,
+ APIProtocolAnthropic: DefaultMiniMaxAnthropicBaseURL,
+ },
+ },
+ AccountModeCoding: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultMiniMaxBaseURL,
+ APIProtocolResponses: DefaultMiniMaxBaseURL,
+ APIProtocolAnthropic: DefaultMiniMaxAnthropicBaseURL,
+ },
+ },
+ },
+ },
+ PlatformOpenCodeGo: {
+ Platform: PlatformOpenCodeGo,
+ DefaultMode: AccountModeGo,
+ Routing: ProviderRoutingByModel,
+ DefaultTestModel: DefaultOpenCodeGoTestModel,
+ Modes: map[string]ProviderEndpoints{
+ AccountModeGo: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultOpenCodeGoBaseURL,
+ APIProtocolResponses: DefaultOpenCodeGoBaseURL,
+ APIProtocolAnthropic: DefaultOpenCodeGoAnthropicBaseURL,
+ },
+ ProtocolRules: DefaultOpenCodeGoProtocolRules(),
+ },
+ AccountModeZen: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultOpenCodeZenBaseURL,
+ APIProtocolResponses: DefaultOpenCodeZenBaseURL,
+ APIProtocolAnthropic: DefaultOpenCodeZenAnthropicBaseURL,
+ },
+ ProtocolRules: DefaultOpenCodeZenProtocolRules(),
+ },
+ },
+ },
+ PlatformCommandCode: {
+ Platform: PlatformCommandCode,
+ DefaultMode: AccountModePayG,
+ Routing: ProviderRoutingByModel,
+ DefaultTestModel: DefaultCommandCodeTestModel,
+ ModelCatalog: true,
+ // 订阅套餐与 Provider 按量计费共用同一个 API Key 与端点,只有一个接入模式。
+ Modes: map[string]ProviderEndpoints{
+ AccountModePayG: {
+ BaseURLs: map[string]string{
+ APIProtocolChatCompletions: DefaultCommandCodeBaseURL,
+ APIProtocolResponses: DefaultCommandCodeBaseURL,
+ APIProtocolAnthropic: DefaultCommandCodeAnthropicBaseURL,
+ },
+ ProtocolRules: DefaultCommandCodeProtocolRules(),
+ },
+ },
+ },
+ PlatformCline: {
+ Platform: PlatformCline,
+ DefaultMode: AccountModePayG,
+ DefaultTestModel: DefaultClineTestModel,
+ // 按量积分与 ClinePass 订阅共用同一个 API Key 与端点,由模型名决定扣哪一边
+ // (cline-pass/* 走订阅),只有一个接入模式;两边的超限分别冷却(见 cline.go)。
+ Modes: map[string]ProviderEndpoints{
+ AccountModePayG: {
+ BaseURLs: map[string]string{APIProtocolChatCompletions: DefaultClineBaseURL},
+ },
+ },
+ },
+}
+
+// LookupProviderProfile 返回 platform 对应的多协议供应商 profile;非此类平台返回 nil。
+func LookupProviderProfile(platform string) *ProviderProfile {
+ return providerProfiles[platform]
+}
+
+func (a *Account) providerProfile() *ProviderProfile {
+ if a == nil {
+ return nil
+ }
+ return LookupProviderProfile(a.Platform)
+}
+
+// defaultProviderBaseURL 按账号 account_mode 返回多协议供应商指定协议的官方默认基址;
+// 非多协议供应商或协议未知时为空串。
+func (a *Account) defaultProviderBaseURL(protocol string) string {
+ profile := a.providerProfile()
+ if profile == nil {
+ return ""
+ }
+ return profile.DefaultBaseURL(a.GetCredential("account_mode"), protocol)
+}
+
+// providerSupportsProtocol 报告账号所在供应商在其 account_mode 下是否提供该协议的原生端点。
+func (a *Account) providerSupportsProtocol(protocol string) bool {
+ profile := a.providerProfile()
+ return profile != nil && profile.SupportsProtocol(a.GetCredential("account_mode"), protocol)
+}
+
+// routesByModel 报告账号所在供应商是否按模型名分流上游协议(多模型聚合平台)。
+func (a *Account) routesByModel() bool {
+ profile := a.providerProfile()
+ return profile != nil && profile.Routing == ProviderRoutingByModel
+}
+
+// RoutesProtocolByInbound 报告账号是否为按入站协议分流的多协议 API Key 供应商
+// (单一厂商型,目前即国产厂商)。这类账号共享"显式协议优先、adaptive 选同协议
+// 原生端点"的转发、Responses 能力标记与本地 token 估算逻辑;按模型分流的聚合
+// 平台由 protocol_rules 决定协议,走 routesByModel 分支。
+func (a *Account) RoutesProtocolByInbound() bool {
+ profile := a.providerProfile()
+ return profile != nil && profile.Routing != ProviderRoutingByModel
+}
diff --git a/backend/internal/service/provider_profile_test.go b/backend/internal/service/provider_profile_test.go
new file mode 100644
index 000000000..e9fc2994b
--- /dev/null
+++ b/backend/internal/service/provider_profile_test.go
@@ -0,0 +1,188 @@
+//go:build unit
+
+package service
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// legacyProviderDefaultBaseURL 复述 provider profile 引入前 account.go 中逐平台
+// switch 的默认端点逻辑,作为等价性基准。
+func legacyProviderDefaultBaseURL(platform, mode, protocol string) string {
+ coding := mode == AccountModeCoding
+ zen := mode == AccountModeZen
+ switch protocol {
+ case APIProtocolAnthropic:
+ switch platform {
+ case PlatformKimi:
+ if coding {
+ return DefaultKimiCodingAnthropicBaseURL
+ }
+ return DefaultKimiPayGAnthropicBaseURL
+ case PlatformZhipu:
+ return DefaultZhipuAnthropicBaseURL
+ case PlatformDeepseek:
+ return DefaultDeepseekAnthropicBaseURL
+ case PlatformMiniMax:
+ return DefaultMiniMaxAnthropicBaseURL
+ case PlatformOpenCodeGo:
+ if zen {
+ return DefaultOpenCodeZenAnthropicBaseURL
+ }
+ return DefaultOpenCodeGoAnthropicBaseURL
+ }
+ case APIProtocolChatCompletions, APIProtocolResponses:
+ if platform == PlatformZhipu && protocol == APIProtocolResponses {
+ // 唯一的函数级差异:旧 switch 对智谱 Responses 也返回 CC 基址,profile
+ // 以"缺条目即不支持"建模后返回空串。所有运行时调用方都先经
+ // UsesNativeCNResponses / SupportsNativeCNResponses 守卫,智谱不会走到这里。
+ return ""
+ }
+ switch platform {
+ case PlatformKimi:
+ if coding {
+ return DefaultKimiCodingBaseURL
+ }
+ return DefaultKimiPayGBaseURL
+ case PlatformZhipu:
+ if coding {
+ return DefaultZhipuCodingBaseURL
+ }
+ return DefaultZhipuPayGBaseURL
+ case PlatformDeepseek:
+ return DefaultDeepseekBaseURL
+ case PlatformMiniMax:
+ return DefaultMiniMaxBaseURL
+ case PlatformOpenCodeGo:
+ if zen {
+ return DefaultOpenCodeZenBaseURL
+ }
+ return DefaultOpenCodeGoBaseURL
+ }
+ }
+ return ""
+}
+
+func TestProviderProfile_DefaultBaseURLsMatchLegacySwitches(t *testing.T) {
+ t.Parallel()
+
+ platforms := []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo}
+ modes := []string{"", AccountModePayG, AccountModeCoding, AccountModeZen, AccountModeGo, " coding ", "unknown"}
+
+ for _, platform := range platforms {
+ for _, mode := range modes {
+ legacyMode := mode
+ if legacyMode == " coding " {
+ legacyMode = AccountModeCoding
+ }
+ newAccount := func(protocol string) *Account {
+ return &Account{
+ Platform: platform,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{
+ "api_key": "sk-test",
+ "account_mode": mode,
+ "api_protocol": protocol,
+ },
+ }
+ }
+ name := platform + "/" + mode
+
+ chat := newAccount(APIProtocolChatCompletions)
+ require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolChatCompletions), chat.GetOpenAIBaseURL(), name)
+
+ anthropic := newAccount(APIProtocolAnthropic)
+ require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolAnthropic), anthropic.GetAnthropicProtocolBaseURL(), name)
+ require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolChatCompletions), anthropic.GetOpenAIFormatBaseURL(), name)
+
+ adaptive := newAccount(APIProtocolAdaptive)
+ for _, protocol := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic, "unknown"} {
+ require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, protocol), adaptive.GetCNProtocolBaseURL(protocol), name+"/"+protocol)
+ }
+ }
+ }
+}
+
+func TestProviderProfile_ProfilesMatchMultiProtocolPlatforms(t *testing.T) {
+ t.Parallel()
+
+ for _, platform := range []string{
+ PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
+ PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformComposite, "",
+ } {
+ want := IsCNProvider(platform) || platform == PlatformOpenCodeGo
+ require.Equal(t, want, IsMultiProtocolAPIKeyProvider(platform), platform)
+ require.Equal(t, want, LookupProviderProfile(platform) != nil, platform)
+ }
+
+ for platform, profile := range providerProfiles {
+ require.Equal(t, platform, profile.Platform)
+ _, ok := profile.Modes[profile.DefaultMode]
+ require.True(t, ok, "%s default mode %q must be registered", platform, profile.DefaultMode)
+ }
+}
+
+func TestProviderProfile_NativeResponsesMatchesLegacy(t *testing.T) {
+ t.Parallel()
+
+ legacy := map[string]bool{
+ PlatformDeepseek: true,
+ PlatformKimi: true,
+ PlatformMiniMax: true,
+ PlatformOpenCodeGo: true,
+ }
+ modes := []string{"", AccountModePayG, AccountModeCoding, AccountModeZen, AccountModeGo, "unknown"}
+ for _, platform := range []string{PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
+ for _, mode := range modes {
+ account := &Account{Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{"account_mode": mode}}
+ require.Equal(t, legacy[platform], account.SupportsNativeCNResponses(), platform+"/"+mode)
+ }
+ }
+ require.False(t, (*Account)(nil).SupportsNativeCNResponses())
+}
+
+func TestProviderProfile_BaseURLKeysAreNativeProtocols(t *testing.T) {
+ t.Parallel()
+
+ for platform, profile := range providerProfiles {
+ for mode, endpoints := range profile.Modes {
+ require.NotEmpty(t, endpoints.BaseURLs[APIProtocolChatCompletions], "%s/%s must have a chat_completions base", platform, mode)
+ for protocol, baseURL := range endpoints.BaseURLs {
+ require.True(t, isNativeUpstreamProtocol(protocol), "%s/%s has unknown protocol key %q", platform, mode, protocol)
+ require.NotEmpty(t, baseURL, "%s/%s/%s", platform, mode, protocol)
+ }
+ }
+ }
+}
+
+func TestProviderProfile_ResponsesPathMatchesLegacy(t *testing.T) {
+ t.Parallel()
+
+ legacy := func(platform, base string) string {
+ if platform == PlatformDeepseek {
+ return buildOpenAIEndpointURL(base, "/responses")
+ }
+ return buildOpenAIResponsesURL(base)
+ }
+ bases := []string{
+ "https://api.deepseek.com", "https://relay.example.com", "https://relay.example.com/v1",
+ "https://opencode.ai/zen/go/v1", "https://open.bigmodel.cn/api/paas/v4", "https://api.moonshot.cn/v1",
+ }
+ for _, platform := range []string{PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} {
+ for _, base := range bases {
+ require.Equal(t, legacy(platform, base), buildOpenAIResponsesURLForPlatform(platform, base), platform+" "+base)
+ }
+ }
+}
+
+func TestProviderProfile_OpenCodeProtocolRulesByMode(t *testing.T) {
+ t.Parallel()
+
+ openCode := LookupProviderProfile(PlatformOpenCodeGo)
+ require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Endpoints(AccountModeGo).ProtocolRules)
+ require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Endpoints("").ProtocolRules)
+ require.Equal(t, DefaultOpenCodeZenProtocolRules(), openCode.Endpoints(AccountModeZen).ProtocolRules)
+ require.Empty(t, LookupProviderProfile(PlatformKimi).Endpoints(AccountModeCoding).ProtocolRules)
+}
diff --git a/backend/internal/service/ratelimit_cline.go b/backend/internal/service/ratelimit_cline.go
new file mode 100644
index 000000000..a91f630fe
--- /dev/null
+++ b/backend/internal/service/ratelimit_cline.go
@@ -0,0 +1,270 @@
+package service
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "regexp"
+ "strings"
+ "time"
+
+ "github.com/tidwall/gjson"
+)
+
+// Cline 上游错误的响应式处理。依据官方错误说明(https://docs.cline.bot/api/errors)与
+// Cline 客户端的错误分类(cline/cline:sdk/packages/llms/src/providers/errors.ts、
+// apps/vscode/src/services/error/ClineError.ts):
+//
+// - 402 insufficient_credits:积分不足;
+// - 429 SPEND_LIMIT_EXCEEDED:组织为成员设的花费上限;
+// - INFERENCE_CAP_ERROR:推理额度上限(客户端归为 QuotaExceeded,文案由服务端给出);
+// - "You have reached your … ClinePass limit … Please try again later.":ClinePass
+// 5 小时 / 7 天 / 30 天滚动用量上限,文案不带重置时间;
+// - "the user is not subscribed to required model plan" 与 "organization accounts
+// cannot use individual model inference subscriptions":没有可用的 ClinePass 订阅;
+// - "Free limit reached on model … try again in …":免费模型的每日额度,只限该模型。
+//
+// 只读取结构化 error.code 与错误消息;ClinePass / 免费模型限额兼容官方固定文案。
+// metadata 等字段可能回显请求内容,不能据此冷却钱包;未识别的错误交回默认逻辑。
+//
+// 作用范围:积分与 ClinePass 是同一个 Key 下互不影响的两个钱包,一边超限只冷却该边的
+// 全部模型(模型级冷却键,见 clineWalletRateLimitKey),不停整个账号;钱包按请求模型
+// 判定——cline-pass/* 请求只会被订阅额度拒绝,其余付费模型只会被积分拒绝。
+
+type clineErrorKind int
+
+const (
+ clineErrorNone clineErrorKind = iota
+ // clineCreditsExhausted 积分不足:冷却积分钱包,用量探测发现余额恢复后解除。
+ clineCreditsExhausted
+ // clineSpendLimit 组织花费上限:冷却后由下一次请求重新确认。
+ clineSpendLimit
+ // clineInferenceCap 推理额度上限:归属由请求模型所在的钱包决定。
+ clineInferenceCap
+ // clinePassLimit ClinePass 用量上限:冷却到对应窗口的重置时间。
+ clinePassLimit
+ // clinePassUnavailable 没有可用的 ClinePass 订阅(未订阅或组织账户)。
+ clinePassUnavailable
+ // clineFreeModelLimit 免费模型的每日额度:只限当前模型。
+ clineFreeModelLimit
+)
+
+const (
+ clinePassLimitReason = "cline_pass_limit"
+ clinePassUnavailableReason = "cline_pass_unavailable"
+ clineSpendLimitReason = "cline_spend_limit"
+ clineInferenceCapReason = "cline_inference_cap"
+ clineFreeModelLimitReason = "cline_free_model_limit"
+ clineCreditsReason = "cline_credits_exhausted"
+
+ // clineLimitRecheck 是无法得知重置时间时的冷却:到期后由下一次请求重新确认
+ // (管理员可能调高上限、订阅可能续费、滚动窗口逐步释放)。
+ clineLimitRecheck = time.Hour
+ // ClinePass 7 天 / 30 天窗口没有用量快照时的冷却:窗口滚动释放,时间点无从得知,
+ // 冷却较长但远短于窗口,由下一次请求或用量探测重新确认。
+ clinePassWeeklyRecheck = 6 * time.Hour
+ clinePassMonthlyRecheck = 24 * time.Hour
+ // clinePassMaxCooldown 限制按快照重置时间冷却的上限(最长的 30 天窗口)。
+ clinePassMaxCooldown = 31 * 24 * time.Hour
+ // clineFreeModelMaxCooldown 是从免费模型文案解析出的重置时长上限(每日额度)。
+ clineFreeModelMaxCooldown = 25 * time.Hour
+)
+
+var (
+ // clinePassLimitPattern 与 Cline 客户端的判定一致:"you have reached your" 开头、
+ // "please try again later." 结尾,中间含 "clinepass limit"。
+ clinePassLimitPattern = regexp.MustCompile(`(?is)you have reached your(.*?)clinepass limit.*?please try again later\.`)
+ clineTryAgainPattern = regexp.MustCompile(`(?i)\btry\s+again\s+in\s+`)
+)
+
+// parseClineError 返回错误分类与命中的限额消息,后者用于解析窗口和重试时间。
+func parseClineError(body []byte) (clineErrorKind, string) {
+ if !gjson.ValidBytes(body) {
+ return clineErrorNone, ""
+ }
+ err := gjson.GetBytes(body, "error")
+ if !err.IsObject() {
+ return clineErrorNone, ""
+ }
+ if code := err.Get("code"); code.Type == gjson.String {
+ if kind := classifyClineErrorCode(code.String()); kind != clineErrorNone {
+ return kind, ""
+ }
+ }
+ // 官方客户端也识别 details.code 中的组织花费上限。
+ if code := err.Get("details.code"); code.Type == gjson.String && classifyClineErrorCode(code.String()) == clineSpendLimit {
+ return clineSpendLimit, ""
+ }
+ for _, path := range []string{"message", "details.message"} {
+ message := err.Get(path)
+ if message.Type != gjson.String {
+ continue
+ }
+ if kind := classifyClineLimitMessage(message.String()); kind != clineErrorNone {
+ return kind, message.String()
+ }
+ }
+ return clineErrorNone, ""
+}
+
+func classifyClineErrorCode(code string) clineErrorKind {
+ switch strings.ToLower(strings.TrimSpace(code)) {
+ case "insufficient_credits":
+ return clineCreditsExhausted
+ case "spend_limit_exceeded":
+ return clineSpendLimit
+ case "inference_cap_error":
+ return clineInferenceCap
+ default:
+ return clineErrorNone
+ }
+}
+
+func classifyClineLimitMessage(message string) clineErrorKind {
+ text := strings.ToLower(message)
+ switch {
+ case strings.Contains(text, "organization accounts cannot use individual model inference subscriptions"),
+ strings.Contains(text, "the user is not subscribed to required model plan"):
+ return clinePassUnavailable
+ case strings.Contains(text, "free limit reached on model"):
+ return clineFreeModelLimit
+ case clinePassLimitPattern.MatchString(message):
+ return clinePassLimit
+ default:
+ return clineErrorNone
+ }
+}
+
+// clineErrorWallet 返回错误本身指明的钱包冷却键,用于请求模型未知的情况。
+func clineErrorWallet(kind clineErrorKind) string {
+ switch kind {
+ case clinePassLimit, clinePassUnavailable, clineInferenceCap:
+ return clinePassRateLimitKey
+ case clineCreditsExhausted, clineSpendLimit:
+ return clineCreditsRateLimitKey
+ default:
+ return ""
+ }
+}
+
+// clinePassWindow 返回 ClinePass 超限文案所指的窗口(5h / weekly / monthly)。
+func clinePassWindow(body []byte) string {
+ match := clinePassLimitPattern.FindSubmatch(body)
+ if match == nil {
+ return "5h"
+ }
+ window := strings.ToLower(string(match[1]))
+ switch {
+ case strings.Contains(window, "month"):
+ return "monthly"
+ case strings.Contains(window, "week"):
+ return "weekly"
+ default:
+ return "5h"
+ }
+}
+
+// clinePassLimitCooldown 冷却到用量快照中该窗口的重置时间;没有可用快照时按窗口估计。
+func clinePassLimitCooldown(account *Account, window string, now time.Time) time.Duration {
+ if account != nil && account.Extra != nil {
+ resetKey := map[string]string{
+ "5h": cnExtraSuffix5hReset,
+ "weekly": cnExtraSuffixWeeklyReset,
+ "monthly": cnExtraSuffixMonthlyReset,
+ }[window]
+ if resetAt := parseSchedulingResetAt(account.Extra[cnExtraKey(PlatformCline, resetKey)]); resetAt != nil {
+ if wait := resetAt.Sub(now); wait > 0 && wait <= clinePassMaxCooldown {
+ return wait
+ }
+ }
+ }
+ switch window {
+ case "monthly":
+ return clinePassMonthlyRecheck
+ case "weekly":
+ return clinePassWeeklyRecheck
+ default:
+ return clineLimitRecheck
+ }
+}
+
+// clineFreeModelResetAfter 解析 "try again in 3h 20m";无法解析或超出上限时返回 0。
+func clineFreeModelResetAfter(body []byte) time.Duration {
+ text := string(body)
+ loc := clineTryAgainPattern.FindStringIndex(text)
+ if loc == nil {
+ return 0
+ }
+ after := parseOpenCodeGoUsageLimitResetDuration("resets in " + text[loc[1]:])
+ if after <= 0 || after > clineFreeModelMaxCooldown {
+ return 0
+ }
+ return after
+}
+
+// handleClineError 处理已识别的 Cline 上游错误:冷却对应钱包(或免费模型本身),不停
+// 整个账号。handled=false 时由调用方继续走默认逻辑。
+func (s *RateLimitService) handleClineError(
+ ctx context.Context,
+ account *Account,
+ statusCode int,
+ responseBody []byte,
+ upstreamMsg string,
+) bool {
+ kind, limitMessage := parseClineError(responseBody)
+ if kind == clineErrorNone && statusCode == http.StatusPaymentRequired {
+ // 402 只会来自积分不足(ClinePass 超限走 429 等其他状态码)。
+ kind = clineCreditsExhausted
+ }
+ if kind == clineErrorNone {
+ return false
+ }
+ now := time.Now()
+ modelKey := modelRateLimitKeyForUpstreamModelNotFound(ctx, account, tempUnschedulableModel(ctx, nil))
+
+ scope := modelKey
+ if kind != clineFreeModelLimit {
+ if scope = clineWalletRateLimitKey(modelKey); scope == "" {
+ scope = clineErrorWallet(kind)
+ }
+ }
+ if scope == "" {
+ return false
+ }
+
+ var cooldown time.Duration
+ var reason string
+ switch kind {
+ case clineCreditsExhausted:
+ cooldown, reason = s.cnBalanceCooldownDuration(), clineCreditsReason
+ case clineSpendLimit:
+ cooldown, reason = clineLimitRecheck, clineSpendLimitReason
+ case clineInferenceCap:
+ cooldown, reason = clineLimitRecheck, clineInferenceCapReason
+ if scope == clinePassRateLimitKey {
+ cooldown = clinePassLimitCooldown(account, "5h", now)
+ }
+ case clinePassLimit:
+ cooldown, reason = clinePassLimitCooldown(account, clinePassWindow([]byte(limitMessage)), now), clinePassLimitReason
+ case clinePassUnavailable:
+ cooldown, reason = clineLimitRecheck, clinePassUnavailableReason
+ case clineFreeModelLimit:
+ cooldown, reason = clineFreeModelResetAfter([]byte(limitMessage)), clineFreeModelLimitReason
+ if cooldown <= 0 {
+ cooldown = clineLimitRecheck
+ }
+ }
+ until := now.Add(cooldown)
+ if msg := strings.TrimSpace(upstreamMsg); msg != "" {
+ reason += ": " + msg
+ }
+
+ setAccountModelRateLimitSnapshot(account, scope, until, reason, now)
+ if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, scope, until, reason); err != nil {
+ slog.Warn("cline_limit_set_failed", "account_id", account.ID, "scope", scope, "error", err)
+ return false
+ }
+ slog.Info("cline_limit", "account_id", account.ID, "scope", scope, "model", modelKey,
+ "status_code", statusCode, "until", until.UTC())
+ return true
+}
diff --git a/backend/internal/service/ratelimit_cline_test.go b/backend/internal/service/ratelimit_cline_test.go
new file mode 100644
index 000000000..efff20dcb
--- /dev/null
+++ b/backend/internal/service/ratelimit_cline_test.go
@@ -0,0 +1,146 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/stretchr/testify/require"
+)
+
+func TestClassifyClineErrorRequiresStructuredFields(t *testing.T) {
+ for name, body := range map[string]string{
+ "code in model message": `{"error":{"code":"invalid_request_error","message":"Model INFERENCE_CAP_ERROR not found"}}`,
+ "code suffix": `{"error":{"code":"model-SPEND_LIMIT_EXCEEDED","message":"Invalid model"}}`,
+ "credits message without code": `{"error":{"message":"Insufficient credits"}}`,
+ "spend message without code": `{"error":{"message":"SPEND_LIMIT_EXCEEDED"}}`,
+ "metadata code": `{"error":{"code":429,"message":"Rate limit exceeded","metadata":{"code":"SPEND_LIMIT_EXCEEDED"}}}`,
+ "metadata pass message": `{"error":{"message":"Invalid model","metadata":{"message":"You have reached your monthly ClinePass limit. Please try again later."}}}`,
+ "metadata free message": `{"error":{"message":"Invalid model","metadata":{"message":"Free limit reached on model x. Try again in 3h 20m"}}}`,
+ "root request code": `{"error":{"message":"Invalid model"},"request":{"model":"insufficient_credits"}}`,
+ "root message": `{"message":"You have reached your monthly ClinePass limit. Please try again later."}`,
+ "error string": `{"error":"SPEND_LIMIT_EXCEEDED"}`,
+ "plain code": `Model SPEND_LIMIT_EXCEEDED not found`,
+ "plain pass message": `You have reached your weekly ClinePass limit. Please try again later.`,
+ "malformed json": `{"error":{"code":"insufficient_credits"}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ kind, _ := parseClineError([]byte(body))
+ require.Equal(t, clineErrorNone, kind)
+ })
+ }
+}
+
+func TestHandleUpstreamError_Cline400DoesNotCoolWallet(t *testing.T) {
+ for name, body := range map[string]string{
+ "credits model echo": `{"error":{"code":"invalid_request_error","message":"Model insufficient_credits not found"}}`,
+ "spend model echo": `{"error":{"message":"Model SPEND_LIMIT_EXCEEDED not found"}}`,
+ "pass model echo": `{"error":{"message":"Model cline-pass/INFERENCE_CAP_ERROR not found"}}`,
+ "metadata echo": `{"error":{"code":400,"message":"Invalid model","metadata":{"model":"SPEND_LIMIT_EXCEEDED"}}}`,
+ "plain echo": `Model SPEND_LIMIT_EXCEEDED not found`,
+ "business code": clineInferenceCapBody,
+ "pass message": clinePassMonthlyBody,
+ } {
+ t.Run(name, func(t *testing.T) {
+ account := clineTestAccount(400)
+ repo := &commandCodeRateLimitRepo{}
+ shouldDisable := NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(
+ context.Background(), account, http.StatusBadRequest, http.Header{}, []byte(body), "cline-pass/INFERENCE_CAP_ERROR")
+
+ require.False(t, shouldDisable)
+ require.Empty(t, repo.modelLimits)
+ require.Zero(t, repo.setErrorCalls)
+ require.Zero(t, repo.tempCalls)
+ require.False(t, account.isModelRateLimitedWithContext(context.Background(), "cline-pass/glm-5.3"))
+ require.False(t, account.isModelRateLimitedWithContext(context.Background(), "anthropic/claude-sonnet-4-6"))
+ })
+ }
+}
+
+func TestHandleUpstreamError_Cline429EchoedKeywordsDoNotCoolWallet(t *testing.T) {
+ for name, body := range map[string]string{
+ "message without code": `{"error":{"message":"Model INFERENCE_CAP_ERROR not found"}}`,
+ "metadata model": `{"error":{"code":429,"message":"Rate limit exceeded","metadata":{"model":"SPEND_LIMIT_EXCEEDED"}}}`,
+ "request model": `{"error":{"code":429,"message":"Rate limit exceeded"},"request":{"model":"insufficient_credits"}}`,
+ "plain text": `Model SPEND_LIMIT_EXCEEDED not found`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ repo := &commandCodeRateLimitRepo{}
+ NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(context.Background(),
+ clineTestAccount(429), http.StatusTooManyRequests, http.Header{}, []byte(body), "deepseek/deepseek-v4-flash")
+ require.Empty(t, repo.modelLimits)
+ })
+ }
+}
+
+func TestHandleUpstreamError_ClineStructuredErrorsPreserveCooldown(t *testing.T) {
+ for _, tc := range []struct {
+ name, model, body, scope, reason string
+ status int
+ wait time.Duration
+ }{
+ {
+ name: "credits code before echoed metadata", model: "deepseek/deepseek-v4-flash",
+ body: `{"error":{"code":"insufficient_credits","message":"Insufficient credits","metadata":{"model":"SPEND_LIMIT_EXCEEDED"}}}`,
+ scope: clineCreditsRateLimitKey, reason: clineCreditsReason, status: http.StatusPaymentRequired, wait: cnBalanceCheckCooldown(nil),
+ },
+ {
+ name: "spend code before pass wording", model: "deepseek/deepseek-v4-flash",
+ body: `{"error":{"code":"SPEND_LIMIT_EXCEEDED","message":"You have reached your monthly ClinePass limit. Please try again later."}}`,
+ scope: clineCreditsRateLimitKey, reason: clineSpendLimitReason, status: http.StatusTooManyRequests, wait: clineLimitRecheck,
+ },
+ {
+ name: "details spend code", model: "deepseek/deepseek-v4-flash",
+ body: `{"error":{"code":429,"message":"Rate limit exceeded","details":{"code":"SPEND_LIMIT_EXCEEDED"}}}`,
+ scope: clineCreditsRateLimitKey, reason: clineSpendLimitReason, status: http.StatusTooManyRequests, wait: clineLimitRecheck,
+ },
+ {
+ name: "inference code", model: "cline-pass/glm-5.3", body: clineInferenceCapBody,
+ scope: clinePassRateLimitKey, reason: clineInferenceCapReason, status: http.StatusTooManyRequests, wait: clineLimitRecheck,
+ },
+ {
+ name: "pass message ignores metadata window", model: "cline-pass/glm-5.3",
+ body: `{"error":{"code":429,"metadata":{"message":"You have reached your monthly ClinePass limit. Please try again later."},"message":"You have reached your 5-hour ClinePass limit. Please try again later."}}`,
+ scope: clinePassRateLimitKey, reason: clinePassLimitReason, status: http.StatusTooManyRequests, wait: clineLimitRecheck,
+ },
+ {
+ name: "details pass message", model: "cline-pass/glm-5.3",
+ body: `{"error":{"code":429,"message":"Rate limit exceeded","details":{"message":"You have reached your monthly ClinePass limit. Please try again later."}}}`,
+ scope: clinePassRateLimitKey, reason: clinePassLimitReason, status: http.StatusTooManyRequests, wait: clinePassMonthlyRecheck,
+ },
+ {
+ name: "details entitlement message", model: "cline-pass/glm-5.3",
+ body: `{"error":{"code":403,"message":"Forbidden","details":{"message":"The user is not subscribed to required model plan"}}}`,
+ scope: clinePassRateLimitKey, reason: clinePassUnavailableReason, status: http.StatusForbidden, wait: clineLimitRecheck,
+ },
+ {
+ name: "free message ignores metadata retry", model: "cline-free/kimi-k3",
+ body: `{"error":{"code":429,"metadata":{"message":"Try again in 20h"},"message":"Free limit reached on model cline-free/kimi-k3. Try again in 5m"}}`,
+ scope: "cline-free/kimi-k3", reason: clineFreeModelLimitReason, status: http.StatusTooManyRequests, wait: 5 * time.Minute,
+ },
+ {
+ name: "details free message", model: "cline-free/kimi-k3",
+ body: `{"error":{"code":429,"message":"Rate limit exceeded","details":{"message":"Free limit reached on model cline-free/kimi-k3. Try again in 3h 20m"}}}`,
+ scope: "cline-free/kimi-k3", reason: clineFreeModelLimitReason, status: http.StatusTooManyRequests, wait: 3*time.Hour + 20*time.Minute,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ repo := &commandCodeRateLimitRepo{}
+ account := clineTestAccount(430)
+ shouldDisable := NewRateLimitService(repo, nil, &config.Config{}, nil, nil).HandleUpstreamError(
+ context.Background(), account, tc.status, http.Header{}, []byte(tc.body), tc.model)
+
+ require.False(t, shouldDisable)
+ require.Len(t, repo.modelLimits, 1)
+ require.WithinDuration(t, time.Now().Add(tc.wait), repo.modelLimits[tc.scope], time.Second)
+ require.True(t, strings.HasPrefix(repo.reasons[tc.scope], tc.reason), repo.reasons[tc.scope])
+ require.Zero(t, repo.setErrorCalls)
+ require.Zero(t, repo.tempCalls)
+ })
+ }
+}
diff --git a/backend/internal/service/ratelimit_cn_providers.go b/backend/internal/service/ratelimit_cn_providers.go
index bb222a9f9..69c62dd1e 100644
--- a/backend/internal/service/ratelimit_cn_providers.go
+++ b/backend/internal/service/ratelimit_cn_providers.go
@@ -7,6 +7,7 @@ import (
"strings"
"time"
+ "github.com/MACOS-DO/sub4api/internal/config"
"github.com/tidwall/gjson"
)
@@ -153,9 +154,17 @@ func (s *RateLimitService) handleCNProviderInsufficientBalance(
// 默认 20 分钟)。周期任务会在余额恢复后提前清除,故此处只需保证冷却覆盖到下一次
// 周期检测即可。
func (s *RateLimitService) cnBalanceCooldownDuration() time.Duration {
+ if s == nil {
+ return cnBalanceCheckCooldown(nil)
+ }
+ return cnBalanceCheckCooldown(s.cfg)
+}
+
+// cnBalanceCheckCooldown 返回余额类冷却时长(= 2× 余额检测周期,默认周期 10 分钟)。
+func cnBalanceCheckCooldown(cfg *config.Config) time.Duration {
minutes := 10
- if s != nil && s.cfg != nil {
- if cfgMin := s.cfg.Gateway.CNProviders.BalanceCheckIntervalMinutes; cfgMin > 0 {
+ if cfg != nil {
+ if cfgMin := cfg.Gateway.CNProviders.BalanceCheckIntervalMinutes; cfgMin > 0 {
minutes = cfgMin
}
}
@@ -175,12 +184,20 @@ func cnProviderQuotaSnapshotReset(account *Account, now time.Time) *time.Time {
if account == nil || len(account.Extra) == 0 {
return nil
}
- if !account.IsOpenCodeGo() && (!account.IsCNProvider() || !account.IsCodingPlan()) {
+ switch {
+ case account.IsOpenCodeGo():
+ case account.IsCommandCode():
+ // 有充值积分时上游跳过窗口检查,429 与窗口无关。
+ if !commandCodeWindowsBinding(account.Extra) {
+ return nil
+ }
+ case account.IsCNProvider() && account.IsCodingPlan():
+ default:
return nil
}
provider := account.Platform
suffixes := []string{cnExtraSuffix5hReset, cnExtraSuffixWeeklyReset}
- if account.IsOpenCodeGo() {
+ if cnQuotaHasMonthlyWindow(provider) {
suffixes = append(suffixes, cnExtraSuffixMonthlyReset)
}
var earliest *time.Time
diff --git a/backend/internal/service/ratelimit_command_code.go b/backend/internal/service/ratelimit_command_code.go
new file mode 100644
index 000000000..4b8d95d01
--- /dev/null
+++ b/backend/internal/service/ratelimit_command_code.go
@@ -0,0 +1,174 @@
+package service
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "regexp"
+ "strings"
+ "time"
+)
+
+// Command Code 用量超限的响应式处理,依据官方错误说明
+// (https://commandcode.ai/docs/troubleshooting/errors):
+//
+// - Rate limit:短时间请求过多,很快恢复,走默认 429 逻辑;
+// - Usage exceeded,三种来源:
+// 1. 5 小时 / 每周滚动窗口用满,文案如
+// "You've reached your 5-hour usage limit. Resets in 2h 41m (3:00 PM)";
+// 2. 月度积分耗尽;
+// 3. 组织为成员设的花费上限,分成员总额度与成员某个模型的额度两种,后者文案如
+// "You've reached the $10.00/mo spending limit your organization set for GLM-5. It resets in 3 days."
+//
+// 文档没有给出状态码与响应体结构,因此按文案分类,402 / 403 / 429 同样处理;
+// 页面路径中的 usage_exceeded 可能是错误码,一并识别。未识别的错误交回默认逻辑。
+//
+// 窗口用满写带原因的临时停调(而非 SetRateLimited):充值积分不受滚动窗口限制,
+// 额度探测发现充值积分后只清除这一类停调(见 queryCommandCodeUsage)。
+
+type commandCodeUsageErrorKind int
+
+const (
+ commandCodeUsageErrorNone commandCodeUsageErrorKind = iota
+ // commandCodeUsageWindowLimit 滚动窗口用满:冷却到窗口重置。
+ commandCodeUsageWindowLimit
+ // commandCodeUsageCreditsExhausted 积分耗尽:可恢复停调,积分恢复后由周期检测解除。
+ commandCodeUsageCreditsExhausted
+ // commandCodeUsageSpendLimit 组织花费上限:模型级只限当前模型,成员总额度按账号冷却。
+ commandCodeUsageSpendLimit
+)
+
+const (
+ // commandCodeUsageLimitReason 是窗口用满临时停调的原因前缀,充值后据此只清除这一类停调。
+ commandCodeUsageLimitReason = "command_code_usage_limit"
+ commandCodeSpendLimitReason = "command_code_spend_limit"
+ // 从文案解析出的重置时长上限:窗口最长为每周,花费上限最长按月。
+ commandCodeMaxWindowCooldown = 8 * 24 * time.Hour
+ commandCodeMaxSpendLimitCooldown = 32 * 24 * time.Hour
+ // commandCodeAccountSpendLimitRecheck 是账号级花费上限(或作用域不明)的最长冷却:
+ // 管理员可能随时调高上限,到期后由下一次请求重新确认。
+ commandCodeAccountSpendLimitRecheck = time.Hour
+)
+
+// commandCodeModelSpendLimitPattern 匹配组织为成员某个模型设的花费上限
+// ("... spending limit your organization set for GLM-5.");成员总额度没有 "for <模型>"。
+var commandCodeModelSpendLimitPattern = regexp.MustCompile(`(?i)spending limit your organization set for\s+([^.\s][^.]*)`)
+
+// commandCodeSpendLimitIsModelScoped 报告花费上限是否只针对单个模型。
+func commandCodeSpendLimitIsModelScoped(body []byte) bool {
+ match := commandCodeModelSpendLimitPattern.FindSubmatch(body)
+ if match == nil {
+ return false
+ }
+ target := strings.ToLower(strings.TrimSpace(string(match[1])))
+ return target != "" && !strings.HasPrefix(target, "you")
+}
+
+func classifyCommandCodeUsageError(body []byte) commandCodeUsageErrorKind {
+ text := strings.ToLower(string(body))
+ switch {
+ case strings.Contains(text, "spending limit"):
+ return commandCodeUsageSpendLimit
+ case strings.Contains(text, "usage limit"):
+ return commandCodeUsageWindowLimit
+ case cnProviderResponseIndicatesInsufficientBalance(body),
+ strings.Contains(text, "insufficient credit"),
+ strings.Contains(text, "out of credits"),
+ strings.Contains(text, "usage_exceeded"),
+ strings.Contains(text, "usage exceeded"):
+ return commandCodeUsageCreditsExhausted
+ default:
+ return commandCodeUsageErrorNone
+ }
+}
+
+// commandCodeResetAt 解析文案中的 "Resets in 2h 41m" / "resets in 3 days";无法解析
+// 或超过 maxWait 时返回 nil。
+func commandCodeResetAt(body []byte, now time.Time, maxWait time.Duration) *time.Time {
+ after := parseOpenCodeGoUsageLimitResetDuration(extractUpstreamErrorMessage(body))
+ if after <= 0 {
+ after = parseOpenCodeGoUsageLimitResetDuration(string(body))
+ }
+ if after <= 0 || after > maxWait {
+ return nil
+ }
+ until := now.Add(after)
+ return &until
+}
+
+// handleCommandCodeUsageError 处理已识别的 Command Code 用量超限;handled=false 时由
+// 调用方继续走默认逻辑。shouldDisable 与同类状态码的既有口径一致:429 不置位;
+// 只限单个模型时也不置位,避免调用方把整个账号拉黑。
+func (s *RateLimitService) handleCommandCodeUsageError(
+ ctx context.Context,
+ account *Account,
+ statusCode int,
+ responseBody []byte,
+ upstreamMsg string,
+) (handled, shouldDisable bool) {
+ accountWide := statusCode != http.StatusTooManyRequests
+ now := time.Now()
+ switch classifyCommandCodeUsageError(responseBody) {
+ case commandCodeUsageWindowLimit:
+ until := commandCodeResetAt(responseBody, now, commandCodeMaxWindowCooldown)
+ if until == nil {
+ until = cnProviderQuotaSnapshotReset(account, now)
+ }
+ if until == nil {
+ return false, false
+ }
+ reason := commandCodeUsageLimitReason
+ if msg := strings.TrimSpace(upstreamMsg); msg != "" {
+ reason += ": " + msg
+ }
+ s.notifyAccountSchedulingBlocked(account, *until, commandCodeUsageLimitReason)
+ if err := s.accountRepo.SetTempUnschedulable(ctx, account.ID, *until, reason); err != nil {
+ slog.Warn("command_code_usage_limit_set_failed", "account_id", account.ID, "error", err)
+ return false, false
+ }
+ slog.Info("command_code_usage_limit", "account_id", account.ID, "status_code", statusCode, "reset_at", until.UTC())
+ return true, accountWide
+ case commandCodeUsageCreditsExhausted:
+ s.handleCNProviderInsufficientBalance(ctx, account, upstreamMsg)
+ return true, accountWide
+ case commandCodeUsageSpendLimit:
+ return true, s.handleCommandCodeSpendLimit(ctx, account, statusCode, responseBody, now)
+ default:
+ return false, false
+ }
+}
+
+// handleCommandCodeSpendLimit 处理组织花费上限:文案指明模型且请求模型已知时只限该
+// 模型,冷却到文案中的重置时间;成员总额度或作用域不明时整个账号冷却,但最长
+// commandCodeAccountSpendLimitRecheck,避免管理员调高上限后账号仍停用数天,也不会
+// 因累积 403 被永久禁用。
+func (s *RateLimitService) handleCommandCodeSpendLimit(ctx context.Context, account *Account, statusCode int, responseBody []byte, now time.Time) (shouldDisable bool) {
+ reset := commandCodeResetAt(responseBody, now, commandCodeMaxSpendLimitCooldown)
+ modelKey := modelRateLimitKeyForUpstreamModelNotFound(ctx, account, tempUnschedulableModel(ctx, nil))
+ if modelKey != "" && commandCodeSpendLimitIsModelScoped(responseBody) {
+ until := reset
+ if until == nil {
+ fallback, ok := s.get429FallbackCooldown(ctx, account)
+ if !ok || fallback <= 0 {
+ fallback = time.Duration(defaultRateLimit429CooldownSeconds) * time.Second
+ }
+ next := now.Add(fallback)
+ until = &next
+ }
+ if err := s.accountRepo.SetModelRateLimit(ctx, account.ID, modelKey, *until, commandCodeSpendLimitReason); err != nil {
+ slog.Warn("command_code_spend_limit_set_failed", "account_id", account.ID, "model", modelKey, "error", err)
+ }
+ slog.Info("command_code_spend_limit", "account_id", account.ID, "model", modelKey, "status_code", statusCode, "reset_at", until.UTC())
+ return false
+ }
+ until := now.Add(commandCodeAccountSpendLimitRecheck)
+ if reset != nil && reset.Before(until) {
+ until = *reset
+ }
+ s.notifyAccountSchedulingBlocked(account, until, commandCodeSpendLimitReason)
+ if err := s.accountRepo.SetTempUnschedulable(ctx, account.ID, until, commandCodeSpendLimitReason); err != nil {
+ slog.Warn("command_code_spend_limit_set_failed", "account_id", account.ID, "error", err)
+ }
+ slog.Info("command_code_spend_limit", "account_id", account.ID, "status_code", statusCode, "until", until.UTC())
+ return statusCode != http.StatusTooManyRequests
+}
diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go
index 7669262c3..b4861c64b 100644
--- a/backend/internal/service/ratelimit_service.go
+++ b/backend/internal/service/ratelimit_service.go
@@ -399,6 +399,28 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc
upstreamMsg = truncateForLog([]byte(upstreamMsg), 512)
}
+ // Command Code 用量超限按文案区分、与状态码无关(见 ratelimit_command_code.go);
+ // 未识别的错误(含普通频率限制)继续走下面的默认逻辑。
+ if account.IsCommandCode() && (statusCode == http.StatusPaymentRequired ||
+ statusCode == http.StatusForbidden || statusCode == http.StatusTooManyRequests) {
+ if handled, disable := s.handleCommandCodeUsageError(ctx, account, statusCode, responseBody, upstreamMsg); handled {
+ return disable
+ }
+ }
+ // Cline 积分、花费上限与 ClinePass 超限按结构化错误区分,只冷却对应的钱包。
+ // 400 是请求错误,不能因回显的模型名或请求内容触发钱包冷却。
+ if account.IsCline() && (statusCode == http.StatusPaymentRequired ||
+ statusCode == http.StatusForbidden || statusCode == http.StatusTooManyRequests) {
+ if s.handleClineError(ctx, account, statusCode, responseBody, upstreamMsg) {
+ return false
+ }
+ // 402 只会是积分不足:冷却没写进去也不能落到下面的 402 默认分支——那里永久置
+ // status=error,而周期探测只覆盖激活账号,充值后无法自动恢复。
+ if statusCode == http.StatusPaymentRequired {
+ return false
+ }
+ }
+
switch statusCode {
case 400:
// "organization has been disabled" → 永久禁用
@@ -515,9 +537,10 @@ func (s *RateLimitService) HandleUpstreamError(ctx context.Context, account *Acc
shouldDisable = true
}
case 402:
- // 国产供应商:余额不足是可恢复状态(充值/检测恢复后由周期任务自动解除),
- // 不能走 handleAuthError 永久置 status=error。改为可恢复的临时停调。
- if account.IsCNProvider() || account.IsOpenCodeZen() {
+ // 国产供应商 / OpenCode Zen / Command Code:余额(积分)不足是可恢复状态
+ // (充值/检测恢复后由周期任务自动解除),不能走 handleAuthError 永久置
+ // status=error。改为可恢复的临时停调。
+ if account.IsCNProvider() || account.IsOpenCodeZen() || account.IsCommandCode() {
s.handleCNProviderInsufficientBalance(ctx, account, upstreamMsg)
shouldDisable = true
break
@@ -1003,7 +1026,7 @@ func (s *RateLimitService) handle403(ctx context.Context, account *Account, upst
// 国产供应商与 openai 同口径:HTML 403(CDN/代理拦截页)不构成账号失效证据,
// 且 403 在 failover 状态集里会被逐账号重放——直接 SetError 会让一个坏请求/
// 一层坏代理连环永久禁用整组账号。走 HTML 豁免 + N 次累计 + 临时冷却。
- if account.Platform == PlatformOpenAI || IsCNProvider(account.Platform) || account.IsOpenCodeGo() {
+ if account.Platform == PlatformOpenAI || account.IsMultiProtocolAPIKey() {
return s.handleOpenAI403(ctx, account, upstreamMsg, responseBody)
}
// 非 Antigravity 平台:保持原有行为
diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go
index af45661dc..d9086e7b3 100644
--- a/backend/internal/service/scheduler_snapshot_service.go
+++ b/backend/internal/service/scheduler_snapshot_service.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/MACOS-DO/sub4api/internal/config"
+ "github.com/MACOS-DO/sub4api/internal/domain"
"github.com/MACOS-DO/sub4api/internal/pkg/logger"
)
@@ -608,10 +609,10 @@ func (s *SchedulerSnapshotService) handleBulkAccountEvent(ctx context.Context, p
continue
}
accountGroupIDs := s.normalizeGroupIDs(account.GroupIDs)
- switch account.Platform {
- case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS:
+ switch {
+ case account.Platform != PlatformAntigravity && isConcreteRequestPlatform(account.Platform):
addPlatformGroups(account.Platform, accountGroupIDs)
- case PlatformAntigravity:
+ case account.Platform == PlatformAntigravity:
// 批量更新可能刚关闭 mixed_scheduling,仍需清理两个兼容平台的旧快照。
addPlatformGroups(PlatformAntigravity, accountGroupIDs)
addPlatformGroups(PlatformAnthropic, accountGroupIDs)
@@ -824,8 +825,9 @@ func (s *SchedulerSnapshotService) rebuildByAccount(ctx context.Context, account
return s.rebuildBuckets(ctx, buckets, reason)
}
-func schedulerSnapshotPlatforms() [11]string {
- return [11]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformOpenAIBPS}
+// schedulerSnapshotPlatforms 返回需要维护调度快照的全部具体平台(平台清单)。
+func schedulerSnapshotPlatforms() []string {
+ return domain.CompositePrecedencePlatformIDs()
}
// 生命周期辅助函数有意排除 group0;full rebuild 构造 group0 canonical 集时必须显式调用 canonical helper。
diff --git a/backend/internal/service/testdata/record_upstream_protocol_routing_main.py b/backend/internal/service/testdata/record_upstream_protocol_routing_main.py
new file mode 100644
index 000000000..dd12d90e4
--- /dev/null
+++ b/backend/internal/service/testdata/record_upstream_protocol_routing_main.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python3
+"""Record the routing golden from the pinned main source, never the checkout."""
+
+import io
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import tarfile
+import tempfile
+
+
+def format_golden(fixture):
+ """Keep observations readable and wrap case indexes in compact rows."""
+ metadata = {key: value for key, value in fixture.items() if key != "results"}
+ prefix = json.dumps(metadata, ensure_ascii=False, indent=2)[:-2]
+ indexes = fixture["results"]
+ rows = [" " + ", ".join(map(str, indexes[i:i + 32])) for i in range(0, len(indexes), 32)]
+ return (prefix + ',\n "results": [\n' + ",\n".join(rows) + "\n ]\n}\n").encode("utf-8")
+
+
+def main():
+ repo = Path(__file__).resolve().parents[4]
+ driver = repo / "backend/internal/service/upstream_protocol_routing_matrix_test.go"
+ source = driver.read_text()
+ revision = re.search(r'const routingMatrixMainRevision = "([0-9a-f]{40})"', source).group(1)
+ subprocess.run(["git", "cat-file", "-e", revision + "^{commit}"], cwd=repo, check=True)
+ archive = subprocess.check_output(["git", "archive", revision, "backend"], cwd=repo)
+
+ with tempfile.TemporaryDirectory(prefix="sub2api-routing-main-") as scratch:
+ root = Path(scratch)
+ with tarfile.open(fileobj=io.BytesIO(archive)) as files:
+ files.extractall(root, filter="data")
+ recording_driver = root / "backend/internal/service/upstream_protocol_routing_matrix_test.go"
+ recording_driver.write_text(source + r'''
+
+func TestRecordUpstreamProtocolRoutingMainGolden(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ data, err := json.MarshalIndent(captureRoutingMatrixGolden(), "", " ")
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(os.Getenv("ROUTING_MATRIX_RECORD_OUTPUT"), append(data, '\n'), 0o644))
+}
+''')
+ output = root / "routing_main_golden.json"
+ environment = dict(os.environ, ROUTING_MATRIX_RECORD_OUTPUT=str(output))
+ subprocess.run(
+ ["go", "test", "-tags", "unit", "./internal/service/", "-run", "^TestRecordUpstreamProtocolRoutingMainGolden$", "-count=1"],
+ cwd=root / "backend", env=environment, check=True,
+ )
+ data = output.read_bytes()
+ fixture = json.loads(data)
+ if fixture["source_revision"] != revision:
+ raise RuntimeError("Recorded source revision differs from the pinned revision")
+ destination = driver.parent / "testdata/upstream_protocol_routing_main_golden.json"
+ destination.write_bytes(format_golden(fixture))
+ print(f"Recorded {fixture['case_count']} cases from {revision} into {destination}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/internal/service/testdata/upstream_protocol_routing_main_golden.json b/backend/internal/service/testdata/upstream_protocol_routing_main_golden.json
new file mode 100644
index 000000000..6db675bb4
--- /dev/null
+++ b/backend/internal/service/testdata/upstream_protocol_routing_main_golden.json
@@ -0,0 +1,3931 @@
+{
+ "source_revision": "5fc0e486c3f6a8a191b8bd140f39b60457f611cf",
+ "case_count": 63600,
+ "case_keys_sha256": "639577ac93cdf9b12c3ae7070ff272d44415fdd0a03de6b783ae70bb53c21862",
+ "observations": [
+ {
+ "upstream": [
+ {
+ "url": "https://api.moonshot.cn/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.moonshot.cn/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "error": "unsupported account type: upstream",
+ "status": 200
+ },
+ {
+ "error": "get access token: unsupported account type: upstream",
+ "status": 200
+ },
+ {
+ "error": "access_token not found in credentials",
+ "status": 200
+ },
+ {
+ "error": "get access token: access_token not found in credentials",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.kimi.com/coding/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.kimi.com/coding/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.moonshot.cn/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.moonshot.cn/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " kimi-k2 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.moonshot.cn/anthropic/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.moonshot.cn/anthropic/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " kimi-k2 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " kimi-k2 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://cc.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " kimi-k2 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "error": "account 801 missing api_key",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.kimi.com/coding/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.kimi.com/coding/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " kimi-k2 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.kimi.com/coding/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.kimi.com/coding/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " kimi-k2 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " kimi-k2 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "kimi-k2"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " kimi-k2 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://open.bigmodel.cn/api/paas/v4/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://open.bigmodel.cn/api/paas/v4/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://open.bigmodel.cn/api/anthropic/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://open.bigmodel.cn/api/anthropic/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " glm-4.7 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://cc.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " glm-4.7 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "glm-4.7"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " glm-4.7 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.deepseek.com/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.deepseek.com/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.deepseek.com/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.deepseek.com/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " deepseek-chat "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.deepseek.com/anthropic/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.deepseek.com/anthropic/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " deepseek-chat "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " deepseek-chat "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://cc.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " deepseek-chat "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " deepseek-chat "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "deepseek-chat"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " deepseek-chat "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.minimaxi.com/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.minimaxi.com/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.minimaxi.com/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.minimaxi.com/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " minimax-m3 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.minimaxi.com/anthropic/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.minimaxi.com/anthropic/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " minimax-m3 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " minimax-m3 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://cc.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " minimax-m3 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " minimax-m3 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " minimax-m3 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.openai.com/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "gpt-5"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.openai.com/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " gpt-5 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "gpt-5"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " gpt-5 "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.openai.com/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "gpt-5"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.openai.com/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "gpt-5"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "gpt-5"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "gpt-5"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "error": "opencode unsupported model: gemini-3.8-flash",
+ "status": 400,
+ "client_error_type": "invalid_request_error",
+ "client_error_code": "model_not_supported",
+ "client_error_message": "Model 'gemini-3.8-flash' is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)"
+ },
+ {
+ "error": "opencode unsupported model: jev-1.13",
+ "status": 400,
+ "client_error_type": "invalid_request_error",
+ "client_error_code": "model_not_supported",
+ "client_error_message": "Model 'jev-1.13' is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)"
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " opencode/gpt-5.6-luna "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "error": "opencode unsupported model: gemini-3.8-flash",
+ "status": 400,
+ "client_error_type": "invalid_request_error",
+ "client_error_message": "Model 'gemini-3.8-flash' is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)"
+ },
+ {
+ "error": "opencode unsupported model: jev-1.13",
+ "status": 400,
+ "client_error_type": "invalid_request_error",
+ "client_error_message": "Model 'jev-1.13' is not supported on OpenCode standard gateway (gemini models require Google SDK endpoint, jev models require System One endpoint)"
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://cc.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://cc.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " opencode/gpt-5.6-luna "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://responses.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://cc.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://cc.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " opencode/gpt-5.6-luna "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://anthropic.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/chat/completions",
+ "authorization": "Bearer sk-test",
+ "body_kind": "messages",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " opencode/gpt-5.6-luna "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " opencode/gpt-5.6-luna "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/messages",
+ "api_key": "sk-test",
+ "body_kind": "messages",
+ "model": " opencode/gpt-5.6-luna "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/go/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": " opencode/gpt-5.6-luna "
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "opencode/gpt-5.6-luna"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "minimax-m3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "glm-5.3"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "claude-sonnet-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "qwen3.8-max"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://opencode.ai/zen/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "qwen3.8-flash"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "https://api.x.ai/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "grok-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "upstream": [
+ {
+ "url": "http://base.example/v1/responses",
+ "authorization": "Bearer sk-test",
+ "body_kind": "input",
+ "model": "grok-4"
+ }
+ ],
+ "error": "upstream error: 502 (failover)",
+ "status": 200
+ },
+ {
+ "error": "get access token: credential failure: grok_oauth_provider_config (failover)",
+ "status": 200
+ }
+ ],
+ "results": [
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 20, 21, 8, 8, 20, 20, 22, 23, 20, 21, 2, 2, 20, 20, 22, 23, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 20, 21, 8, 8, 20, 20, 22, 23, 20, 21, 2, 2, 20, 20, 22, 23, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 20, 21, 8, 8, 20, 20, 22, 23, 20, 21, 2, 2, 20, 20, 22, 23, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 10, 11, 0, 0, 10, 10, 12, 13, 10, 11, 2, 2, 10, 10, 12, 13, 14, 15, 16, 16, 14, 14, 17, 18, 14, 15, 16, 16, 14, 14, 17, 18,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 22, 22, 22, 22, 22, 22, 22, 23, 24, 24, 24, 24, 24, 24, 24, 25, 22, 22, 22, 22, 22, 22, 22, 23, 24, 24, 24, 24, 24, 24, 24, 25,
+ 22, 22, 22, 22, 22, 22, 22, 23, 24, 24, 24, 24, 24, 24, 24, 25, 22, 22, 22, 22, 22, 22, 22, 23, 24, 24, 24, 24, 24, 24, 24, 25,
+ 22, 22, 22, 22, 22, 22, 22, 23, 24, 24, 24, 24, 24, 24, 24, 25, 22, 22, 22, 22, 22, 22, 22, 23, 24, 24, 24, 24, 24, 24, 24, 25,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25, 12, 12, 12, 12, 12, 12, 12, 13, 24, 24, 24, 24, 24, 24, 24, 25,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 20, 21, 20, 20, 20, 20, 20, 20, 26, 27, 26, 26, 26, 26, 26, 26, 20, 21, 20, 20, 20, 20, 20, 20, 26, 27, 26, 26, 26, 26, 26, 26,
+ 20, 21, 20, 20, 20, 20, 20, 20, 26, 27, 26, 26, 26, 26, 26, 26, 20, 21, 20, 20, 20, 20, 20, 20, 26, 27, 26, 26, 26, 26, 26, 26,
+ 20, 21, 20, 20, 20, 20, 20, 20, 26, 27, 26, 26, 26, 26, 26, 26, 20, 21, 20, 20, 20, 20, 20, 20, 26, 27, 26, 26, 26, 26, 26, 26,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26, 10, 11, 10, 10, 10, 10, 10, 10, 26, 27, 26, 26, 26, 26, 26, 26,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2, 8, 8, 8, 8, 9, 9, 8, 8, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2, 3, 3, 2, 2,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 32, 32, 32, 32, 32, 32, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 32, 32, 32, 32, 32, 32, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 32, 32, 32, 32, 32, 32, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 28, 28, 28, 28, 28, 28, 34, 35, 30, 30, 30, 30, 30, 30, 34, 35, 36, 36, 36, 36, 36, 36, 37, 38, 36, 36, 36, 36, 36, 36, 37, 38,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19, 4, 4, 4, 4, 4, 4, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19, 6, 6, 6, 6, 6, 6, 19, 19,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40, 34, 34, 34, 34, 34, 34, 34, 35, 39, 39, 39, 39, 39, 39, 39, 40,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30, 32, 32, 32, 32, 33, 33, 32, 32, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30, 28, 28, 28, 28, 29, 29, 28, 28, 30, 30, 30, 30, 31, 31, 30, 30,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 45, 46, 41, 41, 45, 45, 47, 48, 45, 46, 43, 43, 45, 45, 47, 48, 49, 50, 51, 51, 49, 49, 52, 53, 49, 50, 51, 51, 49, 49, 52, 53,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55, 47, 47, 47, 47, 47, 47, 47, 48, 54, 54, 54, 54, 54, 54, 54, 55,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56, 45, 46, 45, 45, 45, 45, 45, 45, 56, 57, 56, 56, 56, 56, 56, 56,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43, 41, 41, 41, 41, 42, 42, 41, 41, 43, 43, 43, 43, 44, 44, 43, 43,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 62, 63, 58, 58, 62, 62, 64, 65, 62, 63, 60, 60, 62, 62, 64, 65, 66, 67, 68, 68, 66, 66, 69, 70, 66, 67, 68, 68, 66, 66, 69, 70,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19, 4, 4, 4, 4, 5, 5, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19, 6, 6, 6, 6, 7, 7, 19, 19,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72, 64, 64, 64, 64, 64, 64, 64, 65, 71, 71, 71, 71, 71, 71, 71, 72,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73, 62, 63, 62, 62, 62, 62, 62, 62, 73, 74, 73, 73, 73, 73, 73, 73,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60, 58, 58, 58, 58, 59, 59, 58, 58, 60, 60, 60, 60, 61, 61, 60, 60,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81, 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81, 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81, 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81, 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81, 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77, 75, 76, 75, 75, 75, 75, 75, 75, 77, 78, 77, 77, 77, 77, 77, 77,
+ 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81, 79, 79, 79, 79, 80, 80, 79, 79, 81, 81, 81, 81, 82, 82, 81, 81,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 5, 5, 5,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 7, 7, 7,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 113, 114, 115, 116, 117, 118, 89, 90, 119, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113,
+ 89, 113, 114, 115, 116, 117, 118, 93, 94, 120, 113, 93, 113, 114, 121, 122, 117, 123, 89, 90, 119, 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120,
+ 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120, 113, 89, 113, 114, 121, 122, 117, 123, 93, 94, 120, 113, 93, 113, 60, 99, 116, 101, 118, 89, 90,
+ 119, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 93,
+ 94, 120, 113, 93, 113, 60, 121, 100, 101, 102, 89, 90, 119, 113, 89, 113, 60, 121, 100, 101, 102, 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102,
+ 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102, 93, 94, 120, 113, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111,
+ 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68,
+ 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 113, 114, 115, 116, 117, 118, 89, 90, 119, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113,
+ 89, 113, 114, 115, 116, 117, 118, 93, 94, 120, 113, 93, 113, 114, 121, 122, 117, 123, 89, 90, 119, 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120,
+ 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120, 113, 89, 113, 114, 121, 122, 117, 123, 93, 94, 120, 113, 93, 113, 60, 99, 116, 101, 118, 89, 90,
+ 119, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 93,
+ 94, 120, 113, 93, 113, 60, 121, 100, 101, 102, 89, 90, 119, 113, 89, 113, 60, 121, 100, 101, 102, 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102,
+ 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102, 93, 94, 120, 113, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111,
+ 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68,
+ 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4,
+ 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4,
+ 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4,
+ 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4,
+ 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 113, 114, 115, 116, 117, 118, 89, 90, 119, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113,
+ 89, 113, 114, 115, 116, 117, 118, 93, 94, 120, 113, 93, 113, 114, 121, 122, 117, 123, 89, 90, 119, 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120,
+ 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120, 113, 89, 113, 114, 121, 122, 117, 123, 93, 94, 120, 113, 93, 113, 60, 99, 116, 101, 118, 89, 90,
+ 119, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 93,
+ 94, 120, 113, 93, 113, 60, 121, 100, 101, 102, 89, 90, 119, 113, 89, 113, 60, 121, 100, 101, 102, 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102,
+ 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102, 93, 94, 120, 113, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111,
+ 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68,
+ 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 113, 114, 115, 116, 117, 118, 89, 90, 119, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113,
+ 89, 113, 114, 115, 116, 117, 118, 93, 94, 120, 113, 93, 113, 114, 121, 122, 117, 123, 89, 90, 119, 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120,
+ 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120, 113, 89, 113, 114, 121, 122, 117, 123, 93, 94, 120, 113, 93, 113, 60, 99, 116, 101, 118, 89, 90,
+ 119, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 93,
+ 94, 120, 113, 93, 113, 60, 121, 100, 101, 102, 89, 90, 119, 113, 89, 113, 60, 121, 100, 101, 102, 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102,
+ 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102, 93, 94, 120, 113, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111,
+ 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68,
+ 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4,
+ 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4,
+ 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4,
+ 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4,
+ 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125,
+ 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126,
+ 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90,
+ 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93,
+ 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102,
+ 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97,
+ 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86,
+ 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85,
+ 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60,
+ 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127,
+ 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93,
+ 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125,
+ 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126,
+ 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90,
+ 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93,
+ 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102,
+ 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97,
+ 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86,
+ 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85,
+ 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60,
+ 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127,
+ 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4,
+ 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4,
+ 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4,
+ 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4,
+ 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4,
+ 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4,
+ 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4,
+ 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4,
+ 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4,
+ 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4,
+ 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125,
+ 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126,
+ 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90,
+ 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93,
+ 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102,
+ 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97,
+ 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86,
+ 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85,
+ 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60,
+ 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127,
+ 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93,
+ 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125,
+ 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126,
+ 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90,
+ 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93,
+ 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102,
+ 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97,
+ 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86,
+ 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85,
+ 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60,
+ 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127,
+ 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4,
+ 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4,
+ 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4,
+ 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4,
+ 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4,
+ 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4,
+ 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4,
+ 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4,
+ 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4,
+ 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4,
+ 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129,
+ 89, 129, 114, 115, 122, 117, 123, 93, 94, 130, 129, 93, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130,
+ 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 93, 94, 130, 129, 93, 127, 60, 99, 100, 101, 102, 89, 90,
+ 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93,
+ 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102,
+ 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117,
+ 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 93, 94, 130, 129, 93, 129, 114, 115, 122,
+ 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115,
+ 122, 117, 123, 93, 94, 130, 129, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60,
+ 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127,
+ 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93,
+ 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129,
+ 89, 129, 114, 115, 122, 117, 123, 93, 94, 130, 129, 93, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130,
+ 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 93, 94, 130, 129, 93, 127, 60, 99, 100, 101, 102, 89, 90,
+ 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93,
+ 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102,
+ 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117,
+ 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 93, 94, 130, 129, 93, 129, 114, 115, 122,
+ 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115, 122, 117, 123, 89, 90, 130, 129, 89, 129, 114, 115,
+ 122, 117, 123, 93, 94, 130, 129, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60,
+ 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127,
+ 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4,
+ 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4,
+ 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4,
+ 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4,
+ 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4,
+ 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4,
+ 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4,
+ 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4,
+ 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4,
+ 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4,
+ 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125,
+ 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126,
+ 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90,
+ 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93,
+ 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102,
+ 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97,
+ 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86,
+ 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85,
+ 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60,
+ 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127,
+ 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93,
+ 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125,
+ 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126,
+ 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90,
+ 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93,
+ 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102,
+ 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97,
+ 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 93, 94, 126, 125, 93, 125, 95, 85, 86,
+ 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85, 86, 97, 98, 89, 90, 126, 125, 89, 125, 95, 85,
+ 86, 97, 98, 93, 94, 126, 125, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60,
+ 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127,
+ 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 89, 90, 128, 127, 89, 127, 60, 99, 100, 101, 102, 93, 94, 128, 127, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4,
+ 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4,
+ 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4,
+ 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4,
+ 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4,
+ 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4,
+ 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4,
+ 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4,
+ 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4,
+ 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 4,
+ 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131,
+ 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133,
+ 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90,
+ 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93,
+ 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139,
+ 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87,
+ 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132,
+ 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96,
+ 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71,
+ 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135,
+ 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93,
+ 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131,
+ 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133,
+ 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90,
+ 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93,
+ 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139,
+ 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87,
+ 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132,
+ 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96,
+ 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71,
+ 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135,
+ 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19,
+ 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19,
+ 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19,
+ 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19,
+ 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19,
+ 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19,
+ 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19,
+ 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19,
+ 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19,
+ 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19,
+ 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131,
+ 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133,
+ 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90,
+ 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93,
+ 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139,
+ 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87,
+ 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132,
+ 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96,
+ 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71,
+ 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135,
+ 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93,
+ 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131,
+ 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133,
+ 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90,
+ 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93,
+ 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139,
+ 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87,
+ 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132,
+ 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96,
+ 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71,
+ 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135,
+ 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19,
+ 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19,
+ 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19,
+ 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19,
+ 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19,
+ 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19,
+ 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19,
+ 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19,
+ 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19,
+ 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19,
+ 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142,
+ 89, 142, 143, 121, 116, 144, 118, 93, 94, 146, 142, 93, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145,
+ 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 93, 94, 146, 142, 93, 135, 71, 136, 137, 138, 139, 89, 90,
+ 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93,
+ 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139,
+ 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144,
+ 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 93, 94, 146, 142, 93, 142, 143, 121, 116,
+ 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121,
+ 116, 144, 118, 93, 94, 146, 142, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71,
+ 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135,
+ 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93,
+ 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142,
+ 89, 142, 143, 121, 116, 144, 118, 93, 94, 146, 142, 93, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145,
+ 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 93, 94, 146, 142, 93, 135, 71, 136, 137, 138, 139, 89, 90,
+ 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93,
+ 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139,
+ 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144,
+ 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 93, 94, 146, 142, 93, 142, 143, 121, 116,
+ 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121, 116, 144, 118, 89, 90, 145, 142, 89, 142, 143, 121,
+ 116, 144, 118, 93, 94, 146, 142, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71,
+ 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135,
+ 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19,
+ 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19,
+ 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19,
+ 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19,
+ 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19,
+ 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19,
+ 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19,
+ 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19,
+ 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19,
+ 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19,
+ 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131,
+ 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133,
+ 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90,
+ 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93,
+ 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139,
+ 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87,
+ 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132,
+ 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96,
+ 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71,
+ 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135,
+ 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93,
+ 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131,
+ 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133,
+ 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90,
+ 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93,
+ 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139,
+ 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87,
+ 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 93, 94, 134, 131, 93, 131, 84, 96, 132,
+ 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96, 132, 87, 88, 89, 90, 133, 131, 89, 131, 84, 96,
+ 132, 87, 88, 93, 94, 134, 131, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71,
+ 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135,
+ 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 89, 90, 140, 135, 89, 135, 71, 136, 137, 138, 139, 93, 94, 141, 135, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19,
+ 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19,
+ 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19,
+ 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19,
+ 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19,
+ 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19,
+ 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19,
+ 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90,
+ 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93,
+ 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19,
+ 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19,
+ 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19,
+ 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19,
+ 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19,
+ 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19,
+ 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 89, 90, 19, 19, 89, 19, 19, 19, 19, 19, 19, 93, 94, 19, 19, 93,
+ 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83,
+ 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92,
+ 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90,
+ 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93,
+ 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156,
+ 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150,
+ 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149,
+ 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148,
+ 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73,
+ 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152,
+ 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93,
+ 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83,
+ 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92,
+ 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90,
+ 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93,
+ 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156,
+ 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150,
+ 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149,
+ 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148,
+ 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73,
+ 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152,
+ 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93,
+ 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5,
+ 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5,
+ 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90,
+ 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93,
+ 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5,
+ 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5,
+ 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4,
+ 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5,
+ 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5,
+ 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5,
+ 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93,
+ 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5,
+ 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5,
+ 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90,
+ 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93,
+ 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5,
+ 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5,
+ 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4,
+ 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5,
+ 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5,
+ 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5,
+ 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93,
+ 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83,
+ 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92,
+ 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90,
+ 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93,
+ 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156,
+ 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150,
+ 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149,
+ 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148,
+ 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73,
+ 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152,
+ 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93,
+ 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83,
+ 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92,
+ 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90,
+ 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93,
+ 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156,
+ 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150,
+ 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149,
+ 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148,
+ 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73,
+ 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152,
+ 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93,
+ 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5,
+ 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5,
+ 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90,
+ 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93,
+ 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5,
+ 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5,
+ 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4,
+ 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5,
+ 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5,
+ 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5,
+ 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93,
+ 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5,
+ 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5,
+ 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90,
+ 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93,
+ 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5,
+ 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5,
+ 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4,
+ 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5,
+ 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5,
+ 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5,
+ 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93,
+ 113, 159, 160, 161, 162, 163, 89, 90, 119, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113,
+ 89, 113, 159, 160, 161, 162, 163, 93, 94, 120, 113, 93, 113, 159, 160, 161, 162, 163, 89, 90, 119, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120,
+ 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 93, 94, 120, 113, 93, 152, 73, 153, 154, 155, 156, 89, 90,
+ 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93,
+ 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156,
+ 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 113, 159, 160, 161, 162, 163, 89, 90, 119, 113, 89, 113, 159, 160, 161, 162,
+ 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 93, 94, 120, 113, 93, 113, 159, 160, 161,
+ 162, 163, 89, 90, 119, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160,
+ 161, 162, 163, 93, 94, 120, 113, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73,
+ 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152,
+ 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93,
+ 113, 159, 160, 161, 162, 163, 89, 90, 119, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113,
+ 89, 113, 159, 160, 161, 162, 163, 93, 94, 120, 113, 93, 113, 159, 160, 161, 162, 163, 89, 90, 119, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120,
+ 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 93, 94, 120, 113, 93, 152, 73, 153, 154, 155, 156, 89, 90,
+ 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93,
+ 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156,
+ 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 113, 159, 160, 161, 162, 163, 89, 90, 119, 113, 89, 113, 159, 160, 161, 162,
+ 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 93, 94, 120, 113, 93, 113, 159, 160, 161,
+ 162, 163, 89, 90, 119, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160, 161, 162, 163, 89, 90, 120, 113, 89, 113, 159, 160,
+ 161, 162, 163, 93, 94, 120, 113, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73,
+ 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152,
+ 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93,
+ 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5,
+ 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5,
+ 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90,
+ 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93,
+ 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5,
+ 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5,
+ 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4,
+ 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5,
+ 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5,
+ 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5,
+ 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93,
+ 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5,
+ 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5,
+ 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90,
+ 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93,
+ 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5,
+ 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5,
+ 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4,
+ 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5,
+ 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5,
+ 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5,
+ 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93,
+ 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83,
+ 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92,
+ 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90,
+ 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93,
+ 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156,
+ 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150,
+ 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149,
+ 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148,
+ 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73,
+ 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152,
+ 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93,
+ 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83,
+ 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92,
+ 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90,
+ 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93,
+ 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156,
+ 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 83, 147, 148, 149, 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150,
+ 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 93, 94, 92, 83, 93, 83, 147, 148, 149,
+ 150, 151, 89, 90, 91, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148, 149, 150, 151, 89, 90, 92, 83, 89, 83, 147, 148,
+ 149, 150, 151, 93, 94, 92, 83, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73,
+ 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93, 152, 73, 153, 154, 155, 156, 89, 90, 157, 152, 89, 152,
+ 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 89, 90, 158, 152, 89, 152, 73, 153, 154, 155, 156, 93, 94, 158, 152, 93,
+ 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5,
+ 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5,
+ 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90,
+ 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93,
+ 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5,
+ 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5,
+ 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4,
+ 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5,
+ 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5,
+ 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5,
+ 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93,
+ 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5,
+ 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5,
+ 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90,
+ 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93,
+ 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5,
+ 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5,
+ 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4,
+ 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5,
+ 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5,
+ 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93, 4, 4, 4, 4, 4, 4, 89, 90, 4, 4, 89, 5,
+ 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 89, 90, 5, 5, 89, 5, 5, 5, 5, 5, 5, 93, 94, 5, 5, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 113, 114, 115, 116, 117, 118, 89, 90, 119, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113,
+ 89, 113, 114, 115, 116, 117, 118, 93, 94, 120, 113, 93, 113, 114, 121, 122, 117, 123, 89, 90, 119, 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120,
+ 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120, 113, 89, 113, 114, 121, 122, 117, 123, 93, 94, 120, 113, 93, 113, 60, 99, 116, 101, 118, 89, 90,
+ 119, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 93,
+ 94, 120, 113, 93, 113, 60, 121, 100, 101, 102, 89, 90, 119, 113, 89, 113, 60, 121, 100, 101, 102, 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102,
+ 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102, 93, 94, 120, 113, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111,
+ 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68,
+ 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 113, 114, 115, 116, 117, 118, 89, 90, 119, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113, 89, 113, 114, 115, 116, 117, 118, 89, 90, 120, 113,
+ 89, 113, 114, 115, 116, 117, 118, 93, 94, 120, 113, 93, 113, 114, 121, 122, 117, 123, 89, 90, 119, 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120,
+ 113, 89, 113, 114, 121, 122, 117, 123, 89, 90, 120, 113, 89, 113, 114, 121, 122, 117, 123, 93, 94, 120, 113, 93, 113, 60, 99, 116, 101, 118, 89, 90,
+ 119, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 89, 90, 120, 113, 89, 113, 60, 99, 116, 101, 118, 93,
+ 94, 120, 113, 93, 113, 60, 121, 100, 101, 102, 89, 90, 119, 113, 89, 113, 60, 121, 100, 101, 102, 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102,
+ 89, 90, 120, 113, 89, 113, 60, 121, 100, 101, 102, 93, 94, 120, 113, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111,
+ 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 68, 104, 124, 111, 107, 89, 90, 108, 103, 89, 103, 68, 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68,
+ 104, 124, 111, 107, 89, 90, 109, 103, 89, 103, 68, 104, 124, 111, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4,
+ 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4,
+ 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4,
+ 19, 89, 90, 5, 5, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 4,
+ 4, 19, 4, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 83, 84, 85, 86, 87, 88, 89, 90, 91, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83, 89, 83, 84, 85, 86, 87, 88, 89, 90, 92, 83,
+ 89, 83, 84, 85, 86, 87, 88, 93, 94, 92, 83, 93, 83, 95, 96, 86, 97, 98, 89, 90, 91, 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92,
+ 83, 89, 83, 95, 96, 86, 97, 98, 89, 90, 92, 83, 89, 83, 95, 96, 86, 97, 98, 93, 94, 92, 83, 93, 83, 84, 99, 100, 87, 88, 89, 90,
+ 91, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 89, 90, 92, 83, 89, 83, 84, 99, 100, 87, 88, 93,
+ 94, 92, 83, 93, 83, 60, 96, 100, 101, 102, 89, 90, 91, 83, 89, 83, 60, 96, 100, 101, 102, 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102,
+ 89, 90, 92, 83, 89, 83, 60, 96, 100, 101, 102, 93, 94, 92, 83, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106,
+ 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105,
+ 111, 112, 89, 90, 108, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110,
+ 105, 111, 112, 93, 94, 109, 103, 93, 103, 69, 104, 105, 106, 107, 89, 90, 108, 103, 89, 103, 69, 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69,
+ 104, 105, 106, 107, 89, 90, 109, 103, 89, 103, 69, 104, 105, 106, 107, 93, 94, 109, 103, 93, 103, 68, 110, 105, 111, 112, 89, 90, 108, 103, 89, 103,
+ 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 89, 90, 109, 103, 89, 103, 68, 110, 105, 111, 112, 93, 94, 109, 103, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5,
+ 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5,
+ 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90,
+ 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93,
+ 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4,
+ 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19,
+ 19, 89, 90, 5, 5, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19,
+ 19, 19, 89, 90, 4, 4, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19,
+ 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5, 19, 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19,
+ 4, 4, 19, 19, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93, 4, 19, 19, 19, 19, 19, 89, 90, 4, 4, 89, 5,
+ 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 4, 19, 4, 4, 4, 89, 90, 5, 5, 89, 5, 19, 19, 19, 19, 19, 93, 94, 5, 5, 93,
+ 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 19, 19, 19, 19, 19, 19, 19, 19, 5, 5, 5, 5, 5, 5, 5, 5,
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166,
+ 166, 166, 166, 166, 166, 166, 166, 166, 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 19, 19, 19, 19, 19, 19, 19, 19,
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 166, 166, 166, 166, 166, 166, 166, 166,
+ 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165,
+ 19, 19, 19, 19, 19, 19, 19, 19, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+ 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 164, 164, 165, 165, 164, 164, 165, 165,
+ 164, 164, 165, 165, 164, 164, 165, 165, 19, 19, 19, 19, 19, 19, 19, 19, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+ 5, 5, 5, 5, 5, 5, 5, 5, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166,
+ 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 19, 19, 19, 19, 19, 19, 19, 19, 5, 5, 5, 5, 5, 5, 5, 5,
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166,
+ 166, 166, 166, 166, 166, 166, 166, 166, 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 164, 164, 165, 165, 19, 19, 19, 19, 19, 19, 19, 19,
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 166, 166, 166, 166, 166, 166, 166, 166,
+ 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166
+ ]
+}
diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go
index c529c1357..871092815 100644
--- a/backend/internal/service/upstream_billing_probe.go
+++ b/backend/internal/service/upstream_billing_probe.go
@@ -19,6 +19,7 @@ import (
"sync"
"time"
+ "github.com/MACOS-DO/sub4api/internal/domain"
infraerrors "github.com/MACOS-DO/sub4api/internal/pkg/errors"
"github.com/MACOS-DO/sub4api/internal/pkg/logger"
"github.com/MACOS-DO/sub4api/internal/pkg/tlsfingerprint"
@@ -626,7 +627,7 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac
return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "missing_api_key", 0)
}
baseURL := account.GetCredential("base_url")
- if account.IsCNProvider() && account.IsAdaptiveAPIProtocol() {
+ if account.RoutesProtocolByInbound() && account.IsAdaptiveAPIProtocol() {
baseURL = account.GetCNProtocolBaseURL(APIProtocolChatCompletions)
}
if account.Platform == PlatformOpenAI {
@@ -1008,16 +1009,8 @@ func decodeUpstreamBillingProbeSnapshot(extra map[string]any) *UpstreamBillingPr
// type=apikey by the admin form, so only pre-existing type=upstream rows
// cannot turn the probe on.
func IsUpstreamBillingProbeIdentity(platform, accountType string) bool {
- if accountType != AccountTypeAPIKey {
- return false
- }
- switch platform {
- case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok,
- PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo:
- return true
- default:
- return false
- }
+ // Sub4API: OpenAI BPS has no upstream billing endpoint to probe.
+ return accountType == AccountTypeAPIKey && platform != PlatformOpenAIBPS && domain.IsConcretePlatform(platform)
}
func isUpstreamBillingProbeAccount(account *Account) bool {
@@ -1052,6 +1045,9 @@ var upstreamBillingProbeOfficialAPIDomains = []string{
"bigmodel.cn",
"deepseek.com",
"opencode.ai",
+ "typesafe.ai",
+ "commandcode.ai",
+ "cline.bot",
}
func upstreamBillingProbeTargetIsOfficialAPI(baseURL string) bool {
@@ -1103,6 +1099,12 @@ func (s *UpstreamBillingProbeService) currentTime() time.Time {
}
func nextProbeDelay(intervalMinutes int, retryAfterDuration time.Duration) time.Duration {
+ if retryAfterDuration < 0 {
+ retryAfterDuration = 0
+ }
+ if retryAfterDuration > upstreamBillingProbeMaxDelay {
+ retryAfterDuration = upstreamBillingProbeMaxDelay
+ }
interval := time.Duration(intervalMinutes) * time.Minute
if interval < upstreamBillingProbeMinIntervalMinutes*time.Minute {
interval = upstreamBillingProbeMinIntervalMinutes * time.Minute
@@ -1118,8 +1120,8 @@ func nextProbeDelay(intervalMinutes int, retryAfterDuration time.Duration) time.
interval += time.Duration(rand.Int64N(int64(jitterRange)*2+1)) - jitterRange
}
if retryAfterDuration > interval {
- // Retry-After is an explicit upstream instruction; do not shorten it
- // with the local maximum delay.
+ // Retry-After is an explicit upstream instruction; honor it over the
+ // local backoff interval, clamped to the same 24h ceiling.
return retryAfterDuration
}
if interval > upstreamBillingProbeMaxDelay {
@@ -1131,8 +1133,7 @@ func nextProbeDelay(intervalMinutes int, retryAfterDuration time.Duration) time.
// unsupportedProbeDelay 拉长 unsupported 账号的重探间隔,让无效候选自然退出
// 热队列,不再和真正接入 sub2api 的中转账号抢每周期的探测名额。
// 仍按 upstreamBillingProbeMaxDelay 封顶,保证上游后来接入 sub2api 时最迟一天
-// 内会被重新发现;base 本身已达上限(例如 Retry-After 明确要求更久)时原样返回,
-// 不缩短上游指令。
+// 内会被重新发现;base 本身亦受 24h 封顶保护。
func unsupportedProbeDelay(intervalMinutes int, retryAfterDuration time.Duration) time.Duration {
base := nextProbeDelay(intervalMinutes, retryAfterDuration)
if base >= upstreamBillingProbeMaxDelay {
diff --git a/backend/internal/service/upstream_billing_probe_multiplatform_test.go b/backend/internal/service/upstream_billing_probe_multiplatform_test.go
index 450cec373..2af41cff4 100644
--- a/backend/internal/service/upstream_billing_probe_multiplatform_test.go
+++ b/backend/internal/service/upstream_billing_probe_multiplatform_test.go
@@ -17,6 +17,7 @@ func TestUpstreamBillingProbeIdentityCoversAllAPIKeyPlatforms(t *testing.T) {
for _, platform := range []string{
PlatformOpenAI, PlatformGrok, PlatformAnthropic, PlatformGemini, PlatformAntigravity,
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
+ PlatformTypeSafe,
} {
require.True(t, IsUpstreamBillingProbeIdentity(platform, AccountTypeAPIKey), platform)
require.True(t, isUpstreamBillingProbeAccount(&Account{Platform: platform, Type: AccountTypeAPIKey}), platform)
@@ -174,6 +175,8 @@ func TestUpstreamBillingProbeOfficialAPIBaseURLIsUnsupportedWithoutRequest(t *te
{PlatformDeepseek, "https://api.deepseek.com/anthropic"},
{PlatformOpenCodeGo, "https://opencode.ai/zen/go/v1"},
{PlatformOpenCodeGo, "https://opencode.ai/zen/go"},
+ {PlatformTypeSafe, "https://api.typesafe.ai"},
+ {PlatformTypeSafe, "https://api.typesafe.ai/v1"},
}
for i, tc := range cases {
account := &Account{
@@ -217,6 +220,7 @@ func TestUpstreamBillingProbeOfficialAPIHostMatchingIsNormalized(t *testing.T) {
require.True(t, upstreamBillingProbeTargetIsOfficialAPI("https://api.deepseek.com/anthropic"))
require.True(t, upstreamBillingProbeTargetIsOfficialAPI("https://opencode.ai/zen/go/v1"))
require.True(t, upstreamBillingProbeTargetIsOfficialAPI("https://opencode.ai/zen/go"))
+ require.True(t, upstreamBillingProbeTargetIsOfficialAPI("https://api.typesafe.ai"))
// 相似但不同的注册域不拦:中转完全可能叫 *-x.ai 之外的任何名字。
require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://relay.example/v1"))
require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://notx.ai"))
@@ -228,6 +232,7 @@ func TestUpstreamBillingProbeOfficialAPIHostMatchingIsNormalized(t *testing.T) {
require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://notmoonshot.cn/v1"))
require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://moonshot.cn.evil.example/v1"))
require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://kimi.example/v1"))
+ require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://nottypesafe.ai"))
require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://notbigmodel.cn"))
require.False(t, upstreamBillingProbeTargetIsOfficialAPI("https://deepseek.example.com"))
}
@@ -276,3 +281,16 @@ func TestUpstreamBillingProbeSetAccountEnabledAcceptsGrokAPIKey(t *testing.T) {
err := svc.SetAccountEnabled(context.Background(), grokOAuth.ID, true)
require.ErrorIs(t, err, ErrUpstreamBillingProbeAccountInvalid)
}
+
+func TestBuildAccountForCreateAcceptsTypeSafeAPIKeyWithProbeEnabled(t *testing.T) {
+ enabled := true
+ account, err := buildAccountForCreate(&CreateAccountInput{
+ Name: "typesafe",
+ Platform: PlatformTypeSafe,
+ Type: AccountTypeAPIKey,
+ Credentials: map[string]any{"api_key": "ts-key", "base_url": "https://api.typesafe.ai"},
+ ProbeEnabled: &enabled,
+ }, map[string]any{})
+ require.NoError(t, err)
+ require.Equal(t, true, account.Extra[UpstreamBillingProbeEnabledExtraKey])
+}
diff --git a/backend/internal/service/upstream_billing_probe_test.go b/backend/internal/service/upstream_billing_probe_test.go
index e1f87c830..6a8dd82fe 100644
--- a/backend/internal/service/upstream_billing_probe_test.go
+++ b/backend/internal/service/upstream_billing_probe_test.go
@@ -767,13 +767,13 @@ func TestUpstreamBillingProbeFailurePreservesLastSuccessAndRetryAfter(t *testing
require.Equal(t, initialRate, *account.RateMultiplier)
}
-func TestUpstreamBillingProbeRetryAfterIsNotShortened(t *testing.T) {
+func TestUpstreamBillingProbeRetryAfterIsCappedAtMaxDelay(t *testing.T) {
delay := nextProbeDelay(30, 48*time.Hour)
- require.Equal(t, 48*time.Hour, delay)
+ require.Equal(t, upstreamBillingProbeMaxDelay, delay)
}
// unsupported 的重探间隔明显长于普通失败,但始终有上界:上游后来接入 sub2api
-// 时最迟一天内会被重新发现,且不会缩短上游 Retry-After 指令。
+// 时最迟一天内会被重新发现,且上游超长 Retry-After 亦受 24h 封顶保护。
func TestUpstreamBillingProbeUnsupportedDelayIsStretchedAndBounded(t *testing.T) {
// 默认 30 分钟 interval:普通失败 24~36 分钟,unsupported 为其 8 倍。
stretched := unsupportedProbeDelay(30, 0)
@@ -785,8 +785,8 @@ func TestUpstreamBillingProbeUnsupportedDelayIsStretchedAndBounded(t *testing.T)
require.LessOrEqual(t, unsupportedProbeDelay(upstreamBillingProbeMaxIntervalMinutes, 0), upstreamBillingProbeMaxDelay)
require.Positive(t, unsupportedProbeDelay(upstreamBillingProbeMinIntervalMinutes, 0))
- // Retry-After 更长时原样保留,不被封顶缩短;更短时至少不早于该指令。
- require.Equal(t, 48*time.Hour, unsupportedProbeDelay(30, 48*time.Hour))
+ // Retry-After 更长时受封顶保护,不超过 upstreamBillingProbeMaxDelay;更短时至少不早于该指令。
+ require.Equal(t, upstreamBillingProbeMaxDelay, unsupportedProbeDelay(30, 48*time.Hour))
require.GreaterOrEqual(t, unsupportedProbeDelay(30, time.Hour), time.Hour)
}
diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go
index a5e9f70f0..b980c4358 100644
--- a/backend/internal/service/upstream_models.go
+++ b/backend/internal/service/upstream_models.go
@@ -625,7 +625,7 @@ func upstreamModelRegistryBaseURL(account *Account) string {
return ""
}
switch {
- case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo():
+ case account.IsOpenAI() || account.IsMultiProtocolAPIKey():
return account.GetOpenAIFormatBaseURL()
case account.IsGrok():
return account.GetGrokBaseURL()
@@ -792,9 +792,8 @@ func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, acc
return s.buildAntigravityAPIKeyModelsRequest(ctx, account)
case account.IsGrok():
return s.buildGrokUpstreamModelsRequest(ctx, account)
- case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo():
- // 国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go
- // 复用 OpenAI /v1/models 探测。
+ case account.IsOpenAI() || account.IsMultiProtocolAPIKey():
+ // 多协议 API Key 供应商(国产厂商与聚合平台)复用 OpenAI /v1/models 探测。
return s.buildOpenAIUpstreamModelsRequest(ctx, account)
case account.IsGemini():
return s.buildGeminiUpstreamModelsRequest(ctx, account)
diff --git a/backend/internal/service/upstream_protocol_routing.go b/backend/internal/service/upstream_protocol_routing.go
new file mode 100644
index 000000000..de8b610fd
--- /dev/null
+++ b/backend/internal/service/upstream_protocol_routing.go
@@ -0,0 +1,139 @@
+package service
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/apicompat"
+)
+
+// resolveUpstreamProtocol 决定 OpenAI 网关本次请求发往上游的协议
+// (chat_completions / responses / anthropic),是 /v1/responses、
+// /v1/chat/completions、/v1/messages 三个入站入口共用的唯一判定。
+// 只做判断,不改写请求体、不发请求;各入口再按「入站 × 上游」选择转换路径。
+//
+// inbound 为入站协议;/v1/chat/completions 收到 Responses 形状请求体时按
+// responses 计。model 仅按模型分流的账号使用,取 upstreamRoutingModel 的结果。
+// catalog 为上游模型目录给出的该模型支持的协议(见 model_protocol_catalog.go),未知时为 nil。
+//
+// 优先级:
+// 1. 按模型分流的供应商(多模型聚合平台,如 OpenCode、Command Code):显式
+// api_protocol 直接生效;否则先得到该模型支持的协议集合(见 modelProtocolSet),
+// 入站协议在集合中时同协议直通,不在时走集合首项(首选协议)。
+// 2. adaptive(按入站协议分流):供应商提供入站协议的原生端点则走同协议,
+// 否则回落 Chat Completions。
+// 3. 显式 anthropic 协议 → Anthropic。
+// 4. shouldForwardOpenAIResponsesViaRawChatCompletions(显式 chat_completions、
+// 探针确认不支持 Responses 等)→ Chat Completions。
+// 5. 其余 → Responses。
+//
+// Grok 在 Responses / Chat Completions 入口有专属链路,须在调用本函数前分流。
+func resolveUpstreamProtocol(account *Account, inbound, model string, catalog []string) string {
+ if account.routesByModel() {
+ return account.resolveModelRoutedProtocolFor(model, inbound, catalog)
+ }
+ if account.IsAdaptiveAPIProtocol() {
+ if account.providerSupportsProtocol(inbound) {
+ return inbound
+ }
+ return APIProtocolChatCompletions
+ }
+ if account.IsAnthropicProtocol() {
+ return APIProtocolAnthropic
+ }
+ if shouldForwardOpenAIResponsesViaRawChatCompletions(account) {
+ return APIProtocolChatCompletions
+ }
+ return APIProtocolResponses
+}
+
+// resolveModelRoutedProtocol 返回按模型分流账号对该模型的首选上游协议(不考虑入站
+// 协议与上游模型目录),供连接测试等没有入站协议的场景使用。
+func (a *Account) resolveModelRoutedProtocol(model string) string {
+ return a.resolveModelRoutedProtocolFor(model, "", nil)
+}
+
+// resolveModelRoutedProtocolFor 按模型名解析按模型分流账号的上游协议:显式 pinned
+// 协议直接生效;否则取该模型支持的协议集合,入站协议在其中时同协议直通(省去一次
+// 协议转换),不在时走首选协议。
+func (a *Account) resolveModelRoutedProtocolFor(model, inbound string, catalog []string) string {
+ switch proto := a.GetAPIProtocol(); proto {
+ case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses:
+ return proto
+ }
+ set := a.modelProtocolSet(model, catalog)
+ if slices.Contains(set, inbound) {
+ return inbound
+ }
+ return set[0]
+}
+
+// modelProtocolSet 返回模型支持的上游协议集合(首项为首选),来源依次为:
+// 1. 账号 protocol_rules 中命中的规则(管理员显式配置);
+// 2. 上游模型目录(catalog):首选沿用内置规则对该模型的首选(在集合内时),否则取目录首项;
+// 3. profile 内置规则——仅在账号未配置 protocol_rules 时,已配置但未命中视为有意不走内置规则;
+// 4. Chat Completions,避免落入 Responses 转换链。
+func (a *Account) modelProtocolSet(model string, catalog []string) []string {
+ rules, configured := a.configuredProtocolRules()
+ if configured {
+ if set, ok := matchProtocolRuleSet(model, rules); ok {
+ return set
+ }
+ }
+ profileRules := a.providerProfile().Endpoints(a.GetCredential("account_mode")).ProtocolRules
+ if set := a.supportedCatalogProtocols(catalog); len(set) > 0 {
+ preferred := matchProtocolRules(model, profileRules)
+ if slices.Contains(set, preferred) {
+ return normalizeProtocolSet(preferred, set)
+ }
+ return set
+ }
+ if !configured {
+ if set, ok := matchProtocolRuleSet(model, profileRules); ok {
+ return set
+ }
+ }
+ return []string{APIProtocolChatCompletions}
+}
+
+// supportedCatalogProtocols 过滤出账号接入模式确有原生端点的目录协议。
+func (a *Account) supportedCatalogProtocols(catalog []string) []string {
+ out := make([]string, 0, len(catalog))
+ for _, protocol := range catalog {
+ if isNativeUpstreamProtocol(protocol) && a.providerSupportsProtocol(protocol) && !slices.Contains(out, protocol) {
+ out = append(out, protocol)
+ }
+ }
+ return out
+}
+
+// upstreamRoutingModel 返回参与协议分流的模型名:仅按模型分流的账号需要,按账号
+// 模型映射与上游归一后的名字匹配规则;其余账号的分流与模型无关,返回空串。
+func upstreamRoutingModel(account *Account, body []byte, defaultMappedModel string) string {
+ if !account.routesByModel() {
+ return ""
+ }
+ return resolveMappedUpstreamModel(account, body, defaultMappedModel)
+}
+
+// convertResponsesShapedChatBody 把发到 /v1/chat/completions 的 Responses 形状
+// 请求体(Cursor 兼容)转换为 Chat Completions 请求体。
+func (s *OpenAIGatewayService) convertResponsesShapedChatBody(body []byte) ([]byte, error) {
+ var responsesReq apicompat.ResponsesRequest
+ if err := json.Unmarshal(body, &responsesReq); err != nil {
+ return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err)
+ }
+ chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions(
+ &responsesReq,
+ &apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID},
+ )
+ if err != nil {
+ return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err)
+ }
+ chatBody, err := json.Marshal(chatReq)
+ if err != nil {
+ return nil, fmt.Errorf("marshal converted chat completions request: %w", err)
+ }
+ return chatBody, nil
+}
diff --git a/backend/internal/service/upstream_protocol_routing_matrix_test.go b/backend/internal/service/upstream_protocol_routing_matrix_test.go
new file mode 100644
index 000000000..5ffa75954
--- /dev/null
+++ b/backend/internal/service/upstream_protocol_routing_matrix_test.go
@@ -0,0 +1,350 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/openai_compat"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// The fixture is captured through the real gateway entry points on this main
+// revision, before provider profiles and resolveUpstreamProtocol were added.
+// Expected results never call routing helpers from the implementation under test.
+// Regenerate with python3 testdata/record_upstream_protocol_routing_main.py, which exports
+// this pinned revision before compiling and recording the same matrix driver.
+const routingMatrixMainRevision = "5fc0e486c3f6a8a191b8bd140f39b60457f611cf"
+const routingMatrixGoldenPath = "testdata/upstream_protocol_routing_main_golden.json"
+
+type routingMatrixIngress struct {
+ name string
+ path string
+ responsesBody bool
+ forward func(*OpenAIGatewayService, *gin.Context, *Account, []byte) error
+}
+
+func routingMatrixIngresses() []routingMatrixIngress {
+ return []routingMatrixIngress{
+ {
+ name: "responses", path: "/v1/responses", responsesBody: true,
+ forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
+ _, err := svc.Forward(context.Background(), c, account, body)
+ return err
+ },
+ },
+ {
+ name: "chat", path: "/v1/chat/completions",
+ forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
+ _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
+ return err
+ },
+ },
+ {
+ name: "chat_responses_shape", path: "/v1/chat/completions", responsesBody: true,
+ forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
+ _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
+ return err
+ },
+ },
+ {
+ name: "messages", path: "/v1/messages",
+ forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error {
+ _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "")
+ return err
+ },
+ },
+ }
+}
+
+type routingMatrixCase struct {
+ platform string
+ apiProtocol string
+ mode string
+ accountType string
+ probe string
+ addresses string
+ rules bool
+ ingress routingMatrixIngress
+ model string
+}
+
+func (tc routingMatrixCase) key() string {
+ return fmt.Sprintf("%s|proto=%s|mode=%s|type=%s|probe=%s|addresses=%s|rules=%t|%s|%s",
+ tc.platform, tc.apiProtocol, tc.mode, tc.accountType, tc.probe, tc.addresses, tc.rules, tc.ingress.name, tc.model)
+}
+
+func (tc routingMatrixCase) account() *Account {
+ credentials := map[string]any{"api_key": "sk-test"}
+ if tc.addresses == "base" || tc.addresses == "both" {
+ credentials["base_url"] = "http://base.example"
+ }
+ if tc.addresses == "split" || tc.addresses == "both" {
+ credentials["api_base_urls"] = map[string]any{
+ APIProtocolChatCompletions: "http://cc.example",
+ APIProtocolResponses: "http://responses.example",
+ APIProtocolAnthropic: "http://anthropic.example",
+ }
+ }
+ if tc.apiProtocol != "" {
+ credentials["api_protocol"] = tc.apiProtocol
+ }
+ if tc.mode != "" {
+ credentials["account_mode"] = tc.mode
+ }
+ if tc.rules {
+ credentials["protocol_rules"] = []any{
+ map[string]any{"pattern": "glm-*", "protocol": APIProtocolAnthropic},
+ map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses},
+ }
+ }
+ if tc.platform == PlatformOpenCodeGo {
+ credentials["model_mapping"] = map[string]any{
+ "mapped-gpt": "gpt-5.6-luna",
+ "mapped-unsupported": "gemini-3.8-flash",
+ }
+ }
+ extra := map[string]any{}
+ switch tc.probe {
+ case "yes":
+ extra[openai_compat.ExtraKeyResponsesSupported] = true
+ case "no":
+ extra[openai_compat.ExtraKeyResponsesSupported] = false
+ }
+ return &Account{
+ ID: 801, Name: "routing-matrix", Platform: tc.platform, Type: tc.accountType,
+ Concurrency: 1, Credentials: credentials, Extra: extra,
+ }
+}
+
+func (tc routingMatrixCase) body() []byte {
+ switch {
+ case tc.ingress.responsesBody:
+ return []byte(fmt.Sprintf(`{"model":%q,"input":"hello","max_output_tokens":32,"stream":false}`, tc.model))
+ case tc.ingress.name == "messages":
+ return []byte(fmt.Sprintf(`{"model":%q,"max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`, tc.model))
+ default:
+ return []byte(fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hello"}],"stream":false}`, tc.model))
+ }
+}
+
+func routingMatrixCases() []routingMatrixCase {
+ var cases []routingMatrixCase
+ protocols := []string{"", APIProtocolAdaptive, APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses, "invalid"}
+ types := []string{AccountTypeAPIKey, AccountTypeUpstream, AccountTypeOAuth}
+ probes := []string{"", "yes", "no"}
+ addresses := []string{"none", "base", "split", "both"}
+ add := func(platform string, modes, models []string, rulesOptions []bool, probeOptions, typeOptions []string, ingresses []routingMatrixIngress) {
+ for _, proto := range protocols {
+ for _, mode := range modes {
+ for _, accountType := range typeOptions {
+ for _, probe := range probeOptions {
+ for _, address := range addresses {
+ for _, rules := range rulesOptions {
+ for _, ingress := range ingresses {
+ for _, model := range models {
+ cases = append(cases, routingMatrixCase{
+ platform: platform, apiProtocol: proto, mode: mode, accountType: accountType,
+ probe: probe, addresses: address, rules: rules, ingress: ingress, model: model,
+ })
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ all := routingMatrixIngresses()
+ modes := []string{"", AccountModePayG, AccountModeCoding, "invalid"}
+ for _, provider := range []struct{ platform, model string }{
+ {PlatformKimi, "kimi-k2"}, {PlatformZhipu, "glm-4.7"},
+ {PlatformDeepseek, "deepseek-chat"}, {PlatformMiniMax, "minimax-m3"},
+ } {
+ add(provider.platform, modes, []string{provider.model, " " + provider.model + " "}, []bool{false}, probes, types, all)
+ }
+ add(PlatformOpenAI, []string{""}, []string{"gpt-5", " gpt-5 "}, []bool{false}, probes, types, all)
+ add(PlatformOpenCodeGo, []string{"", AccountModeGo, AccountModeZen, "invalid"},
+ []string{"gpt-5.6-luna", "minimax-m3", "glm-5.3", "claude-sonnet-4", "qwen3.8-max", "qwen3.8-flash",
+ "gemini-3.8-flash", "jev-1.13", " opencode/gpt-5.6-luna ", "mapped-gpt", "mapped-unsupported"},
+ []bool{false, true}, []string{"", "no"}, []string{AccountTypeAPIKey, AccountTypeUpstream}, all)
+ // Grok has its own Responses and Chat Completions implementations; only the
+ // Messages entry uses the routing logic covered by this compatibility matrix.
+ add(PlatformGrok, []string{""}, []string{"grok-4", " grok-4 "}, []bool{false}, probes, types, all[3:])
+ return cases
+}
+
+type routingUpstreamRequest struct {
+ URL string `json:"url"`
+ Authorization string `json:"authorization,omitempty"`
+ APIKey string `json:"api_key,omitempty"`
+ AnthropicVersion string `json:"anthropic_version,omitempty"`
+ BodyKind string `json:"body_kind"`
+ Model string `json:"model"`
+}
+
+type routingObservation struct {
+ Requests []routingUpstreamRequest `json:"upstream,omitempty"`
+ Error string `json:"error,omitempty"`
+ Panic string `json:"panic,omitempty"`
+ Status int `json:"status"`
+ ClientErrorType string `json:"client_error_type,omitempty"`
+ ClientErrorCode string `json:"client_error_code,omitempty"`
+ ClientErrorMessage string `json:"client_error_message,omitempty"`
+}
+
+func (o routingObservation) String() string {
+ data, _ := json.Marshal(o)
+ return string(data)
+}
+
+func observeRouting(tc routingMatrixCase) (obs routingObservation) {
+ upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+ body := tc.body()
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, tc.ingress.path, bytes.NewReader(body))
+ c.Request.Header.Set("Content-Type", "application/json")
+ defer func() {
+ if r := recover(); r != nil {
+ obs.Panic = fmt.Sprint(r)
+ }
+ for i, req := range upstream.requests {
+ kind := "other"
+ switch {
+ case gjson.GetBytes(upstream.bodies[i], "messages").Exists():
+ kind = "messages"
+ case gjson.GetBytes(upstream.bodies[i], "input").Exists():
+ kind = "input"
+ }
+ obs.Requests = append(obs.Requests, routingUpstreamRequest{
+ URL: req.URL.String(), Authorization: req.Header.Get("Authorization"),
+ APIKey: req.Header.Get("X-Api-Key"), AnthropicVersion: req.Header.Get("Anthropic-Version"),
+ BodyKind: kind, Model: gjson.GetBytes(upstream.bodies[i], "model").String(),
+ })
+ }
+ obs.Status = c.Writer.Status()
+ obs.ClientErrorType = gjson.Get(recorder.Body.String(), "error.type").String()
+ obs.ClientErrorCode = gjson.Get(recorder.Body.String(), "error.code").String()
+ obs.ClientErrorMessage = gjson.Get(recorder.Body.String(), "error.message").String()
+ }()
+ err := tc.ingress.forward(svc, c, tc.account(), body)
+ if err != nil {
+ obs.Error = err.Error()
+ }
+ return obs
+}
+
+// Cases share many outcomes. Store each distinct observation once, then one
+// observation index per case in routingMatrixCases order. The key digest detects
+// any change to case identity or ordering, so matrix edits require a new capture.
+type routingMatrixGolden struct {
+ SourceRevision string `json:"source_revision"`
+ CaseCount int `json:"case_count"`
+ CaseKeysSHA256 string `json:"case_keys_sha256"`
+ Observations []routingObservation `json:"observations"`
+ Results []int `json:"results"`
+}
+
+func routingMatrixCaseDigest(cases []routingMatrixCase) string {
+ var keys strings.Builder
+ for _, tc := range cases {
+ keys.WriteString(tc.key())
+ keys.WriteByte('\n')
+ }
+ return fmt.Sprintf("%x", sha256.Sum256([]byte(keys.String())))
+}
+
+func captureRoutingMatrixGolden() routingMatrixGolden {
+ cases := routingMatrixCases()
+ golden := routingMatrixGolden{SourceRevision: routingMatrixMainRevision, CaseCount: len(cases), CaseKeysSHA256: routingMatrixCaseDigest(cases)}
+ indexByObservation := make(map[string]int)
+ for _, tc := range cases {
+ obs := observeRouting(tc)
+ key := obs.String()
+ index, ok := indexByObservation[key]
+ if !ok {
+ index = len(golden.Observations)
+ golden.Observations = append(golden.Observations, obs)
+ indexByObservation[key] = index
+ }
+ golden.Results = append(golden.Results, index)
+ }
+ return golden
+}
+
+// Zhipu has no Responses endpoint. The refactor routes adaptive /responses to
+// Chat Completions even for unsupported upstream/oauth account types. Both
+// versions reject these accounts before transport, with these exact errors.
+// Only this complete before/after observation is permitted; other no-upstream
+// results and new panics still fail the golden comparison.
+func matchesKnownZhipuNonAPIKeyDifference(tc routingMatrixCase, want, got routingObservation) bool {
+ if tc.platform != PlatformZhipu || tc.apiProtocol != APIProtocolAdaptive || tc.ingress.name != "responses" {
+ return false
+ }
+ var oldError string
+ switch tc.accountType {
+ case AccountTypeUpstream:
+ oldError = "unsupported account type: upstream"
+ case AccountTypeOAuth:
+ oldError = "access_token not found in credentials"
+ default:
+ return false
+ }
+ return reflect.DeepEqual(want, routingObservation{Error: oldError, Status: http.StatusOK}) &&
+ reflect.DeepEqual(got, routingObservation{Error: "account 801 missing api_key", Status: http.StatusOK})
+}
+
+func TestUpstreamProtocolRoutingMatrixMatchesMainGolden(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ data, err := os.ReadFile(routingMatrixGoldenPath)
+ require.NoError(t, err)
+ var golden routingMatrixGolden
+ require.NoError(t, json.Unmarshal(data, &golden))
+ cases := routingMatrixCases()
+ require.Equal(t, routingMatrixMainRevision, golden.SourceRevision)
+ require.Equal(t, len(cases), golden.CaseCount)
+ require.Equal(t, routingMatrixCaseDigest(cases), golden.CaseKeysSHA256)
+ require.Len(t, golden.Results, len(cases))
+
+ var differences []string
+ mismatched := 0
+ knownDifferences := 0
+ for i, tc := range cases {
+ index := golden.Results[i]
+ require.GreaterOrEqual(t, index, 0)
+ require.Less(t, index, len(golden.Observations))
+ want := golden.Observations[index]
+ got := observeRouting(tc)
+ if reflect.DeepEqual(want, got) {
+ continue
+ }
+ if matchesKnownZhipuNonAPIKeyDifference(tc, want, got) {
+ knownDifferences++
+ continue
+ }
+ mismatched++
+ if len(differences) < 12 {
+ differences = append(differences, fmt.Sprintf("%s\nmain: %s\ncurrent: %s", tc.key(), want, got))
+ }
+ }
+ require.Zero(t, mismatched, "routing differs from main %s in %d cases:\n%s", golden.SourceRevision, mismatched, strings.Join(differences, "\n"))
+ // 2 account types × 4 modes × 3 probe states × 4 address configurations ×
+ // 2 model spellings. A disappeared or expanded exception requires review.
+ require.Equal(t, 192, knownDifferences, "unexpected change to the declared Zhipu non-API-Key difference")
+}
diff --git a/backend/internal/service/upstream_protocol_routing_test.go b/backend/internal/service/upstream_protocol_routing_test.go
new file mode 100644
index 000000000..7939d0ebf
--- /dev/null
+++ b/backend/internal/service/upstream_protocol_routing_test.go
@@ -0,0 +1,165 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/MACOS-DO/sub4api/internal/pkg/openai_compat"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func routingTestAccount(platform, accountType string, credentials, extra map[string]any) *Account {
+ if credentials == nil {
+ credentials = map[string]any{}
+ }
+ credentials["api_key"] = "sk-test"
+ return &Account{Platform: platform, Type: accountType, Credentials: credentials, Extra: extra}
+}
+
+func TestResolveUpstreamProtocol(t *testing.T) {
+ t.Parallel()
+
+ const (
+ cc = APIProtocolChatCompletions
+ responses = APIProtocolResponses
+ anthropic = APIProtocolAnthropic
+ )
+ adaptive := func(platform string) *Account {
+ return routingTestAccount(platform, AccountTypeAPIKey, map[string]any{"api_protocol": APIProtocolAdaptive}, nil)
+ }
+ pinned := func(platform, protocol string) *Account {
+ return routingTestAccount(platform, AccountTypeAPIKey, map[string]any{"api_protocol": protocol}, nil)
+ }
+ openCode := func(mode string, credentials map[string]any) *Account {
+ if credentials == nil {
+ credentials = map[string]any{}
+ }
+ credentials["account_mode"] = mode
+ return routingTestAccount(PlatformOpenCodeGo, AccountTypeAPIKey, credentials, nil)
+ }
+ openAIWithProbe := func(accountType string, supported any) *Account {
+ extra := map[string]any{}
+ if supported != nil {
+ extra[openai_compat.ExtraKeyResponsesSupported] = supported
+ }
+ return routingTestAccount(PlatformOpenAI, accountType, nil, extra)
+ }
+
+ cases := []struct {
+ name string
+ account *Account
+ inbound string
+ model string
+ want string
+ }{
+ // 按入站协议分流(国产单一厂商 adaptive)
+ {"kimi adaptive anthropic inbound", adaptive(PlatformKimi), anthropic, "", anthropic},
+ {"kimi adaptive cc inbound", adaptive(PlatformKimi), cc, "", cc},
+ {"kimi adaptive responses inbound", adaptive(PlatformKimi), responses, "", responses},
+ {"zhipu adaptive responses inbound falls back to cc", adaptive(PlatformZhipu), responses, "", cc},
+ {"zhipu adaptive anthropic inbound", adaptive(PlatformZhipu), anthropic, "", anthropic},
+
+ // 显式固定协议,与入站无关
+ {"kimi pinned anthropic", pinned(PlatformKimi, anthropic), cc, "", anthropic},
+ {"kimi pinned cc", pinned(PlatformKimi, cc), responses, "", cc},
+ {"kimi pinned responses", pinned(PlatformKimi, responses), anthropic, "", responses},
+ {"zhipu pinned responses is unsupported and stays cc", pinned(PlatformZhipu, responses), responses, "", cc},
+
+ // 按模型分流(多模型聚合平台),与入站无关
+ {"opencode go gpt", openCode(AccountModeGo, nil), anthropic, "gpt-5.6-luna", responses},
+ {"opencode go minimax", openCode(AccountModeGo, nil), responses, "minimax-m3", anthropic},
+ {"opencode go glm falls back to cc", openCode(AccountModeGo, nil), anthropic, "glm-5.3", cc},
+ {"opencode go claude has no rule", openCode(AccountModeGo, nil), anthropic, "claude-sonnet-4", cc},
+ {"opencode zen claude", openCode(AccountModeZen, nil), cc, "claude-sonnet-4", anthropic},
+ {"opencode account rules override defaults", openCode(AccountModeGo, map[string]any{
+ "protocol_rules": []any{map[string]any{"pattern": "glm-*", "protocol": anthropic}},
+ }), cc, "glm-5.3", anthropic},
+ {"opencode account rules miss falls back to cc", openCode(AccountModeGo, map[string]any{
+ "protocol_rules": []any{map[string]any{"pattern": "glm-*", "protocol": anthropic}},
+ }), cc, "gpt-5.6-luna", cc},
+ {"opencode pinned protocol beats rules", openCode(AccountModeGo, map[string]any{"api_protocol": cc}), anthropic, "gpt-5.6-luna", cc},
+ {"opencode ignores responses probe", func() *Account {
+ account := openCode(AccountModeGo, nil)
+ account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: false}
+ return account
+ }(), cc, "gpt-5.6-luna", responses},
+
+ // 无 profile 的账号按探针决定 Responses / CC
+ {"openai apikey unknown probe", openAIWithProbe(AccountTypeAPIKey, nil), cc, "", responses},
+ {"openai apikey probe unsupported", openAIWithProbe(AccountTypeAPIKey, false), anthropic, "", cc},
+ {"openai oauth ignores probe", openAIWithProbe(AccountTypeOAuth, false), cc, "", responses},
+ }
+ for _, tc := range cases {
+ require.Equal(t, tc.want, resolveUpstreamProtocol(tc.account, tc.inbound, tc.model, nil), tc.name)
+ }
+}
+
+func TestRoutesByModelOnlyForAggregators(t *testing.T) {
+ t.Parallel()
+
+ aggregators := map[string]bool{PlatformOpenCodeGo: true, PlatformCommandCode: true}
+ for platform, profile := range providerProfiles {
+ account := &Account{Platform: platform}
+ require.Equal(t, aggregators[platform], account.routesByModel(), platform)
+ require.Equal(t, aggregators[platform], profile.Routing == ProviderRoutingByModel, platform)
+ }
+ require.False(t, (&Account{Platform: PlatformOpenAI}).routesByModel())
+ require.False(t, (*Account)(nil).routesByModel())
+}
+
+func TestUpstreamRoutingModelOnlyForModelRoutedAccounts(t *testing.T) {
+ t.Parallel()
+
+ body := []byte(`{"model":"gpt-5.6-luna","input":"hi"}`)
+ openCode := routingTestAccount(PlatformOpenCodeGo, AccountTypeAPIKey, map[string]any{
+ "model_mapping": map[string]any{"gpt-5.6-luna": "glm-5.3"},
+ }, nil)
+ require.Equal(t, "glm-5.3", upstreamRoutingModel(openCode, body, ""))
+ require.Empty(t, upstreamRoutingModel(routingTestAccount(PlatformKimi, AccountTypeAPIKey, nil, nil), body, ""))
+}
+
+// /v1/responses 转 Anthropic 上游时,计费模型名与上游模型名都应是去除首尾空白的
+// 请求模型;按模型分流(OpenCode)与显式 anthropic 协议(Kimi)账号行为一致。
+func TestResponsesToNativeAnthropicTrimsBillingModel(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ openCode := &Account{
+ ID: 703,
+ Name: "opencode-go",
+ Platform: PlatformOpenCodeGo,
+ Type: AccountTypeAPIKey,
+ Concurrency: 1,
+ Credentials: map[string]any{
+ "api_key": "sk-test",
+ "account_mode": AccountModeGo,
+ "api_base_urls": map[string]any{
+ APIProtocolAnthropic: "http://anthropic.example",
+ },
+ },
+ }
+ for _, tc := range []struct {
+ name string
+ account *Account
+ model string
+ }{
+ {"opencode by model", openCode, "minimax-m3"},
+ {"kimi pinned anthropic", nativeAnthropicTestAccount(), "kimi-k2"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ body := []byte(`{"model":" ` + tc.model + ` ","input":"hello","stream":false}`)
+ upstream := &httpUpstreamRecorder{resp: nativeAnthropicStreamResponse()}
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
+
+ result, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), tc.account, body)
+ require.NoError(t, err)
+ require.True(t, strings.HasSuffix(upstream.lastReq.URL.Path, "/v1/messages"), upstream.lastReq.URL.String())
+ require.Equal(t, tc.model, gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Equal(t, tc.model, result.BillingModel)
+ })
+ }
+}
diff --git a/backend/internal/service/user_service.go b/backend/internal/service/user_service.go
index 85049f986..d58c065d3 100644
--- a/backend/internal/service/user_service.go
+++ b/backend/internal/service/user_service.go
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"crypto/sha256"
- "crypto/subtle"
"encoding/base64"
"encoding/hex"
"fmt"
@@ -1318,28 +1317,7 @@ func (s *UserService) VerifyAndAddNotifyEmail(ctx context.Context, userID int64,
// verifyNotifyCode validates the verification code against the cached data.
func verifyNotifyCode(ctx context.Context, cache EmailCache, email, code string) error {
- data, err := cache.GetNotifyVerifyCode(ctx, email)
- if err != nil || data == nil {
- return ErrInvalidVerifyCode
- }
- if data.Attempts >= maxVerifyCodeAttempts {
- return ErrVerifyCodeMaxAttempts
- }
- if subtle.ConstantTimeCompare([]byte(data.Code), []byte(code)) != 1 {
- data.Attempts++
- remaining := time.Until(data.ExpiresAt)
- if remaining <= 0 {
- return ErrInvalidVerifyCode
- }
- if err := cache.SetNotifyVerifyCode(ctx, email, data, remaining); err != nil {
- slog.Error("failed to update notify verify code attempts", "email", email, "error", err)
- }
- if data.Attempts >= maxVerifyCodeAttempts {
- return ErrVerifyCodeMaxAttempts
- }
- return ErrInvalidVerifyCode
- }
- return nil
+ return verifyCodeWithAttempts(ctx, email, code, cache.GetNotifyVerifyCode, cache.IncrNotifyVerifyCodeAttempts, nil)
}
// addOrVerifyNotifyEmail adds the email to user's extra notification emails or marks it as verified.
diff --git a/backend/internal/setup/cli.go b/backend/internal/setup/cli.go
index 2b323acf4..8d4e9e419 100644
--- a/backend/internal/setup/cli.go
+++ b/backend/internal/setup/cli.go
@@ -4,7 +4,6 @@ package setup
import (
"bufio"
"fmt"
- "net/mail"
"os"
"regexp"
"strconv"
@@ -29,11 +28,6 @@ func cliValidateUsername(name string) bool {
return validName.MatchString(name) && len(name) <= 63
}
-func cliValidateEmail(email string) bool {
- _, err := mail.ParseAddress(email)
- return err == nil && len(email) <= 254
-}
-
func cliValidatePort(port int) bool {
return port > 0 && port <= 65535
}
@@ -163,9 +157,14 @@ func RunCLI() error {
fmt.Println()
fmt.Println("── Admin Account ──")
+ // 默认值使用随机邮箱,避免直接回车得到可被猜中的固定管理员用户名(issue #7850)。
+ defaultAdminEmail, err := generateAdminEmail()
+ if err != nil {
+ return err
+ }
for {
- cfg.Admin.Email = promptString(reader, "Admin Email", "admin@example.com")
- if cliValidateEmail(cfg.Admin.Email) {
+ cfg.Admin.Email = promptString(reader, "Admin Email (login username)", defaultAdminEmail)
+ if validateEmail(cfg.Admin.Email) {
break
}
fmt.Println(" Invalid email format.")
@@ -173,13 +172,9 @@ func RunCLI() error {
for {
cfg.Admin.Password = promptPassword("Admin Password")
- // SECURITY: Match Web API requirement of 8 characters minimum
- if len(cfg.Admin.Password) < 8 {
- fmt.Println(" Password must be at least 8 characters")
- continue
- }
- if len(cfg.Admin.Password) > 128 {
- fmt.Println(" Password must be at most 128 characters")
+ // SECURITY: Match Web API password requirements
+ if err := validatePassword(cfg.Admin.Password); err != nil {
+ fmt.Printf(" Invalid password: %v\n", err)
continue
}
confirm := promptPassword("Confirm Password")
diff --git a/backend/internal/setup/handler.go b/backend/internal/setup/handler.go
index 06a9e1788..dee031e29 100644
--- a/backend/internal/setup/handler.go
+++ b/backend/internal/setup/handler.go
@@ -13,6 +13,7 @@ import (
"github.com/MACOS-DO/sub4api/internal/pkg/sysutil"
"github.com/gin-gonic/gin"
+ "github.com/gin-gonic/gin/binding"
)
// installMutex prevents concurrent installation attempts (TOCTOU protection)
@@ -83,19 +84,29 @@ func validateUsername(name string) bool {
return validName.MatchString(name) && len(name) <= 63
}
-// validateEmail checks if email format is valid
+// validateEmail checks if email format is valid. The address must also pass the
+// login endpoint's `binding:"email"` rule, otherwise the admin could be created
+// with an email (e.g. "a@b" or "Name ") that can never log in.
func validateEmail(email string) bool {
- _, err := mail.ParseAddress(email)
- return err == nil && len(email) <= 254
+ if _, err := mail.ParseAddress(email); err != nil || len(email) > 254 {
+ return false
+ }
+ loginReq := struct {
+ Email string `binding:"required,email"`
+ }{Email: email}
+ return binding.Validator.ValidateStruct(&loginReq) == nil
}
+// maxPasswordBytes is bcrypt's input limit; longer passwords fail to hash.
+const maxPasswordBytes = 72
+
// validatePassword checks password strength
func validatePassword(password string) error {
if len(password) < 8 {
return fmt.Errorf("password must be at least 8 characters")
}
- if len(password) > 128 {
- return fmt.Errorf("password must be at most 128 characters")
+ if len(password) > maxPasswordBytes {
+ return fmt.Errorf("password must be at most %d bytes", maxPasswordBytes)
}
return nil
}
diff --git a/backend/internal/setup/setup.go b/backend/internal/setup/setup.go
index 77ec825e9..669ad3f78 100644
--- a/backend/internal/setup/setup.go
+++ b/backend/internal/setup/setup.go
@@ -417,6 +417,10 @@ func createAdminUser(cfg *SetupConfig) (bool, string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
+ return bootstrapAdminUser(ctx, db, cfg)
+}
+
+func bootstrapAdminUser(ctx context.Context, db *sql.DB, cfg *SetupConfig) (bool, string, error) {
var totalUsers int64
if err := db.QueryRowContext(ctx, "SELECT COUNT(1) FROM users").Scan(&totalUsers); err != nil {
return false, "", err
@@ -430,12 +434,14 @@ func createAdminUser(cfg *SetupConfig) (bool, string, error) {
return false, decision.reason, nil
}
- if strings.TrimSpace(cfg.Admin.Password) == "" {
- password, genErr := generateSecret(16)
- if genErr != nil {
- return false, "", fmt.Errorf("failed to generate admin password: %w", genErr)
- }
- cfg.Admin.Password = password
+ emailGenerated, passwordGenerated, err := prepareAdminCredentials(&cfg.Admin)
+ if err != nil {
+ return false, "", err
+ }
+ if emailGenerated {
+ fmt.Printf("Generated admin email (login username): %s\n", cfg.Admin.Email)
+ }
+ if passwordGenerated {
fmt.Printf("Generated admin password (one-time): %s\n", cfg.Admin.Password)
fmt.Println("IMPORTANT: Save this password! It will not be shown again.")
}
@@ -473,6 +479,47 @@ func createAdminUser(cfg *SetupConfig) (bool, string, error) {
return true, decision.reason, nil
}
+// prepareAdminCredentials fills in missing admin credentials with random values
+// and rejects invalid user-supplied emails and weak passwords. It only runs
+// when an admin is actually about to be created, so existing deployments are
+// never affected. A random email keeps fresh installs off the well-known
+// default username that brute-force scanners target (issue #7850).
+func prepareAdminCredentials(admin *AdminConfig) (emailGenerated, passwordGenerated bool, err error) {
+ admin.Email = strings.TrimSpace(admin.Email)
+ if admin.Email == "" {
+ email, genErr := generateAdminEmail()
+ if genErr != nil {
+ return false, false, genErr
+ }
+ admin.Email = email
+ emailGenerated = true
+ } else if !validateEmail(admin.Email) {
+ return false, false, fmt.Errorf("invalid admin email: %q is not a valid login email", admin.Email)
+ }
+
+ if strings.TrimSpace(admin.Password) == "" {
+ password, genErr := generateSecret(16)
+ if genErr != nil {
+ return false, false, fmt.Errorf("failed to generate admin password: %w", genErr)
+ }
+ admin.Password = password
+ passwordGenerated = true
+ } else if validateErr := validatePassword(admin.Password); validateErr != nil {
+ return false, false, fmt.Errorf("invalid admin password: %w", validateErr)
+ }
+
+ return emailGenerated, passwordGenerated, nil
+}
+
+// generateAdminEmail returns a random, non-guessable admin login email.
+func generateAdminEmail() (string, error) {
+ suffix, err := generateSecret(6)
+ if err != nil {
+ return "", fmt.Errorf("failed to generate admin email: %w", err)
+ }
+ return fmt.Sprintf("admin-%s@sub2api.local", suffix), nil
+}
+
func writeConfigFile(cfg *SetupConfig) error {
// Ensure timezone has a default value
tz := cfg.Timezone
@@ -596,7 +643,7 @@ func AutoSetupFromEnv() error {
EnableTLS: getEnvOrDefault("REDIS_ENABLE_TLS", "false") == "true",
},
Admin: AdminConfig{
- Email: getEnvOrDefault("ADMIN_EMAIL", "admin@sub2api.local"),
+ Email: getEnvOrDefault("ADMIN_EMAIL", ""),
Password: getEnvOrDefault("ADMIN_PASSWORD", ""),
},
Server: ServerConfig{
diff --git a/backend/internal/setup/setup_test.go b/backend/internal/setup/setup_test.go
index 7d4320ada..8f3868f03 100644
--- a/backend/internal/setup/setup_test.go
+++ b/backend/internal/setup/setup_test.go
@@ -1,15 +1,19 @@
package setup
import (
+ "context"
"database/sql"
"fmt"
"os"
"path/filepath"
+ "regexp"
"strings"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
+ "github.com/MACOS-DO/sub4api/internal/service"
+ "github.com/gin-gonic/gin/binding"
"github.com/lib/pq"
"gopkg.in/yaml.v3"
)
@@ -398,3 +402,235 @@ func TestDatabaseConnectionDoesNotFallbackForTargetAuthenticationError(t *testin
t.Fatalf("opened databases = %v, want only configured target %q", opened, cfg.DBName)
}
}
+
+func TestPrepareAdminCredentialsGeneratesMissingValues(t *testing.T) {
+ t.Parallel()
+
+ admin := AdminConfig{Email: " ", Password: ""}
+ emailGenerated, passwordGenerated, err := prepareAdminCredentials(&admin)
+ if err != nil {
+ t.Fatalf("prepareAdminCredentials() error = %v", err)
+ }
+ if !emailGenerated || !passwordGenerated {
+ t.Fatalf("generated flags = (%v, %v), want (true, true)", emailGenerated, passwordGenerated)
+ }
+ if !regexp.MustCompile(`^admin-[0-9a-f]{12}@sub2api\.local$`).MatchString(admin.Email) {
+ t.Fatalf("generated email = %q, want admin-<12 hex>@sub2api.local", admin.Email)
+ }
+ // 生成的邮箱必须能通过登录接口的 binding:"required,email" 校验。
+ loginReq := struct {
+ Email string `binding:"required,email"`
+ }{Email: admin.Email}
+ if err := binding.Validator.ValidateStruct(&loginReq); err != nil {
+ t.Fatalf("generated email %q rejected by login validator: %v", admin.Email, err)
+ }
+ if len(admin.Password) != 32 {
+ t.Fatalf("generated password length = %d, want 32", len(admin.Password))
+ }
+
+ other := AdminConfig{}
+ if _, _, err := prepareAdminCredentials(&other); err != nil {
+ t.Fatalf("prepareAdminCredentials() second call error = %v", err)
+ }
+ if other.Email == admin.Email {
+ t.Fatalf("generated emails should be random, got %q twice", admin.Email)
+ }
+}
+
+func TestPrepareAdminCredentialsKeepsProvidedValues(t *testing.T) {
+ t.Parallel()
+
+ admin := AdminConfig{Email: "owner@example.com", Password: "a-strong-password"}
+ emailGenerated, passwordGenerated, err := prepareAdminCredentials(&admin)
+ if err != nil {
+ t.Fatalf("prepareAdminCredentials() error = %v", err)
+ }
+ if emailGenerated || passwordGenerated {
+ t.Fatalf("generated flags = (%v, %v), want (false, false)", emailGenerated, passwordGenerated)
+ }
+ if admin.Email != "owner@example.com" || admin.Password != "a-strong-password" {
+ t.Fatalf("provided credentials were modified: %+v", admin)
+ }
+}
+
+func TestPrepareAdminCredentialsRejectsWeakPassword(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ password string
+ }{
+ {name: "too short", password: "123456"},
+ {name: "seven chars", password: "1234567"},
+ {name: "exceeds bcrypt limit", password: strings.Repeat("a", 73)},
+ {name: "former 128 limit", password: strings.Repeat("a", 128)},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ admin := AdminConfig{Email: "owner@example.com", Password: tt.password}
+ _, _, err := prepareAdminCredentials(&admin)
+ if err == nil || !strings.Contains(err.Error(), "invalid admin password") {
+ t.Fatalf("prepareAdminCredentials(%q) error = %v, want invalid admin password error", tt.password, err)
+ }
+ })
+ }
+}
+
+func TestPrepareAdminCredentialsRejectsUnloginableEmail(t *testing.T) {
+ t.Parallel()
+
+ for _, email := range []string{"admin", "a@b", "Owner ", ""} {
+ t.Run(email, func(t *testing.T) {
+ t.Parallel()
+
+ admin := AdminConfig{Email: email, Password: "a-strong-password"}
+ _, _, err := prepareAdminCredentials(&admin)
+ if err == nil || !strings.Contains(err.Error(), "invalid admin email") {
+ t.Fatalf("prepareAdminCredentials(%q) error = %v, want invalid admin email error", email, err)
+ }
+ })
+ }
+}
+
+func TestPrepareAdminCredentialsTrimsProvidedEmail(t *testing.T) {
+ t.Parallel()
+
+ admin := AdminConfig{Email: " owner@example.com\n", Password: "a-strong-password"}
+ if _, _, err := prepareAdminCredentials(&admin); err != nil {
+ t.Fatalf("prepareAdminCredentials() error = %v", err)
+ }
+ if admin.Email != "owner@example.com" {
+ t.Fatalf("email = %q, want trimmed owner@example.com", admin.Email)
+ }
+}
+
+func TestPrepareAdminCredentialsAcceptsBcryptMaxLengthPassword(t *testing.T) {
+ t.Parallel()
+
+ admin := AdminConfig{Email: "owner@example.com", Password: strings.Repeat("a", 72)}
+ if _, _, err := prepareAdminCredentials(&admin); err != nil {
+ t.Fatalf("prepareAdminCredentials() error = %v", err)
+ }
+ // 校验上限必须与 bcrypt 实际可哈希的上限一致,否则通过校验后仍会在建号时失败。
+ user := service.User{}
+ if err := user.SetPassword(admin.Password); err != nil {
+ t.Fatalf("SetPassword() with max-length password error = %v", err)
+ }
+}
+
+func expectAdminBootstrapCounts(mock sqlmock.Sqlmock, totalUsers, adminUsers int64) {
+ mock.ExpectQuery(regexp.QuoteMeta("SELECT COUNT(1) FROM users")).
+ WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(totalUsers))
+ mock.ExpectQuery(regexp.QuoteMeta("SELECT COUNT(1) FROM users WHERE role = $1")).
+ WithArgs(service.RoleAdmin).
+ WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(adminUsers))
+}
+
+func TestBootstrapAdminUserSkipsValidationWhenNotCreating(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ totalUsers int64
+ adminUsers int64
+ reason string
+ }{
+ {name: "admin exists", totalUsers: 3, adminUsers: 1, reason: adminBootstrapReasonAdminExists},
+ {name: "users exist without admin", totalUsers: 3, adminUsers: 0, reason: adminBootstrapReasonUsersExistWithoutAdmin},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ db, mock, err := sqlmock.New()
+ if err != nil {
+ t.Fatalf("sqlmock.New() error = %v", err)
+ }
+ defer func() { _ = db.Close() }()
+ expectAdminBootstrapCounts(mock, tt.totalUsers, tt.adminUsers)
+
+ // 已有部署里遗留的弱密码/非法邮箱不能阻断启动。
+ cfg := &SetupConfig{Admin: AdminConfig{Email: "admin", Password: "123456"}}
+ created, reason, err := bootstrapAdminUser(context.Background(), db, cfg)
+ if err != nil || created || reason != tt.reason {
+ t.Fatalf("bootstrapAdminUser() = (%v, %q, %v), want (false, %q, nil)", created, reason, err, tt.reason)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Fatalf("unexpected database interaction: %v", err)
+ }
+ })
+ }
+}
+
+func TestBootstrapAdminUserRejectsWeakPasswordWithoutInsert(t *testing.T) {
+ t.Parallel()
+
+ db, mock, err := sqlmock.New()
+ if err != nil {
+ t.Fatalf("sqlmock.New() error = %v", err)
+ }
+ defer func() { _ = db.Close() }()
+ expectAdminBootstrapCounts(mock, 0, 0)
+
+ cfg := &SetupConfig{Admin: AdminConfig{Password: "123456"}}
+ created, _, err := bootstrapAdminUser(context.Background(), db, cfg)
+ if err == nil || created || !strings.Contains(err.Error(), "invalid admin password") {
+ t.Fatalf("bootstrapAdminUser() = (%v, %v), want invalid admin password error", created, err)
+ }
+ // 未设置 INSERT 期望:若发生插入,sqlmock 会返回非预期调用错误,上面的错误断言即失败。
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Fatalf("unexpected database interaction: %v", err)
+ }
+}
+
+func TestBootstrapAdminUserCreatesAdminWithGeneratedCredentials(t *testing.T) {
+ t.Parallel()
+
+ db, mock, err := sqlmock.New()
+ if err != nil {
+ t.Fatalf("sqlmock.New() error = %v", err)
+ }
+ defer func() { _ = db.Close() }()
+ expectAdminBootstrapCounts(mock, 0, 0)
+ mock.ExpectExec(regexp.QuoteMeta("INSERT INTO users")).
+ WithArgs(
+ sqlmock.AnyArg(), sqlmock.AnyArg(), service.RoleAdmin, sqlmock.AnyArg(),
+ sqlmock.AnyArg(), service.StatusActive, sqlmock.AnyArg(), sqlmock.AnyArg(),
+ ).
+ WillReturnResult(sqlmock.NewResult(1, 1))
+
+ cfg := &SetupConfig{}
+ created, reason, err := bootstrapAdminUser(context.Background(), db, cfg)
+ if err != nil || !created || reason != adminBootstrapReasonEmptyDatabase {
+ t.Fatalf("bootstrapAdminUser() = (%v, %q, %v), want (true, %q, nil)", created, reason, err, adminBootstrapReasonEmptyDatabase)
+ }
+ if !regexp.MustCompile(`^admin-[0-9a-f]{12}@sub2api\.local$`).MatchString(cfg.Admin.Email) {
+ t.Fatalf("admin email = %q, want generated admin-<12 hex>@sub2api.local", cfg.Admin.Email)
+ }
+ if len(cfg.Admin.Password) != 32 {
+ t.Fatalf("admin password length = %d, want generated 32", len(cfg.Admin.Password))
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Fatalf("database expectations not met: %v", err)
+ }
+}
+
+func TestPrepareAdminCredentialsAcceptsMinimumLengthPassword(t *testing.T) {
+ t.Parallel()
+
+ admin := AdminConfig{Password: "12345678"}
+ emailGenerated, passwordGenerated, err := prepareAdminCredentials(&admin)
+ if err != nil {
+ t.Fatalf("prepareAdminCredentials() error = %v", err)
+ }
+ if !emailGenerated || passwordGenerated {
+ t.Fatalf("generated flags = (%v, %v), want (true, false)", emailGenerated, passwordGenerated)
+ }
+ if admin.Password != "12345678" {
+ t.Fatalf("password = %q, want unchanged", admin.Password)
+ }
+}
diff --git a/backend/internal/web/embed_on.go b/backend/internal/web/embed_on.go
index a81f147e0..0b5d09aa6 100644
--- a/backend/internal/web/embed_on.go
+++ b/backend/internal/web/embed_on.go
@@ -362,10 +362,26 @@ func shouldBypassEmbeddedFrontend(path string) bool {
strings.HasPrefix(trimmed, "/setup/") ||
trimmed == "/health" ||
trimmed == "/models" ||
+ strings.HasPrefix(trimmed, "/models/") ||
trimmed == "/responses" ||
strings.HasPrefix(trimmed, "/responses/") ||
+ trimmed == "/chat/completions" ||
+ trimmed == "/embeddings" ||
+ trimmed == "/messages/count_tokens" ||
trimmed == "/alpha/search" ||
+ trimmed == "/web_search" ||
+ trimmed == "/x_search" ||
+ trimmed == "/tts" ||
+ trimmed == "/stt" ||
+ trimmed == "/realtime" ||
+ trimmed == "/custom-voices" ||
+ strings.HasPrefix(trimmed, "/custom-voices/") ||
+ trimmed == "/contents/generations/tasks" ||
+ strings.HasPrefix(trimmed, "/contents/generations/tasks/") ||
+ trimmed == "/v3/contents/generations/tasks" ||
+ strings.HasPrefix(trimmed, "/v3/contents/generations/tasks/") ||
strings.HasPrefix(trimmed, "/images/") ||
+ trimmed == "/videos" ||
strings.HasPrefix(trimmed, "/videos/")
}
diff --git a/backend/internal/web/embed_test.go b/backend/internal/web/embed_test.go
index ea8f28dc6..329eb19bf 100644
--- a/backend/internal/web/embed_test.go
+++ b/backend/internal/web/embed_test.go
@@ -530,6 +530,9 @@ func TestFrontendServer_Middleware(t *testing.T) {
"/health",
"/responses",
"/responses/compact",
+ "/chat/completions",
+ "/models/gpt-5.5",
+ "/v3/contents/generations/tasks/task-123",
}
for _, path := range apiPaths {
@@ -689,6 +692,40 @@ func TestEmbeddedFrontendBypassesBareVideoAPIRoutes(t *testing.T) {
}
}
+func TestEmbeddedFrontendBypassesBareAPIAliases(t *testing.T) {
+ for _, path := range []string{
+ "/chat/completions",
+ "/embeddings",
+ "/messages/count_tokens",
+ "/models/gpt-5.5",
+ "/videos",
+ "/tts",
+ "/stt",
+ "/custom-voices",
+ "/custom-voices/voice-123",
+ "/custom-voices/voice-123/audio",
+ "/realtime",
+ "/web_search",
+ "/x_search",
+ "/contents/generations/tasks",
+ "/contents/generations/tasks/task-123",
+ "/v3/contents/generations/tasks",
+ "/v3/contents/generations/tasks/task-123",
+ } {
+ require.True(t, shouldBypassEmbeddedFrontend(path), "path=%s", path)
+ }
+
+ for _, path := range []string{
+ "/model-plaza",
+ "/custom/page-1",
+ "/monitor",
+ "/setup",
+ "/v3/other",
+ } {
+ require.False(t, shouldBypassEmbeddedFrontend(path), "path=%s", path)
+ }
+}
+
func TestNewFrontendServer(t *testing.T) {
t.Run("creates_server_successfully", func(t *testing.T) {
provider := &mockSettingsProvider{
@@ -792,6 +829,9 @@ func TestServeEmbeddedFrontend(t *testing.T) {
"/health",
"/responses",
"/responses/compact",
+ "/chat/completions",
+ "/models/gpt-5.5",
+ "/v3/contents/generations/tasks/task-123",
}
for _, path := range apiPaths {
diff --git a/backend/migrations/241_add_payment_order_bonus_amount.sql b/backend/migrations/241_add_payment_order_bonus_amount.sql
new file mode 100644
index 000000000..1eeddfadb
--- /dev/null
+++ b/backend/migrations/241_add_payment_order_bonus_amount.sql
@@ -0,0 +1,3 @@
+-- 充值赠送额度:余额充值订单命中赠送阶梯时的赠送 USD 金额。
+-- 已计入 payment_orders.amount(到账总额),单独落列用于订单展示与推广返利基数剔除。
+ALTER TABLE payment_orders ADD COLUMN IF NOT EXISTS bonus_amount DECIMAL(20,2) NOT NULL DEFAULT 0;
diff --git a/backend/migrations/241_add_typesafe_platform.sql b/backend/migrations/241_add_typesafe_platform.sql
new file mode 100644
index 000000000..5bef23554
--- /dev/null
+++ b/backend/migrations/241_add_typesafe_platform.sql
@@ -0,0 +1,29 @@
+-- Add TypeSafe (Jev System One) as a first-class platform.
+--
+-- 1. user_platform_quotas.platform CHECK
+-- 2. composite_model_routes.target_platform CHECK
+--
+-- TypeSafe 不是对话模型,不进入渠道监控 provider,因此 channel_monitors /
+-- channel_monitor_request_templates 的约束保持不变。
+--
+-- Sub4API: 保留 openai_bps(245_openai_bps_platform.sql),否则已有 openai_bps 行的
+-- 存量库在此迁移会校验失败。
+--
+-- Runs after 238_opencode_go_platform.sql. DROP ... IF EXISTS 保证可重入;
+-- 新约束是 238 的超集,存量行瞬时校验通过。
+
+ALTER TABLE user_platform_quotas
+ DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;
+
+ALTER TABLE user_platform_quotas
+ ADD CONSTRAINT user_platform_quotas_platform_check
+ CHECK (platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok',
+ 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'));
+
+ALTER TABLE composite_model_routes
+ DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check;
+
+ALTER TABLE composite_model_routes
+ ADD CONSTRAINT composite_model_routes_target_platform_check
+ CHECK (target_platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok',
+ 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'));
diff --git a/backend/migrations/242_drop_platform_check_constraints.sql b/backend/migrations/242_drop_platform_check_constraints.sql
new file mode 100644
index 000000000..7307be715
--- /dev/null
+++ b/backend/migrations/242_drop_platform_check_constraints.sql
@@ -0,0 +1,18 @@
+-- 平台白名单改由应用层的平台清单(internal/domain/platforms.go)统一校验,
+-- 新增平台不再需要修改数据库约束的迁移。
+--
+-- 1. user_platform_quotas.platform:admin 接口 / 设置校验 service.AllowedQuotaPlatforms,
+-- repository 写入前校验 domain.IsConcretePlatform,ent schema Validate 同源。
+-- 2. composite_model_routes.target_platform:admin 接口 binding、service
+-- compositeRouteFromInput 与 ent schema Validate 均校验为已登记的具体平台。
+--
+-- channel_monitors / channel_monitor_request_templates 的 provider CHECK 表示
+-- 渠道监控已实现的探测能力,不属于平台清单,保留不动。
+--
+-- DROP ... IF EXISTS 保证可重入。
+
+ALTER TABLE user_platform_quotas
+ DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;
+
+ALTER TABLE composite_model_routes
+ DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check;
diff --git a/backend/migrations/246_redrop_platform_check_constraints.sql b/backend/migrations/246_redrop_platform_check_constraints.sql
new file mode 100644
index 000000000..2ffd61da0
--- /dev/null
+++ b/backend/migrations/246_redrop_platform_check_constraints.sql
@@ -0,0 +1,14 @@
+-- Sub4API: 245_openai_bps_platform.sql 按文件名排序晚于上游的
+-- 242_drop_platform_check_constraints.sql,会在新库上重新加回平台 CHECK 约束。
+-- 平台白名单已改由应用层平台清单(internal/domain/platforms.go)统一校验,
+-- 此处再次删除,与 242 保持一致。
+--
+-- channel_monitors / channel_monitor_request_templates 的 provider CHECK 保留不动。
+--
+-- DROP ... IF EXISTS 保证可重入。
+
+ALTER TABLE user_platform_quotas
+ DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;
+
+ALTER TABLE composite_model_routes
+ DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check;
diff --git a/backend/migrations/platform_check_constraints_drop_migration_test.go b/backend/migrations/platform_check_constraints_drop_migration_test.go
new file mode 100644
index 000000000..998823149
--- /dev/null
+++ b/backend/migrations/platform_check_constraints_drop_migration_test.go
@@ -0,0 +1,60 @@
+package migrations
+
+import (
+ "io/fs"
+ "regexp"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestDropPlatformCheckConstraintsMigration(t *testing.T) {
+ content, err := FS.ReadFile("242_drop_platform_check_constraints.sql")
+ require.NoError(t, err)
+
+ sql := strings.Join(strings.Fields(string(content)), " ")
+ require.Contains(t, sql,
+ "ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;")
+ require.Contains(t, sql,
+ "ALTER TABLE composite_model_routes DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check;")
+ require.NotContains(t, sql, "ADD CONSTRAINT")
+ require.NotContains(t, sql, "DROP CONSTRAINT IF EXISTS channel_monitors_provider_check")
+ require.NotContains(t, sql, "DROP CONSTRAINT IF EXISTS channel_monitor_request_templates_provider_check")
+}
+
+// Platform membership is validated against the application catalog after 242.
+// A later migration must not restore a database whitelist that can drift from it.
+func TestLaterMigrationsDoNotRestorePlatformCheckConstraints(t *testing.T) {
+ const droppedAt = "242_drop_platform_check_constraints.sql"
+ // Sub4API 的 245_openai_bps_platform.sql 已在存量库应用(不可修改),
+ // 由 246_redrop_platform_check_constraints.sql 再次删除约束。
+ const redroppedAt = "246_redrop_platform_check_constraints.sql"
+ allowed := map[string]struct{}{"245_openai_bps_platform.sql": {}}
+ redrop, err := FS.ReadFile(redroppedAt)
+ require.NoError(t, err)
+ redropSQL := strings.Join(strings.Fields(string(redrop)), " ")
+ require.Contains(t, redropSQL,
+ "ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;")
+ require.Contains(t, redropSQL,
+ "ALTER TABLE composite_model_routes DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check;")
+ entries, err := fs.ReadDir(FS, ".")
+ require.NoError(t, err)
+ comments := regexp.MustCompile(`(?ms)/\*.*?\*/|--[^\n]*`)
+ addConstraint := regexp.MustCompile(`(?i)\bADD\s+CONSTRAINT\s+"?(user_platform_quotas_platform_check|composite_model_routes_target_platform_check)\b`)
+ for _, entry := range entries {
+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") || entry.Name() <= droppedAt {
+ continue
+ }
+ if _, ok := allowed[entry.Name()]; ok {
+ require.Less(t, entry.Name(), redroppedAt)
+ continue
+ }
+ t.Run(entry.Name(), func(t *testing.T) {
+ content, err := FS.ReadFile(entry.Name())
+ require.NoError(t, err)
+ sql := comments.ReplaceAll(content, nil)
+ require.Nil(t, addConstraint.Find(sql), "platform CHECK constraints removed in 242 must remain managed by application validation")
+ })
+ }
+}
diff --git a/backend/migrations/typesafe_platform_migration_test.go b/backend/migrations/typesafe_platform_migration_test.go
new file mode 100644
index 000000000..04f94bdba
--- /dev/null
+++ b/backend/migrations/typesafe_platform_migration_test.go
@@ -0,0 +1,21 @@
+package migrations
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestTypeSafePlatformMigration(t *testing.T) {
+ content, err := FS.ReadFile("241_add_typesafe_platform.sql")
+ require.NoError(t, err)
+
+ sql := strings.Join(strings.Fields(string(content)), " ")
+ require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check")
+ require.Contains(t, sql, "DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check")
+ require.Contains(t, sql,
+ "CHECK (platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))")
+ require.Contains(t, sql,
+ "CHECK (target_platform IN ('anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))")
+}
diff --git a/changelog/1.1.10/CHANGELOG.md b/changelog/1.1.10/CHANGELOG.md
new file mode 100644
index 000000000..7766b125c
--- /dev/null
+++ b/changelog/1.1.10/CHANGELOG.md
@@ -0,0 +1,5 @@
+# v1.1.10
+
+## 更新内容
+
+- 合并 SUB2API 0.2.12 ~ 0.2.15 版本。
diff --git a/deploy/.env.example b/deploy/.env.example
index 1299e45c5..fa10e83e7 100644
--- a/deploy/.env.example
+++ b/deploy/.env.example
@@ -206,10 +206,12 @@ REDIS_ENABLE_TLS=false
# -----------------------------------------------------------------------------
# Admin Account
# -----------------------------------------------------------------------------
-# Email for the admin account
-ADMIN_EMAIL=admin@sub2api.local
+# Email for the admin account (used as the login username)
+# Leave empty to auto-generate a random one (will be shown in logs on first run).
+# Avoid well-known values such as admin@sub2api.local: they are brute-force targets.
+ADMIN_EMAIL=
-# Password for admin account
+# Password for admin account (8-72 bytes)
# Leave empty to auto-generate (will be shown in logs on first run)
ADMIN_PASSWORD=
diff --git a/deploy/APPLE_CONTAINER.md b/deploy/APPLE_CONTAINER.md
index 42f7efc37..69cc4aa2c 100644
--- a/deploy/APPLE_CONTAINER.md
+++ b/deploy/APPLE_CONTAINER.md
@@ -41,7 +41,7 @@ nano .env
./apple-container.sh status
```
-Open `http://localhost:8080`. If `ADMIN_PASSWORD` is empty, retrieve the generated password with:
+Open `http://localhost:8080`. If `ADMIN_EMAIL` / `ADMIN_PASSWORD` are empty, retrieve the generated admin email (login username) and password with:
```bash
./apple-container.sh logs app
diff --git a/deploy/Dockerfile b/deploy/Dockerfile
index a22bb5961..c2e0ef7ef 100644
--- a/deploy/Dockerfile
+++ b/deploy/Dockerfile
@@ -7,7 +7,7 @@
# =============================================================================
ARG NODE_IMAGE=node:24-alpine
-ARG GOLANG_IMAGE=golang:1.27.0-alpine
+ARG GOLANG_IMAGE=golang:1.27.2-alpine
ARG ALPINE_IMAGE=alpine:3.20
ARG GOPROXY=https://goproxy.cn,direct
ARG GOSUMDB=sum.golang.google.cn
diff --git a/deploy/README.md b/deploy/README.md
index 2b2c5900c..7d3bacac2 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -79,8 +79,8 @@ docker compose -f docker-compose.local.yml up -d
# View logs
docker compose -f docker-compose.local.yml logs -f sub2api
-# If admin password was auto-generated, find it in logs:
-docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
+# If admin email/password were auto-generated, find them in logs:
+docker compose -f docker-compose.local.yml logs sub2api | grep "Generated admin"
# Access Web UI
# http://localhost:8080
@@ -112,7 +112,7 @@ mkdir -p data postgres_data redis_data
# Start all services using local directory version
docker compose -f docker-compose.local.yml up -d
-# View logs (check for auto-generated admin password)
+# View logs (check for auto-generated admin email and password)
docker compose -f docker-compose.local.yml logs -f sub2api
# Access Web UI
@@ -136,14 +136,14 @@ When using Docker Compose with `AUTO_SETUP=true`:
- Connects to PostgreSQL and Redis
- Applies database migrations (SQL files in `backend/migrations/*.sql`) and records them in `schema_migrations`
- Generates JWT secret (if not provided)
- - Creates admin account (password auto-generated if not provided)
+ - Creates admin account (email and password auto-generated if not provided; a provided password must be 8-72 bytes)
- Writes config.yaml
2. No manual Setup Wizard needed - just configure `.env` and start
-3. If `ADMIN_PASSWORD` is not set, check logs for the generated password:
+3. If `ADMIN_EMAIL` / `ADMIN_PASSWORD` are not set, check logs for the generated admin email (login username) and password:
```bash
- docker compose logs sub2api | grep "admin password"
+ docker compose logs sub2api | grep "Generated admin"
```
### Startup and Database Recovery
@@ -257,8 +257,8 @@ docker compose down -v
| `JWT_SECRET` | **Recommended** | *(auto-generated)* | JWT secret (fixed for persistent sessions) |
| `TOTP_ENCRYPTION_KEY` | **Recommended** | *(auto-generated)* | TOTP encryption key (fixed for persistent 2FA) |
| `SERVER_PORT` | No | `8080` | Server port |
-| `ADMIN_EMAIL` | No | `admin@sub2api.local` | Admin email |
-| `ADMIN_PASSWORD` | No | *(auto-generated)* | Admin password |
+| `ADMIN_EMAIL` | No | *(auto-generated)* | Admin email (login username) |
+| `ADMIN_PASSWORD` | No | *(auto-generated)* | Admin password (8-72 bytes) |
| `TZ` | No | `Asia/Shanghai` | Timezone |
| `UPDATE_GITHUB_TOKEN` | No | *(empty)* | Token for `api.github.com` release checks only; asset downloads remain anonymous. |
| `GEMINI_OAUTH_CLIENT_ID` | No | *(builtin)* | Google OAuth client ID (Gemini OAuth). Leave empty to use the built-in Gemini CLI client. |
diff --git a/deploy/docker-compose.dev.yml b/deploy/docker-compose.dev.yml
index 80d9db178..45789f48a 100644
--- a/deploy/docker-compose.dev.yml
+++ b/deploy/docker-compose.dev.yml
@@ -43,7 +43,7 @@ services:
- REDIS_USERNAME=${REDIS_USERNAME:-}
- REDIS_PASSWORD=${REDIS_PASSWORD:-}
- REDIS_DB=${REDIS_DB:-0}
- - ADMIN_EMAIL=${ADMIN_EMAIL:-admin@sub2api.local}
+ - ADMIN_EMAIL=${ADMIN_EMAIL:-}
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-}
- JWT_SECRET=${JWT_SECRET:-}
- SETUP_MIGRATION_TIMEOUT_SECONDS=${SETUP_MIGRATION_TIMEOUT_SECONDS:-0}
diff --git a/deploy/docker-compose.local.yml b/deploy/docker-compose.local.yml
index 672463c4d..32bc439f4 100644
--- a/deploy/docker-compose.local.yml
+++ b/deploy/docker-compose.local.yml
@@ -88,7 +88,7 @@ services:
# =======================================================================
# Admin Account (auto-created on first run)
# =======================================================================
- - ADMIN_EMAIL=${ADMIN_EMAIL:-admin@sub2api.local}
+ - ADMIN_EMAIL=${ADMIN_EMAIL:-}
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-}
# =======================================================================
diff --git a/deploy/docker-compose.standalone.yml b/deploy/docker-compose.standalone.yml
index abbd8c23f..fe9619df1 100644
--- a/deploy/docker-compose.standalone.yml
+++ b/deploy/docker-compose.standalone.yml
@@ -74,7 +74,7 @@ services:
# =======================================================================
# Admin Account (auto-created on first run)
# =======================================================================
- - ADMIN_EMAIL=${ADMIN_EMAIL:-admin@sub2api.local}
+ - ADMIN_EMAIL=${ADMIN_EMAIL:-}
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-}
# =======================================================================
diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml
index 3308df0ff..84c98643e 100644
--- a/deploy/docker-compose.yml
+++ b/deploy/docker-compose.yml
@@ -85,7 +85,7 @@ services:
# =======================================================================
# Admin Account (auto-created on first run)
# =======================================================================
- - ADMIN_EMAIL=${ADMIN_EMAIL:-admin@sub2api.local}
+ - ADMIN_EMAIL=${ADMIN_EMAIL:-}
- ADMIN_PASSWORD=${ADMIN_PASSWORD:-}
# =======================================================================
diff --git a/deploy/docker-deploy.sh b/deploy/docker-deploy.sh
index 38d9403c4..c572a7a62 100644
--- a/deploy/docker-deploy.sh
+++ b/deploy/docker-deploy.sh
@@ -5,6 +5,7 @@
# This script prepares deployment files for Sub2API:
# - Downloads docker-compose.local.yml and .env.example
# - Generates secure secrets (JWT_SECRET, TOTP_ENCRYPTION_KEY, POSTGRES_PASSWORD)
+# - Generates a random admin login email (ADMIN_EMAIL)
# - Creates necessary data directories
#
# After running this script, you can start services with:
@@ -45,6 +46,14 @@ generate_secret() {
openssl rand -hex 32
}
+# Generate a random admin login email so new installs never use a guessable default
+generate_admin_email() {
+ local suffix
+ suffix=$(openssl rand -hex 6) || return 1
+ [ -n "$suffix" ] || return 1
+ echo "admin-${suffix}@sub2api.local"
+}
+
# Check if command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
@@ -104,6 +113,7 @@ main() {
JWT_SECRET=$(generate_secret)
TOTP_ENCRYPTION_KEY=$(generate_secret)
POSTGRES_PASSWORD=$(generate_secret)
+ ADMIN_EMAIL=$(generate_admin_email)
# Create .env from .env.example
cp .env.example .env
@@ -114,11 +124,13 @@ main() {
sed -i "s/^JWT_SECRET=.*/JWT_SECRET=${JWT_SECRET}/" .env
sed -i "s/^TOTP_ENCRYPTION_KEY=.*/TOTP_ENCRYPTION_KEY=${TOTP_ENCRYPTION_KEY}/" .env
sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=${POSTGRES_PASSWORD}/" .env
+ sed -i "s/^ADMIN_EMAIL=.*/ADMIN_EMAIL=${ADMIN_EMAIL}/" .env
else
# BSD sed (macOS)
sed -i '' "s/^JWT_SECRET=.*/JWT_SECRET=${JWT_SECRET}/" .env
sed -i '' "s/^TOTP_ENCRYPTION_KEY=.*/TOTP_ENCRYPTION_KEY=${TOTP_ENCRYPTION_KEY}/" .env
sed -i '' "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=${POSTGRES_PASSWORD}/" .env
+ sed -i '' "s/^ADMIN_EMAIL=.*/ADMIN_EMAIL=${ADMIN_EMAIL}/" .env
fi
# Create data directories
@@ -139,6 +151,7 @@ main() {
echo " POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}"
echo " JWT_SECRET: ${JWT_SECRET}"
echo " TOTP_ENCRYPTION_KEY: ${TOTP_ENCRYPTION_KEY}"
+ echo " ADMIN_EMAIL: ${ADMIN_EMAIL} (admin login username)"
echo ""
print_warning "These credentials have been saved to .env file."
print_warning "Please keep them secure and do not share publicly!"
diff --git a/frontend/package.json b/frontend/package.json
index ea14f6196..e714a702f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -21,7 +21,7 @@
"@stripe/stripe-js": "^9.0.1",
"@tanstack/vue-virtual": "^3.13.23",
"@vueuse/core": "^10.7.0",
- "axios": "^1.18.0",
+ "axios": "^1.20.0",
"chart.js": "^4.4.1",
"dompurify": "^3.4.14",
"driver.js": "^1.4.0",
@@ -29,7 +29,7 @@
"marked": "^17.0.1",
"pinia": "^2.1.7",
"qrcode": "^1.5.4",
- "vue": "^3.4.0",
+ "vue": "^3.5.43",
"vue-chartjs": "^5.3.0",
"vue-draggable-plus": "^0.6.1",
"vue-i18n": "^9.14.5",
@@ -65,7 +65,8 @@
"js-cookie": "3.0.7",
"form-data@<4.0.6": ">=4.0.6",
"postcss@<8.5.18": ">=8.5.18",
- "dompurify@<3.4.14": ">=3.4.14"
+ "dompurify@<3.4.14": ">=3.4.14",
+ "source-map-js@<1.2.2": ">=1.2.2"
}
}
}
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index fef7a9441..1e36493ef 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -9,6 +9,7 @@ overrides:
form-data@<4.0.6: '>=4.0.6'
postcss@<8.5.18: '>=8.5.18'
dompurify@<3.4.14: '>=3.4.14'
+ source-map-js@<1.2.2: '>=1.2.2'
importers:
@@ -25,13 +26,13 @@ importers:
version: 9.0.1
'@tanstack/vue-virtual':
specifier: ^3.13.23
- version: 3.13.23(vue@3.5.26(typescript@5.6.3))
+ version: 3.13.23(vue@3.5.43(typescript@5.6.3))
'@vueuse/core':
specifier: ^10.7.0
- version: 10.11.1(vue@3.5.26(typescript@5.6.3))
+ version: 10.11.1(vue@3.5.43(typescript@5.6.3))
axios:
- specifier: ^1.18.0
- version: 1.18.1
+ specifier: ^1.20.0
+ version: 1.20.0
chart.js:
specifier: ^4.4.1
version: 4.5.1
@@ -49,25 +50,25 @@ importers:
version: 17.0.1
pinia:
specifier: ^2.1.7
- version: 2.3.1(typescript@5.6.3)(vue@3.5.26(typescript@5.6.3))
+ version: 2.3.1(typescript@5.6.3)(vue@3.5.43(typescript@5.6.3))
qrcode:
specifier: ^1.5.4
version: 1.5.4
vue:
- specifier: ^3.4.0
- version: 3.5.26(typescript@5.6.3)
+ specifier: ^3.5.43
+ version: 3.5.43(typescript@5.6.3)
vue-chartjs:
specifier: ^5.3.0
- version: 5.3.3(chart.js@4.5.1)(vue@3.5.26(typescript@5.6.3))
+ version: 5.3.3(chart.js@4.5.1)(vue@3.5.43(typescript@5.6.3))
vue-draggable-plus:
specifier: ^0.6.1
version: 0.6.1(@types/sortablejs@1.15.9)
vue-i18n:
specifier: ^9.14.5
- version: 9.14.5(vue@3.5.26(typescript@5.6.3))
+ version: 9.14.5(vue@3.5.43(typescript@5.6.3))
vue-router:
specifier: ^4.2.5
- version: 4.6.4(vue@3.5.26(typescript@5.6.3))
+ version: 4.6.4(vue@3.5.43(typescript@5.6.3))
xlsx:
specifier: ^0.18.5
version: 0.18.5
@@ -98,7 +99,7 @@ importers:
version: 7.18.0(eslint@8.57.1)(typescript@5.6.3)
'@vitejs/plugin-vue':
specifier: ^5.2.3
- version: 5.2.4(vite@5.4.21(@types/node@20.19.27))(vue@3.5.26(typescript@5.6.3))
+ version: 5.2.4(vite@5.4.21(@types/node@20.19.27))(vue@3.5.43(typescript@5.6.3))
'@vitest/coverage-v8':
specifier: ^2.1.9
version: 2.1.9(vitest@2.1.9(@types/node@20.19.27)(jsdom@24.1.3))
@@ -216,15 +217,28 @@ packages:
resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==}
engines: {node: '>=6.9.0'}
+ '@babel/helper-string-parser@7.29.7':
+ resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==}
+ engines: {node: '>=6.9.0'}
+
'@babel/helper-validator-identifier@7.28.5':
resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}
engines: {node: '>=6.9.0'}
+ '@babel/helper-validator-identifier@7.29.7':
+ resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}
+ engines: {node: '>=6.9.0'}
+
'@babel/parser@7.28.5':
resolution: {integrity: sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==}
engines: {node: '>=6.0.0'}
hasBin: true
+ '@babel/parser@7.29.9':
+ resolution: {integrity: sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
'@babel/runtime@7.28.4':
resolution: {integrity: sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==}
engines: {node: '>=6.9.0'}
@@ -245,6 +259,10 @@ packages:
resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==}
engines: {node: '>=6.9.0'}
+ '@babel/types@7.29.8':
+ resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
+ engines: {node: '>=6.9.0'}
+
'@base-ui/react@1.3.0':
resolution: {integrity: sha512-FwpKqZbPz14AITp1CVgf4AjhKPe1OeeVKSBMdgD10zbFlj3QSWelmtCMLi2+/PFZZcIm3l87G7rwtCZJwHyXWA==}
engines: {node: '>=14.0.0'}
@@ -1692,14 +1710,20 @@ packages:
'@vue/compiler-core@3.5.26':
resolution: {integrity: sha512-vXyI5GMfuoBCnv5ucIT7jhHKl55Y477yxP6fc4eUswjP8FG3FFVFd41eNDArR+Uk3QKn2Z85NavjaxLxOC19/w==}
+ '@vue/compiler-core@3.5.43':
+ resolution: {integrity: sha512-zdiLhnbe1QQqgDT8xZMpNmyqZ3qlI+/Q/FHQco57Kwl/b05HhCzN6eVGN9QU9rbga4CrS0H5SYY8VGHZCt/1Hg==}
+
'@vue/compiler-dom@3.5.26':
resolution: {integrity: sha512-y1Tcd3eXs834QjswshSilCBnKGeQjQXB6PqFn/1nxcQw4pmG42G8lwz+FZPAZAby6gZeHSt/8LMPfZ4Rb+Bd/A==}
- '@vue/compiler-sfc@3.5.26':
- resolution: {integrity: sha512-egp69qDTSEZcf4bGOSsprUr4xI73wfrY5oRs6GSgXFTiHrWj4Y3X5Ydtip9QMqiCMCPVwLglB9GBxXtTadJ3mA==}
+ '@vue/compiler-dom@3.5.43':
+ resolution: {integrity: sha512-PEZoAk3NQmsn/ejMzSOCyTYqwGqczrWm70PuhBKjjv1+TCoQAaO/zOqNwjV+honlNstT5ILxtc+8r8UUfj+iEQ==}
+
+ '@vue/compiler-sfc@3.5.43':
+ resolution: {integrity: sha512-FCbrG3XNCRl+js3huuKx4IVHBLTvMkJhVepjbxSPu1gn4yWLaYtGNQdjJGZaMytXB6qb76qQDDmDSLy/vkmleQ==}
- '@vue/compiler-ssr@3.5.26':
- resolution: {integrity: sha512-lZT9/Y0nSIRUPVvapFJEVDbEXruZh2IYHMk2zTtEgJSlP5gVOqeWXH54xDKAaFS4rTnDeDBQUYDtxKyoW9FwDw==}
+ '@vue/compiler-ssr@3.5.43':
+ resolution: {integrity: sha512-GF62orf7KiJX9RqrHNGrYBudsQGD0OhJ5nDs90O8UiDuS40+YMYomiXu6w6EuvtXuRDc3MSNis3EaaSKAVSWpg==}
'@vue/compiler-vue2@2.7.16':
resolution: {integrity: sha512-qYC3Psj9S/mfu9uVi5WvNZIzq+xnXMhOwbTFKKDD7b1lhpnn71jXSFdTQ+WsIEk0ONCd7VV2IMm7ONl6tbQ86A==}
@@ -1715,23 +1739,24 @@ packages:
typescript:
optional: true
- '@vue/reactivity@3.5.26':
- resolution: {integrity: sha512-9EnYB1/DIiUYYnzlnUBgwU32NNvLp/nhxLXeWRhHUEeWNTn1ECxX8aGO7RTXeX6PPcxe3LLuNBFoJbV4QZ+CFQ==}
+ '@vue/reactivity@3.5.43':
+ resolution: {integrity: sha512-G/c9GyOZNI2jVaaS6OX1EF1SSFSv7H0ERqNTl4+DTFMlZmB5eVAB53aLQNam/7NL2NPtaDD7RdVrzf8uJzMuOA==}
- '@vue/runtime-core@3.5.26':
- resolution: {integrity: sha512-xJWM9KH1kd201w5DvMDOwDHYhrdPTrAatn56oB/LRG4plEQeZRQLw0Bpwih9KYoqmzaxF0OKSn6swzYi84e1/Q==}
+ '@vue/runtime-core@3.5.43':
+ resolution: {integrity: sha512-hU6U6VnVhBGQDpvlnnDlIB8ZGJBiOcgk2lh/0InltHiz3D8oSkluvuvY+do1G2H3+udeKFsmaBlgVYP7gXQzEw==}
- '@vue/runtime-dom@3.5.26':
- resolution: {integrity: sha512-XLLd/+4sPC2ZkN/6+V4O4gjJu6kSDbHAChvsyWgm1oGbdSO3efvGYnm25yCjtFm/K7rrSDvSfPDgN1pHgS4VNQ==}
+ '@vue/runtime-dom@3.5.43':
+ resolution: {integrity: sha512-Bb2Jc0YjjJdMt1SJmb9b2L/IWd3I8lIT9x9eS/xvvP9CiVgna0ffua74xKRmt4/uSJ+0r4iN8ex1jrqkhQGWQw==}
- '@vue/server-renderer@3.5.26':
- resolution: {integrity: sha512-TYKLXmrwWKSodyVuO1WAubucd+1XlLg4set0YoV+Hu8Lo79mp/YMwWV5mC5FgtsDxX3qo1ONrxFaTP1OQgy1uA==}
- peerDependencies:
- vue: 3.5.26
+ '@vue/server-renderer@3.5.43':
+ resolution: {integrity: sha512-l2Ygjv9NehV94PSBxNWsAHC0j/eIIKbn92mBuWXAPGLnn6HfJ6MH5ubsd+Nk0YoZ5FRuxWI1P2VSoh+dbPQhCQ==}
'@vue/shared@3.5.26':
resolution: {integrity: sha512-7Z6/y3uFI5PRoKeorTOSXKcDj0MSasfNNltcslbFrPpcw6aXRUALq4IfJlaTRspiWIUOEZbrpM+iQGmCOiWe4A==}
+ '@vue/shared@3.5.43':
+ resolution: {integrity: sha512-uksS7YGMR5NZyr4JNq0Rp+QyLns0ueaz20KwzIPW9R0LH1Vnt4E+XUM29PNseEbf1www2gOuhuDi5AKOIXag9Q==}
+
'@vue/test-utils@2.4.6':
resolution: {integrity: sha512-FMxEjOpYNYiFe0GkaHsnJPXFHxQ6m4t8vI/ElPGpMWxZKpmRvQ33OIrvRXemy6yha03RxhOlQuy+gZMC3CQSow==}
@@ -1858,8 +1883,8 @@ packages:
peerDependencies:
postcss: '>=8.5.18'
- axios@1.18.1:
- resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==}
+ axios@1.20.0:
+ resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==}
babel-plugin-macros@3.1.0:
resolution: {integrity: sha512-Cg7TFGpIr01vOQNODXOOaGz2NpCU5gl8x1qJFbb6hbZxR7XrcE2vtbAsTAbJ7/xwJtUuJEw8K8Zr/AE0LHlesg==}
@@ -2342,6 +2367,10 @@ packages:
resolution: {integrity: sha512-FDWG5cmEYf2Z00IkYRhbFrwIwvdFKH07uV8dvNy0omp/Qb1xcyCWp2UDtcwJF4QZZvk0sLudP6/hAu42TaqVhQ==}
engines: {node: '>=0.12'}
+ entities@7.0.1:
+ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
+ engines: {node: '>=0.12'}
+
error-ex@1.3.4:
resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==}
@@ -3304,6 +3333,11 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
+ nanoid@3.3.20:
+ resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+
natural-compare@1.4.0:
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
@@ -3532,6 +3566,10 @@ packages:
resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==}
engines: {node: ^10 || ^12 || >=14}
+ postcss@8.5.29:
+ resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==}
+ engines: {node: ^10 || ^12 || >=14}
+
prelude-ls@1.2.1:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
@@ -3928,8 +3966,8 @@ packages:
resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
engines: {node: '>=8'}
- source-map-js@1.2.1:
- resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
+ source-map-js@1.2.2:
+ resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
engines: {node: '>=0.10.0'}
source-map@0.5.7:
@@ -4390,8 +4428,8 @@ packages:
peerDependencies:
typescript: '>=5.0.0'
- vue@3.5.26:
- resolution: {integrity: sha512-SJ/NTccVyAoNUJmkM9KUqPcYlY+u8OVL1X5EW9RIs3ch5H2uERxyyIUI4MRxVCSOiEcupX9xNGde1tL9ZKpimA==}
+ vue@3.5.43:
+ resolution: {integrity: sha512-o5qZoksdnjIKvW1srZ3ab7pcDNYAerBjRe54D0LBLfRdCYFrSgBHVXokMas35czQc0//lmx4/tuY4ZNQ+Rf2Ng==}
peerDependencies:
typescript: '*'
peerDependenciesMeta:
@@ -4620,12 +4658,20 @@ snapshots:
'@babel/helper-string-parser@7.27.1': {}
+ '@babel/helper-string-parser@7.29.7': {}
+
'@babel/helper-validator-identifier@7.28.5': {}
+ '@babel/helper-validator-identifier@7.29.7': {}
+
'@babel/parser@7.28.5':
dependencies:
'@babel/types': 7.28.5
+ '@babel/parser@7.29.9':
+ dependencies:
+ '@babel/types': 7.29.8
+
'@babel/runtime@7.28.4': {}
'@babel/runtime@7.29.2': {}
@@ -4653,6 +4699,11 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
+ '@babel/types@7.29.8':
+ dependencies:
+ '@babel/helper-string-parser': 7.29.7
+ '@babel/helper-validator-identifier': 7.29.7
+
'@base-ui/react@1.3.0(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
'@babel/runtime': 7.29.2
@@ -4988,7 +5039,7 @@ snapshots:
'@intlify/message-compiler@9.14.5':
dependencies:
'@intlify/shared': 9.14.5
- source-map-js: 1.2.1
+ source-map-js: 1.2.2
'@intlify/shared@9.14.5': {}
@@ -5044,7 +5095,7 @@ snapshots:
'@lobehub/icons@4.0.2(@lobehub/ui@4.9.2)(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
dependencies:
- '@lobehub/ui': 4.9.2(@lobehub/fluent-emoji@4.1.0(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(@lobehub/icons@4.0.2)(@types/mdast@4.0.4)(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(micromark-util-types@2.0.2)(micromark@4.0.2)(motion@12.23.26(@emotion/is-prop-valid@1.4.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vue@3.5.26(typescript@5.6.3))
+ '@lobehub/ui': 4.9.2(@lobehub/fluent-emoji@4.1.0(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(@lobehub/icons@4.0.2)(@types/mdast@4.0.4)(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(micromark-util-types@2.0.2)(micromark@4.0.2)(motion@12.23.26(@emotion/is-prop-valid@1.4.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vue@3.5.43(typescript@5.6.3))
antd: 6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
antd-style: 4.1.0(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
lucide-react: 0.469.0(react@19.2.3)
@@ -5055,7 +5106,7 @@ snapshots:
- '@types/react'
- supports-color
- '@lobehub/ui@4.9.2(@lobehub/fluent-emoji@4.1.0(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(@lobehub/icons@4.0.2)(@types/mdast@4.0.4)(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(micromark-util-types@2.0.2)(micromark@4.0.2)(motion@12.23.26(@emotion/is-prop-valid@1.4.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vue@3.5.26(typescript@5.6.3))':
+ '@lobehub/ui@4.9.2(@lobehub/fluent-emoji@4.1.0(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(@lobehub/icons@4.0.2)(@types/mdast@4.0.4)(@types/react@19.2.7)(antd@6.1.3(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(micromark-util-types@2.0.2)(micromark@4.0.2)(motion@12.23.26(@emotion/is-prop-valid@1.4.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vue@3.5.43(typescript@5.6.3))':
dependencies:
'@ant-design/cssinjs': 2.1.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
'@base-ui/react': 1.3.0(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
@@ -5120,7 +5171,7 @@ snapshots:
remark-github: 12.0.0
remark-math: 6.0.0
shiki: 3.23.0
- shiki-stream: 0.1.4(react@19.2.3)(vue@3.5.26(typescript@5.6.3))
+ shiki-stream: 0.1.4(react@19.2.3)(vue@3.5.43(typescript@5.6.3))
swr: 2.4.1(react@19.2.3)
ts-md5: 2.0.1
unified: 11.0.5
@@ -5872,10 +5923,10 @@ snapshots:
'@tanstack/virtual-core@3.13.23': {}
- '@tanstack/vue-virtual@3.13.23(vue@3.5.26(typescript@5.6.3))':
+ '@tanstack/vue-virtual@3.13.23(vue@3.5.43(typescript@5.6.3))':
dependencies:
'@tanstack/virtual-core': 3.13.23
- vue: 3.5.26(typescript@5.6.3)
+ vue: 3.5.43(typescript@5.6.3)
'@types/d3-array@3.2.2': {}
@@ -6147,10 +6198,10 @@ snapshots:
'@use-gesture/core': 10.3.1
react: 19.2.3
- '@vitejs/plugin-vue@5.2.4(vite@5.4.21(@types/node@20.19.27))(vue@3.5.26(typescript@5.6.3))':
+ '@vitejs/plugin-vue@5.2.4(vite@5.4.21(@types/node@20.19.27))(vue@3.5.43(typescript@5.6.3))':
dependencies:
vite: 5.4.21(@types/node@20.19.27)
- vue: 3.5.26(typescript@5.6.3)
+ vue: 3.5.43(typescript@5.6.3)
'@vitest/coverage-v8@2.1.9(vitest@2.1.9(@types/node@20.19.27)(jsdom@24.1.3))':
dependencies:
@@ -6228,29 +6279,42 @@ snapshots:
'@vue/shared': 3.5.26
entities: 7.0.0
estree-walker: 2.0.2
- source-map-js: 1.2.1
+ source-map-js: 1.2.2
+
+ '@vue/compiler-core@3.5.43':
+ dependencies:
+ '@babel/parser': 7.29.9
+ '@vue/shared': 3.5.43
+ entities: 7.0.1
+ estree-walker: 2.0.2
+ source-map-js: 1.2.2
'@vue/compiler-dom@3.5.26':
dependencies:
'@vue/compiler-core': 3.5.26
'@vue/shared': 3.5.26
- '@vue/compiler-sfc@3.5.26':
+ '@vue/compiler-dom@3.5.43':
dependencies:
- '@babel/parser': 7.28.5
- '@vue/compiler-core': 3.5.26
- '@vue/compiler-dom': 3.5.26
- '@vue/compiler-ssr': 3.5.26
- '@vue/shared': 3.5.26
+ '@vue/compiler-core': 3.5.43
+ '@vue/shared': 3.5.43
+
+ '@vue/compiler-sfc@3.5.43':
+ dependencies:
+ '@babel/parser': 7.29.9
+ '@vue/compiler-core': 3.5.43
+ '@vue/compiler-dom': 3.5.43
+ '@vue/compiler-ssr': 3.5.43
+ '@vue/shared': 3.5.43
estree-walker: 2.0.2
magic-string: 0.30.21
- postcss: 8.5.23
- source-map-js: 1.2.1
+ postcss: 8.5.29
+ source-map-js: 1.2.2
- '@vue/compiler-ssr@3.5.26':
+ '@vue/compiler-ssr@3.5.43':
dependencies:
- '@vue/compiler-dom': 3.5.26
- '@vue/shared': 3.5.26
+ '@vue/compiler-dom': 3.5.43
+ '@vue/shared': 3.5.43
'@vue/compiler-vue2@2.7.16':
dependencies:
@@ -6272,50 +6336,52 @@ snapshots:
optionalDependencies:
typescript: 5.6.3
- '@vue/reactivity@3.5.26':
+ '@vue/reactivity@3.5.43':
dependencies:
- '@vue/shared': 3.5.26
+ '@vue/shared': 3.5.43
- '@vue/runtime-core@3.5.26':
+ '@vue/runtime-core@3.5.43':
dependencies:
- '@vue/reactivity': 3.5.26
- '@vue/shared': 3.5.26
+ '@vue/reactivity': 3.5.43
+ '@vue/shared': 3.5.43
- '@vue/runtime-dom@3.5.26':
+ '@vue/runtime-dom@3.5.43':
dependencies:
- '@vue/reactivity': 3.5.26
- '@vue/runtime-core': 3.5.26
- '@vue/shared': 3.5.26
+ '@vue/reactivity': 3.5.43
+ '@vue/runtime-core': 3.5.43
+ '@vue/shared': 3.5.43
csstype: 3.2.3
- '@vue/server-renderer@3.5.26(vue@3.5.26(typescript@5.6.3))':
+ '@vue/server-renderer@3.5.43':
dependencies:
- '@vue/compiler-ssr': 3.5.26
- '@vue/shared': 3.5.26
- vue: 3.5.26(typescript@5.6.3)
+ '@vue/compiler-ssr': 3.5.43
+ '@vue/runtime-dom': 3.5.43
+ '@vue/shared': 3.5.43
'@vue/shared@3.5.26': {}
+ '@vue/shared@3.5.43': {}
+
'@vue/test-utils@2.4.6':
dependencies:
js-beautify: 1.15.4
vue-component-type-helpers: 2.2.12
- '@vueuse/core@10.11.1(vue@3.5.26(typescript@5.6.3))':
+ '@vueuse/core@10.11.1(vue@3.5.43(typescript@5.6.3))':
dependencies:
'@types/web-bluetooth': 0.0.20
'@vueuse/metadata': 10.11.1
- '@vueuse/shared': 10.11.1(vue@3.5.26(typescript@5.6.3))
- vue-demi: 0.14.10(vue@3.5.26(typescript@5.6.3))
+ '@vueuse/shared': 10.11.1(vue@3.5.43(typescript@5.6.3))
+ vue-demi: 0.14.10(vue@3.5.43(typescript@5.6.3))
transitivePeerDependencies:
- '@vue/composition-api'
- vue
'@vueuse/metadata@10.11.1': {}
- '@vueuse/shared@10.11.1(vue@3.5.26(typescript@5.6.3))':
+ '@vueuse/shared@10.11.1(vue@3.5.43(typescript@5.6.3))':
dependencies:
- vue-demi: 0.14.10(vue@3.5.26(typescript@5.6.3))
+ vue-demi: 0.14.10(vue@3.5.43(typescript@5.6.3))
transitivePeerDependencies:
- '@vue/composition-api'
- vue
@@ -6484,7 +6550,7 @@ snapshots:
postcss: 8.5.23
postcss-value-parser: 4.2.0
- axios@1.18.1:
+ axios@1.20.0:
dependencies:
follow-redirects: 1.16.0
form-data: 4.0.6
@@ -6969,6 +7035,8 @@ snapshots:
entities@7.0.0: {}
+ entities@7.0.1: {}
+
error-ex@1.3.4:
dependencies:
is-arrayish: 0.2.1
@@ -7812,7 +7880,7 @@ snapshots:
dependencies:
'@babel/parser': 7.28.5
'@babel/types': 7.28.5
- source-map-js: 1.2.1
+ source-map-js: 1.2.2
make-dir@4.0.0:
dependencies:
@@ -8400,6 +8468,8 @@ snapshots:
nanoid@3.3.18: {}
+ nanoid@3.3.20: {}
+
natural-compare@1.4.0: {}
node-releases@2.0.27: {}
@@ -8532,11 +8602,11 @@ snapshots:
pify@2.3.0: {}
- pinia@2.3.1(typescript@5.6.3)(vue@3.5.26(typescript@5.6.3)):
+ pinia@2.3.1(typescript@5.6.3)(vue@3.5.43(typescript@5.6.3)):
dependencies:
'@vue/devtools-api': 6.6.4
- vue: 3.5.26(typescript@5.6.3)
- vue-demi: 0.14.10(vue@3.5.26(typescript@5.6.3))
+ vue: 3.5.43(typescript@5.6.3)
+ vue-demi: 0.14.10(vue@3.5.43(typescript@5.6.3))
optionalDependencies:
typescript: 5.6.3
transitivePeerDependencies:
@@ -8598,7 +8668,13 @@ snapshots:
dependencies:
nanoid: 3.3.18
picocolors: 1.1.1
- source-map-js: 1.2.1
+ source-map-js: 1.2.2
+
+ postcss@8.5.29:
+ dependencies:
+ nanoid: 3.3.20
+ picocolors: 1.1.1
+ source-map-js: 1.2.2
prelude-ls@1.2.1: {}
@@ -9080,12 +9156,12 @@ snapshots:
shebang-regex@3.0.0: {}
- shiki-stream@0.1.4(react@19.2.3)(vue@3.5.26(typescript@5.6.3)):
+ shiki-stream@0.1.4(react@19.2.3)(vue@3.5.43(typescript@5.6.3)):
dependencies:
'@shikijs/core': 3.23.0
optionalDependencies:
react: 19.2.3
- vue: 3.5.26(typescript@5.6.3)
+ vue: 3.5.43(typescript@5.6.3)
shiki@3.23.0:
dependencies:
@@ -9104,7 +9180,7 @@ snapshots:
slash@3.0.0: {}
- source-map-js@1.2.1: {}
+ source-map-js@1.2.2: {}
source-map@0.5.7: {}
@@ -9504,16 +9580,16 @@ snapshots:
vscode-uri@3.1.0: {}
- vue-chartjs@5.3.3(chart.js@4.5.1)(vue@3.5.26(typescript@5.6.3)):
+ vue-chartjs@5.3.3(chart.js@4.5.1)(vue@3.5.43(typescript@5.6.3)):
dependencies:
chart.js: 4.5.1
- vue: 3.5.26(typescript@5.6.3)
+ vue: 3.5.43(typescript@5.6.3)
vue-component-type-helpers@2.2.12: {}
- vue-demi@0.14.10(vue@3.5.26(typescript@5.6.3)):
+ vue-demi@0.14.10(vue@3.5.43(typescript@5.6.3)):
dependencies:
- vue: 3.5.26(typescript@5.6.3)
+ vue: 3.5.43(typescript@5.6.3)
vue-draggable-plus@0.6.1(@types/sortablejs@1.15.9):
dependencies:
@@ -9532,17 +9608,17 @@ snapshots:
transitivePeerDependencies:
- supports-color
- vue-i18n@9.14.5(vue@3.5.26(typescript@5.6.3)):
+ vue-i18n@9.14.5(vue@3.5.43(typescript@5.6.3)):
dependencies:
'@intlify/core-base': 9.14.5
'@intlify/shared': 9.14.5
'@vue/devtools-api': 6.6.4
- vue: 3.5.26(typescript@5.6.3)
+ vue: 3.5.43(typescript@5.6.3)
- vue-router@4.6.4(vue@3.5.26(typescript@5.6.3)):
+ vue-router@4.6.4(vue@3.5.43(typescript@5.6.3)):
dependencies:
'@vue/devtools-api': 6.6.4
- vue: 3.5.26(typescript@5.6.3)
+ vue: 3.5.43(typescript@5.6.3)
vue-tsc@2.2.12(typescript@5.6.3):
dependencies:
@@ -9550,13 +9626,13 @@ snapshots:
'@vue/language-core': 2.2.12(typescript@5.6.3)
typescript: 5.6.3
- vue@3.5.26(typescript@5.6.3):
+ vue@3.5.43(typescript@5.6.3):
dependencies:
- '@vue/compiler-dom': 3.5.26
- '@vue/compiler-sfc': 3.5.26
- '@vue/runtime-dom': 3.5.26
- '@vue/server-renderer': 3.5.26(vue@3.5.26(typescript@5.6.3))
- '@vue/shared': 3.5.26
+ '@vue/compiler-dom': 3.5.43
+ '@vue/compiler-sfc': 3.5.43
+ '@vue/runtime-dom': 3.5.43
+ '@vue/server-renderer': 3.5.43
+ '@vue/shared': 3.5.43
optionalDependencies:
typescript: 5.6.3
diff --git a/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts b/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts
index 48043150e..de24edbae 100644
--- a/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts
+++ b/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts
@@ -8,16 +8,18 @@ import {
type UpdateSettingsRequest,
type DefaultPlatformQuotasMap,
} from "@/api/admin/settings";
+import { listPlatformIds } from "@/constants/platformCatalog";
-/** 全 null 的平台 map,用于断言归一化默认值(包含 BPS) */
-const allNullQuotas: DefaultPlatformQuotasMap = {
- anthropic: { daily: null, weekly: null, monthly: null },
- openai: { daily: null, weekly: null, monthly: null },
- openai_bps: { daily: null, weekly: null, monthly: null },
- gemini: { daily: null, weekly: null, monthly: null },
- antigravity: { daily: null, weekly: null, monthly: null },
- grok: { daily: null, weekly: null, monthly: null },
-}
+/** 与后端 AllowedQuotaPlatforms 一致的全部具体平台(平台清单)。 */
+const quotaPlatforms = [
+ "anthropic", "openai", "openai_bps", "gemini", "antigravity", "grok",
+ "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", "command_code", "cline",
+];
+
+/** 全部平台全 null 的 map,用于断言归一化默认值 */
+const allNullQuotas: DefaultPlatformQuotasMap = Object.fromEntries(
+ quotaPlatforms.map((platform) => [platform, { daily: null, weekly: null, monthly: null }]),
+)
describe("admin settings auth source defaults helpers", () => {
it("builds auth source defaults state from flat settings fields", () => {
@@ -240,11 +242,17 @@ describe("normalizePlatformQuotasMap", () => {
expect(result.gemini).toEqual({ daily: null, weekly: null, monthly: null });
expect(result.antigravity).toEqual({ daily: null, weekly: null, monthly: null });
expect(result.grok).toEqual({ daily: null, weekly: null, monthly: null });
+ expect(result.kimi).toEqual({ daily: null, weekly: null, monthly: null });
+ expect(result.opencode_go).toEqual({ daily: null, weekly: null, monthly: null });
});
- it("无参数时返回所有平台全 null", () => {
+ it("无参数时返回平台清单中的全部平台全 null", () => {
const result = normalizePlatformQuotasMap();
- expect(result).toEqual(allNullQuotas);
+ expect(listPlatformIds()).toEqual(quotaPlatforms);
+ expect(Object.keys(result)).toEqual(quotaPlatforms);
+ for (const v of Object.values(result)) {
+ expect(v).toEqual({ daily: null, weekly: null, monthly: null });
+ }
});
it("非 number 类型的值归一化为 null", () => {
@@ -289,6 +297,9 @@ describe("sanitizePlatformQuotasMap", () => {
it("缺失平台填充为全 null", () => {
const result = sanitizePlatformQuotasMap({});
- expect(result).toEqual(allNullQuotas);
+ expect(Object.keys(result)).toEqual(quotaPlatforms);
+ for (const v of Object.values(result)) {
+ expect(v).toEqual({ daily: null, weekly: null, monthly: null });
+ }
});
});
diff --git a/frontend/src/api/admin/cnProviders.ts b/frontend/src/api/admin/cnProviders.ts
index 7a4d3f18c..ee0c7df0d 100644
--- a/frontend/src/api/admin/cnProviders.ts
+++ b/frontend/src/api/admin/cnProviders.ts
@@ -12,7 +12,7 @@ export interface CNQuotaTier {
reset_at?: string
}
-/** Coding Plan 额度探测结果(kimi / zhipu),对齐后端 CNProviderQuotaProbeResult。 */
+/** 额度探测结果(Coding Plan / OpenCode Go / Command Code),对齐后端 CNProviderQuotaProbeResult。 */
export interface CNProviderQuotaProbeResult {
provider: string
source?: string
@@ -24,6 +24,8 @@ export interface CNProviderQuotaProbeResult {
fetched_at: number
persisted: boolean
error?: string
+ /** 同一次探测得到的余额(Command Code 积分与窗口同源),其余供应商为空。 */
+ balance?: CNProviderBalanceResult
}
/** 单币种余额明细(deepseek 双币种账号含 CNY + USD 两条)。 */
diff --git a/frontend/src/api/admin/ops.ts b/frontend/src/api/admin/ops.ts
index 8754f1958..f4c1b3740 100644
--- a/frontend/src/api/admin/ops.ts
+++ b/frontend/src/api/admin/ops.ts
@@ -63,6 +63,14 @@ export interface OpsDashboardOverview {
avg: number
}
+ output_tps?: {
+ p5: number | null
+ p10: number | null
+ p50: number | null
+ avg: number | null
+ sample_count: number
+ } | null
+
duration: OpsPercentiles
ttft: OpsPercentiles
}
diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts
index 422dbbb39..dd46dbea3 100644
--- a/frontend/src/api/admin/settings.ts
+++ b/frontend/src/api/admin/settings.ts
@@ -4,12 +4,15 @@
*/
import { apiClient } from "../client";
+import { listPlatformIds } from "@/constants/platformCatalog";
import type {
+ AccountPlatform,
CustomEndpoint,
CustomMenuItem,
LoginAgreementDocument,
NotifyEmailEntry,
} from "@/types";
+import type { RechargeBonusTier } from "@/utils/rechargeBonus";
export interface DefaultSubscriptionSetting {
group_id: number;
@@ -17,7 +20,8 @@ export interface DefaultSubscriptionSetting {
}
// ── 平台限额类型 ──────────────────────────────────────────────────
-export type PlatformType = "anthropic" | "openai" | "openai_bps" | "gemini" | "antigravity" | "grok"
+/** 可设置默认限额的平台:平台清单中的全部具体平台(与后端 AllowedQuotaPlatforms 同源)。 */
+export type PlatformType = AccountPlatform
export type QuotaWindowType = "daily" | "weekly" | "monthly"
/** 单平台三档限额;null = 不限制,undefined = 未填(等价 null) */
@@ -30,7 +34,6 @@ export interface PlatformQuotaLimits {
/** 全平台默认限额 map(key = PlatformType) */
export type DefaultPlatformQuotasMap = Partial>
-const PLATFORMS: PlatformType[] = ["anthropic", "openai", "openai_bps", "gemini", "antigravity", "grok"]
export type SchedulingThresholdPlatformType =
| "openai"
@@ -40,11 +43,12 @@ export type SchedulingThresholdPlatformType =
| "zhipu"
| "minimax"
| "opencode_go"
+ | "command_code"
export type AccountSchedulingThresholdsMap = Record
// 与后端 AllowedSchedulingThresholdPlatforms 保持一致(deepseek 为余额型,
-// 走余额检测而非用量阈值;minimax Coding/Token Plan 与 OpenCode GO 有滚动窗口)。
+// 走余额检测而非用量阈值;minimax Coding/Token Plan、OpenCode GO 与 Command Code 有滚动窗口)。
export const SCHEDULING_THRESHOLD_PLATFORMS: SchedulingThresholdPlatformType[] = [
"openai",
"anthropic",
@@ -53,6 +57,7 @@ export const SCHEDULING_THRESHOLD_PLATFORMS: SchedulingThresholdPlatformType[] =
"zhipu",
"minimax",
"opencode_go",
+ "command_code",
]
export function normalizeAccountSchedulingThresholdsMap(
@@ -74,10 +79,10 @@ export function sanitizeAccountSchedulingThresholdsMap(
return normalizeAccountSchedulingThresholdsMap(input)
}
-/** 归一化为全 4 平台 × 3 窗口(缺失填 null),供模板非空绑定 */
+/** 归一化为全部平台 × 3 窗口(缺失填 null),供模板非空绑定 */
export function normalizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | null): DefaultPlatformQuotasMap {
const result: DefaultPlatformQuotasMap = {}
- for (const p of PLATFORMS) {
+ for (const p of listPlatformIds()) {
const src = input?.[p]
result[p] = {
daily: typeof src?.daily === "number" ? src.daily : null,
@@ -88,11 +93,11 @@ export function normalizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | nu
return result
}
-/** 提交前清洗:非有限数/负数/空字符串 → null(保留 0 = 显式禁用),返回全 4 平台嵌套 map */
+/** 提交前清洗:非有限数/负数/空字符串 → null(保留 0 = 显式禁用),返回全部平台嵌套 map */
export function sanitizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | null): DefaultPlatformQuotasMap {
const clean = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null)
const result: DefaultPlatformQuotasMap = {}
- for (const p of PLATFORMS) {
+ for (const p of listPlatformIds()) {
const src = input?.[p]
result[p] = { daily: clean(src?.daily), weekly: clean(src?.weekly), monthly: clean(src?.monthly) }
}
@@ -676,6 +681,9 @@ export interface SystemSettings {
payment_balance_recharge_multiplier: number;
payment_subscription_usd_to_cny_rate: number;
payment_recharge_fee_rate: number;
+ payment_recharge_bonus_tiers?: RechargeBonusTier[];
+ payment_recharge_bonus_mode?: string;
+ payment_recharge_bonus_notice?: string;
payment_load_balance_strategy: string;
payment_product_name_prefix: string;
payment_product_name_suffix: string;
@@ -1001,6 +1009,9 @@ export interface UpdateSettingsRequest {
payment_balance_recharge_multiplier?: number;
payment_subscription_usd_to_cny_rate?: number;
payment_recharge_fee_rate?: number;
+ payment_recharge_bonus_tiers?: RechargeBonusTier[];
+ payment_recharge_bonus_mode?: string;
+ payment_recharge_bonus_notice?: string;
payment_load_balance_strategy?: string;
payment_product_name_prefix?: string;
payment_product_name_suffix?: string;
diff --git a/frontend/src/api/admin/users.ts b/frontend/src/api/admin/users.ts
index d3b597d0a..d943508e7 100644
--- a/frontend/src/api/admin/users.ts
+++ b/frontend/src/api/admin/users.ts
@@ -4,7 +4,8 @@
*/
import { apiClient } from '../client'
-import type { AdminUser, UpdateUserRequest, PaginatedResponse, ApiKey } from '@/types'
+import { listPlatformIds } from '@/constants/platformCatalog'
+import type { AccountPlatform, AdminUser, UpdateUserRequest, PaginatedResponse, ApiKey } from '@/types'
export interface AdminBindAuthIdentityChannelRequest {
channel: string
@@ -330,12 +331,11 @@ export async function bindUserAuthIdentity(
/**
* Platform quota types
*/
-// Keep aligned with backend/internal/service/domain_constants.go AllowedQuotaPlatforms.
-export const PLATFORM_QUOTA_PLATFORMS = [
- 'anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok',
- 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go',
-] as const
-export type PlatformQuotaPlatform = typeof PLATFORM_QUOTA_PLATFORMS[number]
+// 与后端 AllowedQuotaPlatforms 同源:平台清单中的全部具体平台。
+export function platformQuotaPlatforms(): PlatformQuotaPlatform[] {
+ return listPlatformIds()
+}
+export type PlatformQuotaPlatform = AccountPlatform
export type PlatformQuotaWindow = 'daily' | 'weekly' | 'monthly'
export interface PlatformQuotaItem {
diff --git a/frontend/src/components/account/AccountPriorityCell.vue b/frontend/src/components/account/AccountPriorityCell.vue
new file mode 100644
index 000000000..b24934149
--- /dev/null
+++ b/frontend/src/components/account/AccountPriorityCell.vue
@@ -0,0 +1,182 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue
index b21e79abb..16b165a49 100644
--- a/frontend/src/components/account/AccountUsageCell.vue
+++ b/frontend/src/components/account/AccountUsageCell.vue
@@ -439,8 +439,9 @@
-
-
+
+
-
+
+
MiniMax
+
+
+
+
+
+
@@ -542,6 +577,35 @@
+
+
+
+
+
+
+
+
@@ -1387,7 +1451,7 @@
v-if="isCNPlatform && !isOpenCodeGoPlatform"
class="mt-2"
:platform="cnPresetPlatform"
- :mode="accountMode"
+ :mode="cnPresetMode"
:protocol="apiProtocol"
:current-url="apiKeyBaseUrl"
@select="onCnPresetSelect"
@@ -1408,14 +1472,15 @@
/>
-
+
{{ t('admin.accounts.cnProviders.apiProtocol.responsesFallbackDesc') }}
@@ -3994,8 +4059,15 @@ import {
defaultCNAdaptiveBaseUrls,
defaultCNBaseUrl,
defaultOpenCodeProtocolRules,
+ defaultProviderProtocolRules,
isCNProviderPlatform,
isHeaderOverrideCapable,
+ isMultiProtocolApiKeyPlatform,
+ providerAccountModes,
+ providerModeLabel,
+ providerNativeProtocols,
+ providerRoutesByModel,
+ resolveProviderAccountMode,
validateHeaderOverrideRows,
type CnAccountMode,
type CnApiProtocol,
@@ -4005,6 +4077,7 @@ import {
type OpenCodeAccountMode,
type OpenCodeGoProtocolRule
} from '@/components/account/credentialsBuilder'
+import { listPlatforms } from '@/constants/platformCatalog'
import {
formatDateTimeLocalInput,
getBrowserTimeZone,
@@ -4070,7 +4143,8 @@ const baseUrlHint = computed(() => {
const apiKeyHint = computed(() => {
if (form.platform === 'openai') return t('admin.accounts.openai.apiKeyHint')
if (form.platform === 'gemini') return t('admin.accounts.gemini.apiKeyHint')
- if (form.platform === 'grok') return ''
+ // Grok 与多协议供应商没有对应的说明文案;通用文案指 Claude Console Key。
+ if (form.platform === 'grok' || isMultiProtocolPlatform.value) return ''
return t('admin.accounts.apiKeyHint')
})
@@ -4087,6 +4161,8 @@ const apiKeyBaseUrlPlaceholder = computed(() => {
return 'https://generativelanguage.googleapis.com'
case 'grok':
return 'https://api.x.ai/v1'
+ case 'typesafe':
+ return 'https://api.typesafe.ai'
default:
return 'https://api.anthropic.com'
}
@@ -4109,8 +4185,10 @@ const apiKeyValuePlaceholder = computed(() => {
case 'minimax':
case 'opencode_go':
return 'sk-...'
+ case 'typesafe':
+ return 'ts-...'
default:
- return 'sk-ant-...'
+ return isMultiProtocolPlatform.value ? 'sk-...' : 'sk-ant-...'
}
})
@@ -4199,7 +4277,8 @@ const apiKeyValue = ref('')
const upstreamBillingAutoProbeEnabled = ref(true)
// ── 国产供应商(Kimi / Zhipu / DeepSeek)账号类型、API 协议与端点 ──
-const accountMode = ref
('payg')
+// 多协议供应商(国产厂商与走通用表单的供应商)的接入模式;OpenCode 用 openCodeAccountMode。
+const accountMode = ref('payg')
const openCodeAccountMode = ref('zen')
// API 协议决定转发端点与格式:cc=现有转换链,anthropic=原生直通(Claude Code),
// responses=deepseek / kimi 原生 Responses 端点(Codex)。与账号类型正交。
@@ -4217,8 +4296,19 @@ const adaptiveBaseUrls = ref>({
})
const isCNPlatform = computed(() => isCNProviderPlatform(form.platform))
const isOpenCodeGoPlatform = computed(() => form.platform === 'opencode_go')
-const isMultiProtocolPlatform = computed(() => isCNPlatform.value || isOpenCodeGoPlatform.value)
-function currentOpenCodeOrCNMode(): CnAccountMode | OpenCodeAccountMode {
+const isMultiProtocolPlatform = computed(() => isMultiProtocolApiKeyPlatform(form.platform))
+// 前端没有专属界面、走通用表单的多协议供应商:模式、协议、默认端点
+// 与分流规则全部来自平台清单中的 profile。
+const isGenericMultiProtocolPlatform = computed(
+ () => isMultiProtocolPlatform.value && !isCNPlatform.value && !isOpenCodeGoPlatform.value
+)
+const extraMultiProtocolPlatforms = computed(() =>
+ listPlatforms().filter(spec => !!spec.multi_protocol && !isCNProviderPlatform(spec.id) && spec.id !== 'opencode_go')
+)
+const genericAccountModes = computed(() => providerAccountModes(form.platform))
+// 按模型分流的供应商(OpenCode 等):adaptive 账号携带 protocol_rules。
+const routesByModel = computed(() => providerRoutesByModel(form.platform))
+function currentOpenCodeOrCNMode(): string {
return isOpenCodeGoPlatform.value ? openCodeAccountMode.value : accountMode.value
}
// CnBaseUrlPresets 的 platform prop 是平台字面量联合类型,模板里不能写
@@ -4229,35 +4319,31 @@ const cnPresetPlatform = computed(() => {
}
return 'kimi'
})
-const adaptivePresetPlatform = computed(() => {
- if (form.platform === 'opencode_go') return 'opencode_go'
+// 国产厂商的接入模式只有 payg / coding(selectCNPlatform 已按 profile 规范化)。
+const cnPresetMode = computed(() => (accountMode.value === 'coding' ? 'coding' : 'payg'))
+const adaptivePresetPlatform = computed(() => {
+ if (isMultiProtocolPlatform.value) return form.platform
return cnPresetPlatform.value
})
-// 当前平台可选的协议档(responses 仅 deepseek / kimi)。
-const cnProtocolOptions = computed>(() => {
- const opts: Array<{ value: CnApiProtocol; labelKey: string }> = [
- { value: 'adaptive', labelKey: 'adaptive' },
- { value: 'chat_completions', labelKey: 'chatCompletions' },
- { value: 'anthropic', labelKey: 'anthropic' }
- ]
- if (cnSupportsNativeResponses(form.platform)) {
- opts.push({ value: 'responses', labelKey: 'responses' })
- }
- return opts
-})
-const cnAdaptiveProtocolOptions = computed>(() => {
- const opts: Array<{ value: CnNativeApiProtocol; labelKey: string }> = [
- { value: 'chat_completions', labelKey: 'chatCompletions' },
- { value: 'anthropic', labelKey: 'anthropic' }
- ]
- if (cnSupportsNativeResponses(form.platform)) opts.push({ value: 'responses', labelKey: 'responses' })
- return opts
-})
+const NATIVE_PROTOCOL_LABEL_KEYS: Record = {
+ chat_completions: 'chatCompletions',
+ anthropic: 'anthropic',
+ responses: 'responses'
+}
+// 当前平台与接入模式提供原生端点的协议(profile 中有默认基址的协议)。
+const cnAdaptiveProtocolOptions = computed>(() =>
+ providerNativeProtocols(form.platform, currentOpenCodeOrCNMode()).map(value => ({
+ value,
+ labelKey: NATIVE_PROTOCOL_LABEL_KEYS[value]
+ }))
+)
+// 可选的协议档:adaptive 加上各原生协议(responses 仅 deepseek / kimi 等提供原生端点的供应商)。
+const cnProtocolOptions = computed>(() => [
+ { value: 'adaptive', labelKey: 'adaptive' },
+ ...cnAdaptiveProtocolOptions.value
+])
-function resetAdaptiveBaseUrls(
- platform: CnProviderPlatform | 'opencode_go',
- mode: CnAccountMode | OpenCodeAccountMode
-) {
+function resetAdaptiveBaseUrls(platform: string, mode: string) {
adaptiveBaseUrls.value = defaultCNAdaptiveBaseUrls(platform, mode)
}
// 当前选中平台的品牌色(选中卡片描边 / 图标底色),与 platformColors 取色一致。
@@ -4300,9 +4386,8 @@ function selectCNPlatform(platform: CnProviderPlatform) {
form.type = 'apikey'
accountCategory.value = 'apikey'
apiProtocol.value = 'adaptive'
- if (platform === 'deepseek') {
- accountMode.value = 'payg'
- }
+ // deepseek 无 coding 套餐(profile 仅 payg);从其他供应商切换来的未知模式回落默认模式。
+ accountMode.value = resolveProviderAccountMode(platform, accountMode.value)
apiKeyBaseUrl.value = defaultCNBaseUrl(platform, accountMode.value, apiProtocol.value)
resetAdaptiveBaseUrls(platform, accountMode.value)
}
@@ -4316,6 +4401,23 @@ function selectOpenCodeGoPlatform() {
resetAdaptiveBaseUrls('opencode_go', openCodeAccountMode.value)
openCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(defaultOpenCodeProtocolRules(openCodeAccountMode.value))
}
+function selectTypeSafePlatform() {
+ form.platform = 'typesafe'
+ form.type = 'apikey'
+ accountCategory.value = 'apikey'
+ apiKeyBaseUrl.value = 'https://api.typesafe.ai'
+ allowedModels.value = ['jev-latest']
+}
+function selectGenericMultiProtocolPlatform(platform: string) {
+ form.platform = platform
+ form.type = 'apikey'
+ accountCategory.value = 'apikey'
+ apiProtocol.value = 'adaptive'
+ accountMode.value = resolveProviderAccountMode(platform, undefined)
+ apiKeyBaseUrl.value = defaultCNBaseUrl(platform, accountMode.value, apiProtocol.value)
+ resetAdaptiveBaseUrls(platform, accountMode.value)
+ openCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(defaultProviderProtocolRules(platform, accountMode.value))
+}
// 账号类型 / 协议变更时同步默认 base url。
watch(openCodeAccountMode, (mode, previousMode) => {
if (!isOpenCodeGoPlatform.value) return
@@ -4338,6 +4440,12 @@ watch(openCodeAccountMode, (mode, previousMode) => {
})
watch(accountMode, (mode, previousMode) => {
if (!isMultiProtocolPlatform.value || isOpenCodeGoPlatform.value) return
+ if (routesByModel.value) {
+ const previousRules = JSON.stringify(defaultProviderProtocolRules(form.platform, previousMode))
+ if (JSON.stringify(openCodeGoProtocolRules.value) === previousRules) {
+ openCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(defaultProviderProtocolRules(form.platform, mode))
+ }
+ }
if (apiProtocol.value === 'adaptive') {
const previousDefaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, previousMode)
const nextDefaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, mode)
@@ -4886,7 +4994,7 @@ watch(
() => form.platform,
(newPlatform) => {
// Reset base URL based on platform
- if (isCNProviderPlatform(newPlatform) || newPlatform === 'opencode_go') {
+ if (isMultiProtocolApiKeyPlatform(newPlatform)) {
const mode = newPlatform === 'opencode_go' ? openCodeAccountMode.value : accountMode.value
apiKeyBaseUrl.value = defaultCNBaseUrl(newPlatform, mode, apiProtocol.value)
} else {
@@ -4897,12 +5005,20 @@ watch(
? 'https://generativelanguage.googleapis.com'
: newPlatform === 'grok'
? 'https://api.x.ai/v1'
+ : newPlatform === 'typesafe'
+ ? 'https://api.typesafe.ai'
: 'https://api.anthropic.com'
}
// Clear model-related settings
allowedModels.value = []
upstreamModelsPreviewed.value = false
modelMappings.value = []
+ if (newPlatform === 'typesafe') {
+ accountCategory.value = 'apikey'
+ // Grok 等平台会把模式切到映射;TypeSafe 只用白名单写入 jev-latest。
+ modelRestrictionMode.value = 'whitelist'
+ allowedModels.value = ['jev-latest']
+ }
// Antigravity: 默认使用映射模式并填充默认映射
if (newPlatform === 'antigravity') {
antigravityModelRestrictionMode.value = 'mapping'
@@ -5865,6 +5981,8 @@ const handleSubmit = async () => {
? 'https://generativelanguage.googleapis.com'
: form.platform === 'grok'
? 'https://api.x.ai/v1'
+ : form.platform === 'typesafe'
+ ? 'https://api.typesafe.ai'
: 'https://api.anthropic.com'
// Build credentials with optional model mapping
@@ -5879,7 +5997,7 @@ const handleSubmit = async () => {
// 国产供应商:账号模式 + 协议 + 对应端点写入凭据;后端按 account_mode 路由
// 额度/余额探测,按 api_protocol 路由转发端点与格式。注意 CN apikey 走本函数
// 的通用路径(直接 doCreateAccount),不经过 createAccountAndFinish。
- if (isCNProviderPlatform(form.platform) || form.platform === 'opencode_go') {
+ if (isMultiProtocolApiKeyPlatform(form.platform)) {
credentials.account_mode = form.platform === 'opencode_go' ? openCodeAccountMode.value : accountMode.value
credentials.api_protocol = apiProtocol.value
if (apiProtocol.value === 'adaptive') {
@@ -5905,7 +6023,7 @@ const handleSubmit = async () => {
if (zhipuOrganization.value.trim()) credentials.zhipu_organization = zhipuOrganization.value.trim()
if (zhipuProject.value.trim()) credentials.zhipu_project = zhipuProject.value.trim()
}
- if (form.platform === 'opencode_go') {
+ if (providerRoutesByModel(form.platform)) {
applyOpenCodeGoProtocolRules(credentials, openCodeGoProtocolRules.value, 'create')
}
}
diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue
index ecdc8959e..2da01aec8 100644
--- a/frontend/src/components/account/EditAccountModal.vue
+++ b/frontend/src/components/account/EditAccountModal.vue
@@ -55,10 +55,10 @@
@select="editBaseUrl = $event"
/>
-
+
{{ t('admin.accounts.cnProviders.apiProtocol.responsesFallbackDesc') }}
@@ -130,8 +130,28 @@
+
+
+
+
+
+
+
-
+
@@ -3178,7 +3199,14 @@ import {
buildPlanTypeOptions,
cloneOpenCodeGoProtocolRules,
defaultOpenCodeProtocolRules,
+ defaultProviderProtocolRules,
+ isMultiProtocolApiKeyPlatform,
parseOpenCodeGoProtocolRules,
+ providerAccountModes,
+ providerModeLabel,
+ providerNativeProtocols,
+ providerRoutesByModel,
+ resolveProviderAccountMode,
readPlanType,
resolveOpenCodeAccountMode,
isCustomGrokBaseUrl,
@@ -3389,11 +3417,18 @@ const editApiKey = ref('')
// ── 国产供应商(Kimi / Zhipu / DeepSeek)account_mode / api_protocol 编辑 ──
// account_mode 决定额度/余额监控路径,api_protocol 决定转发端点与格式;
// 二者均可修正(早期创建的账号可能存错默认值),切换时重置 base_url 预置。
+// 覆盖全部多协议 API Key 供应商(国产厂商、OpenCode 与走通用表单的供应商)。
const isCNApiKeyAccount = computed(
+ () => props.account?.type === 'apikey' && isMultiProtocolApiKeyPlatform(props.account.platform)
+)
+// 前端没有专属界面、走通用表单的多协议供应商:模式 / 协议 / 默认端点来自 profile。
+const isGenericMultiProtocolAccount = computed(
() =>
- props.account?.type === 'apikey' &&
- (isCNProviderPlatform(props.account.platform) || props.account.platform === 'opencode_go')
+ isCNApiKeyAccount.value &&
+ !isCNProviderPlatform(props.account?.platform ?? '') &&
+ props.account?.platform !== 'opencode_go'
)
+const genericAccountModes = computed(() => providerAccountModes(props.account?.platform ?? ''))
// CnBaseUrlPresets 的 platform prop 是平台字面量联合类型,模板里不能写
// `as` 断言(其中的 `|` 会被 eslint 误判为 Vue2 filter 语法),经此 computed 传递。
const cnPresetPlatform = computed
(() => {
@@ -3403,15 +3438,18 @@ const cnPresetPlatform = computed(() => {
}
return 'kimi'
})
-const adaptivePresetPlatform = computed(() => {
- if (props.account?.platform === 'opencode_go') return 'opencode_go'
+const adaptivePresetPlatform = computed(() => {
+ if (isCNApiKeyAccount.value) return props.account!.platform
return cnPresetPlatform.value
})
const editApiProtocol = ref('adaptive')
const editOpenCodeGoProtocolRules = ref(cloneOpenCodeGoProtocolRules())
-const editAccountMode = ref('payg')
+// 多协议供应商(国产厂商与走通用表单的供应商)的接入模式;OpenCode 用 editOpenCodeAccountMode。
+const editAccountMode = ref('payg')
const editOpenCodeAccountMode = ref('go')
-function currentOpenCodeOrCNMode(): CnAccountMode | OpenCodeAccountMode {
+// 国产厂商的接入模式只有 payg / coding。
+const cnPresetMode = computed(() => (editAccountMode.value === 'coding' ? 'coding' : 'payg'))
+function currentOpenCodeOrCNMode(): string {
return props.account?.platform === 'opencode_go' ? editOpenCodeAccountMode.value : editAccountMode.value
}
// 智谱团队版 Coding Plan:组织/项目 ID,写入 credentials 供额度探测切换团队端点
@@ -3439,25 +3477,22 @@ const cnAccountModeOptions = computed>(() => {
- const opts: Array<{ value: CnApiProtocol; labelKey: string }> = [
- { value: 'adaptive', labelKey: 'adaptive' },
- { value: 'chat_completions', labelKey: 'chatCompletions' },
- { value: 'anthropic', labelKey: 'anthropic' }
- ]
- if (cnSupportsNativeResponses(props.account?.platform ?? '')) {
- opts.push({ value: 'responses', labelKey: 'responses' })
- }
- return opts
-})
-const editAdaptiveProtocolOptions = computed>(() => {
- const opts: Array<{ value: CnNativeApiProtocol; labelKey: string }> = [
- { value: 'chat_completions', labelKey: 'chatCompletions' },
- { value: 'anthropic', labelKey: 'anthropic' }
- ]
- if (cnSupportsNativeResponses(props.account?.platform ?? '')) opts.push({ value: 'responses', labelKey: 'responses' })
- return opts
-})
+const NATIVE_PROTOCOL_LABEL_KEYS: Record = {
+ chat_completions: 'chatCompletions',
+ anthropic: 'anthropic',
+ responses: 'responses'
+}
+// 当前供应商与接入模式提供原生端点的协议(profile 中有默认基址的协议)。
+const editAdaptiveProtocolOptions = computed>(() =>
+ providerNativeProtocols(props.account?.platform ?? '', currentOpenCodeOrCNMode()).map(value => ({
+ value,
+ labelKey: NATIVE_PROTOCOL_LABEL_KEYS[value]
+ }))
+)
+const cnProtocolOptions = computed>(() => [
+ { value: 'adaptive', labelKey: 'adaptive' },
+ ...editAdaptiveProtocolOptions.value
+])
watch(editApiProtocol, (protocol, previousProtocol) => {
if (!isCNApiKeyAccount.value || syncingForm.value) return
if (protocol === 'adaptive') {
@@ -3481,12 +3516,20 @@ watch(editApiProtocol, (protocol, previousProtocol) => {
watch(editAccountMode, (mode, previousMode) => {
if (!isCNApiKeyAccount.value || syncingForm.value) return
if (props.account?.platform === 'opencode_go') return
- // deepseek 无 coding 套餐:防御性回退(UI 已隐藏该选项)。
- const effectiveMode = props.account!.platform === 'deepseek' && mode === 'coding' ? 'payg' : mode
+ // 供应商没有的接入模式(如 deepseek 无 coding 套餐)防御性回退默认模式(UI 已隐藏该选项)。
+ const effectiveMode = resolveProviderAccountMode(props.account!.platform, mode)
if (effectiveMode !== mode) {
editAccountMode.value = effectiveMode
return
}
+ if (providerRoutesByModel(props.account!.platform)) {
+ const previousRules = JSON.stringify(defaultProviderProtocolRules(props.account!.platform, previousMode))
+ if (JSON.stringify(editOpenCodeGoProtocolRules.value) === previousRules) {
+ editOpenCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(
+ defaultProviderProtocolRules(props.account!.platform, mode)
+ )
+ }
+ }
if (editApiProtocol.value === 'adaptive') {
const previousDefaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, previousMode)
const nextDefaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, mode)
@@ -4027,14 +4070,10 @@ const defaultBaseUrl = computed(() => {
if (props.account?.platform === 'openai') return 'https://api.openai.com'
if (props.account?.platform === 'gemini') return 'https://generativelanguage.googleapis.com'
if (props.account?.platform === 'grok') return 'https://api.x.ai/v1'
+ if (props.account?.platform === 'typesafe') return 'https://api.typesafe.ai'
// CN 供应商:按当前模式/协议回落到官方预设(清空输入框提交时使用),
// 不能落到 anthropic 默认值(会被当 CC base 拼出错误端点)。
- if (
- props.account?.platform === 'kimi' ||
- props.account?.platform === 'zhipu' ||
- props.account?.platform === 'deepseek' ||
- props.account?.platform === 'opencode_go'
- ) {
+ if (props.account && isMultiProtocolApiKeyPlatform(props.account.platform)) {
return defaultCNBaseUrl(props.account.platform, currentOpenCodeOrCNMode(), editApiProtocol.value)
}
return 'https://api.anthropic.com'
@@ -4419,11 +4458,13 @@ const syncFormFromAccount = (newAccount: Account | null) => {
const credentials = newAccount.credentials as Record
// 国产供应商:读取 account_mode 与 api_protocol 作为可编辑初始值
// (编辑弹窗允许修正两者,用于修复早期存错默认值的账号)。
- if (isCNProviderPlatform(newAccount.platform) || newAccount.platform === 'opencode_go') {
+ if (isMultiProtocolApiKeyPlatform(newAccount.platform)) {
if (newAccount.platform === 'opencode_go') {
editOpenCodeAccountMode.value = resolveOpenCodeAccountMode(credentials.account_mode)
- } else {
+ } else if (isCNProviderPlatform(newAccount.platform)) {
editAccountMode.value = credentials.account_mode === 'coding' ? 'coding' : 'payg'
+ } else {
+ editAccountMode.value = resolveProviderAccountMode(newAccount.platform, credentials.account_mode)
}
const storedProtocol = credentials.api_protocol
editApiProtocol.value =
@@ -4433,7 +4474,7 @@ const syncFormFromAccount = (newAccount: Account | null) => {
storedProtocol === 'responses'
? storedProtocol
: 'chat_completions'
- if (!cnSupportsNativeResponses(newAccount.platform) && editApiProtocol.value === 'responses') {
+ if (!cnSupportsNativeResponses(newAccount.platform, currentOpenCodeOrCNMode()) && editApiProtocol.value === 'responses') {
editApiProtocol.value = 'chat_completions'
}
const adaptiveDefaults = defaultCNAdaptiveBaseUrls(newAccount.platform, currentOpenCodeOrCNMode())
@@ -4472,10 +4513,10 @@ const syncFormFromAccount = (newAccount: Account | null) => {
editZhipuOrganization.value = typeof credentials.zhipu_organization === 'string' ? credentials.zhipu_organization : ''
editZhipuProject.value = typeof credentials.zhipu_project === 'string' ? credentials.zhipu_project : ''
}
- if (newAccount.platform === 'opencode_go') {
+ if (providerRoutesByModel(newAccount.platform)) {
editOpenCodeGoProtocolRules.value =
parseOpenCodeGoProtocolRules(credentials.protocol_rules) ??
- cloneOpenCodeGoProtocolRules(defaultOpenCodeProtocolRules(editOpenCodeAccountMode.value))
+ cloneOpenCodeGoProtocolRules(defaultProviderProtocolRules(newAccount.platform, currentOpenCodeOrCNMode()))
}
}
const platformDefaultUrl =
@@ -4485,10 +4526,9 @@ const syncFormFromAccount = (newAccount: Account | null) => {
? 'https://generativelanguage.googleapis.com'
: newAccount.platform === 'grok'
? 'https://api.x.ai/v1'
- : newAccount.platform === 'kimi' ||
- newAccount.platform === 'zhipu' ||
- newAccount.platform === 'deepseek' ||
- newAccount.platform === 'opencode_go'
+ : newAccount.platform === 'typesafe'
+ ? 'https://api.typesafe.ai'
+ : isMultiProtocolApiKeyPlatform(newAccount.platform)
? defaultCNBaseUrl(newAccount.platform, currentOpenCodeOrCNMode(), editApiProtocol.value)
: 'https://api.anthropic.com'
editBaseUrl.value = isCNApiKeyAccount.value && editApiProtocol.value === 'adaptive'
@@ -5241,7 +5281,7 @@ const handleSubmit = async () => {
} else {
delete newCredentials.api_base_urls
}
- if (props.account.platform === 'opencode_go') {
+ if (providerRoutesByModel(props.account.platform)) {
applyOpenCodeGoProtocolRules(newCredentials, editOpenCodeGoProtocolRules.value, 'edit')
}
// 智谱团队版 Coding Plan:组织/项目 ID 写入凭据(非空才写,清空即移除回落个人版路径)
diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue
index d1e7e557c..d953c21ce 100644
--- a/frontend/src/components/account/ModelWhitelistSelector.vue
+++ b/frontend/src/components/account/ModelWhitelistSelector.vue
@@ -154,6 +154,7 @@ import { useClipboard } from '@/composables/useClipboard'
import ModelIcon from '@/components/common/ModelIcon.vue'
import Icon from '@/components/icons/Icon.vue'
import { allModels, getModelsByPlatform } from '@/composables/useModelWhitelist'
+import { supportsUpstreamModelSync } from '@/constants/platformCatalog'
const { t } = useI18n()
@@ -201,25 +202,13 @@ const normalizedPlatforms = computed(() => {
)
})
-const upstreamSyncPlatforms = new Set([
- 'anthropic',
- 'openai',
- 'gemini',
- 'antigravity',
- 'grok',
- 'kimi',
- 'zhipu',
- 'deepseek',
- 'minimax',
- 'opencode_go'
-])
const canSyncUpstream = computed(() => {
if (props.accountId) {
if (normalizedPlatforms.value.length === 0) return true
- return normalizedPlatforms.value.some(platform => upstreamSyncPlatforms.has(platform.toLowerCase()))
+ return normalizedPlatforms.value.some(supportsUpstreamModelSync)
}
if (props.syncCredentials) {
- return upstreamSyncPlatforms.has(props.syncCredentials.platform.toLowerCase())
+ return supportsUpstreamModelSync(props.syncCredentials.platform)
}
return false
})
@@ -301,8 +290,7 @@ const fillRelated = () => {
}
const syncUpstreamModels = async () => {
- if (isSyncingUpstream.value) return
- if (!props.accountId && !props.syncCredentials) return
+ if (isSyncingUpstream.value || !canSyncUpstream.value) return
isSyncingUpstream.value = true
try {
diff --git a/frontend/src/components/account/OpenCodeGoProtocolRulesEditor.vue b/frontend/src/components/account/OpenCodeGoProtocolRulesEditor.vue
index b35037ad6..15922c21e 100644
--- a/frontend/src/components/account/OpenCodeGoProtocolRulesEditor.vue
+++ b/frontend/src/components/account/OpenCodeGoProtocolRulesEditor.vue
@@ -12,41 +12,55 @@
{{ t('admin.accounts.opencodeGo.protocolRules.hint') }}
*
- {{ t('admin.accounts.opencodeGo.protocolRules.fallback') }}
+ {{ t(`admin.accounts.opencodeGo.protocolRules.${hasModelCatalog ? 'catalogFallback' : 'fallback'}`) }}
{{ t('usage.rate') }}
- {{ formatMultiplier(tooltipData?.rate_multiplier || 1) }}x
+ {{ formatMultiplier(tooltipData?.rate_multiplier ?? 1) }}x
{{ t('usage.original') }}
@@ -547,6 +550,7 @@ import {
LATENCY_TEXT_CLASSES,
durationSeverity,
firstTokenSeverity,
+ formatUsageOutputRate,
} from '@/utils/latencyHealth'
import {
BILLING_MODE_TOKEN,
diff --git a/frontend/src/components/admin/usage/__tests__/UsageCleanupDialog.spec.ts b/frontend/src/components/admin/usage/__tests__/UsageCleanupDialog.spec.ts
new file mode 100644
index 000000000..70f526af4
--- /dev/null
+++ b/frontend/src/components/admin/usage/__tests__/UsageCleanupDialog.spec.ts
@@ -0,0 +1,60 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
+import UsageCleanupDialog from '../UsageCleanupDialog.vue'
+import Pagination from '@/components/common/Pagination.vue'
+
+const { listCleanupTasks, showError } = vi.hoisted(() => ({ listCleanupTasks: vi.fn(), showError: vi.fn() }))
+vi.mock('@/components/admin/usage/UsageFilters.vue', () => ({ default: { template: '
' } }))
+vi.mock('@/api/admin/usage', () => ({ adminUsageAPI: { listCleanupTasks } }))
+vi.mock('@/stores/app', () => ({ useAppStore: () => ({ showError }) }))
+vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
+enableAutoUnmount(afterEach)
+beforeEach(() => { vi.clearAllMocks(); vi.spyOn(console, 'error').mockImplementation(() => {}) })
+afterEach(() => { vi.restoreAllMocks() })
+const page = (number: number) => ({ items: [{ id: number, status: 'succeeded', deleted_rows: number, filters: {} }], total: 15, page: number, page_size: 5 })
+async function openDialog() {
+ listCleanupTasks.mockResolvedValueOnce(page(1))
+ const wrapper = mount(UsageCleanupDialog, {
+ props: { show: false, filters: {}, startDate: '2026-09-01', endDate: '2026-09-02' },
+ global: { stubs: { BaseDialog: { template: '
' }, UsageFilters: true, ConfirmDialog: true, Pagination: true } },
+ })
+ await wrapper.setProps({ show: true })
+ await flushPromises()
+ return wrapper
+}
+
+describe('cleanup task pagination', () => {
+ it.each(['success', 'failure'])('ignores an older page request that completes with %s', async (outcome) => {
+ const wrapper = await openDialog()
+ let resolve!: (value: object) => void
+ let reject!: (error: Error) => void
+ listCleanupTasks.mockImplementationOnce(() => new Promise((res, rej) => { resolve = res; reject = rej }))
+ wrapper.findComponent(Pagination).vm.$emit('update:page', 2)
+ await flushPromises()
+ listCleanupTasks.mockResolvedValueOnce(page(3))
+ wrapper.findComponent(Pagination).vm.$emit('update:page', 3)
+ await flushPromises()
+ if (outcome === 'success') resolve(page(2))
+ else reject(new Error('old failure'))
+ await flushPromises()
+ expect(wrapper.findComponent(Pagination).props('page')).toBe(3)
+ expect(wrapper.text()).toContain('#3')
+ expect(showError).not.toHaveBeenCalled()
+ })
+
+ it('ignores a pending result after the dialog is closed and reopened', async () => {
+ const wrapper = await openDialog()
+ let resolve!: (value: object) => void
+ listCleanupTasks.mockImplementationOnce(() => new Promise(res => { resolve = res }))
+ wrapper.findComponent(Pagination).vm.$emit('update:page', 2)
+ await flushPromises()
+ await wrapper.setProps({ show: false })
+ listCleanupTasks.mockResolvedValueOnce(page(1))
+ await wrapper.setProps({ show: true })
+ await flushPromises()
+ resolve(page(2))
+ await flushPromises()
+ expect(wrapper.findComponent(Pagination).props('page')).toBe(1)
+ expect(wrapper.text()).toContain('#1')
+ })
+})
diff --git a/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts b/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts
index d915fa4c4..35a31013e 100644
--- a/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts
+++ b/frontend/src/components/admin/usage/__tests__/UsageTable.spec.ts
@@ -16,9 +16,24 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
import { mount } from '@vue/test-utils'
import { nextTick } from 'vue'
+import en from '@/i18n/locales/en/admin/resources'
+import zh from '@/i18n/locales/zh/admin/resources'
import UsageTable from '../UsageTable.vue'
+let locale: 'en' | 'zh' = 'en'
+const localizedMessages: Record<'en' | 'zh', Record
> = {
+ en: {
+ 'admin.usage.longContext': en.usage.longContext,
+ 'admin.usage.longContextPricingTooltip': en.usage.longContextPricingTooltip,
+ },
+ zh: {
+ 'admin.usage.longContext': zh.usage.longContext,
+ 'admin.usage.longContextPricingTooltip': zh.usage.longContextPricingTooltip,
+ },
+}
+
const messages: Record = {
+ 'usage.outputTps': 'Output TPS',
'admin.usage.userDeletedBadge': 'Deleted',
'usage.costDetails': 'Cost Breakdown',
'admin.usage.inputCost': 'Input Cost',
@@ -78,7 +93,7 @@ vi.mock('vue-i18n', async () => {
return {
...actual,
useI18n: () => ({
- t: (key: string) => messages[key] ?? key,
+ t: (key: string) => localizedMessages[locale][key] ?? messages[key] ?? key,
}),
}
})
@@ -87,11 +102,12 @@ const DataTableStub = {
props: ['data'],
template: `
-
+
+
@@ -129,7 +145,22 @@ const baseImageRow = {
}
describe('admin UsageTable tooltip', () => {
+ it('shows output TPS in the latency cell using total duration', () => {
+ const row = { ...baseImageRow, image_count: 0, billing_mode: 'token', output_tokens: 1000, duration_ms: 20_000, first_token_ms: 10_000 }
+ const wrapper = mount(UsageTable, {
+ props: {
+ data: [row, { ...row, request_id: 'no-duration', duration_ms: null }, { ...row, request_id: 'image', image_count: 1 }],
+ loading: false,
+ columns: [{ key: 'latency', label: 'Latency' }],
+ },
+ global: { stubs: { DataTable: DataTableStub, EmptyState: true, Icon: true, Teleport: true } },
+ })
+ expect(wrapper.findAll('[data-testid="output-tps"]').map(cell => cell.text())).toEqual(['50.0 tok/s', '—', '—'])
+ expect(wrapper.text()).toContain('Output TPS')
+ })
+
beforeEach(() => {
+ locale = 'en'
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({
x: 0,
y: 0,
@@ -143,7 +174,11 @@ describe('admin UsageTable tooltip', () => {
} as DOMRect)
})
- it('marks only usage rows that actually applied long-context billing', () => {
+ it.each([
+ ['en', 'Long context', 'Long-context pricing was applied. Input and output rates depend on the pricing tier, not a uniform multiplier.'],
+ ['zh', '长上下文', '已应用长上下文计费。输入和输出费率取决于定价档位,并非统一倍率。'],
+ ] as const)('marks only applied long-context billing with localized text in %s', (language, label, tooltip) => {
+ locale = language
const wrapper = mount(UsageTable, {
props: {
data: [
@@ -157,6 +192,10 @@ describe('admin UsageTable tooltip', () => {
request_id: 'req-long-context-disabled',
long_context_billing_applied: false,
},
+ {
+ ...baseImageRow,
+ request_id: 'req-long-context-absent',
+ },
],
loading: false,
columns: [],
@@ -172,7 +211,12 @@ describe('admin UsageTable tooltip', () => {
})
expect(wrapper.findAll('[data-testid="long-context-billing-marker"]')).toHaveLength(1)
- expect(wrapper.get('[data-testid="long-context-billing-marker"]').text()).toBe('x2')
+ const marker = wrapper.get('[data-request-id="req-long-context-enabled"] [data-testid="long-context-billing-marker"]')
+ expect(marker.text()).toBe(label)
+ expect(marker.attributes('title')).toBe(tooltip)
+ expect(wrapper.find('[data-request-id="req-long-context-disabled"] [data-testid="long-context-billing-marker"]').exists()).toBe(false)
+ expect(wrapper.find('[data-request-id="req-long-context-absent"] [data-testid="long-context-billing-marker"]').exists()).toBe(false)
+ expect(wrapper.text()).not.toContain('x2')
})
it('keeps the request type badge and adds a separate badge only for native compaction rows', () => {
@@ -225,6 +269,22 @@ describe('admin UsageTable tooltip', () => {
expect(wrapper.get('[data-testid="native-compaction-badge"]').text()).toBe('Compaction')
})
+ it.each([
+ [0, '0.0x'],
+ [0.5, '0.50x'],
+ [undefined, '1.00x'],
+ ])('shows the stored user rate %s in cost details', async (rate, expected) => {
+ const wrapper = mount(UsageTable, {
+ props: { data: [{ ...baseImageRow, rate_multiplier: rate }], loading: false, columns: [] },
+ global: { stubs: { DataTable: DataTableStub, EmptyState: true, Icon: true, Teleport: true } },
+ })
+ const triggers = wrapper.findAll('.group.relative')
+ await triggers[triggers.length - 1].trigger('mouseenter')
+ const rateLabel = wrapper.get('.fixed').findAll('span').find(span => span.text() === 'Rate')!
+ expect(rateLabel.element.parentElement?.textContent).toContain(expected)
+ wrapper.unmount()
+ })
+
it('shows service tier and billing breakdown in cost tooltip', async () => {
const row = {
request_id: 'req-admin-1',
diff --git a/frontend/src/components/admin/user/BulkEditUserModal.vue b/frontend/src/components/admin/user/BulkEditUserModal.vue
index d511dff2f..d38399a9c 100644
--- a/frontend/src/components/admin/user/BulkEditUserModal.vue
+++ b/frontend/src/components/admin/user/BulkEditUserModal.vue
@@ -93,6 +93,7 @@
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { adminAPI } from '@/api/admin'
+import { extractApiErrorMessage } from '@/utils/apiError'
import type { BatchUpdateUserLimitsRequest } from '@/api/admin/users'
import { useAppStore } from '@/stores/app'
import BaseDialog from '@/components/common/BaseDialog.vue'
@@ -203,9 +204,7 @@ const handleSubmit = async () => {
emit('close')
} catch (error: any) {
appStore.showError(
- error.response?.data?.message
- || error.response?.data?.detail
- || t('admin.users.bulkLimits.failed')
+ extractApiErrorMessage(error, t('admin.users.bulkLimits.failed'))
)
} finally {
submitting.value = false
diff --git a/frontend/src/components/admin/user/UserPlatformQuotaModal.vue b/frontend/src/components/admin/user/UserPlatformQuotaModal.vue
index b1c5e799d..6fc3c8694 100644
--- a/frontend/src/components/admin/user/UserPlatformQuotaModal.vue
+++ b/frontend/src/components/admin/user/UserPlatformQuotaModal.vue
@@ -119,7 +119,7 @@ import { ref, reactive, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'
import { adminAPI } from '@/api/admin'
-import { PLATFORM_QUOTA_PLATFORMS } from '@/api/admin/users'
+import { platformQuotaPlatforms } from '@/api/admin/users'
import type { AdminUser, PlatformQuotaItem, PlatformQuotaPlatform, PlatformQuotaWindow } from '@/types'
import BaseDialog from '@/components/common/BaseDialog.vue'
@@ -175,7 +175,7 @@ function emptyRow(p: PlatformQuotaPlatform): QuotaRow {
function normalize(items: PlatformQuotaItem[]): QuotaRow[] {
const byPlatform = new Map
()
for (const it of items) byPlatform.set(it.platform, it)
- return PLATFORM_QUOTA_PLATFORMS.map((p) => {
+ return platformQuotaPlatforms().map((p) => {
const it = byPlatform.get(p)
if (!it) return emptyRow(p)
return {
@@ -204,7 +204,7 @@ async function load() {
savedConfigured.value = configuredPlatforms(data.platform_quotas || [])
} catch {
appStore.showError(t('admin.users.platformQuota.loadFailed'))
- quotas.value = PLATFORM_QUOTA_PLATFORMS.map(emptyRow)
+ quotas.value = platformQuotaPlatforms().map(emptyRow)
savedConfigured.value = new Set()
} finally {
loading.value = false
diff --git a/frontend/src/components/admin/user/__tests__/BulkEditUserModal.spec.ts b/frontend/src/components/admin/user/__tests__/BulkEditUserModal.spec.ts
index 1b0277e16..6f6bf9c57 100644
--- a/frontend/src/components/admin/user/__tests__/BulkEditUserModal.spec.ts
+++ b/frontend/src/components/admin/user/__tests__/BulkEditUserModal.spec.ts
@@ -59,6 +59,27 @@ describe('BulkEditUserModal', () => {
vi.restoreAllMocks()
})
+ it.each([
+ [{ message: 'Selected users are no longer available' }, 'Selected users are no longer available'],
+ [{ response: { data: { message: 'Legacy message' } } }, 'Legacy message'],
+ [{ response: { data: { detail: 'Legacy detail' } } }, 'Legacy detail'],
+ [{}, 'admin.users.bulkLimits.failed'],
+ ])('shows API error details and allows retry after failure', async (error, expected) => {
+ vi.spyOn(window, 'confirm').mockReturnValue(true)
+ batchUpdateLimits.mockRejectedValueOnce(error)
+ const wrapper = mountModal()
+ await wrapper.get('[data-test="enable-concurrency"]').trigger('click')
+ await wrapper.get('[data-test="concurrency-input"]').setValue('5')
+ await wrapper.get('form').trigger('submit')
+ await flushPromises()
+
+ expect(showError).toHaveBeenCalledWith(expected)
+ expect(wrapper.emitted('close')).toBeUndefined()
+ expect(wrapper.emitted('success')).toBeUndefined()
+ expect(wrapper.get('[data-test="submit"]').attributes('disabled')).toBeUndefined()
+ wrapper.unmount()
+ })
+
it('disables submission until at least one enabled field has a value', async () => {
const wrapper = mountModal()
diff --git a/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts b/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts
index 719e73cbd..534e16211 100644
--- a/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts
+++ b/frontend/src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts
@@ -75,7 +75,7 @@ beforeEach(() => {
})
describe('UserPlatformQuotaModal', () => {
- it.each([0, 4, 14])('does not turn a negative limit in input %s into unlimited', async (index) => {
+ it.each([0, 4, 14, 17])('does not turn a negative limit in input %s into unlimited', async (index) => {
const w = await mountAndOpen()
await w.findAll('input[type=number]')[index].setValue('-1')
await w.findAll('button').find(b => b.text() === 'admin.users.platformQuota.save')!.trigger('click')
@@ -101,12 +101,12 @@ describe('UserPlatformQuotaModal', () => {
expect(apiMocks.getPlatformQuotas).toHaveBeenCalledWith(99)
})
- it('renders all eleven supported platforms with empty limits', async () => {
+ it('renders all fourteen supported platforms with empty limits', async () => {
const w = await mountAndOpen()
const rows = w.findAll('tbody tr')
expect(rows.map(row => row.find('td').text())).toEqual([
'anthropic', 'openai', 'openai_bps', 'gemini', 'antigravity', 'grok',
- 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go',
+ 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'command_code', 'cline',
])
for (const row of rows) {
const inputs = row.findAll('input[type=number]')
@@ -116,11 +116,11 @@ describe('UserPlatformQuotaModal', () => {
w.unmount()
})
- it.each(['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go'] as const)(
+ it.each(['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'command_code', 'cline'] as const)(
'saves edits to %s without erasing existing platform limits', async (platform) => {
const existing: PlatformQuotaUpdateItem[] = [
{ platform: 'openai', daily_limit_usd: 10, weekly_limit_usd: 20, monthly_limit_usd: 100 },
- ...(['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go'] as const).map(p => ({
+ ...(['kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', 'command_code', 'cline'] as const).map(p => ({
platform: p, daily_limit_usd: 0, weekly_limit_usd: null, monthly_limit_usd: 50,
})),
]
@@ -137,7 +137,7 @@ describe('UserPlatformQuotaModal', () => {
: item)
expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledTimes(1)
expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledWith(99, expect.arrayContaining(expected))
- expect(apiMocks.updatePlatformQuotas.mock.calls[0][1]).toHaveLength(11)
+ expect(apiMocks.updatePlatformQuotas.mock.calls[0][1]).toHaveLength(14)
expect(w.emitted('success')).toHaveLength(1)
w.unmount()
},
@@ -152,13 +152,13 @@ describe('UserPlatformQuotaModal', () => {
})
const w = await mountAndOpen()
const inputs = w.findAll('input[type=number]')
- // 11 platforms × 3 windows = 33 inputs
- expect(inputs.length).toBe(33)
+ // 14 platforms × 3 windows = 42 inputs
+ expect(inputs.length).toBe(42)
// 第一个 input 是 anthropic.daily = 10
expect((inputs[0].element as HTMLInputElement).value).toBe('10')
})
- it('保存提交完整 11 platform payload', async () => {
+ it('保存提交完整 14 platform payload', async () => {
apiMocks.getPlatformQuotas.mockResolvedValueOnce({
platform_quotas: [
{ platform: 'openai', daily_limit_usd: null, weekly_limit_usd: 20, monthly_limit_usd: null,
@@ -175,7 +175,7 @@ describe('UserPlatformQuotaModal', () => {
expect(apiMocks.updatePlatformQuotas).toHaveBeenCalledTimes(1)
const [uid, payload] = apiMocks.updatePlatformQuotas.mock.calls[0]
expect(uid).toBe(99)
- expect(payload).toHaveLength(11) // 11 platforms always submitted
+ expect(payload).toHaveLength(14) // 14 platforms always submitted
const openai = payload.find((p: any) => p.platform === 'openai')
expect(openai.weekly_limit_usd).toBe(20)
})
@@ -240,7 +240,7 @@ describe('UserPlatformQuotaModal', () => {
it('未配置限额的平台重置按钮禁用并提示不可用', async () => {
const w = await mountAndOpen()
const resetBtns = w.findAll('button').filter((b) => b.text() === '↻')
- expect(resetBtns.length).toBe(33) // 11 平台 × 3 窗口
+ expect(resetBtns.length).toBe(42) // 14 平台 × 3 窗口
for (const b of resetBtns) {
expect((b.element as HTMLButtonElement).disabled).toBe(true)
expect(b.attributes('title')).toBe('admin.users.platformQuota.reset.unavailable')
diff --git a/frontend/src/components/auth/PendingOAuthCreateAccountForm.vue b/frontend/src/components/auth/PendingOAuthCreateAccountForm.vue
index 5a8ed84fe..8c97d38b8 100644
--- a/frontend/src/components/auth/PendingOAuthCreateAccountForm.vue
+++ b/frontend/src/components/auth/PendingOAuthCreateAccountForm.vue
@@ -168,6 +168,7 @@ const captchaEnabled = computed(
)
let countdownTimer: ReturnType | null = null
+let disposed = false
watch(
() => props.initialEmail,
@@ -288,6 +289,7 @@ async function handleSendCode() {
tencent_captcha_ticket: tencentCaptchaEnabled.value ? turnstileToken.value : undefined,
tencent_captcha_randstr: tencentCaptchaEnabled.value ? tencentCaptchaRandstr.value : undefined
})
+ if (disposed) return
sendCodeSuccess.value = true
startCountdown(response.countdown)
} catch (error: unknown) {
@@ -373,6 +375,7 @@ onMounted(async () => {
})
onUnmounted(() => {
+ disposed = true
clearCountdown()
})
diff --git a/frontend/src/components/auth/__tests__/PendingOAuthCreateAccountForm.spec.ts b/frontend/src/components/auth/__tests__/PendingOAuthCreateAccountForm.spec.ts
index a1a5841ea..b006a4a3f 100644
--- a/frontend/src/components/auth/__tests__/PendingOAuthCreateAccountForm.spec.ts
+++ b/frontend/src/components/auth/__tests__/PendingOAuthCreateAccountForm.spec.ts
@@ -51,6 +51,30 @@ describe('PendingOAuthCreateAccountForm', () => {
})
})
+ it('does not restart the code cooldown after switching away during a send', async () => {
+ vi.useFakeTimers()
+ let finish!: (value: { countdown: number }) => void
+ sendPendingOAuthVerifyCode.mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const wrapper = mount(PendingOAuthCreateAccountForm, {
+ props: { testIdPrefix: 'oidc', initialEmail: 'user@example.com', isSubmitting: false },
+ global: { stubs: { TurnstileWidget: true } },
+ })
+ try {
+ await flushPromises()
+ await wrapper.get('[data-testid="oidc-create-account-send-code"]').trigger('click')
+ await flushPromises()
+ expect(sendPendingOAuthVerifyCode).toHaveBeenCalledTimes(1)
+ wrapper.unmount()
+ finish({ countdown: 60 })
+ await flushPromises()
+ expect(vi.getTimerCount()).toBe(0)
+ } finally {
+ wrapper.unmount()
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ }
+ })
+
it('acquires separate proofs for pending OAuth send-code and create-account', async () => {
getPublicSettings.mockResolvedValue({
email_verify_enabled: true,
diff --git a/frontend/src/components/common/AnnouncementBell.vue b/frontend/src/components/common/AnnouncementBell.vue
index e80e449f2..afe06ae15 100644
--- a/frontend/src/components/common/AnnouncementBell.vue
+++ b/frontend/src/components/common/AnnouncementBell.vue
@@ -373,14 +373,17 @@ function closeDetail() {
async function markAsRead(id: number) {
try {
- await announcementStore.markAsRead(id)
+ const marked = await announcementStore.markAsRead(id)
+ if (!marked) appStore.showError(t('common.unknownError'))
+ return marked
} catch (err: any) {
appStore.showError(err?.message || t('common.unknownError'))
+ return false
}
}
async function markAsReadAndClose(id: number) {
- await markAsRead(id)
+ if (!await markAsRead(id)) return
appStore.showSuccess(t('announcements.markedAsRead'))
closeDetail()
}
diff --git a/frontend/src/components/common/BaseDialog.vue b/frontend/src/components/common/BaseDialog.vue
index c3ae642dc..dda0b5e12 100644
--- a/frontend/src/components/common/BaseDialog.vue
+++ b/frontend/src/components/common/BaseDialog.vue
@@ -115,7 +115,7 @@ const handleClose = () => {
}
const handleEscape = (event: KeyboardEvent) => {
- if (props.show && props.closeOnEscape && event.key === 'Escape') {
+ if (props.show && props.closeOnEscape && event.key === 'Escape' && [...openDialogs].pop() === dialogId) {
emit('close')
}
}
diff --git a/frontend/src/components/common/PlatformIcon.vue b/frontend/src/components/common/PlatformIcon.vue
index 26eb0e880..92abcb807 100644
--- a/frontend/src/components/common/PlatformIcon.vue
+++ b/frontend/src/components/common/PlatformIcon.vue
@@ -54,6 +54,23 @@
d="M23.748 4.651c-.254-.124-.364.113-.512.233-.051.04-.094.09-.137.137-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.155-.708-.311-.955-.65-.172-.24-.219-.509-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.094.172.187.129.323-.082.28-.18.553-.266.833-.055.179-.137.218-.328.14a5.5 5.5 0 0 1-1.737-1.179c-.857-.828-1.631-1.743-2.597-2.46a12 12 0 0 0-.689-.47c-.985-.957.13-1.743.387-1.836.27-.098.094-.433-.778-.428-.872.003-1.67.295-2.687.685a3 3 0 0 1-.465.136a9.6 9.6 0 0 0-2.883-.101c-1.885.21-3.39 1.1-4.497 2.622C.082 8.776-.231 10.854.152 13.02c.403 2.284 1.568 4.175 3.36 5.653 1.857 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.132-.284 4.994-1.86.47.234.962.328 1.78.398.629.058 1.235-.031 1.705-.129.735-.155.684-.836.418-.961-2.155-1.004-1.682-.595-2.112-.926 1.095-1.295 2.768-3.598 3.284-6.733.05-.346.115-.834.108-1.114-.004-.171.035-.238.23-.257a4.2 4.2 0 0 0 1.545-.475c1.397-.763 1.96-2.016 2.093-3.517.02-.23-.004-.467-.247-.588M11.58 18.168c-2.088-1.642-3.101-2.183-3.52-2.16-.39.024-.32.472-.234.763.09.288.207.487.371.74.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.168-1.361-.801-2.5-1.86-3.301-3.306-.775-1.393-1.225-2.888-1.299-4.482-.02-.385.094-.522.477-.592a4.7 4.7 0 0 1 1.53-.038c2.131.311 3.946 1.264 5.467 2.774.868.86 1.525 1.887 2.202 2.89.72 1.066 1.494 2.082 2.48 2.915.348.291.626.513.892.677-.802.09-2.14.109-3.055-.615zm1.001-6.44a.306.306 0 0 1 .415-.287a.3.3 0 0 1 .113.074a.3.3 0 0 1 .086.214c0 .17-.136.307-.308.307a.303.303 0 0 1-.306-.307m3.11 1.596c-.2.081-.4.151-.591.16a1.25 1.25 0 0 1-.798-.254c-.274-.23-.47-.358-.551-.758a1.7 1.7 0 0 1 .015-.588c.07-.327-.007-.537-.238-.727-.188-.156-.426-.199-.689-.199a.6.6 0 0 1-.254-.078a.253.253 0 0 1-.114-.358a1 1 0 0 1 .192-.21c.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.392.451.462.576.685.915.176.264.336.536.446.848.066.194-.02.353-.25.45"
/>
+
+
+
+