Compare commits

..
Author SHA1 Message Date
shaw 2ad419706d fix(accounts): keep older proxy counts when a newer refresh fails
Review follow-up for the proxy account count refresh:

- Apply a proxy list response only if it is newer than the last applied
  one. Previously a failed newer refresh also discarded a slower older
  success, which could leave the selector empty.
- Refresh proxy counts on every `created` event. Batch creation can
  partially succeed and keep the dialog open, so opening the dialog was
  not enough.
- Test ProxySelector with the real vue-i18n and locale files instead of
  a hand-written mock of the plural rule.
2026-11-27 14:39:04 +08:00
shaw fd2f9770a2 fix(accounts): show proxy account counts on the right and keep them fresh
The proxy selector in the account dialogs showed a bare number next to
the proxy name, and AccountsView loaded the counts only once on mount,
so they went stale after accounts were created, deleted, imported or
rebound.

- Show "N 个账号" / "N account(s)" on the right of each proxy row, before
  the test button, with a tooltip.
- Reload proxies with counts whenever the create, edit or bulk-edit
  dialog opens. A sequence guard drops out-of-order responses and a
  failed reload keeps the previous list.
2026-11-27 13:51:37 +08:00
Wesley Liddick dedeb65c1d Merge pull request #9107
feat(openai): 同步 Codex v0.172.0 内置基础提示词并补齐 5.6/6.0 模板
2026-11-27 10:32:46 +08:00
Wesley Liddick 212f5e5dcf Merge pull request #9105
fix(antigravity): honor group mcp_xml_inject in Claude transform options
2026-11-27 10:32:38 +08:00
Wesley Liddick 187d8e5bbf Merge pull request #9049
fix(gateway): report Anthropic thinking_tokens as reasoning_tokens
2026-11-27 10:32:30 +08:00
Wesley Liddick 8feae1b49c Merge pull request #9042
feat(usage): add toggleable username column to admin usage table and export
2026-11-27 10:32:22 +08:00
Wesley Liddick 3273ae9913 Merge pull request #9027
fix(frontend): theme the MCP consent dropdowns with the common Select
2026-11-27 10:32:14 +08:00
Wesley Liddick 07c52fe25b Merge pull request #9005
test(gateway): measure signed-history allocations in a child process
2026-11-27 10:32:06 +08:00
Wesley Liddick ca236afc8c Merge pull request #9001
fix(antigravity): skip SSE comment keepalives for js-genai < 1.32 (Gemini CLI)
2026-11-27 10:31:58 +08:00
Wesley Liddick 8ac5f4de71 Merge pull request #8987
fix(antigravity): honor final retry reset when cooling models
2026-11-27 10:31:50 +08:00
forgottener 6637b280aa fix(gateway): report Anthropic thinking_tokens as reasoning_tokens
Anthropic reports thinking tokens in usage.output_tokens_details.thinking_tokens,
a subset of output_tokens. AnthropicUsage had no such field, so Anthropic
accounts served through /v1/chat/completions and /v1/responses never exposed
reasoning_tokens.

Decode the field, carry it through the stream state and the buffered
ClaudeUsage merge (a reported value, even 0, replaces the previous one), and
emit it as Responses output_tokens_details.reasoning_tokens, which the existing
Responses-to-Chat mapping turns into completion_tokens_details.reasoning_tokens.
Billing is unchanged.

Fixes #9048
2026-11-27 01:26:37 +08:00
Kripto c5622ce6cf feat(openai): 同步 Codex v0.172.0 内置基础提示词并补齐 5.6/6.0 模板
- 新增 gpt-5.6、gpt-6-sol、gpt-6-luna 内置基础提示词并接入 CodexBaseInstructionsForModel。
- 将 gpt-5.1、gpt-5.2、gpt-5.5、gpt-6-astra 及 gpt-6.1/gpt-6.2 描述文件中的提示词模板同步至 openai/codex rust-v0.172.0,保留既有模型 catalog 元数据不变。
- 补齐 CodexBaseInstructionsForModel 单元测试覆盖。
2026-11-26 03:52:33 -04:00
SipengXie2024 b5e9549c54 fix(antigravity): honor group mcp_xml_inject in Claude transform options 2026-11-26 04:35:01 +00:00
Wesley Liddick 81ce8356d9 Merge pull request #9094 from pood1e/feat/declare-image-input-models
feat(codex): let accounts declare image-input models
2026-11-26 12:06:32 +08:00
shaw 06e7a2ed4b Merge branch 'main' into feat/declare-image-input-models
# Conflicts:
#	backend/internal/service/openai_codex_models_service.go
2026-11-26 11:50:34 +08:00
Wesley Liddick eef63ee7cd Merge pull request #9099 from PMExtra/feat/channel-expose-response-model
feat(channel): 渠道支持向用户显示实际响应模型
2026-11-26 11:49:58 +08:00
Wesley Liddick 76d8d976d5 Merge pull request #9095 from pood1e/fix/anthropic-bridge-deepseek-default-effort
fix(openai): default DeepSeek effort to high in the Anthropic bridge
2026-11-26 11:49:45 +08:00
Wesley Liddick 3db5753641 Merge pull request #9093 from pood1e/feat/openai-chat-reasoning-content
feat(openai): let API-key accounts opt into reasoning_content on raw Chat Completions
2026-11-26 11:49:32 +08:00
Wesley Liddick 164d7056ed Merge pull request #9088 from PMExtra/feat/proxy-ip-checked-at
feat(proxy): 代理列表显示出口 IP 与最后检测时间
2026-11-26 11:49:18 +08:00
Wesley Liddick 7b2a5f5d48 Merge pull request #9087 from wucm667/fix/issue-9086-tooltip-scroll
fix(frontend): keep help tooltips aligned after scrolling
2026-11-26 11:49:05 +08:00
Wesley Liddick 821701e45b Merge pull request #9085 from adamcjm/fix/opencode-user-agent-version
fix(opencode): 上游 User-Agent 版本更新至 1.19.6 并支持环境变量覆盖
2026-11-26 11:48:52 +08:00
Wesley Liddick ab00fef989 Merge pull request #9084 from r266-tech/codex/command-code-image-modalities
fix(codex): include Command Code image capabilities in model catalogs
2026-11-26 11:48:38 +08:00
Wesley Liddick bb7fb85cd5 Merge pull request #9081 from bin-bash-dev/fix/sse-keepalive-retry-accounting
fix(openai): account SSE keepalive bytes across failover attempts
2026-11-26 11:48:25 +08:00
Wesley Liddick e55f9db056 Merge pull request #9080 from bin-bash-dev/fix/content-moderation-lazy-queue
fix(moderation): allocate async moderation queue on demand
2026-11-26 11:48:11 +08:00
Wesley Liddick 3dd9a24957 Merge pull request #9079 from wucm667/fix/issue-9077-versionless-identity
fix(antigravity): handle versionless system identity openers
2026-11-26 11:47:57 +08:00
Wesley Liddick 2c5325ace8 Merge pull request #9076 from r266-tech/codex/optional-antigravity-stream-summaries
feat(antigravity): let upstream choose Gemini stream summaries
2026-11-26 11:47:43 +08:00
Wesley Liddick be8dfee8b2 Merge pull request #9069 from wucm667/feat/issue-9066-proxy-account-count
fix(accounts): show proxy account counts in account dialogs
2026-11-26 11:47:30 +08:00
Wesley Liddick f3ea22ec91 Merge pull request #9064 from PMExtra/feat/account-upstream-error-stats
feat(accounts): 在账号今日统计和用量趋势中展示上游错误次数
2026-11-26 11:47:17 +08:00
Wesley Liddick 8ace90b8d0 Merge pull request #9060 from LagrangeQ/fix/gemini-empty-stream-usage
fix(gemini): preserve stream usage after empty metadata
2026-11-26 11:47:04 +08:00
Wesley Liddick 62b3fa1aac Merge pull request #9046 from alfadb/fix/zhipu-overload-429-short-cooldown
fix(ratelimit): 智谱平台过载 429 改用秒级冷却
2026-11-26 11:46:51 +08:00
Wesley Liddick a55adce0aa Merge pull request #9034 from r266-tech/codex/shorten-proxy-network-cooldown
fix(openai): recover sooner after transport reachability failures
2026-11-26 11:46:38 +08:00
Wesley Liddick d081e563f7 Merge pull request #9012 from Anankke/fix/toolname-stream-restore
fix(gateway): restore tool names split across stream deltas
2026-11-26 11:46:23 +08:00
Wesley Liddick 6f34149c15 Merge pull request #9004 from Anankke/fix/sticky-session-rebind-cas
fix(gateway): do not overwrite a sticky rebind after a long forward
2026-11-26 11:46:10 +08:00
Wesley Liddick ddc855a51d Merge pull request #8995 from r266-tech/codex/show-requester-in-ops-error-detail
fix(ops): show requester in request error details
2026-11-26 11:45:58 +08:00
Wesley Liddick e3eb96c0b5 Merge pull request #8994 from wucm667/fix/issue-8991-terminal-context
fix(openai): normalize standalone terminal context
2026-11-26 11:45:44 +08:00
Wesley Liddick 4ecec232d8 Merge pull request #8860 from Anankke/fix/account-usage-auto-refresh
fix(accounts): refetch Gemini usage when the account's quota tier changes
2026-11-26 11:45:30 +08:00
张屹峰 fc2471c2d5 feat(usage): add toggleable username column to admin usage table and export 2026-11-26 11:32:56 +08:00
PMExtraandClaude Opus 5.5 8c4336eb58 fix(usage): chain Localized on user usage DTO mapping line
TestUserFacingGroupDTOsAreLocalized statically requires every user-facing
dto.*FromService call to chain .Localized( on the same line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 01:01:21 +08:00
PMExtraandClaude Opus 5.5 a1c7be6e90 feat(channel): optionally show actual response model to users
Add a channel-level toggle (features_config.expose_response_model, off by
default). When enabled, regular users see the final response model next to
the requested model in their usage records; the intermediate mapping chain
stays admin-only.

- Channel.IsResponseModelExposed + ChannelService.ResponseModelExposedChannels
  read from the in-memory channel cache, so no extra DB queries
- User usage list/detail fill the new optional response_model field
  (upstream_response_model -> upstream_model -> model, omitted when equal
  to the requested model)
- Channel form toggle, UsageTable rendering and i18n

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:45:37 +08:00
pood1eandClaude Opus 5.5 2945ecf89b fix(openai): default DeepSeek effort to high in the Anthropic bridge
Without a client effort, the Anthropic bridge sends `medium`. DeepSeek's
reasoning scale is low/high/max, as the Codex manifest already declares,
and DeepSeek-V4.1 rejects `medium`. Every Anthropic-format request without
an explicit effort therefore failed on DeepSeek models. The bridge now
sends DeepSeek's default level instead. Explicit efforts, disabled thinking
and other models are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:40:19 -08:00
pood1eandClaude Opus 5.5 5c95c63e15 feat(codex): let accounts declare image-input models
The Codex manifest advertises image input from synced upstream metadata
or a few known model names. Multimodal models served by vLLM or SGLang
match neither, so Codex blocks image attachments for them. The new account
extra key `image_input_models` lists upstream model IDs that accept image
input, and the manifest honors it ahead of synced metadata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 05:52:27 -08:00
pood1eandClaude Opus 5.5 21a95dbaa8 feat(openai): let API-key accounts opt into reasoning_content on raw Chat Completions
vLLM and SGLang stream reasoning in `reasoning`, while DeepSeek-style
clients read `reasoning_content`. The raw Chat Completions path already
mirrors these fields for Ollama Cloud accounts. The new account extra key
`openai_chat_reasoning_content` enables the same normalization for other
OpenAI API-key accounts. Ollama Cloud keeps it unconditionally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 05:51:41 -08:00
wucm667 afd87f38be fix(frontend): keep help tooltips aligned after scrolling 2026-11-25 14:55:16 +08:00
PMExtraandClaude Opus 5.5 1ba1ae8ef0 feat(proxy): show exit IP and last check time in proxy list
- Expose latency_checked_at (from cached UpdatedAt) on admin proxy list
- Show exit IP under location and last check time under created_at
- Include region/city in quality check result
- Quality check now updates row latency/IP/location on failure too,
  matching the backend snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:27:06 +08:00
adam b3fdd01f0b fix(opencode): 上游 User-Agent 版本更新至 1.19.6 并支持环境变量覆盖
出站到 opencode.ai 的规范 User-Agent 一直硬编码为 opencode/1.0.0,已明显落后于
真实客户端(opencode-ai npm 包当前为 1.19.6)。上游按 opencode/<version> 格式
校验客户端身份,陈旧的版本号本身会成为可识别的特征。

- 默认版本号更新为 1.19.6,注释说明跟随 opencode-ai 最新发布
- 新增 OPENCODE_USER_AGENT_VERSION 环境变量覆盖,后续升级无需改代码
- 版本号按三段 semver 校验,非法或空值回退内置默认
- 补充 Normalize/Resolve 与 UA 格式的单元测试
2026-11-25 12:59:28 +08:00
r266-tech f90198a5ee fix(codex): include Command Code image capabilities in model catalogs 2026-11-25 12:50:23 +08:00
bin-bash-dev 1f5ca63440 fix(openai): account SSE keepalive bytes across failover attempts
Problem: on /v1/responses passthrough accounts with
gateway.stream_keepalive_interval enabled, a failover-eligible upstream
error (e.g. an overloaded `event: error` before any visible output) is
only failed over once. If the first attempt has already written a
keepalive comment, the next attempt that fails the same way is treated
as if semantic output had reached the client: the error is delivered as
response.failed and the remaining schedulable accounts are never tried.

Root cause: handleStreamingResponsePassthrough starts a new SSE
keepalive for every attempt, and startOpenAISSEKeepalive replaces the
instance stored on the gin.Context. Keepalive bytes were tracked per
instance, so OpenAICompactKeepaliveAdjustedWrittenSize subtracted only
the current instance's bytes from c.Writer.Size(); comments written by
an earlier attempt stayed in Size() and were counted as real output.
openAIStreamClientOutputStarted therefore reported output as started
and the passthrough stream stopped proposing failover.
StopOpenAICompactSSEKeepaliveCommitted had the same per-instance blind
spot and reported "not committed" when only an earlier instance had
committed the 200 response.

Fix: keep the keepalive byte count in a request-scoped atomic counter
stored on the gin.Context and shared by every keepalive instance of the
request (retries and nested starts). AdjustedWrittenSize subtracts the
cumulative count, and the committed check also reports true once any
keepalive of the request has written a comment. Single-keepalive
behaviour is unchanged.

Tests: a handler-level regression test drives the real Responses
handler with three passthrough accounts (the first attempt emits a real
keepalive and then fails over, the second fails immediately, the third
succeeds); on the previous code only accounts [1 2] are called and the
client receives response.failed. Service-level tests cover cumulative
accounting across restarts, the committed check after a previous
attempt, restarts without beats, and nested keepalives; they drive beats
manually instead of relying on timer scheduling.
2026-11-25 04:01:48 +08:00
bin-bash-dev fe72ddf1ae fix(moderation): allocate async moderation queue on demand
问题:NewContentModerationService 在构造时就执行
make(chan contentModerationTask, maxContentModerationQueueSize)。
maxContentModerationQueueSize=100000,单个任务 288 字节,因此每个实例一
构造就常驻约 28.8MB,与是否启用异步审核、是否有流量都无关。service 包测
试会创建数百个短生命周期实例,测试进程的提交内存随之涨到 GiB 级;生产上
任何额外构造的实例也要白白付出同样的代价。

根因:队列深度按允许的最大值预分配,而真正的丢弃判据
len(queue) >= cfg.QueueSize 只依赖运行期配置,并不需要预先占满容量。

修法:
- 构造函数不再创建队列,只标记 asyncQueueLazy;首次入队时按
  min(64, QueueSize) 创建,满且仍低于 QueueSize 时按 2 倍扩容(上限
  QueueSize),迁移已排队任务;运行期调大 QueueSize 也能继续扩容。
- 丢弃判据仍是 len >= QueueSize,丢弃计数与告警日志保持不变。
- 未经构造函数创建的零值服务入队仍是 no-op(不计数、不告警)。
- 队列创建/扩容时关闭并替换 asyncWake 广播唤醒 worker,阻塞在旧
  channel 上的 worker 会重新读取新队列,不空转、不漏取任务。
- GetStatus 与日志读取队列长度改为加锁读取,不会触发分配。

测试:
- content_moderation_queue_contract_test.go 只使用既有接口:构造后不预
  留队列;在独立子进程中测量 64 个空闲实例的堆增量(旧实现约
  28,803,490 字节/实例,修复后约 451 字节/实例,阈值 64KiB);
  QueueSize=8 时收 8 丢 12、记录路径同样受限、4096 全收且调大到 8192
  后继续接收;零值服务 no-op;真实 worker 并发消费 400 条记录不丢不重。
  结构与内存用例在修复前失败,其余语义用例修复前后均通过。
- content_moderation_queue_lazy_test.go 用 synctest 覆盖初始容量与扩容
  上限、多生产者/消费者恰好一次投递、扩容期间消费者持续读取、首次创建
  与替换队列时的唤醒、取消与空闲超时。
2026-11-25 03:56:32 +08:00
wucm667 2b836b7b7c fix(antigravity): handle versionless system identity openers 2026-11-25 02:44:44 +08:00
r266-tech 876f137d8f feat(antigravity): let upstream choose Gemini stream summaries 2026-11-25 01:15:18 +08:00
PMExtraandClaude Opus 5.5 8decae9779 feat(accounts): show upstream error counts in today stats and usage trend
Count provider-owned, non-business-limited rows in ops_error_logs per
account (same definition as the ops dashboard) and expose them as
`upstream_errors` on today stats and per-day account usage history.

- Today stats column shows today's upstream errors (highlighted when > 0).
- Usage statistics modal adds an upstream error trend line plus today and
  30-day totals; days with only errors are merged into the history.
- Counts are omitted when ops monitoring is disabled so the UI hides them
  instead of showing a misleading 0. Failover intermediate attempts are
  attributed only to the last failing account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:46:46 +08:00
wucm667 0c7d3ff58c fix(accounts): show proxy account counts in account dialogs 2026-11-24 18:42:21 +08:00
LagrangeQ 52b5d71d60 fix(gemini): preserve stream usage after empty metadata
Ignore usageMetadata without counters so a trailing placeholder cannot overwrite measured input, output, or cached tokens. Preserve explicit zero counters and add regression coverage for the Gemini native, Chat Completions, Messages, and stream collection paths.
2026-11-24 14:57:23 +08:00
github-actions[bot] 0f66714571 chore: sync VERSION to 0.2.25 [skip ci] 2026-11-24 03:21:26 +00:00
Wesley Liddick 348997267d Merge pull request #9052 from Wei-Shaw/feat/header-override-identity-variables
feat(accounts): 请求头覆写支持身份上报变量
2026-11-24 11:11:32 +08:00
shaw c5147eab16 fix(accounts): 身份上报变量审计修复
- request_id 可由客户端经 X-Request-ID 自带:代入前只保留字母数字与
  . _ -,其余替换为下划线并限长,防止在组合模板里伪造其它身份字段
- 模板不合法的存量条目不再被提前丢弃:应用时删除同名客户端头且不发送
- 错误记录中的上报请求头不再包含固定文本(可能是中转密钥),混合模板
  记为 "…name=value" 形态
- 模型列表/清单等跨用户共享缓存的请求不携带用户身份,避免缓存被打散
- 只改账号类型(不带 credentials)的更新同样校验变量使用
- 编辑器连点同一变量不再产生重名行
- 补充认证中间件到真实转发构建器的端到端用例
2026-11-24 10:56:25 +08:00
shaw 0f1e3c1f6a feat(accounts): 请求头覆写支持身份上报变量
API Key 账号的请求头覆写值可使用 {{user_id}} / {{api_key_id}} /
{{group_id}} / {{request_id}},转发时替换为本次请求的网关身份,便于
逐层定位到具体用户。

- 仅 api_key 账号解析变量;OAuth(含 Grok OAuth)保存时拒绝,运行时
  整条请求头不发送
- 变量取不到值(无用户上下文的后台请求)时整条不发送,同名的客户端
  请求头照样删除,防止伪造
- OpenAI WS 连接池按上报身份分桶,握手头不解析 request_id
- 错误记录的上游事件记录实际上报的请求头(仅变量生成的部分),错误
  详情新增「身份上报请求头」区块
- 编辑器新增变量面板、发送示例预览与行内错误提示
2026-11-24 10:28:55 +08:00
Wesley Liddick 00c51f07d2 Merge pull request #9045 from itzhan/fix/openai-passthrough-400-error-forwarding
fix(openai): preserve invalid_encrypted_content and apply error passthrough rules in passthrough mode
2026-11-24 09:58:02 +08:00
Wesley Liddick 4d4433df09 Merge pull request #9008 from Brisbanehuang/codex/key-billing-group-details
feat(accounts): 支持从上游分组同步账号名称与备注
2026-11-24 09:57:35 +08:00
shaw eabf37852a fix(openai): compact response.failed 改写容量降载码,空白 code 回退内嵌提取
- 透传结构化错误在 compact 心跳已提交时写 response.failed,上游的
  server_is_overloaded / slow_down 必须与其它写 response.failed 的路径一样
  改写为可重试的 server_error,否则 Codex 会直接终止会话
- error.code 为空白字符串时回退到 message 内嵌 JSON 的 code,与错误分类
  看到的 code 保持一致
- 移除测试文件中仅为保留 import 而存在的占位变量
2026-11-24 09:42:41 +08:00
shaw 34423bf1e1 fix(accounts): 上游分组文字先修剪再校验控制字符
首尾的换行或制表符只是多余空白,不应导致整个字段被丢弃而不同步;
修剪后仍含控制字符的才拒绝。
2026-11-24 09:42:39 +08:00
shaw 797fde4e95 fix(deps): 升级 gorilla/websocket 修复 GO-2026-6278
govulncheck 新收录 GO-2026-6278(WebSocket mask key 使用弱随机数),
v1.5.3 受影响且上游尚无带修复的正式 tag,升级到 govulncheck 指定的修复
提交 v1.5.4-0.20240701034025-d67f41855da4。

该库仅用于管理端 ops WebSocket 的服务端升级;服务端只声明 sub2api-admin
一个子协议,上游对子协议匹配顺序的调整不改变协商结果。
2026-11-24 09:21:39 +08:00
shaw ba9df6f1c3 fix(deps): 升级 gorilla/websocket 修复 GO-2026-6278
govulncheck 新收录 GO-2026-6278(WebSocket mask key 使用弱随机数),
v1.5.3 受影响且上游尚无带修复的正式 tag,升级到 govulncheck 指定的修复
提交 v1.5.4-0.20240701034025-d67f41855da4。

该库仅用于管理端 ops WebSocket 的服务端升级;服务端只声明 sub2api-admin
一个子协议,上游对子协议匹配顺序的调整不改变协商结果。
2026-11-24 09:21:38 +08:00
shaw 38903b6d1d fix(accounts): 上游分组文字入库前校验,include 支持多值
- 上游分组名称/描述与探测快照、倍率在同一条 UPDATE 中写库。gjson 对未转义
  字符串返回原始字节,非法 UTF-8 会被 PostgreSQL 以 22021 拒绝,导致整条
  UPDATE 失败:快照与倍率都写不进去,next_probe_at 不推进,账号每个调度
  周期都被重试并挤占探测名额。现在非法 UTF-8 只丢弃对应字段
- 名称拒绝控制字符,备注仅保留换行与制表符,避免上游向管理端写入
  转义序列等不可见内容
- /v1/sub2api/billing 的 include 按逗号分隔列表解析并支持重复参数,
  后续新增可选段时不会让 include=group 失效
2026-11-24 08:58:55 +08:00
shaw 4339d50615 fix(openai): 修复透传错误脱敏越界并收紧结构化错误字段
- replaceCaseInsensitive 改为在原始字节上做大小写不敏感匹配。原实现用
  strings.ToLower 后的下标切原串,遇到折叠后字节长度变化的字符(Ⱥ、Kelvin
  符号、非法 UTF-8)会越界 panic 或把上游主机名原样漏给客户端;同时消除
  该函数的 errcheck 告警
- error.type/code/param 只接受字符串或数字并限长 256 字节,避免上游把对象
  或数组以原始 JSON 形式塞进这三个字段
- 规则命中且未配置自定义文案时,上游消息同样经过凭据与主机名脱敏
- compact 心跳已提交时 response.failed 保留结构化 error.code
2026-11-24 08:56:01 +08:00
alfadb f3a0a65245 fix(ratelimit): 智谱平台过载 429 改用秒级冷却
线上实测报文 {"error":{"code":"1305","message":"该模型当前访问量过大,请您稍后再试"}} 表示平台服务过载,与账号额度无关。该文案既不命中 cnFrequencyLimitMarkers 的频率型特征,也不含额度类词,于是被当成额度耗尽,冷却到配额快照最早的窗口重置点(5h 或周窗,实测 16 分钟到数小时,需人工恢复)。

将「访问量过大」加入频率型 429 文案白名单,并补充注释说明 1305 的实测文案;命中后交给通用 429 兜底使用秒级冷却。90% 用量守卫(cnProviderQuotaSnapshotNearExhausted)保持不变:快照任一窗口用量达到 90% 或快照缺失时仍按窗口冷却。新增 1305 回归测试覆盖该报文。
2026-11-23 20:19:23 +08:00
itzhan 2b74378321 fix(openai): preserve invalid_encrypted_content and apply error passthrough rules in passthrough mode 2026-11-23 20:16:47 +08:00
r266-tech 33ce4ae914 fix(openai): recover sooner after transport reachability failures 2026-11-23 14:05:47 +08:00
kunghim 3b6095912c fix(frontend): theme the MCP consent dropdowns with the common Select 2026-11-23 04:41:14 +08:00
Anankke 30fe563b1f fix(gateway): restore tool names split across stream deltas
On streams the response side renames tool names back on each SSE event by itself, so a rewritten name split across two text_delta or input_json_delta events matches in neither and reaches the client unrestored.

Keep, per content block, the tail of a text or partial_json payload that could be the start of a rewritten name and join it to the block's next text or JSON delta before renaming back. Held bytes go out as one more delta before content_block_stop, or before the closing event when the stream ends another way. Other delta types such as citations_delta pass through and leave the tail held. The native stream applies this to the events it writes, the Chat Completions and Responses bridges to the upstream event before conversion.
2026-11-21 08:18:28 -08:00
Brisbanehuang 03aa05fd9f feat(accounts): 按账号自动同步上游分组名称与备注 2026-11-21 07:02:53 -08:00
Brisbanehuang a95c9e2631 feat(accounts): 支持从上游分组同步账号名称与备注 2026-11-21 06:03:52 -08:00
chengjingtaoandClaude Opus 5.5 bff0f1554f fix(antigravity): skip SSE comment keepalives for js-genai < 1.32 (Gemini CLI)
js-genai before 1.32.0 parses the stream with
/^\s*data: (.*)(?:\n\n|\r\r|\r\n\r\n)/ anchored at the head of its
buffer, so the first ":\n\n" keepalive blocks every later event and the
stream fails with "Incomplete JSON segment at the end". Gemini CLI (up to
0.70.0) pins js-genai 1.30.0 and sends it in X-Goog-Api-Client
("google-genai-sdk/1.30.0 gl-node/..."), so long native Gemini streams
fail for every Gemini CLI user (#8941). js-genai 1.32.0 (c9c1359) splits
the buffer at each delimiter and drops non-data events, so newer Node
clients keep the keepalive.

Treat gl-node clients with google-genai-sdk < 1.32 like go-genai and
python-genai. The old "js-genai tolerates comments" test case used 1.9.0,
which also stalls; it now expects the skip.

Fixes #8941

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 12:23:25 +00:00
Anankke c3219a14ed fix(gateway): do not overwrite a sticky rebind after a long forward
GatewayHandler.Messages writes the sticky binding back after a successful forward. The write was a plain SET, so a long request put its account back over a binding another request made while it was forwarding.

The write now runs a Lua compare in the Redis cache. It sets the key when the key is missing or holds an account this request was admitted on under profit control and failed over from, refreshes the TTL when the key already holds the served account, and leaves any other value alone.

The compare sits behind GatewayStickySessionCompareCache, an optional capability; a cache without it keeps the plain write.
2026-11-20 21:20:09 -08:00
Anankke 20a6b86a4a test(gateway): measure signed-history allocations in a child process
TestFilterThinkingBlocksSignedHistorySkipsDecode asserts testing.AllocsPerRun < 16, and AllocsPerRun reads the process-wide malloc counter, so allocations by background goroutines that earlier tests in the package leave running are counted against it and the test fails intermittently in full package runs.
Run the measurement in a child test process that runs only this test, as TestOpenAIResponsesOrphanPrecheckLargeEscapedContent already does. The assertions and the threshold are unchanged.
2026-11-20 16:57:53 -08:00
Anankke cc2a2616d8 fix(accounts): refetch Gemini usage when the account's quota tier changes
The usage refresh key has no Gemini quota input. When a Gemini account's
tier changes, as when the token refresher re-detects the Google One tier,
auto refresh replaces the row but the key is unchanged: the tier badge
shows the new tier, the quota bars keep the old limits until the account
is used, Refresh is clicked or the page is reloaded. An API key account
moved from a third-party base URL to the official one gets no bars for
the same reason.

The Gemini key now carries credentials.oauth_type, project_id, tier_id and
base_url, the credentials geminiQuotaTierKeyForAccount depends on. Gemini
usage is read from local usage logs, so the refetch sends nothing
upstream, and a token refresh that leaves these four fields alone keeps
the key.
2026-11-20 16:28:16 -08:00
Anankke 53fa92d0a6 Merge remote-tracking branch 'origin/main' into upstream/account-usage-auto-refresh 2026-11-20 14:36:12 -08:00
r266-tech bb110fda53 fix(ops): show requester in request error details 2026-11-20 22:38:07 +08:00
wucm667 88b1924bd9 fix(openai): normalize standalone terminal context 2026-11-20 21:39:18 +08:00
sxinandClaude Code 5f9c4d0135 fix(antigravity): honor final retry reset when cooling models
Use the final structured rate-limit delay for cooldown, including long delays that no longer qualify for in-place retries. Keep capacity policy and unrelated model responses separate.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-20 03:02:23 -08:00
sxinandClaude Code 08970a804b test: reproduce stale Antigravity cooldown after final retry
Cover both short and long reset delays returned by the last structured 429 response.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-20 03:02:23 -08:00
github-actions[bot] 328db26f45 chore: sync VERSION to 0.2.24 [skip ci] 2026-11-20 09:20:06 +00:00
Wesley Liddick 5c2982a81b Merge commit from fork
fix(gateway): reject request bodies whose duplicate fields disagree
2026-11-20 16:57:02 +08:00
Wesley Liddick 62cebadf54 Merge pull request #8886 from SipengXie2024/fix/images-sse-usage-single-line
fix(openai): keep relayed image usage on a single SSE data line
2026-11-20 15:59:27 +08:00
Wesley Liddick eb9143956f Merge pull request #8979 from SipengXie2024/fix/antigravity-quota-forward-endpoint
fix(antigravity): query quota from the account's forward endpoint
2026-11-20 15:54:52 +08:00
Wesley Liddick 1eea0d750a Merge pull request #8976 from yan9651688/feat/model-plaza-copy-model-id
feat(model-plaza): add copy button for model IDs
2026-11-20 15:54:49 +08:00
Wesley Liddick 242556f973 Merge pull request #8973 from william-drakemond/pr/antigravity-bare429-request-scoped
fix(antigravity): 一个请求的裸 429 最多冷却一个账号 / A bare 429 cools at most one account per request
2026-11-20 15:54:45 +08:00
Wesley Liddick cdf3af4b84 Merge pull request #8972 from r266-tech/codex/typesafe-apply-account-model-mapping
fix(typesafe): apply account model mapping to System One
2026-11-20 15:54:41 +08:00
Wesley Liddick 58659ec579 Merge pull request #8968 from wucm667/fix/issue-8967-image-timeout-failover
fix(openai): fail over upstream request timeouts
2026-11-20 15:54:38 +08:00
Wesley Liddick ba5ddded9c Merge pull request #8963 from Daiyangcheng/fix/responses-stop-passthrough
fix(gateway): preserve stop sequences and Kimi tool definitions across protocol conversions
2026-11-20 15:54:34 +08:00
Wesley Liddick c03fc529b8 Merge pull request #8962 from wucm667/fix/issue-8957-grok-edit-input
fix(grok): accept five edit sources and preserve validation errors
2026-11-20 15:54:31 +08:00
Wesley Liddick 55898028ad Merge pull request #8946 from r266-tech/codex/gemini-upstream-comment-frames
fix(antigravity): preserve upstream Gemini SSE comment frames
2026-11-20 15:54:28 +08:00
Wesley Liddick 50dc3141e7 Merge pull request #8943 from alfadb/fix/deepseek-thinking-passback
fix(gateway): 补齐 DeepSeek Anthropic 工具续接历史缺失的 thinking 块
2026-11-20 15:54:24 +08:00
Wesley Liddick 1134f5dffb Merge pull request #8937 from TeacherLi07/fix/ops-duration-weighted-token-rate
fix(ops): 按累计请求耗时计算模型平均 Tokens/秒
2026-11-20 15:54:21 +08:00
Wesley Liddick 320695ae72 Merge pull request #8932 from superman2003/fix/codex-catalog-audio-input
fix(codex): preserve native audio input capabilities
2026-11-20 15:54:17 +08:00
Wesley Liddick fe1f2b6d76 Merge pull request #8931 from superman2003/fix/responses-requested-effort
fix(usage): record per-turn Responses reasoning effort
2026-11-20 15:54:14 +08:00
Wesley Liddick a641897402 Merge pull request #8929 from superman2003/fix/codex-standalone-context-names
fix(openai): preserve VS Code IDE context in HTTP Responses
2026-11-20 15:54:10 +08:00
Wesley Liddick 16b67d9afd Merge pull request #8923 from iam1maker/fix/gemini-final-turn-trailing-parts
fix(gemini): keep trailing parts out of the final tool-result turn
2026-11-20 15:54:07 +08:00
Wesley Liddick a912d13e62 Merge pull request #8918 from XYZ0901/codex/fix-admin-user-default-platform-quotas
fix(admin): 后台创建用户初始化默认平台限额
2026-11-20 15:54:02 +08:00
Wesley Liddick 69237d2ebd Merge pull request #8911 from Echways/fix/anthropic-account-test-temperature
fix(accounts): omit temperature from account tests for models that reject it
2026-11-20 15:53:58 +08:00
Wesley Liddick 2f49048cb8 Merge pull request #8902 from Ming-Sir-69/feat/refresh-button-risk-hint
feat(frontend): warn on frequent manual token refreshes
2026-11-20 15:53:55 +08:00
Wesley Liddick 88ff563f73 Merge pull request #8900 from stevelee477/feat/claude-window-cost-estimate
feat(accounts): estimate Claude OAuth and setup-token window costs
2026-11-20 15:53:52 +08:00
Wesley Liddick 6eb32ab445 Merge pull request #8899 from r266-tech/codex/bulk-passthrough-model-filter-opt-in
fix(accounts): preserve model filters during bulk passthrough edits
2026-11-20 15:53:48 +08:00
Wesley Liddick fe2d953f52 Merge pull request #8893 from SipengXie2024/fix/openai-oauth-skip-claude-models
fix(openai): skip foreign-vendor models on ChatGPT OAuth accounts, passthrough included
2026-11-20 15:53:45 +08:00
Wesley Liddick 490af330d7 Merge pull request #8883 from wucm667/fix/issue-8880-anthropic-model-metadata
fix(anthropic): expose metadata-backed long-context models
2026-11-20 15:53:42 +08:00
Wesley Liddick fb7d8fc7b9 Merge pull request #8875 from zhx8702/fix/openai-body-copy-reduction
fix(openai): stop pinning large request bodies after the handler
2026-11-20 15:53:38 +08:00
Wesley Liddick 356cdccbe8 Merge pull request #8872 from lishuangqiang/perf/tool-schema-sanitizer
perf(openai): stop walking every request body in the tool-schema sanitizer
2026-11-20 15:53:35 +08:00
Wesley Liddick 67b2df8d91 Merge pull request #8870 from lishuangqiang/perf/openai-namespace-strip-copies
perf(openai): stop copying the whole input array when stripping namespaces
2026-11-20 15:53:32 +08:00
Wesley Liddick a437224cd2 Merge pull request #8868 from lishuangqiang/perf/gateway-request-single-scan
perf(gateway): parse the request body once instead of eight times
2026-11-20 15:53:28 +08:00
Wesley Liddick 50c802c518 Merge pull request #8866 from lishuangqiang/perf/image-intent-prefilter
perf(openai): stop re-validating the same body when classifying image intent
2026-11-20 15:53:24 +08:00
Wesley Liddick 9cf9921eb4 Merge pull request #8864 from Anankke/fix/grok-search-billing-usage
fix(grok): bill search calls from xAI usage success counts
2026-11-20 15:53:21 +08:00
Wesley Liddick 998d1c8e2e Merge pull request #8862 from lishuangqiang/perf/cache-control-ttl-short-circuit
perf(gateway): skip the cache_control TTL walk when no 1h breakpoint exists
2026-11-20 15:53:17 +08:00
Wesley Liddick 3ad84e1333 Merge pull request #8859 from Anankke/fix/composite-route-thinking-adapt
fix(composite): adapt thinking to the Claude 5.5 model a route rewrites to
2026-11-20 15:53:14 +08:00
Wesley Liddick 29d9fe2ad0 Merge pull request #8858 from wucm667/fix/issue-8854-passive-usage-refresh
fix(accounts): refresh Claude and Gemini usage snapshots
2026-11-20 15:53:10 +08:00
Wesley Liddick 84a293056a Merge pull request #8845 from r266-tech/codex/scheduler-compact-account-groups
perf(scheduler): omit expanded groups from account cache
2026-11-20 15:53:07 +08:00
Wesley Liddick 600e1e1888 Merge pull request #8820 from Anankke/fix/buffered-hosted-output-items
fix(openai): rebuild empty buffered output from done items
2026-11-20 15:53:03 +08:00
Wesley Liddick 135aff88e1 Merge pull request #8804 from Anankke/fix/messages-bridge-native-tool-search
fix(apicompat): map ToolSearch to native tool_search for Codex OAuth
2026-11-20 15:52:59 +08:00
Wesley Liddick d36670a041 Merge pull request #8803 from Anankke/feat/web-search-sources-bridge
feat(apicompat): return web_search sources in web_search_tool_result blocks
2026-11-20 15:52:56 +08:00
Wesley Liddick fb60f04173 Merge pull request #8801 from Anankke/feat/websearch-exa-provider
feat(websearch): add Exa as a web search emulation provider
2026-11-20 15:52:53 +08:00
Wesley Liddick 3027001928 Merge pull request #8794 from Anankke/feat/compaction-cache-ttl-5m
feat(gateway): write Claude Code compaction requests at 5m cache TTL
2026-11-20 15:52:50 +08:00
Wesley Liddick c38a534be9 Merge pull request #8671 from xuemk/fix/openai-oauth-token-rotation-persistence
fix(openai): protect rotated oauth credentials from enrichment timeout and race conditions
2026-11-20 15:52:46 +08:00
Wesley Liddick 16b53b60a8 Merge pull request #8982 from Wei-Shaw/fix/openai-alpha-search-403-account-penalty
fix(openai): stop alpha/search tool-level 403s from benching OAuth accounts
2026-11-20 14:34:17 +08:00
shaw fe5e7fa404 fix(openai): stop alpha/search tool-level 403s from benching OAuth accounts
A Codex literature search (gpt-6.2-astra with literature_search_query)
on a plan without that capability gets 403
{"detail":"Literature search is unavailable."} from /alpha/search. The
alpha/search side-effect gate only exempted 401/404/405, so the 403 went
through the generic OpenAI 403 path: the first hit cools the account for
10 minutes and three hits within 3 hours mark it errored until an admin
clears it. 403 is also a failover status, so one request replays across
the pool. In production, one request paused all 9 OAuth accounts within
4 seconds.

On alpha/search (and the PAT Responses fallback), a 403 now writes account
state only when it is an account or workspace access-state error
(deactivated, disabled, ...). Every other 403 is the search tool refusing
the request: the request still fails over, since another account's plan
may allow it, but no account is cooled, counted or errored.
2026-11-20 14:22:44 +08:00
shaw a436766de3 fix(gateway): satisfy errcheck in duplicate-field scanner
Build the conflict path by appending to a byte slice instead of ignoring
strings.Builder write results, and discard builder results explicitly in
tests. golangci-lint v2.14.0 (CI version) reports 0 issues.

Refs: GHSA-p3r4-jcm3-2hph
2026-11-20 13:55:58 +08:00
SipengXie2024 7ded9ffb46 fix(antigravity): query quota from the account's forward endpoint 2026-11-20 04:25:09 +00:00
shaw 88d5a20b73 fix(gateway): reject multipart parts with an RFC 2231 extended field name
Go's mime parser prefers name*= over name=, so a part declared as
name="model"; name*=UTF-8''prompt is read as prompt by the gateway (no
model candidate reaches the group allowlist) but as model by an upstream
that ignores extended parameters. Reject parts whose Content-Disposition
carries name*, name*0 or name*0*. filename* stays allowed: it is the
standard way to send a non-ASCII file name.

Refs: GHSA-p3r4-jcm3-2hph
2026-11-20 11:40:25 +08:00
shaw 263a13f160 fix(gateway): close second-round audit findings on the duplicate scanner
A re-audit of ce86c1b30 found, and running code confirmed:

- scanJSONString re-scanned to the closing quote after every escape, so
  scanning was quadratic in escapes (200k "\n": 0.56 s; a 10 MB code-like
  body: 24 s). It now visits each quote once and counts the backslashes
  before it: 6 us and 0.7 ms for the same bodies.
- A multipart body with a JSON preamble (RFC 2046; skipped by Go's
  multipart reader) took the JSON branch only, bypassing both the group
  allowlist and the multipart duplicate check. A multipart Content-Type
  now always runs the multipart check, FromBodyCandidates merges JSON and
  multipart candidates, and a body that is both JSON and a form with parts
  is rejected as ambiguous. The JSON scan stops after the first top-level
  value, matching gjson, so binary file parts are never tokenised.
- LooksLikeJSON now skips every byte <= 0x20 before the first value, as
  gjson does.
- Freeform key spaces gained variables, headers, dependentRequired,
  dependencies and labels, matched on the decoded name. metadata is no
  longer freeform: Antigravity binds metadata.user_id case-insensitively
  while sticky sessions read it with gjson.
- Multipart also rejects file parts named model/session, parts without a
  parsable name, and parts carrying two Content-Disposition headers, and
  counts file and text parts with the same name together.
- WebSocket: passthrough forwards session.update and every other client
  event verbatim, and dedicated parsing reads fields from the raw frame
  before any re-encode. Both now reject a frame with repeated fields
  before reading it.
- The linear-compare limit rises to 32 to cut map churn for mid-sized
  objects.

Tests that relied on duplicates passing now assert rejection: a dedicated
WS recovery test that sent two previous_response_id keys, and WS
allowlist cases whose close reason comes from the earlier duplicate check.

Refs: GHSA-p3r4-jcm3-2hph
2026-11-20 11:32:05 +08:00
shaw ce86c1b306 fix(gateway): close bypasses found in the duplicate-field audit
An independent audit of the conflicting-field fix found, and running code
confirmed, the following. Each is fixed here.

- A JSON body labelled multipart/form-data skipped the check: the JSON
  branch was chosen from the Content-Type header, but JSON handlers never
  look at it. ConflictingField and FromBodyCandidates now detect JSON by
  content. The same header-only branch, and a UTF-8 BOM prefix (stripped by
  the handlers' lenient reader), also let a body bypass the group model
  allowlist on main; both are closed.
- Identical duplicates passed and the gateway's own sjson rewrites then
  split them: reasoning-effort downgrade, model mapping and the fast-policy
  service_tier delete only touch the first occurrence. Every repeated member
  is now rejected, whatever its value. Multipart rejects repeated scalar
  fields (model, n, size, ...) except list fields (name[], image,
  image[...], image_url).
- Nested case variants bound case-insensitively by struct-based protocol
  conversions ({"reasoning":{"effort":"low","Effort":"xhigh"}}). Members
  are now folded at every depth, except inside user-defined key spaces
  (JSON Schema properties/$defs, tool arguments, metadata, ...), where id
  and ID are distinct and only exact repeats are rejected.
- The recursive walker cost depth x size (1 MB at depth 9990: 1.6 s) and
  stored every key as a string (~16x the body). It is replaced by one
  linear byte scan with an explicit stack that compares 64-bit hashes
  (random per-process seed) of the decoded, folded names: 0.6 ms for the
  same body, ~3.7 GB/s on a Claude Code-shaped body. Subtrees deeper than
  10000 levels are bracket-counted, so later same-level members are still
  checked.
- text_max_body_size no longer bounded what group middleware buffered:
  the route-level limit ran after them. The limit is now chosen per route
  at group level.
- Body read failures in gateway middleware answered in the OpenAI shape
  with a different message than the handlers. They now use the entry
  protocol's shape and the handler's "limit is N" message. Rejections
  are recorded as ingress reason conflicting_request_fields.
- The middleware strips a leading BOM and restores the body, so composite
  routing and handlers parse the bytes that were checked.

Refs: GHSA-p3r4-jcm3-2hph
2026-11-20 10:50:32 +08:00
shaw d270d6434f fix(gateway): reject conflicting duplicates in nested objects too
The first pass checked top-level members and the session object only.
Nested fields drive billing and policy as well: reasoning.effort selects
the reasoning-effort billing multiplier and the group effort ceiling, yet
gjson reads the first occurrence, sjson downgrades only the first, and
map re-encoding keeps the last. {"reasoning":{"effort":"low",
"effort":"xhigh"}} therefore passed admission as low and could be served
as xhigh.

ConflictingField now also walks every nested object, including array
elements, and reports the first member that repeats with a different raw
value by path (reasoning.effort, messages[1].role). Nested names are
compared exactly after unescaping, without case folding, because user
data such as tool JSON Schemas may legitimately carry both id and ID.
Identical duplicates still pass. The walk stops below encoding/json's
10000-level limit and only allocates a path string on conflict
(~660 MB/s, 9 allocs for a 225 KB Claude Code-shaped body).

Responses WebSocket frames now apply the full ConflictingField rule
instead of comparing model candidates only, so service_tier and nested
reasoning.effort conflicts close the connection as on HTTP.

Refs: GHSA-p3r4-jcm3-2hph
2026-11-20 10:06:24 +08:00
yan9651688 f2386f9b2d feat(model-plaza): add copy button for model IDs 2026-11-19 16:08:16 -08:00
William Drake e0328a62ac fix(antigravity): a bare 429 after the retry loop cools no account the loop skipped
(cherry picked from commit 3547841e4f33fe9c8c091f649730b286346c865b)
2026-11-19 12:59:41 -07:00
William Drake e7a556ff53 test(antigravity): a bare 429 after the retry loop cools no second account
(cherry picked from commit bfb89961cef3e7fee878c58220a1c1fd40f41b82)
2026-11-19 12:59:41 -07:00
William Drake 26b68da5c5 fix(antigravity): one request cools at most one account for a bare 429
A bare 429 (no ErrorInfo, no reset time) is also what Google sends for a
single request it will not serve. When it follows the request to another
account, the request is the likely cause: the loop still fails over, but
it no longer cools that account and logs bare_429_cooldown_skipped. An
account throttled for everyone is cooled by the next request that
reaches it first, as with the empty-stream rule (4ce6281f). 429s that
carry a reason or a reset time are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit dc2124e238e865db6bcc1b85e8fd235b56d9b1ab)
2026-11-19 12:59:41 -07:00
William Drake 747d228a21 test(antigravity): a bare 429 on several accounts is request-scoped
On 2026-11-16 one 1.8 MB gemini-4-argon-high request got Google's bare
429 ("Resource has been exhausted", no reason, no reset time) on four
accounts in a row while those accounts kept serving other requests. Each
account was cooled for the whole antigravity:gemini group, and a second
customer whose group held only those accounts got "No available
accounts" for a minute.

The request should cool only the first account; another request still
cools the next one, and a 429 with a reset time still cools every
account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 8bee4caee6e9f60f43d4a2fec3abe792c78731e6)
2026-11-19 12:59:41 -07:00
AIBIN GEandclaude-mythos-5-2 2b67d1ede2 fix(gateway): reject request bodies whose duplicate fields disagree
A body such as {"model":"cheap",...,"model":"expensive"} was scheduled and
billed under the first model, while paths that decode and re-encode the
body forwarded the last one. gjson returns the first member with a name;
encoding/json keeps the last and matches struct fields case-insensitively.
The group allowlist already validates every model candidate, but billing
did not, and groups without an allowlist had no check at all.

RejectConflictingRequestFields runs on every gateway chain after the
allowlist and before the composite rewrite. It answers 400 when a
top-level JSON member, a member of the session object, or a multipart
model/session field is declared more than once with different values.
Repeated fields with identical values still pass, as they do in the
allowlist. Responses WebSocket frames apply the same rule to their model
candidates on the first frame and on later turns.

The source-level chain assertion in gateway_model_allowlist_test.go is
updated for the new middleware position.

Not covered: repeated non-model members inside WebSocket frames (an
existing test accepts a repeated previous_response_id there), and nested
objects other than session.

Refs: GHSA-p3r4-jcm3-2hph

Co-Authored-By: claude-mythos-5-2 <noreply@anthropic.com>
2026-11-20 04:00:28 +09:00
r266-tech 3e190f7e05 fix(typesafe): apply account model mapping to System One 2026-11-20 02:39:02 +08:00
wucm667 4480cd90a4 fix(openai): fail over upstream request timeouts 2026-11-19 23:45:59 +08:00
Anankke 3eca473aa1 Merge remote-tracking branch 'origin/main' into upstream/compaction-cache-ttl-5m 2026-11-19 01:53:19 -08:00
Anankke 2cf2c33226 Merge remote-tracking branch 'origin/main' into upstream/websearch-exa-provider 2026-11-19 01:52:18 -08:00
Anankke 6d4fcbad47 Merge remote-tracking branch 'origin/main' into upstream/bridge-web-search-sources 2026-11-19 01:51:05 -08:00
Daiyangcheng fec3de4a73 fix(gateway): resolve an issue where 'stop' and Kimi dynamic tool definitions were lost during protocol conversio 2026-11-19 16:23:51 +08:00
wucm667 92fd567a47 fix(grok): accept five edit sources and classify input errors 2026-11-19 15:47:59 +08:00
wucm667 155b83badb fix(i18n): clarify Ultra Fast service tier hints 2026-11-19 09:49:44 +08:00
wucm667 baf058f645 chore: sync upstream main for current validation 2026-11-19 09:49:44 +08:00
r266-tech 735bcb0573 fix(antigravity): preserve upstream Gemini SSE comment frames 2026-11-19 00:14:38 +08:00
alfadb 26e0be3392 fix(gateway): ensure DeepSeek Anthropic tool-use history carries thinking blocks
DeepSeek 官方 Anthropic 原生端点在 thinking 模式下要求工具续接请求把
assistant 历史里的 thinking 块完整回传;缺失时上游会按 tool-call ID 尝试
自动恢复,恢复失败返回 400:The content[].thinking in the thinking mode
must be passed back to the API。

本补位仅对 api.deepseek.com 账号(targetsDeepSeekAPIHost)且请求启用
thinking 时生效:给含 tool_use 但缺 thinking/redacted_thinking 的
assistant 消息在 content 首部插入单个空格占位的 thinking 块
(DeepSeek 可能把空串按缺失处理){"type":"thinking","thinking":" "}。
signature 可省略——官方文档说明 input 侧的 signature 不做校验。其他上游
与无需改动的请求体保持字节不变。
2026-11-18 21:00:32 +08:00
TeacherLi e2148a1813 fix(ops): weight average token rate by request duration 2026-11-18 08:25:44 +00:00
superman2003 75de2de480 fix(codex): preserve native audio input capabilities 2026-11-18 14:48:14 +08:00
superman2003 e52bc308bb fix(usage): record per-turn Responses reasoning effort 2026-11-18 14:30:09 +08:00
superman2003 e3872e1615 fix(openai): preserve VS Code IDE context in HTTP Responses 2026-11-18 14:05:43 +08:00
iam1maker 44db3dd72b fix(gemini): keep trailing parts out of the final tool-result turn
Clients legally send a user text message right after tool results (step
budget reminders, mid-turn steering, context-management notices). The
Chat Completions -> Responses -> Anthropic chain merges that text into the
same Anthropic user message as the tool_result blocks
(mergeConsecutiveMessages), and convertClaudeMessagesToGeminiContents maps
each Anthropic message 1:1 to one contents entry, so the final contents
entry ends with functionResponse parts followed by text.

Vertex rejects that shape with HTTP 400 "Requests ending with a model turn
are not supported.", even though the turn is a user turn. The same happens
when tool-result media is appended after the function responses for models
without multimodal function responses.

Split trailing non-functionResponse parts into their own trailing user
turn. Part order is preserved, only the turn boundary moves; Vertex accepts
the split form (verified against generateContent directly and through
/v1/chat/completions).
2026-11-18 13:38:31 +08:00
github-actions[bot] 2af3f1e15c chore: sync VERSION to 0.2.23 [skip ci] 2026-11-18 03:51:52 +00:00
Wesley Liddick 5af9afb588 Merge pull request #8920 from Wei-Shaw/fix/openai-stream-idle-failover-budget
fix(openai): bound pre-output idle failover to the first-output switch budget
2026-11-18 11:40:09 +08:00
Wesley Liddick 2354c78288 Merge pull request #8174 from wucm667/fix/issue-8172-anthropic-cache-ttl
Preserve Anthropic cache creation TTL details
2026-11-18 11:39:55 +08:00
Wesley Liddick 19d4cb222a Merge pull request #8577 from WGeorgezzzz/fix/openai-stream-idle-timeout-failover
fix(openai): enforce stream idle deadlines and pre-output failover
2026-11-18 11:16:36 +08:00
wucm667 82395b0b5a test(usage): distinguish EOF before and after client output 2026-11-18 11:07:28 +08:00
XYZ0901 a4b72bef09 fix(admin): initialize default platform quotas for new users
AI-Co-Authored-By: Codex
2026-11-18 10:58:24 +08:00
shaw 29809eef09 fix(openai): bound pre-output idle failover to the first-output switch budget
The pre-output idle timeout failover did not set SafeToFailoverAfterWrite,
so it escaped maxOpenAIFirstOutputTimeoutSwitches and fell back to
max_account_switches (default 10). With the defaults (180s idle, first-output
timeout disabled) one stalled request could walk 11 accounts and apply
HandleStreamTimeout to each of them.

Mark the error like the other pre-output failovers in this function so it
shares the one-switch first-output budget. Only keepalive comments can have
reached the client at this point, which is exactly what the flag asserts.
2026-11-18 10:57:38 +08:00
Wesley Liddick 9e9ca6fe95 Merge pull request #8914 from r266-tech/codex/channel-ultrafast-pricing
fix(channels): support configurable Ultra Fast pricing
2026-11-18 10:40:58 +08:00
Wesley Liddick 4e10912b4e Merge pull request #8598 from lkon2112/fix/billing-heap-test
test(billing): reuse rate resolver and isolate heap checks
2026-11-18 10:40:41 +08:00
wucm667 23c3eb7f8b fix(usage): align cache usage across Anthropic conversion boundaries 2026-11-18 10:19:03 +08:00
wucm667 202e23b2b8 chore(build): upgrade Go toolchain to 1.27.4 2026-11-18 10:19:03 +08:00
Wesley Liddick 69d2fae913 Merge pull request #8903 from jianjianai/perf/openai-raw-chat-stream-flush
perf(openai): 原生 Chat Completions 流式透传在等待上游前才 flush
2026-11-18 09:07:48 +08:00
Wesley Liddick 45632495f5 Merge pull request #8904 from jianjianai/perf/openai-chat-reasoning-single-pass
perf(openai): DeepSeek reasoning 占位与 Ollama Cloud reasoning 回填改为单遍改写请求体
2026-11-18 09:07:36 +08:00
Wesley Liddick a4d3103cd5 Merge pull request #8906 from lyy0709/codex/gpt62-astra-sol
feat(openai): 接入 GPT-6.2 Sol 和 Astra
2026-11-18 09:01:08 +08:00
r266-tech b36cb244f3 fix(channels): support configurable Ultra Fast pricing 2026-11-18 07:05:45 +08:00
Echways 75290a9f26 fix(accounts): omit temperature from account tests for models that reject it
The Anthropic and Bedrock account test payloads always sent
temperature: 1, so testing claude-opus-4-8 failed with HTTP 400
("temperature is deprecated for this model") and a working account was
reported as broken.

Add claude.RejectsTemperature for Opus 4.7/4.8, Opus 5.5, Fable 5.2 and
Mythos 5.2, and skip the field for those models. Other models keep the
existing payload.

Fixes #8625
2026-11-17 23:08:42 +03:00
lyy0709 2d20707f16 fix(openai): honor GPT-6.2 Ultrafast entitlements by Pro plan 2026-11-18 03:53:56 +08:00
lyy0709 6107cf1748 feat(openai): support GPT-6.2 Sol and Astra 2026-11-18 03:09:38 +08:00
jianjianaiandClaude Opus 5.5 d867299264 perf(openai): DeepSeek reasoning 占位与 Ollama Cloud reasoning 回填改为单遍改写请求体
ensureDeepSeekChatReasoningPlaceholders 对每条缺 reasoning_content 的 assistant
消息调用一次 sjson.SetBytes,每次都复制整个请求体并从头定位路径,k 条消息、
请求体长 n 时是 O(k·n)。agent 对话里 assistant 消息常有几百条、请求体几百 KB
到数 MB,一个请求就要复制上百 MB。生产环境 60 秒 CPU profile 中该函数约占
网关 CPU 的 3%,是请求体处理里最大的单项。normalizeOllamaCloudChatCompletionsRequest
是同一写法。

新增 setStringFieldInJSONObjects:按 gjson 给出的元素偏移只复制一次请求体,
输出与逐条 sjson.SetBytes 逐字节相同(新增键的位置与逗号、已有键的替换、
字符串编码都按 sjson 的规则)。偏移无法可靠核对时返回 ok=false,调用方回退到
原来的逐条写法。

基准(300 轮 agent 对话,请求体约 1 MB):
  逐条 sjson:396 ms/op,514 MB/op
  单遍改写:  3.4 ms/op,2.4 MB/op

测试:固定用例(紧凑/带空白格式、已有空串/null/false 值、嵌套同名字段、重复键、
Unicode 与转义)和 300 个随机生成的请求体,均与逐条 sjson 的输出逐字节比对,
并断言走的是单遍路径;另测无法定位时拒绝改写。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:46:39 +00:00
jianjianaiandClaude Opus 5.5 2c67844964 perf(openai): 原生 Chat Completions 流式透传在等待上游前才 flush
streamRawChatCompletions 之前每写一行就 Flush 一次,包括事件之间的空行,
所以每个 SSE 事件至少两次写系统调用。生产环境 60 秒 CPU profile 中,这条
路径下的 Flush(含 chunked 编码与 write 系统调用)约占网关 CPU 的 8%。

改为把上游响应体包一层 flushBeforeUpstreamRead:bufio.Scanner 只有在缓冲里
没有完整行、要向上游读新数据时才调用 Read,就在这时 flush 已写出的内容。

- 已到达的事件仍在开始等待上游之前写给客户端,延迟不变
- data 行与事件间空行、同一次读取到达的多个事件合并成一次 flush
- 扫描、改写、计费、截断判定逻辑不变

测试:
- 一次读取到达 5 个事件:flush 从 10 次降到 1 次,输出逐字节不变
- 上游在客户端收到第一个事件前不再发送数据:第一个事件仍被及时 flush
  (若推迟到下一次读取之后才 flush,该用例会超时失败)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:34:49 +00:00
Ming-Sir-69 65be27787c feat(frontend): warn on frequent manual token refreshes
Manual refresh racing the single-use rotating refresh token (e.g. against
the background auto-refresh) can invalidate the grant and pause the
account. Surface this with a tooltip on the refresh action and a
non-blocking warning when the same account is refreshed again within a
minute; the action itself is never blocked.
2026-11-18 00:21:53 +08:00
stevelee477 f358f0a41a feat(accounts): estimate Claude OAuth and setup-token window costs 2026-11-17 23:10:31 +08:00
r266-tech 3b95559788 fix(accounts): opt in to bulk passthrough model filter changes 2026-11-17 21:46:58 +08:00
SipengXie2024 77ba3346d1 fix(openai): skip foreign-vendor models on ChatGPT OAuth accounts, passthrough included
Empty-mapping OpenAI OAuth accounts accepted claude-* models, and OAuth or
setup-token accounts with openai_passthrough accepted every model. Both send
requests to chatgpt.com/backend-api/codex, which answers foreign models with
a non-retryable 400 ("not supported when using Codex with a ChatGPT
account"), so mixed groups handed claude-* requests from Codex clients to
the OAuth account instead of the API-key account that serves them.

- Add "claude-" to openAIOAuthForeignModelPrefixes.
- Apply the foreign-prefix check to OAuth and setup-token passthrough too;
  API-key passthrough keeps allowing every model.
- Schedule /v1/messages by the channel-mapped model, as Responses, Chat
  Completions and the Responses WebSocket already do, so a channel mapping
  a claude-* alias to a GPT model still lands on OAuth accounts.
2026-11-17 09:50:16 +00:00
r266-tech 18c42a29d2 perf(scheduler): omit expanded groups from account cache 2026-11-17 16:50:37 +08:00
SipengXie2024 f66984fc5d fix(openai): keep relayed image usage on a single SSE data line
The Codex direct Images endpoints pretty-print their JSON. When a streaming
request gets a plain JSON answer, the usage object is copied verbatim into the
completed event, so its newlines split the SSE data payload. Strict SSE
clients then read a truncated JSON line and report no image even though the
event carries b64_json. Compact usage before embedding it.
2026-11-17 08:28:24 +00:00
wucm667 570d59e9ac fix(anthropic): expose metadata-backed long-context models 2026-11-17 15:13:03 +08:00
zhanghuaxiangandCursor bcb22d4de8 fix(openai): stop pinning large request bodies after the handler
Clone the few request-view strings that outlive the handler instead of aliasing the request body, drop the converted Responses input once it is marshaled, and avoid pointing usage logs at the forward input. Async prompt audit checks its scope before copying the body and no longer clones twice, splits and trims prompts without full []rune copies, and skips redaction rewrites that cannot match.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 11:28:53 +08:00
wucm667 d0c232401f ci: rerun checks after allocation guard failure 2026-11-17 11:22:55 +08:00
github-actions[bot] 15871f9040 chore: sync VERSION to 0.2.22 [skip ci] 2026-11-17 02:48:29 +00:00
Wesley Liddick b0fa9f3e6e Merge pull request #7540 from alfadb/fix/qwen3-embedding-fallback-pricing
fix(billing): 为硅基流动 Qwen3-Embedding/Reranker 系列补兜底定价
2026-11-17 10:13:23 +08:00
Wesley Liddick 8b13851ac8 Merge pull request #8812 from Wei-Shaw/feat/group-force-openai-ultrafast
feat(groups): 分组支持强制 OpenAI Ultra Fast 档位
2026-11-17 09:37:43 +08:00
shaw 926d3cd86d test(billing): 将 Ultrafast 门控与计费一致性用例移入 unit 标签文件
用例依赖仅在 unit 标签下定义的 newTestBillingService,放在无标签的
openai_fast_policy_test.go 中导致 lint 与 integration 构建失败。
2026-11-17 09:25:25 +08:00
lishuangqiang e7c587e14d perf(openai): stop walking every request body in the tool-schema sanitizer
sanitizeOpenAIResponsesToolSchemasForPlatform runs on every OpenAI Responses
forward attempt, on WS normalization and on /v1/messages conversion, and its two
passes both ran far more often than they need to:

  * the regex-pattern pass was gated on "the body contains '('", and tool
    descriptions, code samples and user messages contain parentheses
    constantly, so the gate let essentially everything through;
  * the parameter-type pass had no gate at all and ran for OpenAI, Anthropic,
    Grok and every CN platform.

A 1MiB Codex request therefore walked its body twice with the hand-written
parser before reaching the upstream. Profiling put 92% of that in parseString,
which scanned strings byte by byte while long content strings are most of a
request body.

Changes:

1. parseString skips the plain run of a string eight bytes at a time (SWAR),
   stopping only on '"', '\\' or a control byte - exactly the three bytes it has
   to stop at. 2.2 GB/s -> 10.5 GB/s.
2. An input item is no longer walked twice. The type probe walked the whole item
   and then the item was walked again just to skip it; the probe's end position
   is now reused. Messages dominate input history.
3. json.Valid(body) only runs when the walk actually produced an edit. With no
   edits the body is returned untouched, so that second full-body validation
   proved nothing; patches are still validated after they are applied.
4. Both gates are now necessary conditions that can be proven complete.
   hasUnsupportedOpenAIRegexPattern only fires on an unsupported backslash
   escape, a trailing backslash, or group syntax "(?"; the first two need a
   decoded backslash, which JSON can only spell "\\\\" or \\u005c, and the third
   can have either character escaped. The parameter pass only edits a literal
   null value or a oneOf/anyOf union, and the union repair accepts any
   parameters object containing a backslash, so an escaped keyword such as
   "one\\u004ff" counts too - hence the \\u00XX needle.
5. Patterns are checked in place when the JSON span carries no escape, instead
   of strconv.Unquote per pattern, and object member names are parsed once into
   openAIResponsesJSONKey rather than rescanning the span for every candidate
   name.

Benchmark (Apple M5 Pro, 1MiB Codex-shaped body: 30 tools + 1MiB input):

  platform entry, OpenAI     7.48ms / 512 allocs -> 96us / 0 allocs
  platform entry, Anthropic  3.75ms / 256 allocs -> 66us / 0 allocs
  patterns pass              3.71ms / 256 allocs -> 30us / 0 allocs
  parameter-types pass       3.69ms / 256 allocs -> 66us / 0 allocs

Existing benchmarks:

  ..._Patterns_ByteSpanPatch        1586609ns / 2017 allocs -> 915199ns / 17
  ..._ParameterTypes_ByteSpanPatch  1011697ns /  17 allocs -> 647160ns / 17

Correctness: parseString keeps the previous byte-at-a-time scanner as legacy*
and compares return values and error positions across a corpus plus fuzzing;
the probe reuse asserts that the probe and the skip walk stop at the same byte;
the gates are pinned by the invariant "if the sanitizer changed the body, the
gate must have let it through", over a corpus that spells out every unsupported
pattern shape and fuzzing; dropping the pre-edit json.Valid relies on "the
parser accepts implies encoding/json accepts", which is fuzzed too.

Fuzzing found two bugs in this change, both fixed and kept as regression seeds
under testdata/fuzz: an out-of-range read when a body ended in "\\\\", and a gate
that was narrower than the necessary condition for a pattern whose value is a
lone backslash. The second means such patterns are now cleaned up where the old
gate only caught them by accident, when the body happened to contain a
parenthesis elsewhere.
2026-11-17 01:39:42 +08:00
lishuangqiang 596696356e style(openai): gofmt the namespace strip equivalence test 2026-11-17 00:29:48 +08:00
lishuangqiang 09840b8027 test(gateway): stop ignoring strings.Builder errors in the scan benchmark
The benchmark body builder discarded the results of strings.Builder.WriteString,
which errcheck rejects (the repo enables errcheck with check-blank off, so a
plain call is flagged even though Builder never returns an error). Route the
writes through one helper that assigns the result.
2026-11-17 00:14:52 +08:00
lishuangqiang 049e0f41b8 perf(openai): stop copying the whole input array when stripping namespaces
stripOpenAIResponsesInputNamespaces runs on every OpenAI OAuth / API-key HTTP
forward attempt. Its entry check only proves that the *body* contains a
namespace literal, and Codex clients advertise the image_gen namespace tool on
ordinary requests, so the check passes for most traffic and the function runs
even when there is nothing to strip.

Three avoidable copies showed up in that path:

1. gjson.GetBytes(body, "input") materialises the input array. On a 1MiB body
   that is a 1MiB allocation on every request, including the no-op case.
   Use the zero-copy parse view (parseRawJSONView) instead.
2. The rewrite built the new input array in a buffer and then handed it to
   sjson.SetRawBytes, which allocates a second full body copy. Assemble the
   output directly instead: prefix + rewritten array + suffix in one buffer
   sized to the body.
3. sjson.DeleteBytes([]byte(item.Raw), ...) converted each changed item to a
   byte slice first. Use the string form.

hasOpenAIResponsesNamespaceToolDeclaration reads input the same way and gets
the same treatment; it runs for API-key accounts on every request.

Benchmark (Apple M5 Pro, -benchmem), legacy = the previous implementation:

  1MiB tools_only    545us / 1056768 B / 1 alloc  ->  495us / 0 B / 0 alloc
  1MiB strip_first   882us / 3170624 B / 8 allocs ->  548us / 1056936 B / 4
  1MiB strip_last    841us / 3170624 B / 8 allocs ->  556us / 1056928 B / 4
  8MiB strip_first  5.95ms / 25190720 B / 8       -> 4.30ms / 8396960 B / 4

So the no-op path stops allocating entirely and the rewriting path copies one
body instead of three.

Behaviour is unchanged for valid JSON: equivalence tests keep the previous
implementation as legacy* and compare output bytes, errors and whether the
input slice was returned untouched, across 36 bodies (duplicate keys, escaped
keys, nested namespace fields, non-object items, keep-tool-call mode, missing
or non-array input) plus 3000 randomized combinations and a fuzz target.

One deliberate difference, pinned by a test: on input that is not valid JSON,
gjson.GetBytes and gjson.Parse return different spans for the same key, and
the new implementation refuses to rewrite an unparseable fragment instead of
truncating it. The only caller forwards a body that the handler has already
validated, so this path is not reachable in production.
2026-11-17 00:10:26 +08:00
xuemk fb52c6e136 fix(openai): protect rotated oauth credentials from enrichment timeout and race conditions 2026-11-17 00:00:55 +08:00
lishuangqiang 8d962ba494 perf(openai): use the validated parse path for chat completions too
Same shape as the responses handler: the body is validated at the top of
ChatCompletions, the only later rewrite is
applyOpenAIReasoningEffortPolicyForRequest (sjson), and the parse error was
already being ignored. Nothing between the two points mutates the bytes:
parseOpenAICompatibleStream, checkSecurityAudit and tokenInflightEstimate only
read them.
2026-11-16 23:34:25 +08:00
lishuangqiang 844459e785 perf(openai): skip the redundant body validation when parsing responses requests
The /v1/responses handler validates the request body with gjson.ValidBytes
before doing anything else, then hands the same bytes to ParseGatewayRequest,
which validates them a second time. After the single-root-walk change the
validation is the majority of what that call does: at 1MiB it is about 510us
of the remaining 730us.

Add ParseGatewayRequestValidated for callers that have already established the
body is valid JSON, and use it in the handler, where the only rewrite between
the two points is applyOpenAIReasoningEffortPolicyForRequest (sjson, which
preserves validity).

The validating entry point is unchanged, so invalid JSON keeps producing a
clean error everywhere else. ReplaceBody / CloneForBody keep validating as
well, because their bytes can differ from the ones a caller validated.

Equivalence tests assert the trusted variant produces identical results to the
validating one on valid JSON, and the fuzz target checks the same for every
input that parses.

Benchmark (Apple M5 Pro, 3 allocs unchanged):
  responses 1MiB: 735us -> 239us
  anthropic 1MiB: 723us -> 207us (not yet wired: that handler has no earlier
  validation, so it keeps the validating path)
2026-11-16 23:24:26 +08:00
lishuangqiang 0c571e9e27 perf(service): parse the gateway request body with a single root walk
parseGatewayRequestCurrentBody looked up eight fields with separate
gjson.Get calls. A lookup for a key that is not present still has to scan the
whole body to prove absence, and for a typical Responses request six of those
keys are absent (metadata.user_id, thinking.type, output_config.effort,
max_tokens, system, messages). On a 1MiB body that is six full passes at about
142us each, while a single root walk over the same body costs about 220us.

Collect every field the parser needs in one ForEach over the root and derive
the raw ranges from the same results.

Nested paths keep gjson semantics: each path segment resolves to the first
duplicate key that actually yields the child, not simply the first key with
that name. {"metadata":"x","metadata":{"user_id":"u"}} resolves to "u", and the
walk reproduces that by retrying while the collected child does not exist.
Duplicate scalar keys keep first-occurrence-wins.

The Anthropic [1m] model normalization rewrites the body mid-parse, so the walk
is repeated after the rewrite. That path only runs when the client leaks the
suffix.

Benchmark (Apple M5 Pro, 3 allocs unchanged):
  responses 128KiB: 208us -> 96us
  responses 1MiB:   1.59ms -> 735us
  anthropic 1MiB:   1.43ms -> 723us

Equivalence tests keep a verbatim copy of the previous implementation as
legacy* and compare every field (model, stream, metadata user id, thinking,
effort, speed, max tokens, system/messages/input ranges, protocol, body after
parsing) across 4 protocols and 44 bodies, plus 3000 deterministic random
combinations. A fuzz target does the same for arbitrary input.
2026-11-16 23:23:13 +08:00
lishuangqiang 62765bb4e7 perf(openai): apply the image-intent precheck to the declaration scanners
openAIRequestBodyHasImageGenerationDeclaration and
openAIRequestBodyImageGenerationToolNeedsNormalization each validate the whole
body up front before looking at tools/input/tool_choice. Both branches only
match image_gen literals, so the same byte-level necessary condition applies
and lets them skip the validation for bodies that cannot match.

Refs #8865
2026-11-16 23:03:38 +08:00
lishuangqiang 487d42c964 perf(openai): reuse an already-validated body when classifying image intent
The handler validates the request body at gateway_handler_responses.go:66 and
ParseGatewayRequest validates it again at gateway_request.go:240. For bodies
that do carry image declarations the byte-level precheck cannot fire, so the
intent classifier still ran gjson.ValidBytes over the same bytes a third time.
That is the dominant remaining cost for Codex traffic, because Codex
advertises the image_gen namespace on ordinary responses requests.

Add IsImageGenerationIntentForPlatformValidated for callers that have already
established the body is valid JSON, and use it at the two call sites where
that holds:

- gateway_handler_responses.go: the body is validated at the top of the
  handler, and afterwards it is only rewritten through sjson
  (applyOpenAIReasoningEffortPolicyForRequest), which preserves validity.
- openai_ws_forwarder_ingress.go: the payload is validated in
  parseClientPayload, and every later rewrite is sjson, a decode/re-marshal
  round trip, or a no-op.

Both call sites carry the reasoning in a comment. The validating entry points
are unchanged, so invalid-JSON semantics stay exactly as they were for every
other caller.

Benchmark (Apple M5 Pro, 1MiB Codex body, 0 allocs):
  intent classifier: 562us -> 50us

Refs #8865
2026-11-16 23:02:17 +08:00
lishuangqiang 59645b7bea perf(openai): skip the image-intent body scan when a request cannot declare one
Every /v1/responses request runs IsImageGenerationIntentForPlatform to decide
whether to mark the context as image generation (capability routing and image
billing). After the two O(1) checks (dedicated image endpoint, image model) the
function unconditionally runs gjson.ValidBytes over the whole body and then
walks the root object with a ForEach.

Both steps are pure overhead for requests that cannot match. Every branch that
can set the intent requires one of two things in the body: the literal
"image_gen" (image_generation tools carry that prefix, and the namespace,
tool_choice and function-reference checks all use image_gen), or an image model
name (gpt-image-*, grok-imagine*) as the "model" value. The same body is also
validated by the handler and again by ParseGatewayRequest, so this pass is a
third redundant validation of the same bytes.

Add a byte-level necessary condition ahead of gjson.ValidBytes:

	bytes.Contains(body, "image_gen")
	|| containsASCIIFold(body, "imag")   // image model names
	|| bytes.Contains(body, "\\u")       // unicode-escaped literal

All three are required:

- "image_gen" alone misses the model branch. {"model":"gpt-image-2"} returns
  true today and does not contain "image_gen"; dropping it would let image
  model requests bypass the group image-generation gate and image billing.
- isOpenAIImageGenerationModel lowercases its argument while bytes.Contains
  does not, so the model token is matched case-insensitively.
- JSON strings may spell any byte as a unicode escape, so a body containing
  "image_generation" only reveals the literal after decoding. Escaped
  bodies therefore fall back to the full scan. None of the target literals
  contain a character JSON escapes, so a "\u" probe is exhaustive.

containsASCIIFold had to be rewritten as well. It compared byte by byte, which
is a full body scan on its own, and a first-byte memchr variant that re-probes
both cases of the first byte per candidate degrades quadratically. The new
implementation keeps one cursor per case and advances only the cursor it just
consumed, so it stays linear. Without this the precheck would cost more than
the scan it replaces (~930us vs 783us on a 1MiB body).

The three scan bodies collapse into two root walkers plus one entry point; the
grok and explicit rules were byte-identical copies.

Codex clients advertise the image_gen namespace on ordinary requests, so those
bodies still take the full scan. Skipping the duplicate validation for callers
that already validated the same bytes is a separate change.

Benchmark (Apple M5 Pro, 1MiB body, 0 allocs):
  no image declarations      783us -> 48us
  codex namespace            560us -> 564us (gate cannot fire, unchanged)

Fixes #8865
2026-11-16 22:52:36 +08:00
Anankke f42dad9b71 fix(composite): adapt thinking to the Claude 5.5 model a route rewrites to
A composite route that rewrites the request model left the client's thinking untouched, so a route from claude-sonnet-5 to claude-opus-5-5 forwarded thinking.type=enabled with budget_tokens and validateClaude55Request answered 400 before the request reached the upstream.

The route middleware now rewrites the model through RewriteCompositeRequestModel, which replaces a thinking mode that validateClaude55Request rejects for the new model with the nearest mode it accepts: enabled becomes adaptive without budget_tokens, and disabled becomes between_tools on Sonnet 5.5.

The mapping is shared with the Bedrock Sonnet 5.5 sanitizer, whose behavior is unchanged.

Modes the target still rejects stay with validateClaude55Request, and a request whose model the route does not rewrite keeps its thinking as sent.
2026-11-16 05:48:26 -08:00
lishuangqiang 833cfcc2fb perf(gateway): skip the cache_control TTL walk when no 1h breakpoint exists
The byte-level precheck added for #8668 still runs both cache_control walks
for any body containing a "thinking" literal, because the thinking-block
cleanup cannot be skipped by that check alone. Claude Code enables extended
thinking by default, so that is the dominant shape: the precheck pays its own
scan and then falls through to the unconditional
normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)).

On the 32KB Claude Code benchmark body with thinking, this made the optimized
path slightly slower than the pre-fix code (112us vs 104us).

Skip the second collectCacheControlPaths pass when the body has no "1h"
literal. The walk is provably a no-op there: last1h stays -1 and nothing is
rewritten. Escaped bodies returned earlier, so the byte check is exact, and
the block-limit deletions only remove cache_control keys, which cannot
introduce a 1h breakpoint.

Benchmark (Apple M5 Pro, -benchtime 2s -count 3):
  thinking, no 1h:  112us / 21 allocs -> 52us / 8 allocs
  common, no 1h:    21.6us / 0 allocs -> 21.3us / 0 allocs
  1h bodies:        unchanged (within noise)

The benchmark gains two thinking cases so future work cannot regress this
shape unnoticed. Equivalence tests compare against the verbatim legacy
implementation.

Fixes #8861
Refs #8668
2026-11-16 21:33:25 +08:00
shaw ad9eeedebb feat(groups): 强制 Ultra Fast 按模型门控,可与强制 Fast 并存
- 强制 Ultra Fast 只对支持的模型(GPT-6 Astra、GPT-6.1 Sol)写入
  service_tier=ultrafast;其余模型在同时开启强制 Fast 时写入 priority,
  否则跟随客户端。优先级:Ultra Fast > Fast > 客户端
- 去掉 force_openai_fast 与 force_openai_ultrafast 的互斥校验
  (GROUP_OPENAI_FORCED_SERVICE_TIER_CONFLICT)
- gpt-6.1-sol 的 Ultra Fast 计费由 2x 修正为 6x,与 Astra 一致;门控与
  计费共用 openAIModelSupportsUltrafast,避免两者漂移
- 管理端由下拉三选一改回两个独立开关,说明文案点名支持的模型与 6x 计费
2026-11-16 21:17:31 +08:00
wucm667 fa796b309a fix(accounts): refresh Claude and Gemini usage snapshots 2026-11-16 20:52:14 +08:00
Anankke e5e1162f42 chore(apicompat): merge main into the native tool_search branch 2026-11-16 04:29:43 -08:00
shaw 9cd1a1eb21 chore: update sponsors 2026-11-16 20:19:48 +08:00
Anankke 2c587f78b0 fix(grok): bill search calls from xAI usage success counts
When a Grok response usage carries server_side_tool_usage_details, take SearchCount from web_search_calls, x_search_calls and document_search_calls instead of counting output items.

xAI documents server_side_tool_usage as the successful calls that determine billing, so failed calls and server-side tools that return nothing are no longer billed. Classes the item counter does not count and the x_posts_fetched / x_users_fetched item counts are not read.

Without server_side_tool_usage_details the existing item counting is unchanged. The usage is read from the JSON body, the SSE body and the terminal stream event, for /v1/responses, /v1/messages and /v1/chat/completions, streaming and not. ResponsesUsage keeps the raw object so the buffered paths, which count from a decoded response, can read it.
2026-11-16 04:06:12 -08:00
Wesley Liddick ef29203002 Merge pull request #8747 from ruixingshi/fix/openai-quota-freshness
fix(openai): preserve quota freshness when refresh fails
2026-11-16 19:52:38 +08:00
Wesley Liddick 7e4c614bcf Merge pull request #8669 from r266-tech/codex/grok-top-level-errors
fix(grok): preserve upstream media error messages and codes
2026-11-16 19:52:30 +08:00
Wesley Liddick 3e8e3254d1 Merge pull request #8772 from Henglie/fix/openai-tool-schema-python-regex
fix(openai): drop tool schema patterns Python re rejects
2026-11-16 19:52:23 +08:00
Wesley Liddick f8d891d6fb Merge pull request #8724 from r266-tech/codex/anthropic-errors-after-keepalive
fix(gateway): emit SSE errors after queue keepalives
2026-11-16 19:52:15 +08:00
Wesley Liddick 7a19bbef73 Merge pull request #8748 from r266-tech/codex/passthrough-model-filter
feat(openai): optionally filter passthrough accounts by model
2026-11-16 19:52:07 +08:00
Wesley Liddick 4328510f28 Merge pull request #8834 from Anankke/fix/grok-server-search-calls
fix(grok): keep xAI server-side search calls out of tool calls
2026-11-16 19:51:59 +08:00
Wesley Liddick 03c17491b3 Merge pull request #8661 from xy3xy3/feat/gemini-4-carbon-8658
feat(gemini): add Gemini 4 Carbon support
2026-11-16 19:51:51 +08:00
shaw 03a489e43e fix(grok): keep xAI flat error parsing out of the shared extractors
extractUpstreamErrorMessage and extractUpstreamErrorCode drive failover,
model-not-found cooldown and account-disable decisions on every platform.
Reading a top-level code there short-circuited the OpenAI-compatible
model-not-found failover for vLLM-style bodies such as
{"object":"error","message":"model not found","code":400}. It also
added top-level token_revoked as a new disable path.

Restore the shared helpers to main. Add Grok-only grokUpstreamErrorMessage
and grokUpstreamErrorCode for the media error path, the content-policy
message and the error passthrough rule, so the Grok media fix in this PR
is unchanged. Adds tests that the shared extractors ignore the xAI flat
shape and that model-not-found still fails over with a top-level code.
2026-11-16 19:28:14 +08:00
shaw 589166e320 Merge remote-tracking branch 'gh/main' into fix-8669 2026-11-16 19:26:42 +08:00
shaw 6613ced573 fix(openai): let enclosing tool-schema edits supersede nested ones
When additionalProperties is reopened to true, or a patternProperties entry
is dropped, any edit nested inside that span is moot. The edit merger
rejected such pairs as overlapping patches, so the sanitizer failed
locally and the gateway returned 502 instead of forwarding. On main the
same bodies reached upstream, which returned a 400. Order edits by start,
then insertions first, then widest span first, and skip spans fully
enclosed by an earlier edit. Every replacement in this sanitizer is a
constant, never derived from inner content. Partial overlaps still
error.
2026-11-16 19:26:32 +08:00
shaw a2dfcc259f Merge remote-tracking branch 'gh/main' into fix-8772 2026-11-16 19:25:48 +08:00
shaw bf3951a59e fix(monitor): don't flip channel monitor to error on OpenAI quota refresh failure
quota_refresh_failed only means the active probe could not refresh the
quota and the values come from an earlier observation. The probe is
throttled by openAIProbeCacheTTL, so only the read that triggered it
carries the code; treating it as a failure made the quota monitor flap
between error and operational roughly every 10 minutes. Exempt it like
grok's quota_unknown, so monitor status is derived from the cached
observation as before. Adds an end-to-end no-flap test.
2026-11-16 19:25:39 +08:00
shaw a535a921f1 Merge remote-tracking branch 'gh/main' into fix-8747 2026-11-16 19:24:41 +08:00
shaw 121a4cca17 fix(scheduler): keep openai_passthrough_model_filter in the scheduler snapshot
Candidate filtering reads the compact scheduler snapshot, which only keeps
allowlisted extra keys. Without openai_passthrough_model_filter the opt-in
filter was always false at selection time, so a passthrough account still
accepted every model while /v1/models (full account) hid them. Keep the
key in the projection and lock it with a round-trip test.
2026-11-16 19:24:32 +08:00
shaw 42efee245e Merge remote-tracking branch 'gh/main' into fix-8748 2026-11-16 19:22:51 +08:00
Wesley Liddick 8ed701382c Merge pull request #8833 from feeeei/perf/scheduler-snapshot-coalesce
perf(scheduler): 调度快照加载与数据库回源按 bucket 合并,减少大分组选号的整组复制
2026-11-16 18:47:48 +08:00
Wesley Liddick b140d5db8c Merge pull request #8816 from feeeei/perf/usage-billing-lane-zero-copy
perf: 同一用户的扣费按用户通道合并结算,请求体热点路径改用零拷贝读取
2026-11-16 18:47:40 +08:00
Wesley Liddick 04503e001e Merge pull request #8822 from feeeei/fix/gemini-native-sticky-session-hash
fix(gemini): 原生请求按稳定前缀生成粘性会话哈希,换号按上游实际用量计费
2026-11-16 18:47:32 +08:00
Wesley Liddick f242a6ea23 Merge pull request #8827 from feeeei/feat/gemini-vertex-multi-region
feat(gemini): Vertex 账号支持 us/eu 多区域端点,并按实际请求区域计价
2026-11-16 18:47:23 +08:00
Wesley Liddick 1cf7eb48c4 Merge pull request #8746 from feeeei/feat/gemini-4-hydrogen-pricing
feat(gemini): 补齐 Gemini 4 Hydrogen 计费
2026-11-16 18:47:15 +08:00
feeeei 32e70f3d40 feat(gemini): 补齐 Gemini 4 Hydrogen 计费
- 内置兜底价:gemini-4-hydrogen 为 $1.50 输入 / $7.50 输出 / $0.075 缓存读取
  (每百万 token),Priority 档为 1.8 倍;所有提示词长度同价
- 本地价格快照新增不带前缀的条目,含 Priority 档价格;只支持隐式缓存,
  不带存储价
2026-11-16 17:46:07 +08:00
ruixingshi 326ae1ffc9 Merge commit 'd70676756fd3a35b854d41aa46c07935bbef283f' into fix/openai-quota-freshness 2026-11-16 17:31:40 +08:00
ruixingshi c4ff9b90a9 test(openai): check quota snapshot timestamp type 2026-11-16 17:30:54 +08:00
Anankke 5f12044f59 fix(accounts): refetch Claude and Gemini usage cells when auto-refresh updates a row
With auto-refresh on, the accounts page replaces a row only when OpenAI or Grok usage inputs change, and AccountUsageCell watches only the OpenAI usage key, so Claude OAuth, setup-token and Gemini bars stay at what they loaded until the refresh button is clicked.

Add usage refresh keys for Claude (session window columns, passive samples in extra, last_used_at) and Gemini (updated_at, last_used_at), replace a row when either changes, and have the cell watch one key across the three platforms.

A change asks the batch loader for a forced refetch, or outside batch mode drops the cached entry and reloads, passive for Claude. Both backend paths read local data only, so a refetch per changed row sends no upstream request.
2026-11-16 01:29:16 -08:00
shaw 7f3fe5bfde Merge main into perf/scheduler-snapshot-coalesce
Resolve conflicts with #8729, which caches the configured account pool
and checks time-based blocks (rate limit, overload, temp-unschedulable)
on every read:

- readSnapshotAccounts filters by IsSchedulable on both the
  GetSnapshotValues path (in-place compaction of the caller-owned slice)
  and the GetSnapshot path.
- The coalesced DB fallback still publishes the full configured pool.
  Each caller's private copy contains only accounts that are
  schedulable now.
- The fallback test stubs now implement ListModelAvailabilityCandidates,
  which #8729 switched the DB fallback to. Values-reader fixtures are
  marked schedulable. Adds tests for time-blocked filtering on both paths
  and for publishing the full pool.
2026-11-16 17:18:20 +08:00
shaw 2164ea4878 fix(billing): apply Vertex multi-region multiplier to default pricing only
Group and channel prices are admin-configured final prices. The 1.1x
multi-region factor now applies only when the token cost comes from
default model pricing (LiteLLM/fallback). This matches account stats
cost, which already applied the factor only at the model-file pricing
tier. Adds a regression test for configured vs default pricing.
2026-11-16 17:06:53 +08:00
shaw 2286c26d1b Merge remote-tracking branch 'gh/main' into fix-8827 2026-11-16 17:05:04 +08:00
shaw 8d57f461ca fix(gemini): keep forced cache billing on sticky-session failover
Keep the stable content session hash from this PR, but restore
ForceCacheBilling on the native v1beta entry. Dropping it changed
billing policy: a sticky session that failed over would be charged
full input price instead of cache-read price. That also hit
Antigravity accounts served by this handler, and made it inconsistent
with /v1/messages, which still forces cache billing. Billing on this
entry is now identical to main.
2026-11-16 17:04:52 +08:00
shaw e391d5fa38 Merge remote-tracking branch 'gh/main' into fix-8822 2026-11-16 17:03:37 +08:00
shaw b46b3cbabc test(handler): follow normalizeCodexUntrustedContext rename from #8769
#8769 renamed normalizeCodexPageContext to normalizeCodexUntrustedContext;
the call-output gate test still referenced the old name, so go vet -tags unit
failed once both changes were on main.
2026-11-16 17:03:29 +08:00
shaw fb07aaee23 Merge remote-tracking branch 'gh/main' into fix-8816 2026-11-16 17:02:10 +08:00
Anankke 413f1cb08a fix(openai): keep xAI server-side search out of rebuilt buffered tool calls
A buffered request on a Grok account rebuilds an empty terminal output from the done items and renders its custom_tool_call items as tool_use or tool_calls.
An item that apicompat.IsServerSideSearchCall accepts is a search xAI ran itself, so it is no longer rendered as a client tool call.
The item stays in the output, so Grok SearchCount still counts it, and stop_reason and finish_reason follow the remaining content.
A new test covers an empty terminal on /v1/messages and /v1/chat/completions, with and without a client tool next to the search.
2026-11-16 00:43:36 -08:00
Anankke 7f1ecfaa2d fix(openai): follow the streaming path for rebuilt buffered items
A rebuilt output skips a web search that is not completed, gives an empty custom tool input as {} and keeps a reasoning signature that only the added event carries.
Deltas without an output_index join their item by item_id or as the newest open item of their kind, and deltas that came before the item was added belong to it.
Items that share an output_index or have none keep their own events: an item of another kind, a done item that is already closed and a different call_id each get their own slot.
2026-11-16 00:41:51 -08:00
Anankke 5279823757 fix(openai): complete buffered item parts by their own index
A message or reasoning item with several parts lost or doubled text when its done item left only some of them empty and the terminal output was empty.
Observe now keeps the deltas per content_index or summary_index, apart for output_text, refusal, summary_text and reasoning_text.
buildMessage and buildReasoning fill only the blank part whose own index has deltas and keep the parts with text and their order as the done item has them.
Deltas of an index the done item has no part for follow its parts.
2026-11-16 00:41:51 -08:00
Anankke 49ef5f6909 fix(openai): render custom tool calls only from rebuilt buffered output
A custom_tool_call in an output the upstream delivered is not a client tool call; 250deb70e5 rendered it on that path too, which turns xAI server-side searches into tool_use.
ResponsesResponse.RenderCustomToolCalls is set only when the buffered reader rebuilds an empty output, so a delivered output behaves as before the rework.
A reasoning done item that carries both a summary and raw reasoning_text content now takes its text from the deltas again, as the streaming path shows it.
2026-11-16 00:41:51 -08:00
Anankke fbe8c39a90 fix(apicompat): keep tool_use input a JSON object in buffered responses
A tool call whose arguments were not a JSON object (truncated by max_output_tokens, empty, or the free-form input of a custom_tool_call) made json.Marshal fail, so /v1/messages answered 200 with an empty body.
ResponsesToAnthropic now keeps an object as it is, uses {} for a function_call with anything else, and wraps a custom_tool_call input as {"input": ...}, the shape extractCustomToolCallInput reads back.
Both converters now render custom_tool_call items, which were dropped when the terminal output carried them.
The streaming converter is unchanged: it forwards the argument deltas as the upstream sent them.
2026-11-16 00:41:51 -08:00
Anankke 00b09b892d fix(openai): rebuild empty buffered terminal output from done items
An empty terminal output was rebuilt from merged deltas, so reasoning lost its per-item signature and segmentation, and message and tool order followed the accumulator instead of output_index.
The buffered reader now records every output item and rebuilds the terminal output from the output_item.done items in output_index order, taking deltas only for a field a done item left empty or for an item that never got a done event.
Items merge by item id, so items sharing an output_index stay apart and a repeated item replaces its earlier copy; response.cancelled terminals are filled too.
A non-empty terminal output is untouched. A new test compares /v1/messages and /v1/chat/completions with the streaming path on shapes taken from real Codex streams.
2026-11-16 00:41:51 -08:00
Anankke f72ef07097 fix(openai): keep hosted output items in buffered compat responses
Non-streaming /v1/messages and /v1/chat/completions force an upstream stream and read it with readOpenAICompatBufferedTerminal, and the Codex OAuth backend ends that stream with an empty terminal output.
The delta accumulator rebuilds only reasoning, message and function calls, so web_search_call, image_generation_call and other hosted items were dropped and /v1/messages lost its server_tool_use and web_search_tool_result blocks.
The reader now collects the output_item.done items of every type the accumulator does not produce and adds them to an empty terminal output, after the leading reasoning item and ahead of the message and function calls.
The accumulator's own items stay exactly as it builds them, so reasoning text, function call arguments and custom tool calls are unchanged, and a non-empty terminal output is untouched.
2026-11-16 00:41:40 -08:00
Anankke 70ad8365d9 fix(grok): keep xAI server-side search calls out of tool calls
On xAI upstreams a custom_tool_call whose call_id starts with xs_ or as_ is an xAI server-side search call, as the xAI tool usage docs define the prefixes.
The Messages and Chat Completions stream converters and the buffered accumulator no longer return such items as tool_use or tool calls, and stop_reason and finish_reason follow the remaining content.
Grok SearchCount counts each such item once; client custom tools and non-xAI upstreams are unchanged.
2026-11-16 00:40:53 -08:00
Wesley Liddick d70676756f Merge pull request #8840 from r266-tech/codex/channel-bedrock-compat-toggle
fix(channels): persist Bedrock compatibility as a boolean
2026-11-16 16:35:31 +08:00
Wesley Liddick 6b7cbc63be Merge pull request #8837 from Daiyangcheng/fix/seedance-scheduler-capability-projection
fix(scheduler): keep openai_capabilities in the scheduler metadata projection so Seedance accounts stay schedulable
2026-11-16 16:35:23 +08:00
Wesley Liddick 46b8792658 Merge pull request #8828 from little-greenbean/fix/gemini-parallel-tool-calls
fix(gemini): separate same-name parallel tool calls in streams
2026-11-16 16:35:14 +08:00
Wesley Liddick 4f3f916317 Merge pull request #8826 from william-drakemond/fix/compat-empty-stream-release-sticky
fix(antigravity): keepalive 后空流释放会话粘性账号 / Release the sticky account after a committed empty compat stream
2026-11-16 16:35:06 +08:00
Wesley Liddick f2eaed31c3 Merge pull request #8825 from r266-tech/codex/deepseek-explicit-pricing-overrides
fix(pricing): honor explicit DeepSeek token price overrides
2026-11-16 16:34:58 +08:00
Wesley Liddick 992ac63308 Merge pull request #8814 from qsy4/fix/openai-compat-stream-account-side-effects
fix(openai): apply account side effects to stream errors after output on compat paths
2026-11-16 16:34:50 +08:00
Wesley Liddick 101c2462dd Merge pull request #8813 from qsy4/fix/openai-sse-keepalive-before-first-output
fix(openai): forward upstream keepalive events before first output
2026-11-16 16:34:42 +08:00
Wesley Liddick 1ca302abf3 Merge pull request #8811 from Anankke/fix/messages-bridge-pre-content-failover
fix(openai): fail over Messages bridge errors before first content
2026-11-16 16:34:33 +08:00
Wesley Liddick 9750f8e039 Merge pull request #8808 from r266-tech/codex/first-output-spool-fallback
fix(openai): fall back to memory when first-output spool creation fails
2026-11-16 16:34:25 +08:00
Wesley Liddick 568db32f22 Merge pull request #8806 from feeeei/fix/usage-account-filter-actual-cost
fix(usage): 按账户筛选时模型与端点分布的实际扣费不再替换为账号成本
2026-11-16 16:34:16 +08:00
Wesley Liddick 119b04f945 Merge pull request #8800 from Anankke/fix/upstream-tcp-keepalive
fix(upstream): detect dead upstream connections in about 30s
2026-11-16 16:34:08 +08:00
Wesley Liddick 857ab95081 Merge pull request #8798 from Anankke/fix/pricing-startup-nonblocking
fix(pricing): check remote hash in background at startup
2026-11-16 16:34:00 +08:00
Wesley Liddick 470c02b399 Merge pull request #8796 from Anankke/fix/composite-route-public-model-response
fix(gateway): restore public model in composite-routed responses
2026-11-16 16:33:53 +08:00
Wesley Liddick 97957edd9e Merge pull request #8790 from Anankke/fix/websearch-account-mode-platforms
fix(websearch): honor account mode on every channel-toggle platform
2026-11-16 16:33:45 +08:00
Wesley Liddick 63751ea4de Merge pull request #8788 from Anankke/fix/count-tokens-passthrough-duplicate-headers
fix(gateway): stop duplicating headers on count_tokens passthrough
2026-11-16 16:33:38 +08:00
Wesley Liddick 1d585c94fd Merge pull request #8786 from Anankke/fix/chat-completions-metadata-user-id
fix(gateway): keep client metadata.user_id in Chat Completions to Anthropic
2026-11-16 16:33:30 +08:00
Wesley Liddick 4cebc098c3 Merge pull request #8779 from lishuangqiang/fix/anthropic-fable-model-limit-recovery
fix(ratelimit): lift Anthropic Fable model limit when the 7d_oi window recovers
2026-11-16 16:33:22 +08:00
Wesley Liddick c7df3b693f Merge pull request #8775 from Henglie/fix/web-no-store-settings-html
fix(web): stop caching settings-injected HTML
2026-11-16 16:33:15 +08:00
Wesley Liddick d31a87a4e2 Merge pull request #8769 from Undertone0809/codex/fix-codex-http-context
fix(openai): normalize additional Codex context on HTTP Responses
2026-11-16 16:33:07 +08:00
Wesley Liddick 56848016c5 Merge pull request #8763 from wc4440222/fix/kimi-monthly-quota
fix(kimi): 解析新套餐月度额度并清理缺席窗口快照
2026-11-16 16:32:59 +08:00
Wesley Liddick 4763569af2 Merge pull request #8761 from CooCoode/fix/8760-cc-responses-strict-default
fix(apicompat): default json_schema strict=false when converting CC to Responses
2026-11-16 16:32:51 +08:00
Wesley Liddick 202740441d Merge pull request #8759 from r266-tech/codex/gemini-schema-array-items
fix(antigravity): match schema items to the selected type
2026-11-16 16:32:44 +08:00
Wesley Liddick 3b5310c5d5 Merge pull request #8757 from Anandb71/arbor/sonnet-4-5-retirement
fix(claude): default account tests to claude-sonnet-4-6
2026-11-16 16:32:36 +08:00
Wesley Liddick e16a349ebb Merge pull request #8754 from r266-tech/codex/preserve-additional-tools-id
fix(codex): preserve and normalize additional_tools IDs
2026-11-16 16:32:27 +08:00
Wesley Liddick 8a585c9141 Merge pull request #8745 from wozhenbang2004/fix/anthropic-compat-observation-8714
fix(gateway): record Anthropic response models in compatibility routes
2026-11-16 16:32:19 +08:00
Wesley Liddick 6247d33eb6 Merge pull request #8743 from r266-tech/codex/fix-peak-rate-usage-test
test(billing): make peak-rate usage tests independent of wall clock
2026-11-16 16:32:11 +08:00
Wesley Liddick 6fd905f30d Merge pull request #8742 from r266-tech/codex/per-turn-control-beta
fix(gateway): preserve message output config with per-turn beta
2026-11-16 16:32:02 +08:00
Wesley Liddick e54a186548 Merge pull request #8741 from r266-tech/codex/native-anthropic-error-endpoint
fix(gateway): record native Anthropic endpoints on error paths
2026-11-16 16:31:55 +08:00
Wesley Liddick 0563176a5d Merge pull request #8740 from r266-tech/codex/gemini-usage-refetch
fix(accounts): keep Gemini usage bars visible during refetch
2026-11-16 16:31:47 +08:00
Wesley Liddick c782537eef Merge pull request #8739 from r266-tech/codex/anthropic-compat-effort-policy
fix(gateway): enforce effort policies on Anthropic compatibility routes
2026-11-16 16:31:39 +08:00
Wesley Liddick d7ae0544e8 Merge pull request #8738 from r266-tech/codex/reactive-cn-quota-snapshots
fix(cn-quota): refresh usage cells with account snapshots
2026-11-16 16:31:31 +08:00
Wesley Liddick 5146728d2f Merge pull request #8737 from r266-tech/codex/claude-rotated-token-retry
fix(claude): recover requests after concurrent token rotation
2026-11-16 16:31:22 +08:00
Wesley Liddick 472ea57525 Merge pull request #8736 from wozhenbang2004/fix/whitelist-wildcard-8710
fix(accounts): reject wildcard model whitelist entries
2026-11-16 16:31:14 +08:00
Wesley Liddick eb25511c71 Merge pull request #8735 from Hato626/perf/oauth-input-metadata-cleanup
perf(openai): avoid repeated full-body copies during OAuth metadata cleanup
2026-11-16 16:31:06 +08:00
Wesley Liddick c6d9d48f9a Merge pull request #8729 from r266-tech/codex/snapshot-transient-expiry
fix(scheduler): recover snapshot accounts after cooldown expiry
2026-11-16 16:30:58 +08:00
Wesley Liddick a38ffc3050 Merge pull request #8728 from r266-tech/codex/chat-fallback-response-observation
fix(usage): retain response models through Chat fallbacks
2026-11-16 16:30:49 +08:00
Wesley Liddick 32e4283894 Merge pull request #8727 from r266-tech/codex/native-anthropic-response-observation
fix(usage): retain native Anthropic response observations
2026-11-16 16:30:41 +08:00
Wesley Liddick 51e76a46c1 Merge pull request #8726 from r266-tech/codex/sticky-writeback-after-disconnect
fix(gateway): retain sticky writes after client disconnects
2026-11-16 16:30:34 +08:00
Wesley Liddick 90eb1744d4 Merge pull request #8723 from cyhhao/fix/keep-weekly-usage-on-5h-rollover
fix(anthropic): keep weekly usage readings across 5h rollovers
2026-11-16 16:30:26 +08:00
Wesley Liddick 0b473ad60b Merge pull request #8703 from Anankke/fix/responses-bridge-mid-system
fix(apicompat): send mid-conversation system messages to Responses as developer
2026-11-16 16:30:18 +08:00
Wesley Liddick 2df3dbcfbb Merge pull request #8698 from r266-tech/codex/anthropic-quota-window-start
fix(usage): advance five-hour window start on active quota sync
2026-11-16 16:30:11 +08:00
Wesley Liddick fde504e343 Merge pull request #8693 from feeeei/fix/group-usage-rollup-nonblocking
fix(usage): 分组日汇总重建与保留期清理不阻塞 usage_logs 写入
2026-11-16 16:30:03 +08:00
Wesley Liddick 910d4d86b2 Merge pull request #8684 from feeeei/fix/login-email-identity-backfill-nil
fix(auth): 登录回填 email 身份失败时不再 panic
2026-11-16 16:29:55 +08:00
Wesley Liddick 89fce5446d Merge pull request #8682 from r266-tech/codex/preserve-sealed-call-content
fix(apicompat): retain encrypted function call content
2026-11-16 16:29:47 +08:00
Wesley Liddick bd3a878ef4 Merge pull request #8678 from Cylion-bot/codex/disable-concurrency-ping
fix: allow disabling concurrency wait pings
2026-11-16 16:29:39 +08:00
Wesley Liddick 0ebc8b2fd6 Merge pull request #8675 from feeeei/fix/bedrock-error-classification
fix(bedrock): 按错误语义区分封号、用例缺失、限流与内容过滤,流中断保留 usage
2026-11-16 16:29:32 +08:00
Wesley Liddick 8da0388542 Merge pull request #8673 from baryon/contrib/antigravity-compat-gemini-stream-timeout
fix(antigravity): stream Gemini compat thoughts and anchor pre-content timeout after headers
2026-11-16 16:29:24 +08:00
Wesley Liddick 41c567b38f Merge pull request #8667 from lishuangqiang/perf/anthropic-request-json
perf(gateway): trim per-request JSON work on the Anthropic request path
2026-11-16 16:29:15 +08:00
Wesley Liddick a6e02a37aa Merge pull request #8664 from jaxxjj/codex/openai-fork-prompt-cache-namespace
fix(openai): keep Codex forks on their parent's prompt cache key
2026-11-16 16:29:06 +08:00
Wesley Liddick 980ddd9425 Merge pull request #8662 from feeeei/fix/gemini-chat-response-format
fix(gemini): 兼容入口 chat 请求转发 response_format 结构化输出
2026-11-16 16:28:58 +08:00
Wesley Liddick 0c641e5ed7 Merge pull request #8659 from lishuangqiang/fix/group-rate-sync-transaction
fix(billing): make group rate/RPM sync transactional
2026-11-16 16:28:50 +08:00
Wesley Liddick 83a1f5dbe8 Merge pull request #8653 from lishuangqiang/perf/anthropic-stream-fast-path
perf(gateway): skip JSON decode for forwarded Anthropic stream events
2026-11-16 16:28:42 +08:00
Wesley Liddick 314de5d0c0 Merge pull request #8651 from lishuangqiang/fix/rpm-override-group-scope
fix(billing): scope RPM override to the group it belongs to
2026-11-16 16:28:34 +08:00
Wesley Liddick d7d45924e8 Merge pull request #8649 from lishuangqiang/fix/alipay-stable-refund-request-id
fix(payment): make Alipay refund request id stable across retries
2026-11-16 16:28:26 +08:00
Wesley Liddick a81a345a17 Merge pull request #8644 from r266-tech/codex/claude-usage-scoped-limits
fix(usage): read Fable weekly quotas from scoped limits
2026-11-16 16:28:19 +08:00
Wesley Liddick e3151c5201 Merge pull request #8767 from lishuangqiang/chore/bump-go-1.27.4
chore(ci): bump Go toolchain to 1.27.4 for GO-2026-6859
2026-11-16 16:14:25 +08:00
r266-tech 5c96ee4d29 fix(channels): persist Bedrock compatibility as a boolean 2026-11-16 05:53:22 +08:00
Daiyangcheng cca745e8be fix(scheduler): keep openai_capabilities in the scheduler projection 2026-11-15 21:17:48 +08:00
feeeei 9c32800986 perf(scheduler): 调度快照加载与数据库回源按 bucket 合并,减少大分组选号的整组复制
分组账号数多时,进程内快照条目失效后每个并发请求各自 ZRANGE + MGET 全部精简记录并
逐个解码;Redis 读失败时每个请求又各自回源数据库并回写整份快照。每次选号还要把整组
账号按值复制三遍,并分块串行 MGET 全部 last_used。

- 快照条目加载按 (bucket, active, 修订号) 合并为一次,加载与调用方取消解耦;
  (active, 修订号) 未变、仅超过 10s 直接复用时长的条目在 20s 宽限期内先返回,
  同时由一次后台加载刷新,修订号或 active 变化时仍等待新数据
- 重新加载时,精简记录原文未变且模型映射预解析对应当前运行时版本的账号沿用已解码母本
- last_used 读取结果在条目内复用 200ms,本进程写入 last_used 后立即失效;
  多个分块的 MGET 放进同一个 pipeline 一次往返
- 新增 GetSnapshotValues 直接返回值切片,服务层优先使用,省掉 derefAccounts 的复制;
  调度阈值过滤改为原地压缩
- 数据库回源按 bucket 合并:取发布令牌、读库与回写在一次共享调用里完成,
  未配置 db_fallback_timeout_seconds 时上限 30s,各调用方得到独立的切片

压测(单用户 Bedrock、关闭在途预留):300 号 57.7K→61.6K RPM,500 号 42.3K→50.0K RPM。
2026-11-15 18:32:56 +08:00
green_bean ce026a2cbf fix(gemini): retain complete string argument snapshots 2026-11-15 13:52:12 +08:00
green_bean ddb7eac633 chore(go): upgrade to 1.27.4 to resolve security check 2026-11-15 13:13:53 +08:00
green_bean 27a61be4c9 fix(gemini): preserve final snapshots of fragmented tool calls 2026-11-15 12:52:06 +08:00
green_bean b0d60a8c86 fix(gemini): separate same-name parallel tool calls in streams 2026-11-15 12:30:23 +08:00
feeeei 68071ddde1 feat(gemini): Vertex 多区域端点按实际请求区域加价 10%
- 转发结果记录上游端点价格倍数:Gemini 请求实际发往 us/eu 且模型在
  vertexModelLocations 中声明支持该多区域时为 1.1,发往 global 时为 1;
  引用显式缓存的请求按缓存所在区域判断
- 倍数只作用于按 token 计费的费用(输入、输出、缓存读取、缓存创建),
  按次与按张计费不变,显式缓存存储费与联网搜索费在其后按原价叠加
- 建缓存的预扣报价与记账按缓存所在区域带上倍数
- 账号统计成本按模型定价文件计算时同样乘倍数,自定义规则与渠道计费档不变
2026-11-15 12:10:46 +08:00
feeeei b32ad6dfe1 feat(gemini): Vertex 账号支持 us/eu 多区域端点并按模型降级 global
- 多区域使用 aiplatform.{us|eu}.rep.googleapis.com 主机,生成、Claude、显式缓存、
  模型列表、批量生图的主机名统一由 vertexAPIHost 生成
- 内置模型可用区域表 vertexModelLocations:Gemini 账号区域为 us/eu 时,表内支持
  该区域的模型走多区域端点,其余模型走 global;global、单区域账号与非 Gemini
  平台账号不查表,vertex_model_locations 按模型覆盖仍优先
- 请求引用 Vertex 显式缓存时按缓存所在区域发送,账号区域变更后存量缓存仍可引用
- 多区域账号查询单个模型时核对 global 模型列表
2026-11-15 12:10:46 +08:00
William Drake 5cbcb1b591 fix(antigravity): release the sticky account after a committed empty compat stream
A compat stream (Responses / Chat Completions over Antigravity) sends a
pre-content keepalive after 15 s, which commits HTTP 200. If the upstream
then ends or times out with no content, the response can no longer fail
over: the client gets an SSE empty_stream / stream_timeout error and
retries. The session stayed bound to the same account, so every retry went
back to it; on 2026-11-15 one Codex session at ~390k tokens hit
empty_stream 22 times in 30 minutes on one account while the others served
the same model.

The stream now returns a typed committed-no-content error for both cases,
and the Responses and Chat Completions handlers remove the session's sticky
binding while it still points at the failed account. Only that session is
affected: the account is not cooled or excluded for anyone else, so a
request-caused empty stream cannot take a shared account offline.
2026-11-14 21:03:17 -07:00
William Drake d3716a1730 test(antigravity): a committed empty compat stream should release the session's sticky account 2026-11-14 21:02:45 -07:00
r266-tech b7878328b6 fix(pricing): honor explicit DeepSeek token price overrides 2026-11-15 11:43:52 +08:00
feeeei b6c21cd5e7 fix(gemini): 原生请求按稳定前缀生成粘性会话哈希,换号按上游实际用量计费
- 非 Gemini CLI 客户端的粘性哈希此前取 IP + UA + Key + system + 全部 contents
  文本,每轮都变,Redis 绑定在后续轮次永远查不到;只有进程内摘要链能把"完整包含
  上一次请求"的纯追加对话留在原号。末尾内容每轮改写(引导/备注)或编辑最后一条
  消息的对话每轮都落到不同账号,Vertex 隐式缓存按项目隔离,因此几乎不命中
- 改为 API Key + 模型(渠道映射前)+ tools + systemInstruction + 第一条 user
  contents 的 parts,取法与 OpenAI 内容兜底 deriveOpenAIContentSessionSeed 一致,
  另加 API Key 隔离租户;JSON 规范化后用 xxhash 流式计算,输出与
  DeriveSessionHashFromSeed 相同
- 第一条 user 指 role 为 user 或省略的第一条 contents,跳过它之前的 model 开场白;
  其 parts 没有有效内容(非空白 text 或带字段的其他 part)时不建立粘性
- Gemini CLI 会话标识仍优先;引用显式缓存的请求仍不参与粘性;摘要链兜底保留,
  只在没有绑定时运行
- 粘性会话换号时不再强制缓存计费:此前整段 input 按缓存读取计费,而新账号上游
  按全价收取,原号上本就不会命中的新增末尾也被一并打折;粘性生效后绑定请求大幅
  增加,该补偿的覆盖面随之扩大。现按上游实际返回的用量计费,缓存读取只来自
  cachedContentTokenCount
2026-11-15 11:28:02 +08:00
lishuangqiang e257b78117 chore(ci): bump Go toolchain to 1.27.4 for GO-2026-6859
backend-security 的 govulncheck 现在报标准库漏洞:

    Vulnerability #1: GO-2026-6859
        HTTP/1 server crash due to MaxBytesReader header race in net/http
        Found in: net/http@go1.27.3
        Fixed in: net/http@go1.27.4

仓库把 Go 版本固定在 1.27.3(go.mod + workflow 硬断言 + 三个 Dockerfile),
所以所有 PR 的 backend-security 都会失败,与具体改动无关。

同步升级 8 处版本点:

- backend/go.mod:go 1.27.3 → 1.27.4
- security-scan.yml / backend-ci.yml(两处)/ release.yml:go1.27.4 断言
- Dockerfile / deploy/Dockerfile / backend/Dockerfile:golang:1.27.4-alpine
- DEV_GUIDE.md 的 CI 要求说明同步更新

验证:GOTOOLCHAIN=go1.27.4 go build ./... 通过,
GOTOOLCHAIN=go1.27.4 go test -tags unit ./internal/service/ 针对性用例通过。

(cherry picked from commit a293214977)
2026-11-15 00:18:54 +08:00
Anankke 3f1a7c6d9d fix(apicompat): keep forced tools, result text and reserved names intact
A revealed tool was declared in tool_search_output under its own name while its replayed function_call used the Codex reserved-name alias, so the two disagreed for python. Reserved-name collection now walks tool_search_output tools like additional_tools. The collector is shared with the /v1/responses passthrough entries, so they now alias tool_search_output definitions too.
The Responses API has no tool_choice value that forces tool_search or a tool that only tool_search_output declares, so a request forcing ToolSearch or a deferred tool keeps the plain function mapping and its body is unchanged.
tool_search_output has no field for the result text, so text and errors from a ToolSearch result ride in a separate input_text part of the user message after the tool outputs, ahead of the user's own parts.
2026-11-14 08:12:29 -08:00
feeeei ade20f4e47 perf(gateway): 请求体热点路径改用零拷贝读取,减少整段解码与复制
大请求体上,几个只读检查一遇到任意 \u 转义就整段解码,gjson.GetBytes 会复制整段
input/messages,sjson 删除不存在的键时也会先复制整个 body。

- 新增 JSONMayEscapePlainASCII:成对扫描 JSON 转义,只有能拼出可见 ASCII 的 \u 才让
  字面量快速判断失效;控制字符、HTML 安全转义和非 ASCII 字符的转义不再触发完整解码。
  用于 codex bootstrap / page context 候选、compaction_trigger、input_image、
  additional_tools 的快速判断。
- OpenAI Responses:
  - namespace 声明、tools 判断、空 base64 图片、compaction_trigger 检测与 namespace
    剥离改用 parseRawJSONView,不再复制整段 input/tools。
  - compaction_trigger 只字面出现一次且是 input 最后一项的 type 时跳过完整解码。
  - codex 调用输出候选在字面量命中后,用零拷贝视图确认 input 中确有对应名字的
    function_call_output 项;只在工具声明里出现同名时不再做唯一性扫描和完整解码。
- Bedrock:
  - 顶层字段删除前先用零拷贝视图确认存在。
  - cache_control 清理和流事件 bytes 字段改用零拷贝读取。
- NormalizeMaxReasoningEffort 复用包级 strings.Replacer。

合法 JSON 上行为不变,新增测试与总走解码/复制的参考实现做差分比较。只在非法或病态
body 上有差异:嵌套超过 10000 层且只含非 ASCII 转义、或 trigger 已在末尾时,不再报
解码深度错误(gjson 校验没有深度上限,无字面量 body 原本即如此);开头带非 JSON
前缀的非法 body,零拷贝视图读不到其后的对象,这类 body 随后仍被 JSON 校验拒绝。
2026-11-15 00:05:38 +08:00
feeeei 2101f4f940 perf(billing): 同一用户的扣费按用户通道合并结算,消除余额热点行排队
每个请求一个扣费事务时,同一用户的 UPDATE users SET balance 在同一行上排队抢行锁,单用户吞吐
约 1000 RPS;用量队列溢出转同步扣费后,延迟升到十几秒、内存涨到 GB 级。

- 新增 UsageBillingLaneCombiner 作为 UsageBillingRepository 注入:按用户 id 分 64 片,每个用户
  一条结算通道。通道空闲时请求立即走单条 Apply;结算进行中到达的请求排队,下一轮最多 128 条在
  一个事务内由 ApplyBatch 结算,每个调用方拿到自己的结果。不设攒批等待计时器,也不设配置开关。
- ApplyBatch 与按顺序逐条 Apply 等价:批量认领 usage_billing_dedup(指纹冲突、归档命中按条返回),
  每个用户只扣一次余额;透支、Key 额度耗尽、账号额度越线等逐条结果用 decimal 前缀和还原。加锁
  顺序为 user_subscriptions → users → api_keys → accounts,表内按 id 升序。账号额度越线时每批
  每个账号写一条 scheduler outbox。
- 批量返回错误或 panic 时整批回滚,逐条回退到单条 Apply,共用一个截止时间;排队请求的结算超时
  从结算开始时计。
- applyUsageBilling 在 Apply 返回后用独立超时做鉴权缓存失效与余额缓存同步。
- BatchUpdateLastUsed 在同一事务内先按 id 升序 FOR NO KEY UPDATE 锁定账号行再更新,不阻塞引用
  accounts 的外键检查。
- 停机时 cleanup 等待各通道排空,之后的请求直连仓储。

bench(关闭在途预留):单用户闭环 200 并发 823 → 1564 RPS;
s1500 成功率 70% → 100%;16 用户闭环 1355 → 1619 RPS;s1000 p99 总耗时 10.2s → 2.3s、内存
3.2GB → 1.2GB(对比改动前)。低负载无回退,对账差额为 0。
2026-11-15 00:05:38 +08:00
Anankke f1013f177f fix(openai): SSE errors after keepalive, passthrough rules on exhaustion
Once keepalive has committed the response as SSE, failover can continue, so every later error in the Messages loop must be an SSE event. ensureAnthropicErrorResponse no longer counts keepalive-only output as a written response, and the OpenCode unsupported-model error goes through writeAnthropicError.

A failover-eligible failed or error frame no longer ends the stream inline but reaches the exhaustion path, so the failover error now carries the frame and exhaustion applies the error passthrough rule that matches it, as the inline path did. The lookup also runs for a first event frame and a stream=false request, where main skipped it.
2026-11-14 08:04:02 -08:00
Anankke 30152d1b16 fix(apicompat): tolerate non-string action.url and skip unfinished web_search calls
WebSearchAction.URL was a strict string, so a web_search_call whose action.url was not a string failed decoding of the whole Responses event and the Messages stream lost its terminal event. It is now raw like Sources and read as a string only for open_page.

The non-streaming converter also filled results for web_search_call items that had not completed, while the streaming one only handles completed items. Both now emit blocks for completed calls only.
2026-11-14 07:47:35 -08:00
qsy4 975b2807d1 fix(openai): apply account side effects to stream errors after output on compat paths
Problem: on /v1/chat/completions and /v1/messages the upstream responses
stream is converted as it arrives, so client output starts with the first
event (a role chunk or message_start written for response.created). A
terminal error event that arrives after that can no longer fail over, and
the branch that handles it only records the error. Unlike /v1/responses
and the WebSocket forwarder, which call
handleOpenAIStreamTerminalAccountSideEffects in the same situation, the
account health is never updated: a rate limited, quota exhausted or
deauthorized account stays schedulable and every new request routed to it
fails the same way.

Fix: call handleOpenAIStreamTerminalAccountSideEffects in the
non-failover branch of both compat stream handlers, before the error is
recorded, with the same arguments the failover constructor uses. The
failover branch is unchanged; it already applies the side effects inside
newOpenAIStreamFailoverErrorWithModel, so each upstream attempt is still
counted once.

Test: TestForwardAsChatCompletions_StreamErrorAfterOutputAppliesAccountSideEffects
and TestForwardAsAnthropic_StreamErrorAfterOutputAppliesAccountSideEffects
check that an auth error after output marks the account exactly once. The
two StreamErrorBeforeOutputCountsOnce tests check that the failover path
still marks the account exactly once.
2026-11-14 07:41:11 -08:00
shaw 330198321f feat(groups): 分组支持强制 OpenAI Ultra Fast 档位
OpenAI / Composite 分组新增 force_openai_ultrafast:开启后该分组经 OpenAI 账号
转发的请求强制写入 service_tier=ultrafast,覆盖客户端传入的值。

- 与 force_openai_fast 互斥,服务层同时为真返回 400
  (GROUP_OPENAI_FORCED_SERVICE_TIER_CONFLICT);不支持的平台两者一并清零
- HTTP Forward、原始 body(chat / messages / 透传)与 WebSocket
  response.create 三条路径统一经 openAIGroupForcedServiceTier 取强制档位
- 分组强制先写入,全局 Fast/Flex 策略随后裁决,仍可按模型白名单过滤、
  拦截或降为 priority
- 计费不变:Ultrafast 按 Ultrafast 价计费,"免费 Fast"只覆盖 priority
- 迁移 251 仅新增列(默认 false);鉴权缓存快照版本升至 28
- 管理端分组表单把"强制使用 Fast"开关改为三选一:跟随客户端 / 强制 Fast /
  强制 Ultra Fast

Closes #8657
2026-11-14 23:35:49 +08:00
qsy4 c1c9d195b3 fix(openai): forward upstream keepalive events before first output
Problem: on native Responses streams the gateway stages every event of an
attempt until the first semantic output, so it can still fail over to
another account. Upstream keepalive events are staged with the rest. When
the upstream is silent for a long time (long high-effort reasoning), the
client only receives ":" comment heartbeats. Codex resets its stream idle
timer on parsed SSE events only, so it gives up after its 300 second idle
timeout ("idle timeout waiting for SSE") while the upstream is still
working, and the gateway keeps reading a stream nobody will receive.

Fix: while the first-output stage is open, write upstream keepalive
events (both the "event: keepalive" + data form and the data-only form)
straight to the client, the same way the comment keepalive bypasses the
stage: only the stable SSE headers are committed, the attempt's
lifecycle events and account headers stay private, and the bytes are
recorded with recordOpenAIStreamKeepaliveBytes so they still do not count
as client output and pre-output failover keeps working. The WebSocket to
HTTP bridge already forwards keepalive before first output this way.
Events after output started are unchanged.

Keepalive events are not output, so they do not stop the first-output
timer: with gateway.openai_first_output_timeout_seconds set, a stalled
attempt still fails over on time while the client stays connected.

Test: TestOpenAINativeStreamForwardsUpstreamKeepaliveBeforeFirstOutput
covers both frame shapes. TestOpenAINativeStreamKeepaliveThenFailoverContinuesWithNextAccount
checks that failover after a forwarded keepalive streams the next account
from its start. TestOpenAINativeStreamKeepaliveDoesNotResetFirstOutputTimeout
checks that paced keepalives do not postpone the timeout.
TestOpenAINativeStreamKeepaliveAfterOutputStaysInOrder guards the
post-output path.

TestOpenAIStreamMetadataAndKeepaliveBeforeOverloadFailOver,
TestOpenAIStreamKeepaliveOnlyFailureDoesNotRecordFirstToken and
TestOpenAINativeMetadataAndKeepaliveDoNotDisarmFirstOutputTimeout asserted
that the client receives nothing before first output on the native path.
Their native cases now assert that only the upstream keepalive frames
reach the client and that those bytes still do not count as output; the
passthrough cases are unchanged.
2026-11-14 07:30:35 -08:00
Anankke 94e56dd192 fix(upstream): do not fail the dial when TCP_USER_TIMEOUT cannot be set
upstreamDialControl returned the setsockopt error, so a kernel or socket that refuses TCP_USER_TIMEOUT made every dial through newUpstreamDialer fail, where the keep-alive options alone never do that.

A failure is now logged and the dial goes on without the option, as the standard library does for the keep-alive options.
2026-11-14 07:03:11 -08:00
Anankke 7349750c01 fix(gateway): limit composite model rewrite to message_start events
On the Anthropic forward streaming path the public model was written into any event carrying a message object, while the API key passthrough path only rewrites message_start. Rewrite message_start only on both.

The passthrough path also added a model field to a message_start that had none, which the non-streaming path does not do. Skip the rewrite when the field is absent.
2026-11-14 06:50:16 -08:00
Anankke 38eb97bd7a fix(openai): fail over Messages bridge errors before first content
The Messages bridge wrote message_start as soon as upstream sent response.created, and a keepalive ping after one silent keepalive interval also counted as output, so the failover branches for failed frames, error frames and a missing terminal event could never run on a real stream and the error went to the client.
The prelude is now held until the first content_block_delta, a terminal event or a failure. No change to which errors fail over: read errors still do not, and failures that do not fail over release the held prelude so the client sees the same bytes as before.
Keepalive pings still flow while held and are counted as keepalive bytes, so the handler compares the written size net of them and writes later errors as SSE events.
A cancelled request context while the prelude is held counts as a client disconnect, not an upstream failure.
2026-11-14 06:08:05 -08:00
r266-tech 82cd13d1ec fix(openai): fall back to memory when first-output spool creation fails 2026-11-14 21:28:25 +08:00
feeeei d05e8ef033 fix(usage): 按账户筛选时模型与端点分布的实际扣费不再替换为账号成本
模型统计和端点统计在仅按 account_id 过滤(无 user_id/api_key_id)时,
把 actual_cost 换成了账号成本 SUM(COALESCE(account_stats_cost, total_cost)
* COALESCE(account_rate_multiplier, 1));展开后的用户明细与分组分布用的是
真实 SUM(actual_cost),于是模型行「实际」会小于其下单个用户行的「实际」,
且与同页「成本」列数值相同。

- actual_cost 统一为用户实际扣费,账号成本由 account_cost 承载;
  EndpointStat 新增 account_cost,端点分布表增加「成本」列,用户侧
  /api/v1/usage/stats 清零该字段、用户页隐藏该列
- Gemini 配额用量(geminiAggregateUsage、GetGeminiUsageTotalsBatch)
  显式按账号成本累计,账号用量窗口展示不变

接口口径变化:仅按账户过滤时,/admin/dashboard/models、/admin/usage/stats
的 endpoints/upstream_endpoints/endpoint_paths、/admin/accounts/:id/stats
的 models/endpoints 中 actual_cost 由账号成本改为用户实际扣费,账号成本改看
account_cost;/admin/accounts/:id/stats 的 history/summary 口径不变。
2026-11-14 21:17:57 +08:00
Anankke 5e322694e7 fix(apicompat): map ToolSearch to native tool_search for Codex OAuth
The Messages to Responses bridge turned every ToolSearch tool_result made of tool_reference blocks into "(empty)" and sent every defer_loading tool as a top-level function.
On ChatGPT/Codex accounts whose model reports supports_search_tool (Grok excluded, xAI has no tool_search) ToolSearch now maps to the native client-executed tool_search, history becomes tool_search_call and tool_search_output carrying the revealed definitions, and an upstream tool_search_call comes back as a ToolSearch tool_use on both the streaming and buffered paths.
Deferred tools stay out of the top-level tools so the prompt cache prefix is the same before and after a reveal.
Requests that do not declare ToolSearch are left untouched.
2026-11-14 04:54:57 -08:00
Anankke e2631bbb38 feat(gateway): write Claude Code compaction requests at 5m cache TTL
With the 1h cache TTL injection on, every breakpoint of a compaction request was rewritten to 1h, although the conversation is replaced by the summary afterwards and nothing reads the tokens added since the last main-thread breakpoint again.

A compaction request is recognised by the fixed preamble of the compact prompt in the last user message. Every breakpoint becomes 5m, including one the client already wrote as 1h.

A 5m breakpoint still reads the prefix the main thread cached at 1h, and an all-5m request keeps the tools, system, messages TTL order Anthropic requires. The admin settings hint for the switch names the exception.
2026-11-14 04:40:24 -08:00
Anankke aee71b85b9 fix(gateway): restore public model in composite-routed responses
When a composite route rewrites the request model to the route's upstream model, Messages responses reported the upstream model instead of the public model the client asked for.

Restore the public name in streaming and non-streaming responses on the Anthropic forward path, the Anthropic API-key passthrough, and the Messages-to-OpenAI Responses and Chat Completions bridges. The Bedrock, Gemini and Antigravity paths and the native Anthropic relay on OpenAI gateway accounts are not covered here.

Responses are unchanged when no route matched or the route did not rename the model.
2026-11-14 04:17:17 -08:00
Anankke 1f22424362 fix(gateway): keep client metadata.user_id in Chat Completions to Anthropic
ChatCompletionsRequest and ResponsesRequest have no metadata field and the conversion never sets AnthropicRequest.Metadata, so the user_id a client sends in metadata never reached the Anthropic request.

withChatCompletionsMetadataUserID sets metadata.user_id on the converted body, byte for byte, when the client's top-level metadata.user_id is a string that ParseMetadataUserID accepts. Other metadata keys and ids that do not parse are not carried, and the body is unchanged in every other case.

It is called right after the Anthropic body is marshaled in GatewayService.ForwardAsChatCompletions, for non-OAuth accounts only, and in OpenAIGatewayService.forwardChatCompletionsViaNativeAnthropic, which only serves API key accounts. OAuth accounts are unchanged: the mimicry already synthesizes their metadata.user_id.

Fixes #8783
2026-11-14 04:16:06 -08:00
Anankke aa5a020bd1 feat(apicompat): return web_search sources in web_search_tool_result blocks
The Messages bridge always answered an OpenAI web_search_call with an empty web_search_tool_result, so clients never saw the pages the search used.

Bridge requests on the OpenAI platform that carry a web_search tool now ask for web_search_call.action.sources. Each call's sources, or the page a completed open_page opened, become that call's web_search_tool_result entries, in both the streaming and non-streaming paths.

Sources are decoded entry by entry so a malformed entry cannot drop the terminal event.
2026-11-14 04:15:35 -08:00
Anankke 5854a1db43 fix(upstream): detect dead upstream connections in about 30s
Connections from newUpstreamDialer were dialed with net.Dialer{KeepAlive: 30s}. Go then keeps TCP_KEEPINTVL 15 s and TCP_KEEPCNT 9, so a peer that stops answering is declared dead 165 s after its last packet, and no TCP_USER_TIMEOUT is set.

The dialer now sets KeepAliveConfig{Idle 15 s, Interval 5 s, Count 3} and, on Linux, TCP_USER_TIMEOUT 30 s (idle + interval x count) through Dialer.Control. Other platforms keep the keep-alive configuration only.

SOCKS5 and TLS fingerprint transports keep their own dialers.
2026-11-14 04:13:19 -08:00
Anankke 2b86d2f6a0 fix(gateway): stop duplicating headers on count_tokens passthrough
The count_tokens passthrough builder copies client headers under their wire casing (lowercase content-type and anthropic-version) but looked them up with the canonical-key Header.Get before filling in defaults. A client that sent them got a second canonical Content-Type and Anthropic-Version next to the wire-cased one. The builder now checks and fills them with getHeaderRaw and setHeaderRaw.

The Claude mimic debug line read the same raw-cased headers with Header.Get and logged empty values. It now reads them with getHeaderRaw.
2026-11-14 04:11:53 -08:00
Anankke c45ef4116f fix(pricing): check remote hash in background at startup
Initialize waited on the remote hash fetch before the server started listening, so when the hash request hung, startup stayed blocked until the client timeout (10 s).
The local price file is already loaded at that point, so the hash check and any download now run in a goroutine; the periodic scheduler is unchanged.
The model-count log in Initialize reads pricingData under the read lock because a background download may replace it.
2026-11-14 04:10:53 -08:00
Anankke a0340d4dde fix(websearch): honor account mode on every channel-toggle platform
GetWebSearchEmulationMode only read extra.web_search_emulation for anthropic and openai API key accounts and returned "default" for every other platform, although the channel form already lists zhipu, command_code, opencode_go and minimax for the same feature.
Those accounts reach shouldEmulateWebSearchFor through the OpenAI gateway /v1/messages path, so "enabled" was ignored and "disabled" could not override a channel that turns the emulation on.
Let every platform in the channel whitelist through the gate and extend the account and channel matrix test to them.
2026-11-14 04:10:41 -08:00
Anankke bf292550a6 feat(websearch): add Exa as a web search emulation provider
The web search emulation answers a WebSearch tool call on accounts without native search by querying a configured provider. Only Brave and Tavily are available. This adds Exa as a third keyed provider, "exa", in the same place the others are registered.

ExaProvider posts {query, numResults, contents: {highlights: true}} to https://api.exa.ai/search with the key in the x-api-key header. The search type and highlight length are left to Exa's defaults. Each result maps url and title as they are, publishedDate to page_age, and its highlights joined by newlines to the snippet. A result without highlights has no snippet. A non-200 answer is returned as an error with the status and the start of the body, as for Tavily.

"exa" is accepted by the emulation config validator, built by the manager and offered in the admin settings provider dropdown.
2026-11-14 04:10:03 -08:00
lishuangqiang 4114fedd18 fix(ratelimit): lift Anthropic Fable model limit when the 7d_oi window recovers
7d_oi 窗口耗尽时 persistAnthropicFableWindowLimit 会给账号写入
model_rate_limits["claude-fable-5"],冷却到窗口重置时间(最长 7 天)。
写入之后没有任何路径会撤销它:

- samplePassiveUsageFromHeaders / syncActiveToPassive 只更新
  passive_usage_7d_oi_utilization,不与 model_rate_limits 联动;
- applyAnthropicFableSchedulingThreshold 只设不清;
- UpdateSessionWindow 的自动清除只看账号级 RateLimitResetAt,
  而窗口耗尽分支刻意不设它(账号对其他模型仍然可调度)。

于是用户用重置卡让上游额度提前归零后,本地仍按旧的 rate_limit_reset_at 返回
503 No available accounts supporting model,只能人工删 extra 或点“清除限流”。

修复:

- 上游明确回报 7d_oi utilization 低于阈值(重置卡生效/窗口滚动)、且该窗口未处于
  rejected/exceeded 时,撤销窗口耗尽写入的限流;缺失数据一律不动,缺失不等于 0;
- 只清 claude-fable-5 这一个 scope(新增 AccountRepository.ClearModelRateLimit,
  jsonb 单键删除),不影响其他模型与并发新写入的限流;
- 只清 reason 为 anthropic_7d_oi_window_exhausted 的记录:credits required 与
  管理端阈值来源语义不同,不能被窗口用量顺手清掉;
- 写库成功后才同步本实例的账号快照;写库失败保持原样,避免本实例放行而调度快照仍拦截。

两个观测点都接上:请求响应头的被动采样,以及管理端主动刷新额度。
2026-11-14 17:50:14 +08:00
Henglie af187f9a50 fix(openai): 保留 patternProperties 删除后的 additionalProperties schema 兼容性 2026-11-14 16:21:47 +08:00
Henglie f1394a1ab4 fix(web): stop caching settings-injected HTML
Settings are injected into index.html and the page also embeds a
per-request CSP nonce. A cached document can paint stale branding, and
answering If-None-Match with 304 while minting a new nonce makes the
browser reuse HTML whose nonce no longer matches the CSP header.

Mark every settings-injected HTML response as uncacheable for browsers
and CDN edges, and only allow 304 when the response has no nonce.
2026-11-14 13:09:07 +08:00
Henglie e0cf4984f0 fix(openai): 删除 patternProperties 时放宽封闭对象
Python re 不接受的 patternProperties 键被删除后,原本匹配该模式的参数键
会变成 additional property。对象若仍带 additionalProperties:false,上游
会拒绝这些合法参数。

现在只在确实删除键时把同级的 additionalProperties:false 改为 true,未删除
键时保持封闭语义不变;补充成员顺序、嵌套字典以及 API Key/OAuth 归一化路径
的回归测试,并用 JSON Schema 校验器确认原先合法的参数键仍可表达。
2026-11-14 13:06:17 +08:00
Henglie dd6329b983 fix(openai): 清洗 Python re 不支持的工具 Schema 正则
OpenAI 用 Python re 校验工具 Schema 的 pattern。lookaround、非 Python 命名组以及 \p、\R 等未知转义都会让请求返回 400,patternProperties 的键此前也完全没检查。

现在统一检查 pattern 值和 patternProperties 键,丢弃 Python re 不接受的表达式;保留 (?P<name>...) 与转义字面量等兼容写法。
2026-11-14 10:16:14 +08:00
wc4440222 694d09379b fix(kimi): harden new-plan quota parsing and absent-window cleanup
Follow-up hardening on the new-plan monthly quota support. All changes are
backward compatible with the legacy response shape.

1. Empty parse is not "unlimited"
   A 2xx response that yields zero recognized windows now counts as a failed
   probe: the previous snapshot is kept and no success timestamp is written.
   Without this, the absent-window cleanup would write 5h/weekly/monthly as
   nil, and the scheduler - which reads "no window" as "no quota limit" -
   would clear the pre-emptive pause and let an exhausted account back into
   rotation.

2. Reject malformed window values instead of fabricating 0%
   limits[].detail now requires limit > 0 and remaining in [0, limit]; the
   legacy top-level usage block gets the same check. `{"detail":{}}` or
   limit=0 used to produce a "0% used" tier, masking real exhaustion.

3. used_ratio must be a finite value in [0, 1]
   Out-of-range ratios (e.g. a provider switching to percent units) produced
   6500%-style values; NaN/Inf were accepted by ParseFloat. cnParseF64 now
   rejects non-finite results for every caller.

4. Monthly reset takes the later window
   total and code are two independent rate-limit windows. Taking the earlier
   reset (11-20) released the account while the other window was still
   exhausted (11-26). Use the later reset: better to stay parked slightly
   longer than to hit upstream 429.

5. Zhipu percentage is validated
   Missing/invalid/out-of-range percentage no longer defaults to 0, which had
   the same fabricated-window problem now that absent-window cleanup also
   covers zhipu.

Tests: added rejection matrices for malformed Kimi and Zhipu payloads, legal
edge-value cases (0%, full usage, single window, integer JSON), and the
dual-monthly-window reset assertions. Existing legacy-shape expectations are
unchanged except the limit=0 case, which must now yield no tier.
2026-11-14 05:26:59 +08:00
lishuangqiang a293214977 chore(ci): bump Go toolchain to 1.27.4 for GO-2026-6859
backend-security 的 govulncheck 现在报标准库漏洞:

    Vulnerability #1: GO-2026-6859
        HTTP/1 server crash due to MaxBytesReader header race in net/http
        Found in: net/http@go1.27.3
        Fixed in: net/http@go1.27.4

仓库把 Go 版本固定在 1.27.3(go.mod + workflow 硬断言 + 三个 Dockerfile),
所以所有 PR 的 backend-security 都会失败,与具体改动无关。

同步升级 8 处版本点:

- backend/go.mod:go 1.27.3 → 1.27.4
- security-scan.yml / backend-ci.yml(两处)/ release.yml:go1.27.4 断言
- Dockerfile / deploy/Dockerfile / backend/Dockerfile:golang:1.27.4-alpine
- DEV_GUIDE.md 的 CI 要求说明同步更新

验证:GOTOOLCHAIN=go1.27.4 go build ./... 通过,
GOTOOLCHAIN=go1.27.4 go test -tags unit ./internal/service/ 针对性用例通过。
2026-11-14 03:46:42 +08:00
Zeeland a0a03be96d fix(openai): normalize additional Codex context on HTTP Responses 2026-11-14 03:22:38 +08:00
wc4440222 c54ebd4f12 fix(kimi): parse new monthly quota plan and clear absent window snapshots
Kimi For Coding now ships two response shapes:

- Legacy plans: limits[].detail (5h counts) + top-level usage (weekly pool).
- New plans (Go/Plus/Pro): usages.limit_5h / limit_7d / limit_month_total /
  limit_month_code reported as used_ratio (0-1) with reset_time. There is no
  top-level usage block, so the monthly pool was never parsed and the monthly
  quota was invisible in the account list.

parseKimiUsageTiers now understands usages.* (used_ratio x100, monthly takes
the larger of total/code with the earlier reset), keeps the legacy usage block
as a fallback, and prefers usages.limit_7d over legacy weekly counts so weekly
is not emitted twice.

Snapshot writes also stopped clearing windows that disappear from the response:
extra updates are JSONB merges, so not writing a window keeps its previous
value forever. After a plan change the old weekly percentage froze (observed
13 days) and the account page kept showing an expired 7D window. Callers now
write explicit nils for absent 5h/weekly/monthly windows.

cnQuotaHasMonthlyWindow includes Kimi so threshold pre-pause and the 429
cooldown snapshot consider the monthly window too.
2026-11-13 21:16:44 +08:00
CooCoode d085bb1a37 fix(apicompat): default json_schema strict=false when converting CC to Responses
Chat Completions treats a missing response_format.json_schema.strict as false,
while Responses validates text.format strictly and rejects schemas without
additionalProperties: false. Forwarding the format unchanged therefore turned
valid requests into upstream 400 invalid_json_schema.

Make the intended mode explicit by adding strict=false only when the field is
absent; explicit strict values are untouched.

Fixes #8760
2026-11-13 20:51:06 +08:00
r266-tech 8dcdfff22a fix(codex): normalize UUID additional tool declaration IDs 2026-11-13 20:16:55 +08:00
r266-tech 8480cb0cd9 fix(antigravity): match schema items to the selected type 2026-11-13 18:06:45 +08:00
r266-tech fd64877581 fix(codex): preserve additional_tools declaration IDs 2026-11-13 16:03:16 +08:00
Anand Biju 734b922bd8 fix(claude): default account tests to claude-sonnet-4-6
claude-sonnet-4-5-20250929 is deprecated and retires on the Claude API
on November 30, 2026:
https://platform.claude.com/docs/en/about-claude/model-deprecations

claude.DefaultTestModel is what an account connection test sends when
no model is picked, so after that date the default test would fail even
for healthy accounts. Move it to claude-sonnet-4-6, which the gateway
already uses for the Antigravity test default and maps for Bedrock.

Signed-off-by: Anand Biju <169837340+Anandb71@users.noreply.github.com>
2026-11-13 10:45:12 +05:30
r266-tech 9d5fb150b9 feat(openai): optionally filter passthrough accounts by model 2026-11-13 12:14:06 +08:00
ruixingshi e677462549 fix(openai): preserve quota freshness when refresh fails 2026-11-13 11:52:22 +08:00
Kayokoi 90f1151324 test(gateway): add observation regression cases 2026-11-12 18:35:33 -08:00
Kayokoi c487b215fa test(gateway): cover Anthropic compatibility observations 2026-11-12 18:33:35 -08:00
Kayokoi de34f50c1a fix(gateway): observe Anthropic Responses models 2026-11-12 18:31:51 -08:00
Kayokoi b9d02c31a5 fix(gateway): observe Anthropic chat completion models 2026-11-12 18:30:13 -08:00
r266-tech fc8af440ed test(billing): fix peak-rate usage test clock 2026-11-12 16:25:44 -08:00
r266-tech bd89d3d943 fix(gateway): preserve message output config with per-turn beta 2026-11-12 15:32:49 -08:00
r266-tech 6d7e6b9d84 fix(gateway): record native Anthropic endpoints for error diagnostics 2026-11-12 11:10:32 -08:00
r266-tech 1772430165 fix(accounts): keep Gemini usage visible during refetch 2026-11-12 10:52:23 -08:00
r266-tech d850b8e3a2 fix(gateway): enforce effort policies on Anthropic compatibility routes 2026-11-12 10:15:59 -08:00
r266-tech e95e9eb748 test(cn-quota): include snapshot regressions in critical CI 2026-11-12 09:20:16 -08:00
r266-tech 849aa593d4 fix(cn-quota): refresh usage cells with account snapshots 2026-11-12 09:14:56 -08:00
Hato 4f8e9ae2f1 test(openai): handle metadata fixture builder return values 2026-11-13 02:14:42 +09:00
r266-tech b0f6f83911 fix(claude): recover requests after concurrent token rotation 2026-11-12 08:46:51 -08:00
Kayokoi 7e75ee4b65 Cover wildcard rejection and corrected model input 2026-11-12 08:46:13 -08:00
Kayokoi 346a7dac02 Add Chinese whitelist validation hint 2026-11-12 08:45:43 -08:00
Kayokoi 24d77b3306 Add English whitelist validation hint 2026-11-12 08:45:09 -08:00
Kayokoi 97705d147e fix(accounts): reject wildcard model whitelist entries
Prevent adding models with wildcard characters and show an info message.
2026-11-12 08:43:27 -08:00
Hato 203de719c3 perf(openai): avoid repeated request copies in OAuth metadata cleanup 2026-11-13 01:33:01 +09:00
r266-tech 39bac35a37 fix(scheduler): retain cooling accounts in snapshot membership 2026-11-12 05:12:33 -08:00
r266-tech 636981b28b test(scheduler): reproduce cooldown expiry absent from snapshots 2026-11-12 03:46:32 -08:00
r266-tech ac981240cc fix(usage): retain response models through Chat fallbacks 2026-11-12 03:25:41 -08:00
r266-tech d30179f4b5 fix(usage): retain native Anthropic response observations 2026-11-12 03:12:37 -08:00
r266-tech 733722f8c7 fix(gateway): retain sticky writes after client disconnects 2026-11-12 02:51:28 -08:00
r266-tech 1280006a1f fix(gateway): emit SSE errors after queue keepalives 2026-11-12 02:33:46 -08:00
cyh c829317fc5 fix(anthropic): keep weekly usage readings across 5h rollovers
A 5h window rollover cleared the sampled 7d and 7d_oi readings along with
the 5h utilization. Only Fable responses carry 7d_oi, and a Fable-exhausted
account stops receiving Fable requests, so its 7d F reading stayed empty
until the weekly reset. Weekly thresholds also lost their input after every
rollover.

Clear the 5h utilization as before, but keep a weekly reading while its own
reset is still ahead. Readings without a reset or past their reset are
still cleared.
2026-11-12 16:56:51 +08:00
Anankke 6c79fdfc7a fix(apicompat): send mid-conversation system messages to Responses as developer
anthropicMsgToResponsesItems only distinguished assistant from everything else, so a role "system" message in the middle of messages (for example Claude Code hook output) was sent to Responses as a user item. Convert such messages to developer items, keeping content and order, as the Chat Completions to Responses conversion already does.
2026-11-11 22:05:58 -08:00
r266-tech fa910c1c38 fix(usage): align five-hour window start with active quota resets 2026-11-12 12:01:29 +08:00
feeeei 829bf2cdb9 fix(usage): 分组日汇总重建与保留期清理不阻塞 usage_logs 写入
保留期清理删除过期 usage_logs 时,DELETE 触发器与清理代码把分组日汇总水位拉回到被删记录的日期,
下一次同步随即在持有 usage_group_rollup_state FOR UPDATE 的事务里重算整个保留窗口(生产环境每次约
28 秒,每 6 小时与每次重启各一次)。usage_logs 的插入触发器需要同一行的 FOR KEY SHARE,期间写入全部
排队,超过写入超时后已扣费请求的 usage_log 丢失。后台用量清理、RecomputeRange、分区删除与 DELETE/UPDATE
触发器同样对该行持 FOR UPDATE。

- 保留下界 expired_before:清理把截止点对齐到配置时区的自然日零点,先推进下界再删除;早于下界的记录
  变更不触发失效,读路径的历史日桶与尾段都不早于下界。
- 重建拆为登记、计算、发布三个事务:计算阶段只持 FOR KEY SHARE,与写入兼容;登记之后落在重建区间内的
  源记录变更记入 build_dirty_from,发布不越过脏日期并续建脏区间。整个重建持会话级 advisory lock。
- DELETE/UPDATE 触发器、后台用量清理、RecomputeRange 与分区删除对状态行只持 FOR KEY SHARE;脏日期已覆盖
  的变更不写状态行。
- 分区删除限定父表锁等待 3 秒,超时跳过该分区,过期记录由按行删除清理。
- 分组日界取本地日期实际开始的时刻,覆盖夏令时在零点跳变或回拨的日期;重算只写入不早于起始日的日桶。
2026-11-12 04:34:38 +08:00
feeeei 197109ebce fix(auth): 登录回填 email 身份失败时不再 panic
ensureEmailAuthIdentity 在 email 身份属于其他账号、并发插入落败或查询出错时
返回 nil,shouldApplyEmailFirstBindDefaults 在判空前读取 identity.Metadata,
导致 RecordSuccessfulLogin 所在的登录请求 panic 并返回 500。判空提到函数开头。
2026-11-11 23:38:12 +08:00
r266-tech 4584dcb392 fix(apicompat): retain encrypted function call content 2026-11-11 22:49:27 +08:00
Shilin Zhou fe40612b80 fix: allow disabling concurrency wait pings 2026-11-11 17:46:45 +08:00
feeeei 23ac69a021 fix(bedrock): 按错误语义区分封号、用例缺失、限流与内容过滤,流中断保留 usage
- 400 消息整句为 "Operation not allowed"(AWS 封号):账号置 error 并换号;其余 Bedrock 400 一律按请求错误处理,不按消息子串改账号状态(ValidationException 会把请求字段名回显进消息)
- 404 "Model use case details have not been submitted..."(未提交模型用例):账号置 error 并换号
- 429 只冷却 (账号, 模型),时长取「429 默认回避」配置,配置关闭时不写;模型未知时沿用账号级兜底
- 500/502/503/504 且消息含 "blocked by content filtering policy":不换号、不惩罚账号,返回客户端 400 invalid_request_error 与上游原文
- 渠道模型映射生效时,handler 经 WithGatewaySchedulingModel 传入选号模型,模型级账号状态写在调度器按客户端模型读取的键上
- 流式输出中断时与错误一起返回已观测的 usage,照常计费
- 临时不可调度规则仍优先于以上默认分类
2026-11-11 16:01:47 +08:00
alfadb 796455c1c9 fix(billing): 为硅基流动 Qwen3-Reranker 系列补兜底定价 2026-11-11 15:48:38 +08:00
alfadb 43c1ca0148 fix(billing): 为硅基流动 Qwen3-Embedding 系列补兜底定价
生产日志出现 WARN openai_usage.pricing_missing_record_zero_cost:模型
Qwen/Qwen3-Embedding-8B 经 OpenAI 兼容 /v1/embeddings(上游硅基流动)调用时,
分组价 → 渠道价 → LiteLLM 目录 → 代码兜底表全链查不到价格,按 0 成本记账。
LiteLLM 目录无 qwen 条目,故在代码兜底表补入白名单条目。

价格(硅基流动官方,2026-09-23 读取,USD per token):
- 8B   $0.04/MTok = 0.04e-6  https://www.siliconflow.com/models/qwen3-embedding-8b
- 4B   $0.02/MTok = 0.02e-6  (同站 4B 模型页)
- 0.6B $0.01/MTok = 0.01e-6  (同站 0.6B 模型页)
国内站参考价(https://www.siliconflow.cn/pricing):8B ¥0.28/MTok、4B ¥0.14/MTok、
0.6B ¥0.07/MTok,输出 ¥0。embedding 只按输入计费,OutputPricePerToken 显式置 0。

匹配规则:getFallbackPricing 入口已 ToLower,按 8b → 4b → 0.6b most-specific-first
用 strings.Contains 命中;0.6B 同时接受 qwen3-embedding-0.6b 与 qwen3-embedding-0-6b
两种拼法。不加泛化的 qwen3-embedding 家族兜底,未知档位(如 2B)继续不回退,
保持本表「白名单、未知型号不猜测计价」的语义。两处均插在 doubao embedding 条目/分支
紧前面,避免与私有分支在 doubao 之后追加的条目冲突。

测试:TestGetFallbackPricing_FamilyMatching 增 5 条正例(校验输入价与输出价 0)
与 2B 负例;新增 TestGetModelPricing_Qwen3EmbeddingFallback、
TestCalculateOpenAIRecordUsageCost_Qwen3EmbeddingFallback(1000 输入 token
= 1000 × 0.04e-6,且不再返回 pricing unavailable)。
2026-11-11 15:48:38 +08:00
Long Li e055d7bafc fix(antigravity): stream Gemini compat thoughts and anchor pre-content timeout after headers 2026-11-11 16:38:33 +09:00
r266-tech c8f4264f8f fix(grok): preserve upstream media error messages and codes 2026-11-11 14:21:00 +08:00
lishuangqiang a8481f0dec test(gateway): satisfy errcheck in request JSON tests 2026-11-11 13:54:37 +08:00
lishuangqiang 71ef577054 perf(gateway): trim per-request JSON work on the Anthropic request path
- Skip both cache_control walks with a byte-level precheck when the body
  has at most 4 cache_control keys, no thinking block and no 1h TTL; skip
  the block-limit walk when only 1h is present. Bodies containing \u
  escapes always take the original path.
- Replace gjson Array() materialization with Get("0")/ForEach in the
  beta, toolset, tool-rewrite, web-search and system-preview helpers.
- Build the Claude Code mimic debug line lazily; it is only read on
  credential-scope errors.
- Compute the billing-header fingerprint once instead of per block.

Differential tests copy the previous implementations verbatim and
compare byte for byte across edge cases and 3000 randomized bodies.
Batching TTL rewrites with sjson ReplaceInPlace was rejected because it
resolves duplicate keys differently.

Common ~32KB Claude Code request: enforceCacheControlLimit 100us/21
allocs -> 21.6us/0 allocs; helper set 47.6us/103KB -> 37.9us/69KB;
debug line 9.1us/53 allocs -> ~0.
2026-11-11 13:45:09 +08:00
jaxxjj 74ba91aa6b fix(openai): keep Codex forks on their parent's prompt cache key
An ephemeral Codex fork, such as app-server thread/sample, keeps its parent's
session-id header and prompt_cache_key but names itself in
client_metadata.session_id. Account identity scoping compared the key only
with client_metadata.session_id, so a fork's key fell into the prompt-cache
namespace and reached upstream as a different value from its parent's, and
the fork lost the parent's prompt cache.

Treat a key that equals either client_metadata.session_id or the client's
session-id header as a session key.
2026-11-10 19:09:30 -08:00
shaw 530c5e3a4f chore: update sponsors 2026-11-11 10:43:23 +08:00
github-actions[bot] 6dd5a045b6 chore: sync VERSION to 0.2.21 [skip ci] 2026-11-11 02:22:16 +00:00
feeeei 5846bfbbfa fix(gemini): 兼容入口 chat 请求转发 response_format 结构化输出
/v1/chat/completions 走 Gemini 账号时,response_format 在 chat→Responses→Anthropic
转换中丢失,上游只能靠 prompt 约束 JSON 格式。现在按客户端原始 response_format 写
generationConfig:json_object 写 responseMimeType=application/json;json_schema 另把
json_schema.schema 原样写入 responseJsonSchema。请求带 tools 或上游模型为图片输出
模型时不写。

Code Assist(OAuth + project_id)包装改为原字节嵌入 request,避免 Unmarshal→Marshal
重排 schema 属性顺序、截断大整数。
2026-11-11 10:17:12 +08:00
xy3 d70a23f84b feat(gemini): add Gemini 4 Carbon support 2026-11-11 10:01:42 +08:00
lishuangqiang 98a44ba3f3 fix(billing): make group rate/RPM sync transactional
SyncGroupRateMultipliers and SyncGroupRPMOverrides ran three destructive
statements in autocommit mode: clear rows missing from the payload,
delete all-NULL rows, then upsert the payload. If the upsert failed
(deleted user FK, duplicate user_id, transient DB error), the clear and
delete had already committed, silently wiping the group's overrides.

Wrap each sync in one transaction and dedupe entries by user_id before
writing so ON CONFLICT cannot hit the same row twice. Any failure now
rolls the whole sync back.

Add sqlmock tests covering commit, rollback and dedupe.
2026-11-11 09:34:54 +08:00
lishuangqiang 1546c0c18e perf(gateway): skip JSON decode for forwarded Anthropic stream events
Anthropic SSE processing decoded every data line into map[string]any even
though most events (content_block_delta, ping, ...) are forwarded
verbatim. A 120-byte text delta cost ~915ns, 1185B and 20 allocations;
a 1500-chunk response burned ~1.4ms CPU and ~30k allocations for no
semantic gain.

Parse only events that can change usage, model, cache_control or
keepalive state. Replace the per-line SSE regex with a prefix check, and
add a string variant of tool-name restoration so the streaming writer no
longer copies each chunk through []byte/string.

Benchmark (content_block_delta): 915ns/20 allocs/1185B -> 164ns/0
allocs/0B. Output remains byte-for-byte identical; existing streaming
tests pass.
2026-11-11 07:57:56 +08:00
lishuangqiang 37a0f3870b fix(billing): scope RPM override to the group it belongs to
The auth cache snapshot records the (user, group) RPM override for the
API key's group. checkRPM used it for any group whenever it was non-nil,
so a fallback request (for example the Antigravity prompt-too-long path)
applied group A's override to group B: override=0 disabled B's
rpm_limit entirely, while a positive override throttled B to the wrong
rate.

Only trust the snapshot override when UserGroupRPMOverrideGroupID
matches the current group; otherwise fall back to the DB lookup as the
snapshot versioning intended.
2026-11-11 00:55:51 +08:00
lishuangqiang 43511b40e9 fix(payment): make Alipay refund request id stable across retries
Alipay refunds used a UnixNano timestamp as out_request_no, so an admin
retry after an ambiguous gateway error minted a new request and refunded
the user twice. Use the same deterministic order+amount id as the other
providers (wxpayRefundID, Stripe idempotency key).

Same order and amount now map to the same Alipay refund request; the
existing QueryRefund prefix contract is unchanged.
2026-11-10 23:56:34 +08:00
r266-tech c115dc27ab fix(usage): read Fable weekly quotas from scoped limits 2026-11-10 19:37:32 +08:00
wucm667 661770bf34 fix(usage): reconcile Anthropic and OpenAI cache TTL accounting 2026-11-10 10:01:06 +08:00
lkon 8a1315e8cc test(billing): reuse rate resolver and isolate heap checks 2026-11-08 16:43:43 +08:00
WGeorgezzzz 189b336f47 fix(openai): enforce stream idle deadlines and pre-output failover 2026-11-07 19:45:33 +08:00
wucm667 4656364337 test(usage): assert incomplete cache streams and isolate allocation guard 2026-11-06 12:13:35 +08:00
wucm667 b25dbe3e4b chore: sync upstream main for cache usage validation 2026-11-06 12:13:35 +08:00
wucm667 71532bf91c fix(usage): preserve compatible cache snapshot semantics 2026-11-05 09:24:56 +08:00
wucm667 9e4c03d2fe fix(usage): reconcile prompt totals across cache-only updates 2026-11-04 09:08:54 +08:00
wucm667 bcb0512132 fix(billing): account for unclassified cache creation tokens and TTL overrides 2026-11-02 09:16:06 +08:00
wucm667 7b879c56a6 chore(deps): update follow-redirects security patch 2026-11-02 09:16:06 +08:00
wucm667 9e8913876f Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-01 09:44:39 +08:00
wucm667 e6bde6b3c6 fix(billing): retain native cache creation accounting 2026-10-25 11:28:55 +08:00
wucm667 efc58486d8 fix(usage): preserve authoritative cache creation totals 2026-10-24 12:16:53 +08:00
wucm667 c91c594cc8 chore: sync latest upstream changes 2026-10-24 12:16:32 +08:00
wucm667 7f6673ead5 fix(apicompat): preserve Anthropic cache creation TTL details 2026-10-17 13:43:55 +08:00
668 changed files with 47837 additions and 3424 deletions

No files matched your search

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

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.27.2-alpine
FROM golang:1.27.4-alpine
WORKDIR /app
+1 -1
View File
@@ -1 +1 @@
0.2.20
0.2.25
+5
View File
@@ -111,6 +111,7 @@ func provideCleanup(
emailQueue *service.EmailQueueService,
billingCache *service.BillingCacheService,
usageRecordWorkerPool *service.UsageRecordWorkerPool,
usageBillingLanes *service.UsageBillingLaneCombiner,
balanceNotify *service.BalanceNotifyService,
digestSessions *service.DigestSessionStore,
subscriptionService *service.SubscriptionService,
@@ -331,6 +332,10 @@ func provideCleanup(
}
return nil
}},
{"UsageBillingLaneCombiner", func() error {
usageBillingLanes.Stop()
return nil
}},
{"OAuthService", func() error {
oauth.Stop()
return nil
+12 -5
View File
@@ -105,7 +105,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
usageLogRepository := repository.NewUsageLogRepository(client, db)
usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator)
opsRepository := repository.NewOpsRepository(db)
usageBillingRepository := repository.NewUsageBillingRepository(client, db)
usageBillingBatchRepository := repository.NewUsageBillingRepository(client, db)
usageBillingLaneCombiner := service.NewUsageBillingLaneCombiner(usageBillingBatchRepository)
usageBillingRepository := service.ProvideUsageBillingRepository(usageBillingLaneCombiner)
gatewayCache := repository.NewGatewayCache(redisClient)
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig)
@@ -173,7 +175,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
authCacheInvalidationOutboxRepository := repository.NewAuthCacheInvalidationOutboxRepository(db)
authCacheInvalidationWorker := service.ProvideAuthCacheInvalidationWorker(authCacheInvalidationOutboxRepository, apiKeyCache, apiKeyService)
opsService := service.ProvideOpsService(opsRepository, settingRepository, configConfig, accountRepository, userRepository, concurrencyService, gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, opsSystemLogSink, settingService, authCacheInvalidationWorker, apiKeyService)
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, opsService, settingService)
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, opsService, settingService, channelService)
redeemHandler := handler.NewRedeemHandler(redeemService)
subscriptionHandler := handler.NewSubscriptionHandler(subscriptionService)
announcementRepository := repository.NewAnnouncementRepository(client)
@@ -195,7 +197,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService)
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, serviceUserPlatformQuotaRepository)
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService)
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
groupHandler := admin.NewGroupHandlerWithConfig(adminService, dashboardService, groupCapacityService, configConfig)
@@ -206,7 +208,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
openAIReferralClient := repository.NewOpenAIReferralClient(privacyClientFactory)
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIReferralClient, openAIGatewayService)
usageCache := service.NewUsageCache()
accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService)
accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService, opsService)
pluginRepository := repository.NewPluginRepository(db)
pluginHostInfo := providePluginHostInfo(buildInfo)
pluginKVStore := repository.NewPluginKVStore(redisClient)
@@ -359,7 +361,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher)
channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService)
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, usageBillingLaneCombiner, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
application := &Application{
Server: httpServer,
PromptAudit: promptService,
@@ -426,6 +428,7 @@ func provideCleanup(
emailQueue *service.EmailQueueService,
billingCache *service.BillingCacheService,
usageRecordWorkerPool *service.UsageRecordWorkerPool,
usageBillingLanes *service.UsageBillingLaneCombiner,
balanceNotify *service.BalanceNotifyService,
digestSessions *service.DigestSessionStore,
subscriptionService *service.SubscriptionService,
@@ -645,6 +648,10 @@ func provideCleanup(
}
return nil
}},
{"UsageBillingLaneCombiner", func() error {
usageBillingLanes.Stop()
return nil
}},
{"OAuthService", func() error {
oauth.Stop()
return nil
+1
View File
@@ -81,6 +81,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
emailQueueSvc,
billingCacheSvc,
&service.UsageRecordWorkerPool{},
nil, // usageBillingLanes
service.ProvideBalanceNotifyService(nil, nil, nil, nil),
service.NewDigestSessionStore(),
&service.SubscriptionService{},
+12 -1
View File
@@ -128,6 +128,8 @@ type Group struct {
AllowLive bool `json:"allow_live,omitempty"`
// 是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority
ForceOpenaiFast bool `json:"force_openai_fast,omitempty"`
// 是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)
ForceOpenaiUltrafast bool `json:"force_openai_ultrafast,omitempty"`
// 是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费
FreeOpenaiFast bool `json:"free_openai_fast,omitempty"`
// 仅允许非 apikey 类型账号关联到此分组
@@ -264,7 +266,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
switch columns[i] {
case group.FieldI18n, group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings:
values[i] = new([]byte)
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageCountBilling, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageCountBilling, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldForceOpenaiUltrafast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
values[i] = new(sql.NullBool)
case group.FieldRateMultiplier, group.FieldPeakRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k, group.FieldBatchImageDiscountMultiplier, group.FieldBatchImageHoldMultiplier, group.FieldVideoRateMultiplier, group.FieldVideoPrice480p, group.FieldVideoPrice720p, group.FieldVideoPrice1080p, group.FieldWebSearchPricePerCall, group.FieldSearchPricePer1k, group.FieldAudioRealtimePricePerMin, group.FieldAudioTtsPricePerMillionChars, group.FieldAudioSttPricePerHour, group.FieldProfitMinMargin, group.FieldProfitSafetyBuffer:
values[i] = new(sql.NullFloat64)
@@ -648,6 +650,12 @@ func (_m *Group) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.ForceOpenaiFast = value.Bool
}
case group.FieldForceOpenaiUltrafast:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field force_openai_ultrafast", values[i])
} else if value.Valid {
_m.ForceOpenaiUltrafast = value.Bool
}
case group.FieldFreeOpenaiFast:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field free_openai_fast", values[i])
@@ -1016,6 +1024,9 @@ func (_m *Group) String() string {
builder.WriteString("force_openai_fast=")
builder.WriteString(fmt.Sprintf("%v", _m.ForceOpenaiFast))
builder.WriteString(", ")
builder.WriteString("force_openai_ultrafast=")
builder.WriteString(fmt.Sprintf("%v", _m.ForceOpenaiUltrafast))
builder.WriteString(", ")
builder.WriteString("free_openai_fast=")
builder.WriteString(fmt.Sprintf("%v", _m.FreeOpenaiFast))
builder.WriteString(", ")
+10
View File
@@ -124,6 +124,8 @@ const (
FieldAllowLive = "allow_live"
// FieldForceOpenaiFast holds the string denoting the force_openai_fast field in the database.
FieldForceOpenaiFast = "force_openai_fast"
// FieldForceOpenaiUltrafast holds the string denoting the force_openai_ultrafast field in the database.
FieldForceOpenaiUltrafast = "force_openai_ultrafast"
// FieldFreeOpenaiFast holds the string denoting the free_openai_fast field in the database.
FieldFreeOpenaiFast = "free_openai_fast"
// FieldRequireOauthOnly holds the string denoting the require_oauth_only field in the database.
@@ -281,6 +283,7 @@ var Columns = []string{
FieldAllowMessagesDispatch,
FieldAllowLive,
FieldForceOpenaiFast,
FieldForceOpenaiUltrafast,
FieldFreeOpenaiFast,
FieldRequireOauthOnly,
FieldRequirePrivacySet,
@@ -410,6 +413,8 @@ var (
DefaultAllowLive bool
// DefaultForceOpenaiFast holds the default value on creation for the "force_openai_fast" field.
DefaultForceOpenaiFast bool
// DefaultForceOpenaiUltrafast holds the default value on creation for the "force_openai_ultrafast" field.
DefaultForceOpenaiUltrafast bool
// DefaultFreeOpenaiFast holds the default value on creation for the "free_openai_fast" field.
DefaultFreeOpenaiFast bool
// DefaultRequireOauthOnly holds the default value on creation for the "require_oauth_only" field.
@@ -699,6 +704,11 @@ func ByForceOpenaiFast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldForceOpenaiFast, opts...).ToFunc()
}
// ByForceOpenaiUltrafast orders the results by the force_openai_ultrafast field.
func ByForceOpenaiUltrafast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldForceOpenaiUltrafast, opts...).ToFunc()
}
// ByFreeOpenaiFast orders the results by the free_openai_fast field.
func ByFreeOpenaiFast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFreeOpenaiFast, opts...).ToFunc()
+15
View File
@@ -300,6 +300,11 @@ func ForceOpenaiFast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiFast, v))
}
// ForceOpenaiUltrafast applies equality check predicate on the "force_openai_ultrafast" field. It's identical to ForceOpenaiUltrafastEQ.
func ForceOpenaiUltrafast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiUltrafast, v))
}
// FreeOpenaiFast applies equality check predicate on the "free_openai_fast" field. It's identical to FreeOpenaiFastEQ.
func FreeOpenaiFast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldFreeOpenaiFast, v))
@@ -2310,6 +2315,16 @@ func ForceOpenaiFastNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldForceOpenaiFast, v))
}
// ForceOpenaiUltrafastEQ applies the EQ predicate on the "force_openai_ultrafast" field.
func ForceOpenaiUltrafastEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiUltrafast, v))
}
// ForceOpenaiUltrafastNEQ applies the NEQ predicate on the "force_openai_ultrafast" field.
func ForceOpenaiUltrafastNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldForceOpenaiUltrafast, v))
}
// FreeOpenaiFastEQ applies the EQ predicate on the "free_openai_fast" field.
func FreeOpenaiFastEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldFreeOpenaiFast, v))
+65
View File
@@ -738,6 +738,20 @@ func (_c *GroupCreate) SetNillableForceOpenaiFast(v *bool) *GroupCreate {
return _c
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_c *GroupCreate) SetForceOpenaiUltrafast(v bool) *GroupCreate {
_c.mutation.SetForceOpenaiUltrafast(v)
return _c
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_c *GroupCreate) SetNillableForceOpenaiUltrafast(v *bool) *GroupCreate {
if v != nil {
_c.SetForceOpenaiUltrafast(*v)
}
return _c
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_c *GroupCreate) SetFreeOpenaiFast(v bool) *GroupCreate {
_c.mutation.SetFreeOpenaiFast(v)
@@ -1183,6 +1197,10 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultForceOpenaiFast
_c.mutation.SetForceOpenaiFast(v)
}
if _, ok := _c.mutation.ForceOpenaiUltrafast(); !ok {
v := group.DefaultForceOpenaiUltrafast
_c.mutation.SetForceOpenaiUltrafast(v)
}
if _, ok := _c.mutation.FreeOpenaiFast(); !ok {
v := group.DefaultFreeOpenaiFast
_c.mutation.SetFreeOpenaiFast(v)
@@ -1395,6 +1413,9 @@ func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.ForceOpenaiFast(); !ok {
return &ValidationError{Name: "force_openai_fast", err: errors.New(`ent: missing required field "Group.force_openai_fast"`)}
}
if _, ok := _c.mutation.ForceOpenaiUltrafast(); !ok {
return &ValidationError{Name: "force_openai_ultrafast", err: errors.New(`ent: missing required field "Group.force_openai_ultrafast"`)}
}
if _, ok := _c.mutation.FreeOpenaiFast(); !ok {
return &ValidationError{Name: "free_openai_fast", err: errors.New(`ent: missing required field "Group.free_openai_fast"`)}
}
@@ -1695,6 +1716,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
_node.ForceOpenaiFast = value
}
if value, ok := _c.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
_node.ForceOpenaiUltrafast = value
}
if value, ok := _c.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
_node.FreeOpenaiFast = value
@@ -2801,6 +2826,18 @@ func (u *GroupUpsert) UpdateForceOpenaiFast() *GroupUpsert {
return u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsert) SetForceOpenaiUltrafast(v bool) *GroupUpsert {
u.Set(group.FieldForceOpenaiUltrafast, v)
return u
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsert) UpdateForceOpenaiUltrafast() *GroupUpsert {
u.SetExcluded(group.FieldForceOpenaiUltrafast)
return u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsert) SetFreeOpenaiFast(v bool) *GroupUpsert {
u.Set(group.FieldFreeOpenaiFast, v)
@@ -4078,6 +4115,20 @@ func (u *GroupUpsertOne) UpdateForceOpenaiFast() *GroupUpsertOne {
})
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsertOne) SetForceOpenaiUltrafast(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetForceOpenaiUltrafast(v)
})
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdateForceOpenaiUltrafast() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdateForceOpenaiUltrafast()
})
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsertOne) SetFreeOpenaiFast(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
@@ -5552,6 +5603,20 @@ func (u *GroupUpsertBulk) UpdateForceOpenaiFast() *GroupUpsertBulk {
})
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsertBulk) SetForceOpenaiUltrafast(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetForceOpenaiUltrafast(v)
})
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdateForceOpenaiUltrafast() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdateForceOpenaiUltrafast()
})
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsertBulk) SetFreeOpenaiFast(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
+34
View File
@@ -1023,6 +1023,20 @@ func (_u *GroupUpdate) SetNillableForceOpenaiFast(v *bool) *GroupUpdate {
return _u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_u *GroupUpdate) SetForceOpenaiUltrafast(v bool) *GroupUpdate {
_u.mutation.SetForceOpenaiUltrafast(v)
return _u
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableForceOpenaiUltrafast(v *bool) *GroupUpdate {
if v != nil {
_u.SetForceOpenaiUltrafast(*v)
}
return _u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_u *GroupUpdate) SetFreeOpenaiFast(v bool) *GroupUpdate {
_u.mutation.SetFreeOpenaiFast(v)
@@ -1887,6 +1901,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.ForceOpenaiFast(); ok {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
}
if value, ok := _u.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
}
if value, ok := _u.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
}
@@ -3243,6 +3260,20 @@ func (_u *GroupUpdateOne) SetNillableForceOpenaiFast(v *bool) *GroupUpdateOne {
return _u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_u *GroupUpdateOne) SetForceOpenaiUltrafast(v bool) *GroupUpdateOne {
_u.mutation.SetForceOpenaiUltrafast(v)
return _u
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableForceOpenaiUltrafast(v *bool) *GroupUpdateOne {
if v != nil {
_u.SetForceOpenaiUltrafast(*v)
}
return _u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_u *GroupUpdateOne) SetFreeOpenaiFast(v bool) *GroupUpdateOne {
_u.mutation.SetFreeOpenaiFast(v)
@@ -4137,6 +4168,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if value, ok := _u.mutation.ForceOpenaiFast(); ok {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
}
if value, ok := _u.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
}
if value, ok := _u.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
}
+1
View File
@@ -957,6 +957,7 @@ var (
{Name: "allow_messages_dispatch", Type: field.TypeBool, Default: false},
{Name: "allow_live", Type: field.TypeBool, Default: false},
{Name: "force_openai_fast", Type: field.TypeBool, Default: false},
{Name: "force_openai_ultrafast", Type: field.TypeBool, Default: false},
{Name: "free_openai_fast", Type: field.TypeBool, Default: false},
{Name: "require_oauth_only", Type: field.TypeBool, Default: false},
{Name: "require_privacy_set", Type: field.TypeBool, Default: false},
+55 -1
View File
@@ -22161,6 +22161,7 @@ type GroupMutation struct {
allow_messages_dispatch *bool
allow_live *bool
force_openai_fast *bool
force_openai_ultrafast *bool
free_openai_fast *bool
require_oauth_only *bool
require_privacy_set *bool
@@ -25058,6 +25059,42 @@ func (m *GroupMutation) ResetForceOpenaiFast() {
m.force_openai_fast = nil
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (m *GroupMutation) SetForceOpenaiUltrafast(b bool) {
m.force_openai_ultrafast = &b
}
// ForceOpenaiUltrafast returns the value of the "force_openai_ultrafast" field in the mutation.
func (m *GroupMutation) ForceOpenaiUltrafast() (r bool, exists bool) {
v := m.force_openai_ultrafast
if v == nil {
return
}
return *v, true
}
// OldForceOpenaiUltrafast returns the old "force_openai_ultrafast" field's value of the Group entity.
// If the Group object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupMutation) OldForceOpenaiUltrafast(ctx context.Context) (v bool, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldForceOpenaiUltrafast is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldForceOpenaiUltrafast requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldForceOpenaiUltrafast: %w", err)
}
return oldValue.ForceOpenaiUltrafast, nil
}
// ResetForceOpenaiUltrafast resets all changes to the "force_openai_ultrafast" field.
func (m *GroupMutation) ResetForceOpenaiUltrafast() {
m.force_openai_ultrafast = nil
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (m *GroupMutation) SetFreeOpenaiFast(b bool) {
m.free_openai_fast = &b
@@ -25995,7 +26032,7 @@ func (m *GroupMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *GroupMutation) Fields() []string {
fields := make([]string, 0, 68)
fields := make([]string, 0, 69)
if m.created_at != nil {
fields = append(fields, group.FieldCreatedAt)
}
@@ -26158,6 +26195,9 @@ func (m *GroupMutation) Fields() []string {
if m.force_openai_fast != nil {
fields = append(fields, group.FieldForceOpenaiFast)
}
if m.force_openai_ultrafast != nil {
fields = append(fields, group.FieldForceOpenaiUltrafast)
}
if m.free_openai_fast != nil {
fields = append(fields, group.FieldFreeOpenaiFast)
}
@@ -26316,6 +26356,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
return m.AllowLive()
case group.FieldForceOpenaiFast:
return m.ForceOpenaiFast()
case group.FieldForceOpenaiUltrafast:
return m.ForceOpenaiUltrafast()
case group.FieldFreeOpenaiFast:
return m.FreeOpenaiFast()
case group.FieldRequireOauthOnly:
@@ -26461,6 +26503,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldAllowLive(ctx)
case group.FieldForceOpenaiFast:
return m.OldForceOpenaiFast(ctx)
case group.FieldForceOpenaiUltrafast:
return m.OldForceOpenaiUltrafast(ctx)
case group.FieldFreeOpenaiFast:
return m.OldFreeOpenaiFast(ctx)
case group.FieldRequireOauthOnly:
@@ -26876,6 +26920,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
}
m.SetForceOpenaiFast(v)
return nil
case group.FieldForceOpenaiUltrafast:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetForceOpenaiUltrafast(v)
return nil
case group.FieldFreeOpenaiFast:
v, ok := value.(bool)
if !ok {
@@ -27647,6 +27698,9 @@ func (m *GroupMutation) ResetField(name string) error {
case group.FieldForceOpenaiFast:
m.ResetForceOpenaiFast()
return nil
case group.FieldForceOpenaiUltrafast:
m.ResetForceOpenaiUltrafast()
return nil
case group.FieldFreeOpenaiFast:
m.ResetFreeOpenaiFast()
return nil
+18 -14
View File
@@ -1183,66 +1183,70 @@ func init() {
groupDescForceOpenaiFast := groupFields[50].Descriptor()
// group.DefaultForceOpenaiFast holds the default value on creation for the force_openai_fast field.
group.DefaultForceOpenaiFast = groupDescForceOpenaiFast.Default.(bool)
// groupDescForceOpenaiUltrafast is the schema descriptor for force_openai_ultrafast field.
groupDescForceOpenaiUltrafast := groupFields[51].Descriptor()
// group.DefaultForceOpenaiUltrafast holds the default value on creation for the force_openai_ultrafast field.
group.DefaultForceOpenaiUltrafast = groupDescForceOpenaiUltrafast.Default.(bool)
// groupDescFreeOpenaiFast is the schema descriptor for free_openai_fast field.
groupDescFreeOpenaiFast := groupFields[51].Descriptor()
groupDescFreeOpenaiFast := groupFields[52].Descriptor()
// group.DefaultFreeOpenaiFast holds the default value on creation for the free_openai_fast field.
group.DefaultFreeOpenaiFast = groupDescFreeOpenaiFast.Default.(bool)
// groupDescRequireOauthOnly is the schema descriptor for require_oauth_only field.
groupDescRequireOauthOnly := groupFields[52].Descriptor()
groupDescRequireOauthOnly := groupFields[53].Descriptor()
// group.DefaultRequireOauthOnly holds the default value on creation for the require_oauth_only field.
group.DefaultRequireOauthOnly = groupDescRequireOauthOnly.Default.(bool)
// groupDescRequirePrivacySet is the schema descriptor for require_privacy_set field.
groupDescRequirePrivacySet := groupFields[53].Descriptor()
groupDescRequirePrivacySet := groupFields[54].Descriptor()
// group.DefaultRequirePrivacySet holds the default value on creation for the require_privacy_set field.
group.DefaultRequirePrivacySet = groupDescRequirePrivacySet.Default.(bool)
// groupDescDefaultMappedModel is the schema descriptor for default_mapped_model field.
groupDescDefaultMappedModel := groupFields[54].Descriptor()
groupDescDefaultMappedModel := groupFields[55].Descriptor()
// group.DefaultDefaultMappedModel holds the default value on creation for the default_mapped_model field.
group.DefaultDefaultMappedModel = groupDescDefaultMappedModel.Default.(string)
// group.DefaultMappedModelValidator is a validator for the "default_mapped_model" field. It is called by the builders before save.
group.DefaultMappedModelValidator = groupDescDefaultMappedModel.Validators[0].(func(string) error)
// groupDescMessagesDispatchModelConfig is the schema descriptor for messages_dispatch_model_config field.
groupDescMessagesDispatchModelConfig := groupFields[55].Descriptor()
groupDescMessagesDispatchModelConfig := groupFields[56].Descriptor()
// group.DefaultMessagesDispatchModelConfig holds the default value on creation for the messages_dispatch_model_config field.
group.DefaultMessagesDispatchModelConfig = groupDescMessagesDispatchModelConfig.Default.(domain.OpenAIMessagesDispatchModelConfig)
// groupDescModelAllowlist is the schema descriptor for model_allowlist field.
groupDescModelAllowlist := groupFields[56].Descriptor()
groupDescModelAllowlist := groupFields[57].Descriptor()
// group.DefaultModelAllowlist holds the default value on creation for the model_allowlist field.
group.DefaultModelAllowlist = groupDescModelAllowlist.Default.(domain.GroupModelAllowlist)
// groupDescCodexModelsManifestConfig is the schema descriptor for codex_models_manifest_config field.
groupDescCodexModelsManifestConfig := groupFields[57].Descriptor()
groupDescCodexModelsManifestConfig := groupFields[58].Descriptor()
// group.DefaultCodexModelsManifestConfig holds the default value on creation for the codex_models_manifest_config field.
group.DefaultCodexModelsManifestConfig = groupDescCodexModelsManifestConfig.Default.(domain.GroupCodexModelsManifestConfig)
// groupDescRpmLimit is the schema descriptor for rpm_limit field.
groupDescRpmLimit := groupFields[58].Descriptor()
groupDescRpmLimit := groupFields[59].Descriptor()
// group.DefaultRpmLimit holds the default value on creation for the rpm_limit field.
group.DefaultRpmLimit = groupDescRpmLimit.Default.(int)
// groupDescMaxReasoningEffort is the schema descriptor for max_reasoning_effort field.
groupDescMaxReasoningEffort := groupFields[59].Descriptor()
groupDescMaxReasoningEffort := groupFields[60].Descriptor()
// group.DefaultMaxReasoningEffort holds the default value on creation for the max_reasoning_effort field.
group.DefaultMaxReasoningEffort = groupDescMaxReasoningEffort.Default.(string)
// group.MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save.
group.MaxReasoningEffortValidator = groupDescMaxReasoningEffort.Validators[0].(func(string) error)
// groupDescMaxReasoningEffortOverLimit is the schema descriptor for max_reasoning_effort_over_limit field.
groupDescMaxReasoningEffortOverLimit := groupFields[60].Descriptor()
groupDescMaxReasoningEffortOverLimit := groupFields[61].Descriptor()
// group.DefaultMaxReasoningEffortOverLimit holds the default value on creation for the max_reasoning_effort_over_limit field.
group.DefaultMaxReasoningEffortOverLimit = groupDescMaxReasoningEffortOverLimit.Default.(string)
// group.MaxReasoningEffortOverLimitValidator is a validator for the "max_reasoning_effort_over_limit" field. It is called by the builders before save.
group.MaxReasoningEffortOverLimitValidator = groupDescMaxReasoningEffortOverLimit.Validators[0].(func(string) error)
// groupDescReasoningEffortMappings is the schema descriptor for reasoning_effort_mappings field.
groupDescReasoningEffortMappings := groupFields[61].Descriptor()
groupDescReasoningEffortMappings := groupFields[62].Descriptor()
// group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field.
group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping)
// groupDescProfitControlEnabled is the schema descriptor for profit_control_enabled field.
groupDescProfitControlEnabled := groupFields[62].Descriptor()
groupDescProfitControlEnabled := groupFields[63].Descriptor()
// group.DefaultProfitControlEnabled holds the default value on creation for the profit_control_enabled field.
group.DefaultProfitControlEnabled = groupDescProfitControlEnabled.Default.(bool)
// groupDescProfitMinMargin is the schema descriptor for profit_min_margin field.
groupDescProfitMinMargin := groupFields[63].Descriptor()
groupDescProfitMinMargin := groupFields[64].Descriptor()
// group.DefaultProfitMinMargin holds the default value on creation for the profit_min_margin field.
group.DefaultProfitMinMargin = groupDescProfitMinMargin.Default.(float64)
// groupDescProfitSafetyBuffer is the schema descriptor for profit_safety_buffer field.
groupDescProfitSafetyBuffer := groupFields[64].Descriptor()
groupDescProfitSafetyBuffer := groupFields[65].Descriptor()
// group.DefaultProfitSafetyBuffer holds the default value on creation for the profit_safety_buffer field.
group.DefaultProfitSafetyBuffer = groupDescProfitSafetyBuffer.Default.(float64)
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
+3
View File
@@ -253,6 +253,9 @@ func (Group) Fields() []ent.Field {
field.Bool("force_openai_fast").
Default(false).
Comment("是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority"),
field.Bool("force_openai_ultrafast").
Default(false).
Comment("是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)"),
field.Bool("free_openai_fast").
Default(false).
Comment("是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费"),
+3 -3
View File
@@ -1,6 +1,6 @@
module github.com/Wei-Shaw/sub2api
go 1.27.3
go 1.27.4
require (
entgo.io/ent v0.14.5
@@ -23,9 +23,10 @@ require (
github.com/go-playground/validator/v10 v10.14.0
github.com/go-webauthn/webauthn v0.17.4
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/jsonschema-go v0.4.2
github.com/google/uuid v1.6.0
github.com/google/wire v0.7.0
github.com/gorilla/websocket v1.5.3
github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4
github.com/hashicorp/go-hclog v1.6.3
github.com/hashicorp/go-plugin v1.8.0
github.com/imroc/req/v3 v3.59.0
@@ -130,7 +131,6 @@ require (
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/go-tpm v0.9.8 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/hcl/v2 v2.18.1 // indirect
+2
View File
@@ -265,6 +265,8 @@ github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORR
github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4 h1:PYKzliEgITjLJoJqbV90S0YRaG8LNAsICH6fp6MApC0=
github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 h1:NmZ1PKzSTQbuGHw9DGPFomqkkLWMC+vZCkfs+FHv1Vg=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3/go.mod h1:zQrxl1YP88HQlA6i9c63DSVPFklWpGX4OWAc9bFuaH4=
github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
+6 -3
View File
@@ -1025,7 +1025,7 @@ type CircuitBreakerConfig struct {
}
type ConcurrencyConfig struct {
// PingInterval: 并发等待期间的 SSE ping 间隔(秒)
// PingInterval: 并发等待期间的 SSE ping 间隔(秒),0 禁用 ping
PingInterval int `mapstructure:"ping_interval"`
}
@@ -1193,6 +1193,8 @@ type GatewayConfig struct {
// Gemini 同账号重试次数(429/5xx 等可重试错误在换号前对同一账号的重发次数,不含首次请求)
MaxSameAccountRetriesGemini int `mapstructure:"max_same_account_retries_gemini"`
// Let the upstream decide whether to stream thought summaries on Antigravity Gemini compatibility requests.
AntigravityGeminiOmitIncludeThoughts bool `mapstructure:"antigravity_gemini_omit_include_thoughts"`
// Antigravity 429 fallback 限流时间(分钟),解析重置时间失败时使用
AntigravityFallbackCooldownMinutes int `mapstructure:"antigravity_fallback_cooldown_minutes"`
@@ -2621,6 +2623,7 @@ func setDefaults() {
viper.SetDefault("gateway.image_concurrency.overflow_mode", ImageConcurrencyOverflowModeReject)
viper.SetDefault("gateway.image_concurrency.wait_timeout_seconds", 30)
viper.SetDefault("gateway.image_concurrency.max_waiting_requests", 100)
viper.SetDefault("gateway.antigravity_gemini_omit_include_thoughts", false)
viper.SetDefault("gateway.antigravity_fallback_cooldown_minutes", 1)
viper.SetDefault("gateway.antigravity_extra_retries", 10)
viper.SetDefault("gateway.max_body_size", int64(256*1024*1024))
@@ -3887,8 +3890,8 @@ func (c *Config) Validate() error {
if c.Ops.Cleanup.Enabled && strings.TrimSpace(c.Ops.Cleanup.Schedule) == "" {
return fmt.Errorf("ops.cleanup.schedule is required when ops.cleanup.enabled=true")
}
if c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30 {
return fmt.Errorf("concurrency.ping_interval must be between 5-30 seconds")
if c.Concurrency.PingInterval != 0 && (c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30) {
return fmt.Errorf("concurrency.ping_interval must be 0 (disabled) or between 5-30 seconds")
}
if c.Gateway.Grok.FreeQuotaSoftGateEnabled {
if c.Gateway.Grok.FreeQuotaTokenLimit <= 0 {
+22 -12
View File
@@ -132,6 +132,14 @@ func TestLoadMinOutputTokensFromEnv(t *testing.T) {
require.Equal(t, 16, cfg.Gateway.MinOutputTokens)
}
func TestLoadAntigravityGeminiOmitIncludeThoughtsFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_ANTIGRAVITY_GEMINI_OMIT_INCLUDE_THOUGHTS", "true")
cfg, err := Load()
require.NoError(t, err)
require.True(t, cfg.Gateway.AntigravityGeminiOmitIncludeThoughts)
}
func TestLoadGeminiSameAccountRetries(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
@@ -1577,18 +1585,20 @@ func TestValidateOpsCleanupScheduleRequired(t *testing.T) {
func TestValidateConcurrencyPingInterval(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
cfg.Concurrency.PingInterval = 3
err = cfg.Validate()
if err == nil {
t.Fatalf("Validate() expected error for concurrency.ping_interval")
}
if !strings.Contains(err.Error(), "concurrency.ping_interval") {
t.Fatalf("Validate() expected concurrency.ping_interval error, got: %v", err)
for _, interval := range []int{-1, 0, 1, 3, 4, 5, 10, 30, 31} {
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
cfg.Concurrency.PingInterval = interval
err = cfg.Validate()
valid := interval == 0 || (interval >= 5 && interval <= 30)
if valid && err != nil {
t.Errorf("Validate() interval %d: %v", interval, err)
}
if !valid && (err == nil || !strings.Contains(err.Error(), "concurrency.ping_interval")) {
t.Errorf("Validate() interval %d: expected concurrency.ping_interval error, got %v", interval, err)
}
}
}
+3 -1
View File
@@ -178,7 +178,9 @@ var DefaultAntigravityModelMapping = map[string]string{
"gemini-3.8-flash-low": "gemini-3.8-flash-low",
"gemini-3.8-flash-medium": "gemini-3.8-flash-medium",
"gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered",
// Gemini 4 Argon tiered models
// Gemini 4 models
// Carbon uses the published model ID; do not infer Argon-style tier aliases.
"gemini-4-carbon": "gemini-4-carbon",
"gemini-4-argon": "gemini-4-argon-high",
"gemini-4-argon-high": "gemini-4-argon-high",
"gemini-4-argon-low": "gemini-4-argon-low",
@@ -107,6 +107,7 @@ func TestDefaultAntigravityModelMapping_Gemini38FlashModels(t *testing.T) {
func TestDefaultAntigravityModelMapping_Gemini4ArgonAndClaude55Models(t *testing.T) {
cases := map[string]string{
"gemini-4-carbon": "gemini-4-carbon",
"gemini-4-argon": "gemini-4-argon-high",
"gemini-4-argon-high": "gemini-4-argon-high",
"gemini-4-argon-low": "gemini-4-argon-low",
@@ -136,6 +136,7 @@ type CreateAccountRequest struct {
ExpiresAt *int64 `json:"expires_at"`
AutoPauseOnExpired *bool `json:"auto_pause_on_expired"`
ProbeEnabled *bool `json:"upstream_billing_probe_enabled"`
GroupSyncEnabled *bool `json:"upstream_billing_group_sync_enabled"`
ConfirmMixedChannelRisk *bool `json:"confirm_mixed_channel_risk"` // 用户确认混合渠道风险
}
@@ -157,6 +158,7 @@ type UpdateAccountRequest struct {
ExpiresAt *int64 `json:"expires_at"`
AutoPauseOnExpired *bool `json:"auto_pause_on_expired"`
ProbeEnabled *bool `json:"upstream_billing_probe_enabled"`
GroupSyncEnabled *bool `json:"upstream_billing_group_sync_enabled"`
RateSyncEnabled *bool `json:"upstream_billing_rate_sync_enabled"`
ConfirmMixedChannelRisk *bool `json:"confirm_mixed_channel_risk"` // 用户确认混合渠道风险
}
@@ -1062,6 +1064,7 @@ func (h *AccountHandler) Create(c *gin.Context) {
ExpiresAt: req.ExpiresAt,
AutoPauseOnExpired: req.AutoPauseOnExpired,
ProbeEnabled: req.ProbeEnabled,
GroupSyncEnabled: req.GroupSyncEnabled,
SkipMixedChannelCheck: skipCheck,
})
if execErr != nil {
@@ -1194,6 +1197,7 @@ func (h *AccountHandler) Update(c *gin.Context) {
ExpiresAt: req.ExpiresAt,
AutoPauseOnExpired: req.AutoPauseOnExpired,
ProbeEnabled: req.ProbeEnabled,
GroupSyncEnabled: req.GroupSyncEnabled,
RateSyncEnabled: req.RateSyncEnabled,
SkipMixedChannelCheck: skipCheck,
})
@@ -2,6 +2,7 @@ package admin
import (
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -91,6 +92,63 @@ func (h *AccountHandler) ProbeUpstreamBilling(c *gin.Context) {
response.Success(c, service.UpstreamBillingProbeResult{AccountID: accountID, Snapshot: snapshot})
}
// PreviewUpstreamGroup reads the saved account's connection or the editor's draft credentials.
func (h *AccountHandler) PreviewUpstreamGroup(c *gin.Context) {
if h.upstreamBillingProbe == nil {
response.ErrorFrom(c, service.ErrUpstreamBillingProbeUnavailable)
return
}
var req struct {
AccountID int64 `json:"account_id" binding:"min=0"`
Platform string `json:"platform"`
BaseURL string `json:"base_url"`
APIKey string `json:"api_key"`
ProxyID *int64 `json:"proxy_id" binding:"omitempty,gt=0"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid group preview request")
return
}
ctx := c.Request.Context()
var account *service.Account
if req.AccountID > 0 {
// A stored key must only be sent with its stored URL, headers and proxy.
if req.Platform != "" || req.BaseURL != "" || req.APIKey != "" || req.ProxyID != nil {
response.BadRequest(c, "Use either a saved account or draft credentials")
return
}
var err error
account, err = h.adminService.GetAccount(ctx, req.AccountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
} else {
if !service.IsUpstreamBillingProbeIdentity(req.Platform, service.AccountTypeAPIKey) || strings.TrimSpace(req.BaseURL) == "" || strings.TrimSpace(req.APIKey) == "" {
response.BadRequest(c, "A supported platform, base URL and API key are required")
return
}
account = &service.Account{
Platform: req.Platform, Type: service.AccountTypeAPIKey, ProxyID: req.ProxyID,
Credentials: map[string]any{"base_url": strings.TrimSpace(req.BaseURL), "api_key": strings.TrimSpace(req.APIKey)},
}
if req.ProxyID != nil {
proxy, err := h.adminService.GetProxy(ctx, *req.ProxyID)
if err != nil {
response.ErrorFrom(c, err)
return
}
account.Proxy = proxy
}
}
group, err := h.upstreamBillingProbe.PreviewGroup(ctx, account)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, group)
}
func (h *AccountHandler) ProbeUpstreamBillingBatch(c *gin.Context) {
if h.upstreamBillingProbe == nil {
response.ErrorFrom(c, service.ErrUpstreamBillingProbeUnavailable)
@@ -20,10 +20,25 @@ func setupUpstreamBillingProbeRouter() *gin.Engine {
router := gin.New()
router.GET("/admin/accounts/upstream-billing-probe/settings", handler.GetUpstreamBillingProbeSettings)
router.POST("/admin/accounts/upstream-billing-probe/batch", handler.ProbeUpstreamBillingBatch)
router.POST("/admin/accounts/upstream-billing-probe/group-preview", handler.PreviewUpstreamGroup)
router.PUT("/admin/accounts/:id/upstream-billing-probe", handler.SetUpstreamBillingProbeEnabled)
return router
}
func TestAccountHandlerUpstreamBillingGroupPreviewKeepsStoredCredentialsBound(t *testing.T) {
router := setupUpstreamBillingProbeRouter()
for _, body := range []string{
`{"account_id":7,"base_url":"https://different.example"}`,
`{"account_id":7,"proxy_id":8}`,
} {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/admin/accounts/upstream-billing-probe/group-preview", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code)
}
}
func TestAccountHandlerGetUpstreamBillingProbeSettingsReturnsDefaults(t *testing.T) {
router := setupUpstreamBillingProbeRouter()
recorder := httptest.NewRecorder()
@@ -69,6 +69,7 @@ type channelModelPricingRequest struct {
CacheReadPrice *float64 `json:"cache_read_price" binding:"omitempty,min=0"`
FastMultiplier *float64 `json:"fast_multiplier" binding:"omitempty,gt=0"`
FlexMultiplier *float64 `json:"flex_multiplier" binding:"omitempty,gt=0"`
UltrafastMultiplier *float64 `json:"ultrafast_multiplier" binding:"omitempty,gt=0"`
ReasoningEffortMultipliers map[string]float64 `json:"reasoning_effort_multipliers"`
ImageInputPrice *float64 `json:"image_input_price" binding:"omitempty,min=0"`
ImageOutputPrice *float64 `json:"image_output_price" binding:"omitempty,min=0"`
@@ -145,6 +146,7 @@ type channelModelPricingResponse struct {
CacheReadPrice *float64 `json:"cache_read_price"`
FastMultiplier *float64 `json:"fast_multiplier"`
FlexMultiplier *float64 `json:"flex_multiplier"`
UltrafastMultiplier *float64 `json:"ultrafast_multiplier"`
ReasoningEffortMultipliers map[string]float64 `json:"reasoning_effort_multipliers"`
ImageInputPrice *float64 `json:"image_input_price"`
ImageOutputPrice *float64 `json:"image_output_price"`
@@ -277,6 +279,7 @@ func pricingToResponse(p *service.ChannelModelPricing) channelModelPricingRespon
CacheReadPrice: p.CacheReadPrice,
FastMultiplier: p.FastMultiplier,
FlexMultiplier: p.FlexMultiplier,
UltrafastMultiplier: p.UltrafastMultiplier,
ReasoningEffortMultipliers: p.ReasoningEffortMultipliers,
ImageInputPrice: p.ImageInputPrice,
ImageOutputPrice: p.ImageOutputPrice,
@@ -361,10 +364,11 @@ func pricingRequestToService(reqs []channelModelPricingRequest, allowChannelMult
SortOrder: iv.SortOrder,
})
}
var fastMultiplier, flexMultiplier *float64
var fastMultiplier, flexMultiplier, ultrafastMultiplier *float64
if allowChannelMultipliers {
fastMultiplier = r.FastMultiplier
flexMultiplier = r.FlexMultiplier
ultrafastMultiplier = r.UltrafastMultiplier
}
result = append(result, service.ChannelModelPricing{
Platform: platform,
@@ -378,6 +382,7 @@ func pricingRequestToService(reqs []channelModelPricingRequest, allowChannelMult
CacheReadPrice: r.CacheReadPrice,
FastMultiplier: fastMultiplier,
FlexMultiplier: flexMultiplier,
UltrafastMultiplier: ultrafastMultiplier,
ReasoningEffortMultipliers: r.ReasoningEffortMultipliers,
ImageInputPrice: r.ImageInputPrice,
ImageOutputPrice: r.ImageOutputPrice,
@@ -11,6 +11,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/stretchr/testify/require"
)
@@ -460,6 +461,7 @@ func TestPricingRequestToService_MultipliersGatedByFlag(t *testing.T) {
BillingMode: "token",
FastMultiplier: float64Ptr(2.5),
FlexMultiplier: float64Ptr(0.5),
UltrafastMultiplier: float64Ptr(3),
ReasoningEffortMultipliers: map[string]float64{"high": 1.5, "max": 3},
Intervals: []pricingIntervalRequest{{
MinTokens: 272000,
@@ -473,6 +475,7 @@ func TestPricingRequestToService_MultipliersGatedByFlag(t *testing.T) {
allowed := pricingRequestToService([]channelModelPricingRequest{req}, true)
require.Equal(t, float64Ptr(2.5), allowed[0].FastMultiplier)
require.Equal(t, float64Ptr(0.5), allowed[0].FlexMultiplier)
require.Equal(t, float64Ptr(3), allowed[0].UltrafastMultiplier)
require.Equal(t, req.ReasoningEffortMultipliers, allowed[0].ReasoningEffortMultipliers)
require.Equal(t, float64Ptr(2), allowed[0].Intervals[0].InputMultiplier)
require.Equal(t, float64Ptr(1.5), allowed[0].Intervals[0].OutputMultiplier)
@@ -482,6 +485,7 @@ func TestPricingRequestToService_MultipliersGatedByFlag(t *testing.T) {
dropped := pricingRequestToService([]channelModelPricingRequest{req}, false)
require.Nil(t, dropped[0].FastMultiplier)
require.Nil(t, dropped[0].FlexMultiplier)
require.Nil(t, dropped[0].UltrafastMultiplier)
require.Equal(t, req.ReasoningEffortMultipliers, dropped[0].ReasoningEffortMultipliers)
require.Nil(t, dropped[0].Intervals[0].InputMultiplier)
require.Nil(t, dropped[0].Intervals[0].OutputMultiplier)
@@ -491,6 +495,22 @@ func TestPricingRequestToService_MultipliersGatedByFlag(t *testing.T) {
require.Equal(t, 272000, dropped[0].Intervals[0].MinTokens)
}
func TestPricingRequestAndResponse_UltrafastMultiplier(t *testing.T) {
var req channelModelPricingRequest
require.NoError(t, json.Unmarshal([]byte(`{"models":["gpt-6-astra"],"ultrafast_multiplier":1.25}`), &req))
pricing := pricingRequestToService([]channelModelPricingRequest{req}, true)
require.Equal(t, float64Ptr(1.25), pricing[0].UltrafastMultiplier)
got := pricingToResponse(&pricing[0])
require.Equal(t, float64Ptr(1.25), got.UltrafastMultiplier)
data, err := json.Marshal(got)
require.NoError(t, err)
require.Contains(t, string(data), `"ultrafast_multiplier":1.25`)
req = channelModelPricingRequest{}
require.NoError(t, json.Unmarshal([]byte(`{"models":["gpt-6-astra"],"ultrafast_multiplier":0}`), &req))
require.Error(t, binding.Validator.ValidateStruct(&req))
}
func TestPricingToResponse_TimePricing(t *testing.T) {
got := pricingToResponse(&service.ChannelModelPricing{
BillingMode: service.BillingModeToken,
@@ -239,6 +239,7 @@ type CreateGroupRequest struct {
AllowMessagesDispatch bool `json:"allow_messages_dispatch"`
AllowLive bool `json:"allow_live"`
ForceOpenAIFast bool `json:"force_openai_fast"`
ForceOpenAIUltrafast bool `json:"force_openai_ultrafast"`
FreeOpenAIFast bool `json:"free_openai_fast"`
RequireOAuthOnly bool `json:"require_oauth_only"`
RequirePrivacySet bool `json:"require_privacy_set"`
@@ -316,6 +317,7 @@ type UpdateGroupRequest struct {
AllowMessagesDispatch *bool `json:"allow_messages_dispatch"`
AllowLive *bool `json:"allow_live"`
ForceOpenAIFast *bool `json:"force_openai_fast"`
ForceOpenAIUltrafast *bool `json:"force_openai_ultrafast"`
FreeOpenAIFast *bool `json:"free_openai_fast"`
RequireOAuthOnly *bool `json:"require_oauth_only"`
RequirePrivacySet *bool `json:"require_privacy_set"`
@@ -719,6 +721,7 @@ func (h *GroupHandler) Create(c *gin.Context) {
AllowMessagesDispatch: req.AllowMessagesDispatch,
AllowLive: req.AllowLive,
ForceOpenAIFast: req.ForceOpenAIFast,
ForceOpenAIUltrafast: req.ForceOpenAIUltrafast,
FreeOpenAIFast: req.FreeOpenAIFast,
RequireOAuthOnly: req.RequireOAuthOnly,
RequirePrivacySet: req.RequirePrivacySet,
@@ -867,6 +870,7 @@ func (h *GroupHandler) Update(c *gin.Context) {
AllowMessagesDispatch: req.AllowMessagesDispatch,
AllowLive: req.AllowLive,
ForceOpenAIFast: req.ForceOpenAIFast,
ForceOpenAIUltrafast: req.ForceOpenAIUltrafast,
FreeOpenAIFast: req.FreeOpenAIFast,
RequireOAuthOnly: req.RequireOAuthOnly,
RequirePrivacySet: req.RequirePrivacySet,
@@ -25,3 +25,21 @@ func TestGroupRequestsDecodeForceOpenAIFast(t *testing.T) {
require.Nil(t, omitted.ForceOpenAIFast)
require.Nil(t, omitted.FreeOpenAIFast)
}
func TestGroupRequestsDecodeForceOpenAIUltrafast(t *testing.T) {
var createReq CreateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{"name":"ultrafast","force_openai_ultrafast":true}`), &createReq))
require.True(t, createReq.ForceOpenAIUltrafast)
require.False(t, createReq.ForceOpenAIFast)
var updateReq UpdateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{"force_openai_fast":false,"force_openai_ultrafast":true}`), &updateReq))
require.NotNil(t, updateReq.ForceOpenAIUltrafast)
require.True(t, *updateReq.ForceOpenAIUltrafast)
require.NotNil(t, updateReq.ForceOpenAIFast)
require.False(t, *updateReq.ForceOpenAIFast)
var omitted UpdateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{}`), &omitted))
require.Nil(t, omitted.ForceOpenAIUltrafast)
}
@@ -23,3 +23,18 @@ func TestGroupMapperExposesForceOpenAIFastOnlyToAdmins(t *testing.T) {
require.Contains(t, string(adminJSON), `"force_openai_fast":true`)
require.Contains(t, string(adminJSON), `"free_openai_fast":true`)
}
func TestGroupMapperExposesForceOpenAIUltrafastOnlyToAdmins(t *testing.T) {
group := &service.Group{
ID: 7, Name: "ultrafast", Platform: service.PlatformOpenAI, Status: service.StatusActive, ForceOpenAIUltrafast: true,
}
userJSON, err := json.Marshal(GroupFromService(group))
require.NoError(t, err)
require.NotContains(t, string(userJSON), "force_openai_ultrafast")
adminJSON, err := json.Marshal(GroupFromServiceAdmin(group))
require.NoError(t, err)
require.Contains(t, string(adminJSON), `"force_openai_ultrafast":true`)
require.Contains(t, string(adminJSON), `"force_openai_fast":false`)
}
+25
View File
@@ -149,6 +149,7 @@ func GroupFromServiceAdmin(g *service.Group) *AdminGroup {
out := &AdminGroup{
Group: groupFromServiceBase(g),
ForceOpenAIFast: g.ForceOpenAIFast,
ForceOpenAIUltrafast: g.ForceOpenAIUltrafast,
FreeOpenAIFast: g.FreeOpenAIFast,
ProfitControlEnabled: g.ProfitControlEnabled,
ProfitMinMargin: g.ProfitMinMargin,
@@ -561,6 +562,7 @@ func ProxyWithAccountCountFromService(p *service.ProxyWithAccountCount) *ProxyWi
QualityGrade: p.QualityGrade,
QualitySummary: p.QualitySummary,
QualityChecked: p.QualityChecked,
LatencyChecked: p.LatencyChecked,
}
}
@@ -606,6 +608,7 @@ func ProxyWithAccountCountFromServiceAdmin(p *service.ProxyWithAccountCount) *Ad
QualityGrade: p.QualityGrade,
QualitySummary: p.QualitySummary,
QualityChecked: p.QualityChecked,
LatencyChecked: p.LatencyChecked,
}
}
@@ -760,6 +763,28 @@ func UsageLogFromService(l *service.UsageLog) *UsageLog {
return &u
}
// ApplyResponseModel fills ResponseModel with the final response model of l
// (upstream_response_model → upstream_model → model). It is left empty when the
// final model equals the client-facing requested model, so users only ever see
// "requested model" and "final response model", never the mapping chain.
func (u *UsageLog) ApplyResponseModel(l *service.UsageLog) {
if u == nil || l == nil {
return
}
final := strings.TrimSpace(derefString(l.UpstreamResponseModel))
if final == "" {
final = strings.TrimSpace(derefString(l.UpstreamModel))
}
if final == "" {
final = strings.TrimSpace(l.Model)
}
if final == "" || final == u.Model {
u.ResponseModel = nil
return
}
u.ResponseModel = &final
}
// UsageLogFromServiceAdmin converts a service UsageLog to DTO for admin users.
// It includes minimal Account info (ID, Name only) and IP address.
func UsageLogFromServiceAdmin(l *service.UsageLog) *AdminUsageLog {
@@ -332,3 +332,69 @@ func TestUsageLogFromService_PreservesHistoricalMissingImageSize(t *testing.T) {
func f64Ptr(value float64) *float64 {
return &value
}
func TestUsageLogApplyResponseModel(t *testing.T) {
t.Parallel()
strPtr := func(s string) *string { return &s }
cases := []struct {
name string
log service.UsageLog
want *string
}{
{
name: "prefers upstream response model and hides mapping chain",
log: service.UsageLog{
Model: "claude-sonnet-4-5",
RequestedModel: "claude-sonnet-4-5",
UpstreamModel: strPtr("mid-model"),
UpstreamResponseModel: strPtr("final-model-20260101"),
ModelMappingChain: strPtr("claude-sonnet-4-5→mid-model→final-model"),
},
want: strPtr("final-model-20260101"),
},
{
name: "falls back to upstream model",
log: service.UsageLog{
Model: "gpt-5",
RequestedModel: "gpt-5",
UpstreamModel: strPtr("gpt-5-mini"),
},
want: strPtr("gpt-5-mini"),
},
{
name: "falls back to billing model when requested differs",
log: service.UsageLog{
Model: "gpt-5-mini",
RequestedModel: "gpt-5",
},
want: strPtr("gpt-5-mini"),
},
{
name: "omitted when final equals requested",
log: service.UsageLog{
Model: "gpt-5",
RequestedModel: "gpt-5",
UpstreamResponseModel: strPtr(" gpt-5 "),
},
want: nil,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
out := UsageLogFromService(&tc.log)
require.Nil(t, out.ResponseModel, "response_model must be opt-in")
out.ApplyResponseModel(&tc.log)
require.Equal(t, tc.want, out.ResponseModel)
raw, err := json.Marshal(out)
require.NoError(t, err)
require.NotContains(t, string(raw), "model_mapping_chain")
require.NotContains(t, string(raw), "upstream_model")
})
}
}
+37 -29
View File
@@ -172,7 +172,8 @@ type Group struct {
type AdminGroup struct {
Group
// ForceOpenAIFast 是管理端请求策略,用户侧分组 DTO 无需暴露。
ForceOpenAIFast bool `json:"force_openai_fast"`
ForceOpenAIFast bool `json:"force_openai_fast"`
ForceOpenAIUltrafast bool `json:"force_openai_ultrafast"`
// FreeOpenAIFast 是管理端计费策略,用户侧分组 DTO 无需暴露。
FreeOpenAIFast bool `json:"free_openai_fast"`
@@ -460,20 +461,21 @@ type Proxy struct {
type ProxyWithAccountCount struct {
Proxy
AccountCount int64 `json:"account_count"`
LatencyMs *int64 `json:"latency_ms,omitempty"`
LatencyStatus string `json:"latency_status,omitempty"`
LatencyMessage string `json:"latency_message,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
Country string `json:"country,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Region string `json:"region,omitempty"`
City string `json:"city,omitempty"`
QualityStatus string `json:"quality_status,omitempty"`
QualityScore *int `json:"quality_score,omitempty"`
QualityGrade string `json:"quality_grade,omitempty"`
QualitySummary string `json:"quality_summary,omitempty"`
QualityChecked *int64 `json:"quality_checked,omitempty"`
AccountCount int64 `json:"account_count"`
LatencyMs *int64 `json:"latency_ms,omitempty"`
LatencyStatus string `json:"latency_status,omitempty"`
LatencyMessage string `json:"latency_message,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
Country string `json:"country,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Region string `json:"region,omitempty"`
City string `json:"city,omitempty"`
QualityStatus string `json:"quality_status,omitempty"`
QualityScore *int `json:"quality_score,omitempty"`
QualityGrade string `json:"quality_grade,omitempty"`
QualitySummary string `json:"quality_summary,omitempty"`
QualityChecked *int64 `json:"quality_checked,omitempty"`
LatencyChecked *time.Time `json:"latency_checked_at,omitempty"`
}
// AdminProxy 是管理员接口使用的 proxy DTO(包含密码等敏感字段)。
@@ -486,20 +488,21 @@ type AdminProxy struct {
// AdminProxyWithAccountCount 是管理员接口使用的带账号统计的 proxy DTO。
type AdminProxyWithAccountCount struct {
AdminProxy
AccountCount int64 `json:"account_count"`
LatencyMs *int64 `json:"latency_ms,omitempty"`
LatencyStatus string `json:"latency_status,omitempty"`
LatencyMessage string `json:"latency_message,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
Country string `json:"country,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Region string `json:"region,omitempty"`
City string `json:"city,omitempty"`
QualityStatus string `json:"quality_status,omitempty"`
QualityScore *int `json:"quality_score,omitempty"`
QualityGrade string `json:"quality_grade,omitempty"`
QualitySummary string `json:"quality_summary,omitempty"`
QualityChecked *int64 `json:"quality_checked,omitempty"`
AccountCount int64 `json:"account_count"`
LatencyMs *int64 `json:"latency_ms,omitempty"`
LatencyStatus string `json:"latency_status,omitempty"`
LatencyMessage string `json:"latency_message,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
Country string `json:"country,omitempty"`
CountryCode string `json:"country_code,omitempty"`
Region string `json:"region,omitempty"`
City string `json:"city,omitempty"`
QualityStatus string `json:"quality_status,omitempty"`
QualityScore *int `json:"quality_score,omitempty"`
QualityGrade string `json:"quality_grade,omitempty"`
QualitySummary string `json:"quality_summary,omitempty"`
QualityChecked *int64 `json:"quality_checked,omitempty"`
LatencyChecked *time.Time `json:"latency_checked_at,omitempty"`
}
type ProxyAccountSummary struct {
@@ -601,6 +604,11 @@ type UsageLog struct {
AccountID int64 `json:"account_id"`
RequestID string `json:"request_id"`
Model string `json:"model"`
// ResponseModel is the final model that actually answered the request. It is
// only populated for regular users when the record's channel enables
// features_config.expose_response_model and it differs from Model. The
// intermediate mapping chain is never exposed.
ResponseModel *string `json:"response_model,omitempty"`
// ServiceTier records the OpenAI service tier used for billing, e.g. "priority" / "flex".
ServiceTier *string `json:"service_tier,omitempty"`
// ReasoningEffort is the client-requested effort (mapping-hidden, like Model).
@@ -0,0 +1,201 @@
//go:build unit
package handler
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestOpenAIResponsesUsageReportsConfigurationUpdateEffort(t *testing.T) {
const input = `[{"role":"user","content":"hello"},{"type":"configuration_update","reasoning":{"effort":"high"}}]`
const body = `{"model":"gpt-6.1-sol","input":` + input + `,"reasoning":{"effort":"medium"}}`
upstream := newAstraProCapturedUpstream(&http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"id":"resp_effort","model":"gpt-6.1-sol","status":"completed","output":[],"usage":{"input_tokens":10,"output_tokens":1}}`)),
})
account := service.Account{
ID: 1, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{"api_key": "test-key"},
}
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
cfg := &config.Config{RunMode: config.RunModeSimple}
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
gateway := service.NewOpenAIGatewayService(
&openAIWSUsageHandlerAccountRepoStub{account: account}, usageRepo, nil, nil, nil, nil, nil, cfg,
nil, nil, service.NewBillingService(cfg, nil), nil, billing, upstream, &service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing,
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg)
c, rec := newAstraProFailoverContext(t, body)
h.Responses(c)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
_, _, bodies := upstream.snapshot()
require.Len(t, bodies, 1)
require.Equal(t, "medium", gjson.GetBytes(bodies[0], "reasoning.effort").String())
require.JSONEq(t, input, gjson.GetBytes(bodies[0], "input").Raw)
require.Len(t, usageRepo.created, 1)
log := dto.UsageLogFromService(<-usageRepo.created)
require.NotNil(t, log.ReasoningEffort)
require.Equal(t, "high", *log.ReasoningEffort)
}
type compatEffortPolicyUpstream struct {
service.HTTPUpstream
bodies [][]byte
}
func (u *compatEffortPolicyUpstream) DoWithTLS(req *http.Request, _ string, _ int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
u.bodies = append(u.bodies, body)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)),
}, nil
}
func TestGatewayCompatibilityHandlersReasoningEffortPolicy(t *testing.T) {
gin.SetMode(gin.TestMode)
const model = "claude-sonnet-4.5"
for _, endpoint := range []string{"chat/completions", "responses"} {
for _, platform := range []string{service.PlatformAnthropic, service.PlatformComposite} {
for _, stream := range []bool{false, true} {
for _, tc := range []struct {
name string
effort string
ceiling string
overLimit string
mappings []service.ReasoningEffortMapping
want string
denied bool
}{
{name: "ceiling", effort: "high", ceiling: "medium", want: "medium"},
{name: "mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low"}}, want: "low"},
{name: "mapping then ceiling", effort: "low", ceiling: "medium", mappings: []service.ReasoningEffortMapping{{From: "low", To: "high"}}, want: "medium"},
{name: "model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: model}}, want: "low"},
{name: "other model mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "low", MatchType: "exact", Model: "other-model"}}, want: "high"},
{name: "deny ceiling", effort: "high", ceiling: "medium", overLimit: service.ReasoningEffortOverLimitDeny, denied: true},
{name: "deny mapping", effort: "high", mappings: []service.ReasoningEffortMapping{{From: "high", To: "deny"}}, denied: true},
{name: "within ceiling", effort: "low", ceiling: "medium", want: "low"},
{name: "no policy", effort: "high", want: "high"},
{name: "omitted", ceiling: "medium"},
} {
t.Run(fmt.Sprintf("%s/%s/stream=%t/%s", endpoint, platform, stream, tc.name), func(t *testing.T) {
cfg := &config.Config{}
groupID := int64(9400)
group := &service.Group{
ID: groupID, Hydrated: true, Platform: platform, Status: service.StatusActive, RateMultiplier: 1,
MaxReasoningEffort: tc.ceiling, MaxReasoningEffortOverLimit: tc.overLimit, ReasoningEffortMappings: tc.mappings,
}
account := &service.Account{
ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
Credentials: map[string]any{"api_key": "test-key"},
AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}},
}
cache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
snapshot := service.NewSchedulerSnapshotService(cache, nil, nil, nil, nil)
upstream := &compatEffortPolicyUpstream{}
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
billingRepo := &compatStreamUsageBillingRepo{}
billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
gateway := service.NewGatewayService(
nil, &fakeGroupRepo{group: group}, usageRepo, billingRepo, nil, nil, nil, nil, cfg,
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
h := &GatewayHandler{
gatewayService: gateway, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
}
request := map[string]any{"model": model, "stream": stream}
if endpoint == "chat/completions" {
request["messages"] = []map[string]string{{"role": "user", "content": "hello"}}
if tc.effort != "" {
request["reasoning_effort"] = tc.effort
}
} else {
request["input"] = "hello"
if tc.effort != "" {
request["reasoning"] = map[string]string{"effort": tc.effort}
}
}
body, err := json.Marshal(request)
require.NoError(t, err)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
ctx := context.WithValue(context.Background(), ctxkey.Group, group)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, bytes.NewReader(body)).WithContext(ctx)
c.Request.Header.Set("Content-Type", "application/json")
apiKey := &service.APIKey{
ID: 9402, UserID: 9403, GroupID: &groupID, Group: group,
User: &service.User{ID: 9403, Balance: 100},
}
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
if endpoint == "chat/completions" {
h.ChatCompletions(c)
} else {
h.Responses(c)
}
if tc.denied {
require.Equal(t, http.StatusForbidden, recorder.Code, recorder.Body.String())
errorField := "error.type"
if endpoint == "responses" {
errorField = "error.code"
}
require.Equal(t, "permission_error", gjson.Get(recorder.Body.String(), errorField).String())
require.Empty(t, upstream.bodies)
require.Zero(t, cache.snapshotCalls.Load(), "local policy denial precedes account selection")
require.Empty(t, usageRepo.created)
require.Empty(t, billingRepo.commands)
return
}
// Check the final Anthropic request, beyond handler parsing and both protocol conversions.
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Len(t, upstream.bodies, 1)
require.Equal(t, tc.want, gjson.GetBytes(upstream.bodies[0], "output_config.effort").String())
require.Equal(t, model, gjson.GetBytes(upstream.bodies[0], "model").String())
require.Contains(t, recorder.Body.String(), "partial")
require.Len(t, usageRepo.created, 1)
usage := <-usageRepo.created
if tc.effort == "" {
require.Nil(t, usage.RequestedReasoningEffort)
} else {
require.Equal(t, &tc.effort, usage.RequestedReasoningEffort)
require.Equal(t, &tc.want, usage.ReasoningEffort)
}
})
}
}
}
}
}
+43 -3
View File
@@ -80,7 +80,7 @@ func NewGatewayHandler(
cfg *config.Config,
settingService *service.SettingService,
) *GatewayHandler {
pingInterval := time.Duration(0)
pingInterval := defaultPingInterval
maxAccountSwitches := 10
maxAccountSwitchesGemini := 3
if cfg != nil {
@@ -651,6 +651,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// 受限的账号被失败请求的 session hash 卡满整个空闲窗口,后续新会话全部被拒。
// 成功请求保持既有空闲超时语义(会话按最后活动时间过期)。
sessionSlotAccounts := make(map[int64]*service.Account)
// 本请求在利润门下实际尝试转发的账号。终值写回只覆盖其中除最终服务账号以外的 ID;
// fs.FailedAccountIDs 会被退避重试重置,不能用作这个集合。
var attemptedAccountIDs []int64
upstreamServedSession := false
defer func() {
if upstreamServedSession {
@@ -915,6 +918,15 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
if fs.ForceCacheBilling {
requestCtx = service.WithForceCacheBilling(requestCtx)
}
if channelMapping.Mapped {
// 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。
requestCtx = service.WithGatewaySchedulingModel(requestCtx, reqModel)
}
// 只记利润门准入的账号:准入时本请求自己写过绑定,failover 后可能留在键里;
// 不开门时每次转发前选号都已把键写成当前账号,键里的失败账号只能是别的请求写的
if selection.ProfitGateActive() {
attemptedAccountIDs = append(attemptedAccountIDs, account.ID)
}
// 记录 Forward 前已写入字节数,Forward 后若增加则说明 SSE 内容已发,禁止 failover
writerSizeBeforeForward := c.Writer.Size()
if account.Platform == service.PlatformAntigravity && account.Type != service.AccountTypeAPIKey {
@@ -1126,9 +1138,21 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// - 选中账号与粘性账号一致:刷新 TTL
// - 粘性账号因负载/RPM 被跳过、选中了其他账号:不覆盖原绑定,
// 下次请求粘性账号恢复后仍可命中
// 写入只覆盖缺失的键与本请求在利润门下 failover 掉的账号(准入时本请求自己写过它),
// 转发期间别的请求改绑的值不动。
failedOverAccountIDs := make([]int64, 0, len(attemptedAccountIDs))
for _, attemptedAccountID := range attemptedAccountIDs {
if attemptedAccountID != account.ID {
failedOverAccountIDs = append(failedOverAccountIDs, attemptedAccountID)
}
}
if sessionKey != "" && (sessionBoundAccountID == 0 || sessionBoundAccountID == account.ID) {
if err := h.gatewayService.BindStickySession(c.Request.Context(), currentAPIKey.GroupID, sessionKey, account.ID); err != nil {
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
// Forward has completed; finish the bounded write even if the client disconnects.
bindCtx, cancelBind := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 5*time.Second)
bindErr := h.gatewayService.BindStickySessionUnlessRebound(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID, failedOverAccountIDs)
cancelBind()
if bindErr != nil {
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Int("failed_over_account_count", len(failedOverAccountIDs)), zap.Error(bindErr))
}
}
@@ -1187,6 +1211,22 @@ func (h *GatewayHandler) Models(c *gin.Context) {
// Get available models from account configurations for the selected group platform.
availableModels := h.gatewayService.GetAvailableModels(c.Request.Context(), groupID, platform)
if platform == service.PlatformAnthropic {
var group *service.Group
if apiKey != nil {
group = apiKey.Group
}
source := availableModels
if group != nil && group.ModelAllowlistEnabled() {
source = modelListingSource(platform, availableModels, defaultModelIDsForPlatform(platform))
} else if len(source) == 0 {
source = defaultModelIDsForPlatform(platform)
}
expanded := h.gatewayService.ExpandAnthropicLongContextModels(c.Request.Context(), group, source)
if len(availableModels) > 0 || len(expanded) > len(source) || (group != nil && group.ModelAllowlistEnabled()) {
availableModels = expanded
}
}
if apiKey != nil && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
source := modelListingSource(platform, availableModels, defaultModelIDsForPlatform(platform))
writeAllowlistedModelsList(c, platform, apiKey.Group.ModelAllowlist.FilterForListing(source))
@@ -85,6 +85,12 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) {
return
}
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
respondOpenAIReasoningEffortPolicyError(c, err, h.chatCompletionsErrorResponse)
return
} else if changed {
body = cappedBody
}
reqStream, ok := parseOpenAICompatibleStream(body)
if !ok {
h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
@@ -168,8 +174,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
defer inflightRelease()
// Parse request for session hash
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
bodyRef := service.NewRequestBodyRef(body)
parsedReq, _ := service.ParseGatewayRequest(bodyRef, "chat_completions")
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "chat_completions")
if parsedReq == nil {
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
}
@@ -390,6 +398,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
zap.Error(err),
)
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(c.Request.Context()), apiKey.GroupID, selectionSessionHash, account.ID, err)
if result != nil {
submitForwardUsage(result)
}
@@ -85,6 +85,12 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) {
return
}
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
respondOpenAIReasoningEffortPolicyError(c, err, h.responsesErrorResponse)
return
} else if changed {
body = cappedBody
}
reqStream, ok := parseOpenAICompatibleStream(body)
if !ok {
h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
@@ -100,7 +106,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
// 里的任何工具声明(含 Codex 被动 image_gen namespace)而关闭。生图意图
// 仅用于能力路由与图片计费;独立图片/视频端点才在利润门范围之外。
requestCtx, pricingAt := service.WithGatewayTokenRequestPricing(requestCtx)
if service.IsImageGenerationIntentForPlatform("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) {
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此走跳过校验的
// 变体,避免对同一份字节再全量校验一次。
if service.IsImageGenerationIntentForPlatformValidated("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) {
requestCtx = service.WithOpenAIImageGenerationIntent(requestCtx)
}
c.Request = c.Request.WithContext(requestCtx)
@@ -172,8 +181,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
defer inflightRelease()
// Parse request for session hash
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
bodyRef := service.NewRequestBodyRef(body)
parsedReq, _ := service.ParseGatewayRequest(bodyRef, "responses")
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "responses")
if parsedReq == nil {
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
}
@@ -373,6 +384,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
zap.Bool("upstream_error_response_already_written", upstreamErrorAlreadyCommunicated),
zap.Error(err),
)
// The response is already committed, so the client retries; send that
// retry through scheduling again instead of back to this account.
h.gatewayService.ReleaseStickySessionAfterCommittedNoContent(context.WithoutCancel(requestCtx), apiKey.GroupID, sessionHash, account.ID, err)
if result != nil {
submitForwardUsage(result)
}
+2 -2
View File
@@ -172,7 +172,7 @@ type ConcurrencyHelper struct {
// NewConcurrencyHelper creates a new ConcurrencyHelper
func NewConcurrencyHelper(concurrencyService *service.ConcurrencyService, pingFormat SSEPingFormat, pingInterval time.Duration) *ConcurrencyHelper {
if pingInterval <= 0 {
if pingInterval < 0 {
pingInterval = defaultPingInterval
}
return &ConcurrencyHelper{
@@ -380,7 +380,7 @@ func (h *ConcurrencyHelper) waitForSlotWithPingTimeout(c *gin.Context, slotType
}
// Determine if ping is needed (streaming + ping format defined)
needPing := isStream && h.pingFormat != ""
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
var flusher http.Flusher
if needPing {
@@ -0,0 +1,67 @@
package handler
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestConcurrencyWaitPingInterval(t *testing.T) {
for _, slotType := range []string{"user", "account"} {
for _, format := range []SSEPingFormat{SSEPingFormatClaude, SSEPingFormatComment} {
for _, interval := range []time.Duration{0, time.Millisecond} {
t.Run(slotType+"/"+string(format)+"/"+interval.String(), func(t *testing.T) {
cache := &helperConcurrencyCacheStub{}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), format, interval)
require.Equal(t, interval, helper.pingInterval)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
started := false
_, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, 150*time.Millisecond, true, &started, false)
var concurrencyErr *ConcurrencyError
require.ErrorAs(t, err, &concurrencyErr)
require.True(t, concurrencyErr.IsTimeout)
if interval == 0 {
require.False(t, started)
require.False(t, c.Writer.Written())
require.False(t, recorder.Flushed)
require.Empty(t, recorder.Body.String())
require.Empty(t, recorder.Header().Get("Content-Type"))
c.JSON(http.StatusTooManyRequests, gin.H{"error": "busy"})
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
} else {
require.True(t, started)
require.True(t, recorder.Flushed)
require.Contains(t, recorder.Body.String(), string(format))
}
})
}
}
}
}
func TestConcurrencyWaitWithoutPingAcquiresSlot(t *testing.T) {
for _, slotType := range []string{"user", "account"} {
t.Run(slotType, func(t *testing.T) {
cache := &helperConcurrencyCacheStub{userSeq: []bool{true}, accountSeq: []bool{true}}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatClaude, 0)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
started := false
release, err := helper.waitForSlotWithPingTimeout(c, slotType, 1, 1, time.Second, true, &started, false)
require.NoError(t, err)
require.NotNil(t, release)
release()
require.False(t, started)
require.False(t, c.Writer.Written())
require.Empty(t, recorder.Body.String())
})
}
}
@@ -1,7 +1,9 @@
package handler
import (
"log/slog"
"net/http"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
@@ -14,6 +16,7 @@ import (
const keyBillingInfoSchemaVersion = 1
type keyBillingInfoResponse struct {
*service.BillingGroupInfo
Object string `json:"object"`
SchemaVersion int `json:"schema_version"`
BillingScope string `json:"billing_scope"`
@@ -31,7 +34,7 @@ type keyBillingInfoResponse struct {
}
// KeyBillingInfo returns the token billing multiplier effective for the authenticated API key.
// GET /v1/sub2api/billing
// GET /v1/sub2api/billing (include=group also returns the group's display name and description).
func (h *GatewayHandler) KeyBillingInfo(c *gin.Context) {
apiKey, ok := middleware2.GetAPIKeyFromContext(c)
if !ok {
@@ -57,8 +60,33 @@ func (h *GatewayHandler) KeyBillingInfo(c *gin.Context) {
return
}
info := buildKeyBillingInfo(apiKey, resolvedRate, timezone.Now())
if keyBillingIncludes(c, "group") {
group, err := h.apiKeyService.GetBillingGroupInfo(c.Request.Context(), *apiKey.GroupID, c.GetHeader("Accept-Language"))
if err != nil {
slog.WarnContext(c.Request.Context(), "billing group display text unavailable", "group_id", *apiKey.GroupID, "error", err)
} else {
info.BillingGroupInfo = group
}
}
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusOK, buildKeyBillingInfo(apiKey, resolvedRate, timezone.Now()))
c.JSON(http.StatusOK, info)
}
// keyBillingIncludes reports whether the caller asked for an optional response section.
// include is a comma-separated list and may be repeated, so a client can request several
// sections in one call (include=group,other or include=group&include=other); unknown sections
// are ignored. An exact-match comparison would stop returning the group as soon as a second
// section exists.
func keyBillingIncludes(c *gin.Context, section string) bool {
for _, value := range c.QueryArray("include") {
for _, item := range strings.Split(value, ",") {
if strings.TrimSpace(item) == section {
return true
}
}
}
return false
}
func (h *GatewayHandler) resolveKeyBillingRate(c *gin.Context, apiKey *service.APIKey) (float64, bool) {
@@ -23,6 +23,82 @@ type gatewayModelsAccountRepoStub struct {
byGroup map[int64][]service.Account
}
func TestGatewayModelsAnthropicLongContextVariants(t *testing.T) {
gin.SetMode(gin.TestMode)
const groupID int64 = 8880
for _, test := range []struct {
name string
platform string
mapping map[string]any
metadata map[string]service.UpstreamModelMetadata
allowlist []string
routing map[string][]int64
otherAccounts []service.Account
wantVariants []string
absent []string
}{
{name: "mapped target and threshold", mapping: map[string]any{"public": "upstream", "short": "short", "max-only": "max-only"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 900_000}, "short": {ContextWindow: 899_999}, "max-only": {MaxContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}},
wantVariants: []string{"public[1m]"}, absent: []string{"upstream", "upstream[1m]", "hidden", "hidden[1m]", "short[1m]", "max-only[1m]", claude.DefaultModels[0].ID}},
{name: "wildcard mappings are not concrete variants", mapping: map[string]any{"public*": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public*[1m]"}},
{name: "source metadata cannot override mapped target", mapping: map[string]any{"public": "short"},
metadata: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}, "short": {ContextWindow: 200_000}}, absent: []string{"public[1m]"}},
{name: "no duplicate suffix", mapping: map[string]any{"public": "upstream", "public[1m]": "upstream", "other[1M]": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, wantVariants: []string{"public[1m]", "other[1M]"}, absent: []string{"public[1m][1m]", "other[1M][1m]"}},
{name: "allowlist filters variants", mapping: map[string]any{"public": "upstream", "private": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public"}, absent: []string{"public[1m]", "private", "private[1m]"}},
{name: "allowlist can select variant", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public[1m]"}, wantVariants: []string{"public[1m]"}, absent: []string{"public"}},
{name: "routing excludes metadata account", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"public": {2}}, absent: []string{"public[1m]"}},
{name: "routing includes metadata account", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"pub*": {1}}, wantVariants: []string{"public[1m]"}},
{name: "non-Anthropic listing", platform: service.PlatformOpenAI, mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public[1m]"}},
{name: "unmapped defaults", metadata: map[string]service.UpstreamModelMetadata{claude.DefaultModels[0].ID: {ContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}},
wantVariants: []string{claude.DefaultModels[0].ID + "[1m]"}, absent: []string{"hidden", "hidden[1m]"}},
{name: "other platform account metadata", mapping: map[string]any{"public": "upstream"},
otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformOpenAI, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}},
{name: "unsupported model metadata", mapping: map[string]any{"public": "upstream"},
otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"private": "private"}}, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}},
} {
t.Run(test.name, func(t *testing.T) {
platform := test.platform
if platform == "" {
platform = service.PlatformAnthropic
}
account := service.Account{ID: 1, Platform: platform, Type: service.AccountTypeOAuth, Credentials: map[string]any{"model_mapping": test.mapping}}
account.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: test.metadata})
outsideAccount := service.Account{ID: 3, Platform: service.PlatformAnthropic}
outsideAccount.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}})
h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{
groupID: append([]service.Account{account}, test.otherAccounts...), groupID + 1: {outsideAccount},
}})
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
ctx.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: &service.Group{
ID: groupID, Platform: platform,
ModelAllowlist: service.GroupModelAllowlist{Enabled: test.allowlist != nil, Models: test.allowlist},
ModelRoutingEnabled: test.routing != nil, ModelRouting: test.routing,
}})
h.Models(ctx)
require.Equal(t, http.StatusOK, rec.Code)
var response gatewayModelsResponseForTest
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response))
ids := modelIDsForTest(response.Data)
for _, variant := range test.wantVariants {
require.Contains(t, ids, variant)
}
for _, absent := range test.absent {
require.NotContains(t, ids, absent)
}
require.Len(t, mergeModelIDs(ids, nil), len(ids))
})
}
}
type gatewayModelsRouteRepoStub struct {
service.CompositeModelRouteRepository
routes []service.CompositeModelRoute
@@ -0,0 +1,384 @@
//go:build unit
package handler
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type stickyWritebackContextKey struct{}
type stickyWritebackCall struct {
err error
groupID int64
account int64
session string
ttl time.Duration
value any
deadline time.Time
replaceable []int64
}
type stickyWritebackCache struct {
service.GatewayCache
accountID int64
// readErr is returned by the first lookup only, then cleared: the binding
// lookup at request start fails while later reads see the key again.
readErr error
finished bool
calls []stickyWritebackCall
lookups []int64
}
func (s *stickyWritebackCache) GetSessionAccountID(context.Context, int64, string) (int64, error) {
s.lookups = append(s.lookups, s.accountID)
if s.readErr != nil {
err := s.readErr
s.readErr = nil
return 0, err
}
return s.accountID, nil
}
func (s *stickyWritebackCache) record(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration, replaceable []int64) {
deadline, _ := ctx.Deadline()
s.calls = append(s.calls, stickyWritebackCall{
err: ctx.Err(), groupID: groupID, account: account, session: session, ttl: ttl,
value: ctx.Value(stickyWritebackContextKey{}), deadline: deadline,
replaceable: append([]int64(nil), replaceable...),
})
}
func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID int64, session string, account int64, ttl time.Duration) error {
if s.finished {
s.record(ctx, groupID, session, account, ttl, nil)
}
if err := ctx.Err(); err != nil {
return err
}
s.accountID = account
return nil
}
// CompareAndBindSessionAccountID mirrors the Redis compare-and-bind script: a
// key already holding the account only gets its TTL refreshed, a missing key or
// one holding an account this request failed over from is overwritten, anything
// else was rebound by another request and is left alone.
func (s *stickyWritebackCache) CompareAndBindSessionAccountID(ctx context.Context, groupID int64, session string, account int64, replaceable []int64, ttl time.Duration) (bool, error) {
if err := ctx.Err(); err != nil {
return false, err
}
if s.accountID == account {
if s.finished {
s.record(ctx, groupID, session, account, ttl, replaceable)
}
return true, nil
}
if s.accountID == 0 || slices.Contains(replaceable, s.accountID) {
if s.finished {
s.record(ctx, groupID, session, account, ttl, replaceable)
}
s.accountID = account
return true, nil
}
return false, nil
}
func (s *stickyWritebackCache) RefreshSessionTTL(context.Context, int64, string, time.Duration) error {
return nil
}
func (s *stickyWritebackCache) DeleteSessionAccountID(context.Context, int64, string) error {
s.accountID = 0
return nil
}
type stickyWritebackBody struct {
io.Reader
finish func()
}
func (b *stickyWritebackBody) Close() error {
b.finish()
return nil
}
// stickyWritebackUpstream answers per account with a freshly built response, so
// a failover row can fail on the first account and serve on the second.
type stickyWritebackUpstream struct {
service.HTTPUpstream
responses map[int64]func() *http.Response
seen []int64
}
func (u *stickyWritebackUpstream) DoWithTLS(_ *http.Request, _ string, accountID int64, _ int, _ *tlsfingerprint.Profile) (*http.Response, error) {
u.seen = append(u.seen, accountID)
build, ok := u.responses[accountID]
if !ok {
return nil, fmt.Errorf("no upstream response for account %d", accountID)
}
return build(), nil
}
func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, stream := range []bool{false, true} {
name := "buffered"
if stream {
name = "streaming"
}
for _, tt := range []struct {
name string
bound int64
cancel bool
fail bool
// failover makes account 9401 fail with a 500 and account 9499 serve,
// mirroring a request that switches accounts mid-flight.
failover bool
// profitGate installs the group profit gate, which makes the request
// write the admitted account eagerly and skip a different binding.
profitGate bool
// readErr fails the binding lookup at request start.
readErr bool
during func(*stickyWritebackCache)
// rebindOnServe runs during on the serving forward instead of the
// failing one.
rebindOnServe bool
wantSeen []int64
// wantWrites counts the terminal writes; reads and admission-time
// writes made before the forward are not counted.
wantWrites int
wantFinal int64
checkFinal bool
wantSecondLookup int64
}{
{name: "new binding", wantWrites: 1},
{name: "new binding after disconnect", cancel: true, wantWrites: 1},
{name: "refresh binding", bound: 9401, wantWrites: 1},
{name: "refresh after disconnect", bound: 9401, cancel: true, wantWrites: 1},
{name: "different binding", bound: 9499, cancel: true},
{name: "forward failed", cancel: true, fail: true},
{
name: "rebound during forward", bound: 9401, checkFinal: true, wantFinal: 9499, wantSecondLookup: 9499,
during: func(c *stickyWritebackCache) { c.accountID = 9499 },
},
{
name: "bound by another request during forward", checkFinal: true, wantFinal: 9499, wantSecondLookup: 9499,
during: func(c *stickyWritebackCache) { c.accountID = 9499 },
},
{
name: "deleted during forward", bound: 9401, wantWrites: 1, checkFinal: true, wantFinal: 9401,
during: func(c *stickyWritebackCache) { c.accountID = 0 },
},
{
name: "rebound away and back during forward", bound: 9401, wantWrites: 1, checkFinal: true, wantFinal: 9401,
during: func(c *stickyWritebackCache) { c.accountID = 9499; c.accountID = 9401 },
},
{
// K1: the key starts missing, the request writes the admitted
// account A, A fails over to B. The key must end on B instead of
// keeping the account that just failed.
name: "profit gate missing binding failover", failover: true, profitGate: true,
wantSeen: []int64{9401, 9499}, wantWrites: 1, checkFinal: true, wantFinal: 9499, wantSecondLookup: 9499,
},
{
name: "profit gate failed start lookup failover", failover: true, profitGate: true, readErr: true,
wantSeen: []int64{9401, 9499}, wantWrites: 1, checkFinal: true, wantFinal: 9499, wantSecondLookup: 9499,
},
{
name: "profit gate bound to the failed account", bound: 9401, failover: true, profitGate: true,
wantSeen: []int64{9401, 9499}, wantWrites: 0, checkFinal: true, wantFinal: 9401, wantSecondLookup: 9401,
},
{
// Another request rebinds to a third account while the failover
// already serves B: the third account was never tried here, so the
// terminal write leaves it alone and writes nothing.
name: "profit gate rebound by another request during failover", failover: true, profitGate: true, rebindOnServe: true,
wantSeen: []int64{9401, 9499}, checkFinal: true, wantFinal: 9455,
during: func(c *stickyWritebackCache) { c.accountID = 9455 },
},
{
// Without a profit gate the scheduler binds before every forward,
// so a failed account found in the key was bound by another request
// and is kept.
name: "rebound to the failed account during failover", failover: true, rebindOnServe: true,
wantSeen: []int64{9401, 9499}, checkFinal: true, wantFinal: 9401,
during: func(c *stickyWritebackCache) { c.accountID = 9401 },
},
} {
t.Run(name+"/"+tt.name, func(t *testing.T) {
groupID := int64(9400)
group := &service.Group{
ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive,
RateMultiplier: 1, SubscriptionType: service.SubscriptionTypeStandard,
ProfitControlEnabled: tt.profitGate, ProfitMinMargin: 0.5,
}
newAccount := func(id int64, priority int, schedulable bool) *service.Account {
rate := 0.1
return &service.Account{
ID: id, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: schedulable, Concurrency: 1, Priority: priority,
RateMultiplier: &rate,
Credentials: map[string]any{"api_key": "test-key"},
Extra: map[string]any{"anthropic_passthrough": true},
AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}},
}
}
account := newAccount(9401, 0, true)
other := newAccount(9499, 1, tt.failover)
// third is only bound by the other request; it only has to resolve
// as a known account.
third := newAccount(9455, 2, true)
servedID := account.ID
if tt.failover {
servedID = other.ID
}
wantCalls := 1
if tt.failover {
wantCalls = 2
}
cache := &stickyWritebackCache{accountID: tt.bound}
if tt.readErr {
cache.readErr = fmt.Errorf("sticky cache read failed")
}
ctx := context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value")
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
t.Cleanup(cancel)
responseBody := `{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`
contentType := "application/json"
if stream {
responseBody = compatStreamUsagePartialStream + compatStreamUsageCompletion
contentType = "text/event-stream"
}
status := http.StatusOK
if tt.fail {
status = http.StatusBadRequest
responseBody = `{"type":"error","error":{"type":"invalid_request_error","message":"invalid input"}}`
}
duringRan := false
runDuring := func() {
if duringRan || tt.during == nil {
return
}
duringRan = true
tt.during(cache)
}
finish := func() {
// Forward closes its upstream body on return. Bound the concurrent
// rebind and cancel precisely after that work, before the handler's
// terminal sticky write.
cache.finished = true
runDuring()
if tt.cancel {
cancel()
}
}
respond := func(status int, contentType, body string, bodyFinish func()) func() *http.Response {
return func() *http.Response {
return &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": []string{contentType}},
Body: &stickyWritebackBody{Reader: strings.NewReader(body), finish: bodyFinish},
}
}
}
responses := map[int64]func() *http.Response{}
if tt.failover {
// By default the failing attempt's body closes before the next
// account is selected, so a rebind there sits inside the
// failover; rebindOnServe moves it into the serving forward.
failingFinish := runDuring
if tt.rebindOnServe {
failingFinish = func() {}
}
responses[account.ID] = respond(http.StatusInternalServerError, "application/json", `{"type":"error","error":{"type":"api_error","message":"upstream boom"}}`, failingFinish)
responses[other.ID] = respond(status, contentType, responseBody, finish)
} else {
responses[account.ID] = respond(status, contentType, responseBody, finish)
}
upstream := &stickyWritebackUpstream{responses: responses}
cfg := &config.Config{RunMode: config.RunModeSimple}
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, other, third}}, nil, nil, nil, nil)
gw := service.NewGatewayService(
nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, cache, cfg,
snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
h := &GatewayHandler{
gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
}
requestBody := `{"model":"claude-sonnet-4.5","max_tokens":16,"stream":false,"messages":[{"role":"user","content":"sticky writeback test"}]}`
if stream {
requestBody = strings.Replace(requestBody, `"stream":false`, `"stream":true`, 1)
}
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)).WithContext(ctx)
c.Request.Header.Set("Content-Type", "application/json")
key := &service.APIKey{ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, User: &service.User{ID: 9403, Balance: 100}}
c.Set(string(middleware.ContextKeyAPIKey), key)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
h.Messages(c)
require.Equal(t, wantCalls, len(upstream.seen))
if tt.wantSeen != nil {
require.Equal(t, tt.wantSeen, upstream.seen)
} else {
require.Equal(t, servedID, upstream.seen[len(upstream.seen)-1])
}
require.True(t, cache.finished)
require.Equal(t, status, rec.Code)
if tt.cancel {
require.ErrorIs(t, ctx.Err(), context.Canceled)
}
require.Len(t, cache.calls, tt.wantWrites)
for _, call := range cache.calls {
require.NoError(t, call.err, "a completed upstream request must retain its terminal sticky write")
require.Equal(t, groupID, call.groupID)
require.Equal(t, servedID, call.account)
require.NotEmpty(t, call.session)
require.Positive(t, call.ttl)
require.Equal(t, "request-scoped value", call.value)
require.False(t, call.deadline.IsZero(), "the detached cache write must have a deadline")
require.WithinDuration(t, time.Now(), call.deadline, 5*time.Second)
}
if tt.checkFinal {
require.Equal(t, tt.wantFinal, cache.accountID, "the terminal write must only cover values this request may have written")
}
if tt.wantSecondLookup != 0 {
nextLookup := len(cache.lookups)
rec2 := httptest.NewRecorder()
c2, _ := gin.CreateTestContext(rec2)
c2.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(requestBody)).WithContext(context.WithValue(context.Background(), stickyWritebackContextKey{}, "request-scoped value"))
c2.Request.Header.Set("Content-Type", "application/json")
c2.Set(string(middleware.ContextKeyAPIKey), key)
c2.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
h.Messages(c2)
require.Equal(t, status, rec2.Code)
require.Equal(t, tt.wantSecondLookup, cache.lookups[nextLookup], "a later request must observe the terminal binding")
}
})
}
}
}
@@ -275,6 +275,7 @@ func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) {
Result: &service.ForwardResult{
Model: modelName, UpstreamModel: mappedModel,
Usage: service.ClaudeUsage{InputTokens: int(tokens)}, CacheStorageTokenHours: storageTokenHours,
UpstreamPriceMultiplier: service.VertexUpstreamPriceMultiplier(account, mappedModel, ""),
},
APIKey: apiKey, User: apiKey.User, Subscription: subscription, PricingAt: pricingAt, ChannelUsageFields: usageFields,
})
@@ -674,15 +675,17 @@ func (h *GatewayHandler) submitGeminiCachedContentUsage(
if inputTokens <= 0 && storageTokenHours <= 0 {
return
}
priceMultiplier := service.VertexUpstreamPriceMultiplier(account, upstreamModel, "")
if upstreamModel == model {
upstreamModel = ""
}
result := &service.ForwardResult{
RequestID: requestID,
Model: model,
UpstreamModel: upstreamModel,
Usage: service.ClaudeUsage{InputTokens: inputTokens},
CacheStorageTokenHours: storageTokenHours,
RequestID: requestID,
Model: model,
UpstreamModel: upstreamModel,
Usage: service.ClaudeUsage{InputTokens: inputTokens},
CacheStorageTokenHours: storageTokenHours,
UpstreamPriceMultiplier: priceMultiplier,
}
inboundEndpoint := GetInboundEndpoint(c)
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
@@ -13,7 +13,6 @@ import (
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/domain"
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
"github.com/Wei-Shaw/sub2api/internal/pkg/gemini"
"github.com/Wei-Shaw/sub2api/internal/pkg/googleapi"
@@ -468,16 +467,8 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
sessionHash = extractGeminiCLISessionHash(c, body)
}
if sessionHash == "" && cachedContentBinding == nil {
// Fallback: 使用通用的会话哈希生成逻辑(适用于其他客户端)
parsedReq, _ := service.ParseGatewayRequest(service.NewRequestBodyRef(body), domain.PlatformGemini)
if parsedReq != nil {
parsedReq.SessionContext = &service.SessionContext{
ClientIP: ip.GetClientIP(c),
UserAgent: c.GetHeader("User-Agent"),
APIKeyID: apiKey.ID,
}
}
sessionHash = h.gatewayService.GenerateSessionHash(parsedReq)
// 其他客户端:按 API Key + 模型 + tools + systemInstruction + 第一条 user contents 的 parts 生成内容哈希
sessionHash = service.GenerateGeminiContentSessionHash(apiKey.ID, reqModel, body)
}
sessionKey := sessionHash
if sessionHash != "" {
+5
View File
@@ -400,6 +400,11 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
service.SetOpsLatencyMs(c, service.OpsResponseLatencyMsKey, responseLatencyMs)
if err != nil {
var validationErr *service.GrokMediaInputValidationError
if errors.As(err, &validationErr) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", validationErr.Error())
return
}
var failoverErr *service.UpstreamFailoverError
if errors.As(err, &failoverErr) {
if failoverClientGone(c) {
@@ -0,0 +1,255 @@
//go:build unit
package handler
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/iotest"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestGrokImageEditLocalValidationSyncAndAsync(t *testing.T) {
enableGrokMediaValidationTestScheduler(t)
for _, oauth := range []bool{false, true} {
for _, async := range []bool{false, true} {
for _, format := range []string{"json", "multipart"} {
for _, count := range []int{3, 4, 5, 6} {
t.Run(fmt.Sprintf("oauth=%t/async=%t/%s/%d", oauth, async, format, count), func(t *testing.T) {
h, slots, _, upstream := newGrokMediaSlotHandler(t, oauth, false)
h.grokMediaEligibilityProber = grokMediaSlotProber(func(context.Context, int64) (bool, string, error) {
return true, "eligible", nil
})
upstream.call = func(req *http.Request, _ int64) (*http.Response, error) {
assert.Equal(t, "/v1/images/edits", req.URL.Path)
body, err := io.ReadAll(req.Body)
assert.NoError(t, err)
assert.Len(t, gjson.GetBytes(body, "images").Array(), count)
assert.NotEmpty(t, gjson.GetBytes(body, "mask.url").String())
return &http.Response{StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"code":"invalid_image","error":"upstream image rejection"}`))}, nil
}
body, contentType := grokImageEditLimitBody(t, format, count)
c, recorder := grokMediaSlotContext(context.Background(), true)
path := "/v1/images/edits"
if async {
path += "/async"
}
c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
c.Request.Header.Set("Content-Type", contentType)
responseBody := []byte(nil)
if async {
store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute)
asyncHandler := NewAsyncImageHandler(tasks, h)
asyncHandler.Submit(c)
require.Equal(t, http.StatusAccepted, recorder.Code, recorder.Body.String())
taskID := gjson.GetBytes(recorder.Body.Bytes(), "task_id").String()
owner := service.ImageTaskOwner{UserID: 10, APIKeyID: 20}
require.Eventually(t, func() bool {
task, err := tasks.Get(context.Background(), owner, taskID)
return err == nil && task.Status != service.ImageTaskStatusProcessing
}, time.Second, 10*time.Millisecond)
poll, pollRecorder := grokMediaSlotContext(context.Background(), false)
poll.Params[0].Key, poll.Params[0].Value = "task_id", taskID
asyncHandler.Get(poll)
require.Equal(t, http.StatusOK, pollRecorder.Code)
responseBody = pollRecorder.Body.Bytes()
require.Equal(t, service.ImageTaskStatusFailed, gjson.GetBytes(responseBody, "status").String())
require.Equal(t, int64(http.StatusBadRequest), gjson.GetBytes(responseBody, "http_status").Int())
} else {
h.GrokImages(c)
require.Equal(t, http.StatusBadRequest, recorder.Code, recorder.Body.String())
responseBody = recorder.Body.Bytes()
}
require.Equal(t, "invalid_request_error", gjson.GetBytes(responseBody, "error.type").String())
metrics := h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics()
if count > 5 {
require.Equal(t, "a maximum of 5 source images is supported for image edits", gjson.GetBytes(responseBody, "error.message").String())
require.Zero(t, upstream.calls)
require.Zero(t, metrics.RuntimeStatsAccountCount, "local rejection must report neither success nor failure")
} else {
require.Equal(t, "upstream image rejection", gjson.GetBytes(responseBody, "error.message").String())
require.Equal(t, 1, upstream.calls)
require.Equal(t, 1, metrics.RuntimeStatsAccountCount, "real upstream failures still report failure")
}
require.Zero(t, metrics.AccountSwitchTotal)
slots.assertReleased(t)
})
}
}
}
}
}
func grokImageEditLimitBody(t *testing.T, format string, count int) ([]byte, string) {
t.Helper()
if format == "json" {
images := make([]string, count)
for index := range images {
images[index] = fmt.Sprintf("https://example.test/%d.png", index)
}
body, err := json.Marshal(map[string]any{"model": "grok-imagine-image-2.0", "prompt": "test", "images": images, "mask": "https://example.test/mask.png"})
require.NoError(t, err)
return body, "application/json"
}
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
require.NoError(t, writer.WriteField("model", "grok-imagine-image-2.0"))
require.NoError(t, writer.WriteField("prompt", "test"))
for index := 0; index < count; index++ {
if index%2 == 0 {
require.NoError(t, writer.WriteField("image", fmt.Sprintf("https://example.test/%d.png", index)))
} else {
part, err := writer.CreateFormFile("image[]", fmt.Sprintf("%d.png", index))
require.NoError(t, err)
_, err = part.Write([]byte("\x89PNG\r\n\x1a\nsynthetic"))
require.NoError(t, err)
}
}
part, err := writer.CreateFormFile("mask", "mask.png")
require.NoError(t, err)
_, err = part.Write([]byte("\x89PNG\r\n\x1a\nmask"))
require.NoError(t, err)
require.NoError(t, writer.Close())
return buffer.Bytes(), writer.FormDataContentType()
}
func TestGrokImageEditInternalAndRetryableErrorsRemainUpstreamErrors(t *testing.T) {
enableGrokMediaValidationTestScheduler(t)
for _, retryable := range []bool{false, true} {
t.Run(fmt.Sprintf("retryable=%t", retryable), func(t *testing.T) {
h, slots, _, upstream := newGrokMediaSlotHandler(t, false, false)
upstream.call = func(*http.Request, int64) (*http.Response, error) {
if !retryable {
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(iotest.ErrReader(errors.New("internal response read failure")))}, nil
}
return &http.Response{StatusCode: http.StatusServiceUnavailable, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"error":"temporarily unavailable"}`))}, nil
}
c, recorder := grokMediaSlotContext(context.Background(), true)
body, contentType := grokImageEditLimitBody(t, "json", 3)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", bytes.NewReader(body))
c.Request.Header.Set("Content-Type", contentType)
h.GrokImages(c)
require.GreaterOrEqual(t, recorder.Code, http.StatusInternalServerError, recorder.Body.String())
require.NotEqual(t, "invalid_request_error", gjson.GetBytes(recorder.Body.Bytes(), "error.type").String())
metrics := h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics()
require.Positive(t, metrics.RuntimeStatsAccountCount, "calls=%d response=%s", upstream.calls, recorder.Body.String())
if retryable {
require.Greater(t, upstream.calls, 1)
require.Positive(t, metrics.AccountSwitchTotal)
} else {
require.Equal(t, http.StatusBadGateway, recorder.Code)
require.Equal(t, 1, upstream.calls)
require.Zero(t, metrics.AccountSwitchTotal)
}
slots.assertReleased(t)
})
}
}
type grokMediaValidationSettingsRepo struct {
service.SettingRepository
}
func (grokMediaSlotRepo) SetTempUnschedulable(context.Context, int64, time.Time, string) error {
return nil
}
func (*grokMediaValidationSettingsRepo) SetMultiple(context.Context, map[string]string) error {
return nil
}
func enableGrokMediaValidationTestScheduler(t *testing.T) {
t.Helper()
settings := service.NewSettingService(&grokMediaValidationSettingsRepo{}, nil)
require.NoError(t, settings.UpdateSettings(context.Background(), &service.SystemSettings{OpenAIAdvancedSchedulerEnabled: true}))
t.Cleanup(func() {
require.NoError(t, settings.UpdateSettings(context.Background(), &service.SystemSettings{}))
})
}
func TestGrokImagesPreservesUpstreamErrorOnSyncAndAsyncRoutes(t *testing.T) {
for _, oauth := range []bool{false, true} {
accountType := "api-key"
if oauth {
accountType = "oauth"
}
for _, async := range []bool{false, true} {
route := "sync"
if async {
route = "async"
}
t.Run(accountType+"/"+route, func(t *testing.T) {
h, slots, _, upstream := newGrokMediaSlotHandler(t, oauth, false)
h.grokMediaEligibilityProber = grokMediaSlotProber(func(context.Context, int64) (bool, string, error) {
return true, "test account is eligible", nil
})
upstream.call = func(req *http.Request, _ int64) (*http.Response, error) {
assert.Equal(t, "/v1/images/edits", req.URL.Path)
return &http.Response{
StatusCode: http.StatusBadRequest,
Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"code":"invalid_image","error":"Image could not be decoded: https://example.test/image?access_token=secret&size=1","debug":"private upstream diagnostic"}`)),
}, nil
}
c, recorder := grokMediaSlotContext(context.Background(), true)
path := "/v1/images/edits"
if async {
path += "/async"
}
c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"grok-imagine-image","prompt":"test","image":{"url":"https://example.test/input.png"}}`))
c.Request.Header.Set("Content-Type", "application/json")
var responseBody []byte
if async {
store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute)
asyncHandler := NewAsyncImageHandler(tasks, h)
asyncHandler.Submit(c)
require.Equal(t, http.StatusAccepted, recorder.Code, recorder.Body.String())
taskID := gjson.GetBytes(recorder.Body.Bytes(), "task_id").String()
owner := service.ImageTaskOwner{UserID: 10, APIKeyID: 20}
require.Eventually(t, func() bool {
task, err := tasks.Get(context.Background(), owner, taskID)
return err == nil && task.Status != service.ImageTaskStatusProcessing
}, time.Second, 10*time.Millisecond)
poll, pollRecorder := grokMediaSlotContext(context.Background(), false)
poll.Params[0].Key, poll.Params[0].Value = "task_id", taskID
asyncHandler.Get(poll)
require.Equal(t, http.StatusOK, pollRecorder.Code)
responseBody = pollRecorder.Body.Bytes()
require.Equal(t, service.ImageTaskStatusFailed, gjson.GetBytes(responseBody, "status").String())
require.Equal(t, int64(http.StatusBadRequest), gjson.GetBytes(responseBody, "http_status").Int())
} else {
h.GrokImages(c)
require.Equal(t, http.StatusBadRequest, recorder.Code, recorder.Body.String())
responseBody = recorder.Body.Bytes()
}
require.Equal(t, "Image could not be decoded: https://example.test/image?access_token=***&size=1", gjson.GetBytes(responseBody, "error.message").String())
require.Equal(t, "invalid_image", gjson.GetBytes(responseBody, "error.code").String())
require.Equal(t, "invalid_request_error", gjson.GetBytes(responseBody, "error.type").String())
require.NotContains(t, string(responseBody), "secret")
require.NotContains(t, string(responseBody), "private upstream diagnostic")
require.Equal(t, 1, upstream.calls, "deterministic image errors must not retry another account")
slots.assertReleased(t)
})
}
}
}
@@ -0,0 +1,63 @@
//go:build unit
package handler
import (
"math/rand"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestCodexCallOutputGateSkipsDeclaredToolsWithoutCandidate(t *testing.T) {
body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"},{"type":"function","name":"create_thread"}],` +
`"input":[{"type":"function_call","call_id":"c1","name":"shell"},{"type":"function_call_output","call_id":"c1","output":"ok"}]}`)
require.False(t, mayContainCodexCallOutputCandidate(body, "automation_update"))
require.False(t, mayContainCodexCallOutputCandidate(body, "create_thread", "send_message_to_thread"))
for name, normalize := range map[string]func([]byte) ([]byte, bool){
"untrusted": normalizeCodexUntrustedContext,
"automation": normalizeCodexAutomationBootstrap,
"delegation": normalizeCodexDelegationBootstrap,
} {
t.Run(name, func(t *testing.T) {
allocs := testing.AllocsPerRun(10, func() {
got, changed := normalize(body)
if changed || &got[0] != &body[0] {
t.Fatal("non-candidate body must be returned unchanged")
}
})
require.Zero(t, allocs)
})
}
}
// Whenever the ungated bootstrap path rewrites a body, the gate must admit it.
func TestCodexCallOutputGateAdmitsEveryRewrite(t *testing.T) {
u := func(hex string) string { return `\` + "u" + hex }
output := mustJSON(t, codexAutomationBootstrap("wiki", "never", automationBootstrapPrompt))
items := []string{
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`,
`{"type":"function_call_output","namespace":"codex_app","name":"` + u("0061") + `utomation_update","output":` + output + `}`,
`{"` + u("0074") + `ype":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + output + `}`,
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","name":"other","output":` + output + `}`,
`{"type":"function_call_output","call_id":"c","output":"ok"}`,
`{"type":"message","role":"user","content":"automation_update function_call_output caf` + u("00e9") + `"}`,
`{"type":"function_call","call_id":"c","name":"automation_update"}`,
}
rng := rand.New(rand.NewSource(11))
rewrites := 0
for i := 0; i < 3000; i++ {
var parts []string
for n := rng.Intn(3); n >= 0; n-- {
parts = append(parts, items[rng.Intn(len(items))])
}
body := []byte(`{"model":"gpt-5","tools":[{"type":"function","name":"automation_update"}],"input":[` + strings.Join(parts, ",") + `]}`)
_, rewritten := normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false)
if rewritten {
rewrites++
require.True(t, mayContainCodexCallOutputCandidate(body, "automation_update"), "%s", body)
}
}
require.Positive(t, rewrites)
}
@@ -364,7 +364,7 @@ func NewOpenAIGatewayHandler(
opsService *service.OpsService,
cfg *config.Config,
) *OpenAIGatewayHandler {
pingInterval := time.Duration(0)
pingInterval := defaultPingInterval
maxAccountSwitches := 3
if cfg != nil {
pingInterval = time.Duration(cfg.Concurrency.PingInterval) * time.Second
@@ -489,9 +489,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
} else if changed {
body = cappedBody
}
if normalizedBody, changed := normalizeCodexPageContext(body); changed {
if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed {
body = normalizedBody
reqLog.Info("openai.codex_page_context_normalized",
reqLog.Info("openai.codex_untrusted_context_normalized",
zap.String("normalization", "call_output_to_user_message"),
)
}
@@ -1250,7 +1250,6 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
return
}
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body)
routingModel := service.NormalizeOpenAICompatRequestedModel(reqModel)
preferredMappedModel := resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel)
reqStream := gjson.GetBytes(body, "stream").Bool()
@@ -1267,6 +1266,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
// 解析渠道级模型映射
channelMappingMsg, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody)
// Schedule by the channel-mapped model, as the Responses and Chat Completions
// paths do: the forwarded body carries that model, so account model filters
// must judge it rather than the client's alias.
routingModel := service.NormalizeOpenAICompatRequestedModel(openAIChannelForwardModel(channelMappingMsg, reqModel))
// 绑定错误透传服务,允许 service 层在非 failover 错误场景复用规则。
if h.errorPassthroughService != nil {
@@ -1413,7 +1416,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
defaultMappedModel := strings.TrimSpace(effectiveMappedModel)
// 应用渠道模型映射到请求体
forwardBody := mappedBodyForMessages(channelMappingMsg.Mapped, channelMappingMsg.MappedModel)
writerSizeBeforeForward := c.Writer.Size()
writerSizeBeforeForward := service.OpenAICompactKeepaliveAdjustedWrittenSize(c)
result, err := func() (*service.OpenAIForwardResult, error) {
defer func() {
if accountReleaseFunc != nil {
@@ -1501,11 +1504,16 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
)
return
}
if c.Writer.Size() != writerSizeBeforeForward {
if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) {
h.gatewayService.ObserveOpenAIAccountHealthFailure(c.Request.Context(), account, err)
h.handleAnthropicFailoverExhausted(c, failoverErr, true)
return
}
// Only keepalive bytes were written, so failover may continue, but
// every later error must be written as an SSE event.
if c.Writer.Written() {
streamStarted = true
}
if failoverErr.ShouldReportAccountScheduleFailure() {
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, currentRoutingModel, false, nil), false, nil, err)
}
@@ -1663,16 +1671,24 @@ func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context,
h.anthropicStreamingAwareError(c, status, "api_error", failoverErr.ClientMessage, streamStarted)
return
}
// A failed or error frame that triggered the failover no longer reaches the
// client in-band, so its error passthrough rule is applied here instead.
if status, errType, msg, ok := service.ApplyOpenAIStreamFailedFrameRule(c, failoverErr); ok {
h.anthropicStreamingAwareError(c, status, errType, msg, streamStarted)
return
}
status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode)
h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted)
}
// ensureAnthropicErrorResponse writes a fallback Anthropic error if no response was written.
func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, streamStarted bool) bool {
if c == nil || c.Writer == nil || c.Writer.Written() {
// Keepalive pings alone do not count as a written response, but they do
// commit the response as SSE, so the fallback must then be an SSE event.
if c == nil || c.Writer == nil || service.OpenAICompactKeepaliveAdjustedWrittenSize(c) >= 0 {
return false
}
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted)
h.anthropicStreamingAwareError(c, http.StatusBadGateway, "api_error", "Upstream request failed", streamStarted || c.Writer.Written())
return true
}
@@ -1729,11 +1745,23 @@ func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) {
// mayContainCodexCallOutputCandidate is a necessary condition for a bootstrap
// candidate, checked before the full uniqueness scan and decode. Its type and
// tool name are JSON strings, which appear literally unless a \u escape spells
// their letters; without either, normalization cannot change the body.
// their letters; without either, normalization cannot change the body. Escapes
// that real clients emit (control characters, HTML-safe and non-ASCII runes)
// cannot spell those letters and must not force the full decode.
//
// Tool declarations carry the same names, so a literal hit is confirmed by a
// zero-copy scan for an input item of type function_call_output whose name
// starts with one of toolNames. The full path rejects bodies with duplicate
// members, and without duplicates the scan reads the same values as the
// decoder.
func mayContainCodexCallOutputCandidate(body []byte, toolNames ...string) bool {
if bytes.Contains(body, []byte(`\u`)) {
return true
if !service.JSONMayEscapePlainASCII(body) && !containsCodexCallOutputLiterals(body, toolNames) {
return false
}
return service.ResponsesInputHasFunctionCallOutputNamed(body, toolNames...)
}
func containsCodexCallOutputLiterals(body []byte, toolNames []string) bool {
if !bytes.Contains(body, []byte("function_call_output")) {
return false
}
@@ -2582,12 +2610,23 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 必须在合成路由解析和上游模型映射之前执行。
// 与 HTTP 准入一致:帧内重复 model 键/大小写变体可能被上游按末值绑定,
// 全部候选值逐一校验,任一未命中即拒绝。
if blocked := blockedModelAllowlistCandidate(apiKey.Group, requestmodel.FromBodyCandidates("", "application/json", firstMessage)); blocked != "" {
firstModelCandidates := requestmodel.FromBodyCandidates("", "application/json", firstMessage)
if blocked := blockedModelAllowlistCandidate(apiKey.Group, firstModelCandidates); blocked != "" {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed)
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for this group", blocked))
return
}
// 帧内重复字段(model、service_tier、reasoning.effort 等,含大小写变体与
// 嵌套对象)会让计费/策略读到的首个值与上游实际绑定的值分叉;取值相同也不
// 放行,因为网关的 sjson 改写只动首个(GHSA-p3r4-jcm3-2hph)。与 HTTP 入口
// (RejectConflictingRequestFields)同一规则,对所有分组生效。放在白名单
// 之后,白名单的拒绝原因保持不变。
if field, conflict := requestmodel.ConflictingField("application/json", firstMessage); conflict {
middleware2.MarkIngressRejected(c, middleware2.IngressRejectConflictingRequestFields)
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, fmt.Sprintf("response.create payload declares field %.64q more than once", field))
return
}
// Keep the client model in the frame for admission, response identity and usage.
// Apply the resolved upstream model through MapRequestModel on every turn.
wsRouteModel := reqModel
@@ -3059,12 +3098,19 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 则关闭整条连接,与推理强度 deny 一致。实际生效模型始终参与校验;
// 帧内重复 model 键/大小写变体/嵌套 session.model 额外逐一校验,
// 防止候选集非空时掩盖被轮换掉的禁用模型。
candidates := append([]string{model}, requestmodel.FromBodyCandidates("", "application/json", payload)...)
frameModelCandidates := requestmodel.FromBodyCandidates("", "application/json", payload)
candidates := append([]string{model}, frameModelCandidates...)
if blocked := blockedModelAllowlistCandidate(apiKey.Group, candidates); blocked != "" {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed)
return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for this group", blocked), nil)
}
// 后续 turn 同首帧:帧内有重复字段即关闭连接,避免计费/策略读到的
// 值与上游实际绑定的值分叉。
if field, conflict := requestmodel.ConflictingField("application/json", payload); conflict {
middleware2.MarkIngressRejected(c, middleware2.IngressRejectConflictingRequestFields)
return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("websocket request payload declares field %.64q more than once", field), nil)
}
if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, model, payload, "subsequent_turn"); decision != nil && !decision.AllowNextStage {
writeSecurityAuditWSError(ctx, wsConn, decision)
return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), nil)
@@ -1959,6 +1959,8 @@ type openAIResponsesWSUsageLogCase struct {
firstFrameCloseExpected bool
// secondTurnCloseExpected:第二个 turn 被拒(连接被 1008 关闭)。
secondTurnCloseExpected bool
// midFrameCloseExpected:midPayload 被拒(连接被 1008 关闭),帧不到达上游。
midFrameCloseExpected bool
}
type openAIResponsesWSUsageLogResult struct {
@@ -3236,6 +3238,19 @@ func runOpenAIResponsesWebSocketUsageLogCase(t *testing.T, tc openAIResponsesWSU
err = clientConn.Write(writeCtx, coderws.MessageText, []byte(tc.midPayload))
cancelWrite()
require.NoError(t, err)
if tc.midFrameCloseExpected {
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
_, _, readErr := clientConn.Read(readCtx)
cancelRead()
require.Error(t, readErr, "mid frame should have been rejected with a close")
var closeErr coderws.CloseError
require.ErrorAs(t, readErr, &closeErr)
require.Equal(t, coderws.StatusPolicyViolation, closeErr.Code)
require.Contains(t, closeErr.Reason, tc.closeReason)
require.Len(t, upstreamPayloadCh, 1, "rejected mid frame must not reach upstream")
_ = clientConn.CloseNow()
return openAIResponsesWSUsageLogResult{}
}
readCompleted()
}
if strings.TrimSpace(tc.secondPayload) != "" && (turnCount >= 2) {
@@ -0,0 +1,336 @@
//go:build unit
package handler
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/model"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"go.uber.org/zap"
)
const (
preContentHandlerCreated = `data: {"type":"response.created","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"in_progress","output":[]}}` + "\n\n"
preContentHandlerFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"An error occurred while processing your request."}}}` + "\n\n"
preContentHandlerSuccess = preContentHandlerCreated +
`data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1","type":"message","role":"assistant","content":[]}}` + "\n\n" +
`data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"answer from second account"}` + "\n\n" +
`data: {"type":"response.completed","response":{"id":"resp_pc","object":"response","model":"gpt-5.4","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":4,"total_tokens":7}}}` + "\n\n"
)
// preContentFailoverUpstream hands each upstream request to respond, which
// gets the 1-based call number.
type preContentFailoverUpstream struct {
service.HTTPUpstream
mu sync.Mutex
hits []int64
respond func(call int) (*http.Response, error)
}
func (u *preContentFailoverUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
if req.Body != nil {
_, _ = io.Copy(io.Discard, req.Body)
}
u.mu.Lock()
u.hits = append(u.hits, accountID)
call := len(u.hits)
u.mu.Unlock()
return u.respond(call)
}
func (u *preContentFailoverUpstream) calls() int {
u.mu.Lock()
defer u.mu.Unlock()
return len(u.hits)
}
func preContentSSEResponse(body io.ReadCloser) *http.Response {
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: body}
}
// preContentStallThenFail stalls past one keepalive tick after the first event
// and then fails with failed.
func preContentStallThenFail(failed string) *http.Response {
pr, pw := io.Pipe()
go func() {
_, _ = io.WriteString(pw, preContentHandlerCreated)
time.Sleep(1300 * time.Millisecond)
_, _ = io.WriteString(pw, failed)
_ = pw.Close()
}()
return preContentSSEResponse(pr)
}
type unexpectedEOFReader struct{}
func (unexpectedEOFReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
type preContentFailoverScenario struct {
accounts []service.Account
respond func(call int) (*http.Response, error)
passthrough *service.ErrorPassthroughService
requestBody string
}
func preContentAccounts(count int) []service.Account {
accounts := make([]service.Account, 0, count)
for i := 0; i < count; i++ {
accounts = append(accounts, service.Account{
ID: int64(9201 + i), Name: "openai-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: i + 1,
Credentials: map[string]any{"api_key": "sk-test", "base_url": "http://upstream.example"},
})
}
return accounts
}
func servePreContentFailoverMessages(t *testing.T, accountCount int) (*httptest.ResponseRecorder, *preContentFailoverUpstream) {
t.Helper()
return serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(accountCount),
respond: func(call int) (*http.Response, error) {
if call == 1 {
return preContentStallThenFail(preContentHandlerFailed), nil
}
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerSuccess))), nil
},
})
}
func serveMessagesScenario(t *testing.T, sc preContentFailoverScenario) (*httptest.ResponseRecorder, *preContentFailoverUpstream) {
t.Helper()
gin.SetMode(gin.TestMode)
groupID := int64(9101)
repo := &grokCredentialHandlerRepo{accounts: sc.accounts, missingOnGet: map[int64]bool{}}
upstream := &preContentFailoverUpstream{respond: sc.respond}
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Gateway.MaxAccountSwitches = 3
cfg.Gateway.StreamKeepaliveInterval = 1
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCache.Stop)
gateway := service.NewOpenAIGatewayService(
repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
service.NewBillingService(cfg, nil), nil, billingCache, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
}
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, sc.passthrough, nil, nil, cfg)
apiKey := &service.APIKey{
ID: 9102, GroupID: &groupID,
User: &service.User{ID: 9103, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, AllowMessagesDispatch: true},
}
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
service.BindErrorPassthroughService(c, sc.passthrough)
c.Next()
})
router.POST("/v1/messages", h.Messages)
rec := httptest.NewRecorder()
requestBody := sc.requestBody
if requestBody == "" {
requestBody = `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":true}`
}
req := httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewBufferString(requestBody))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
return rec, upstream
}
// requireEndsWithSSEError checks that a response already committed as SSE ends
// with an Anthropic error event and never carries a bare JSON line.
func requireEndsWithSSEError(t *testing.T, body string) {
t.Helper()
lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:]
require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent)
require.Contains(t, lastEvent, `"type":"error"`)
for _, line := range strings.Split(body, "\n") {
require.False(t, strings.HasPrefix(line, "{"), "bare JSON line in SSE body: %q", line)
}
}
func TestOpenAIMessagesFailsOverAfterKeepaliveOnlyWrite(t *testing.T) {
rec, upstream := servePreContentFailoverMessages(t, 2)
body := rec.Body.String()
require.Equal(t, 2, upstream.calls(), "body: %q", body)
require.Equal(t, 1, strings.Count(body, "event: message_start"), "body: %q", body)
require.Contains(t, body, "answer from second account")
}
func TestOpenAIMessagesKeepaliveThenFailoverExhaustedEndsWithSSEError(t *testing.T) {
rec, upstream := servePreContentFailoverMessages(t, 1)
body := rec.Body.String()
require.Equal(t, 1, upstream.calls(), "body: %q", body)
require.Contains(t, body, "event: ping")
requireEndsWithSSEError(t, body)
}
func TestOpenAIMessagesFailoverThenSecondAccountReadErrorEndsWithSSEError(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(2),
respond: func(call int) (*http.Response, error) {
if call == 1 {
return preContentStallThenFail(preContentHandlerFailed), nil
}
return preContentSSEResponse(io.NopCloser(unexpectedEOFReader{})), nil
},
})
body := rec.Body.String()
require.Equal(t, 2, upstream.calls(), "body: %q", body)
require.NotContains(t, body, "message_start")
requireEndsWithSSEError(t, body)
}
func TestOpenAIMessagesFailoverThenSecondAccountCredentialErrorEndsWithSSEError(t *testing.T) {
accounts := preContentAccounts(2)
accounts[1].Credentials = map[string]any{"base_url": "http://upstream.example"}
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: accounts,
respond: func(call int) (*http.Response, error) {
return preContentStallThenFail(preContentHandlerFailed), nil
},
})
body := rec.Body.String()
require.Equal(t, 1, upstream.calls(), "body: %q", body)
require.NotContains(t, body, "message_start")
requireEndsWithSSEError(t, body)
}
func TestOpenAIMessagesSlotAcquireFailureAfterKeepaliveIsSSE(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
c.Header("Content-Type", "text/event-stream")
_, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n")
require.NoError(t, err)
streamStarted := true
h := &OpenAIGatewayHandler{}
selection := &service.AccountSelectionResult{Account: &service.Account{ID: 9201}}
_, result := h.acquireResponsesAccountSlot(c, nil, "", selection, true, &streamStarted, zap.NewNop())
require.Equal(t, openAISlotAcquireFailed, result)
body := rec.Body.String()
lastEvent := body[strings.LastIndex(strings.TrimRight(body, "\n"), "\n\n")+2:]
require.True(t, strings.HasPrefix(lastEvent, "event: error\ndata: {"), "last event: %q", lastEvent)
}
func newFailedFrameCodeRule(code string) *service.ErrorPassthroughService {
status := http.StatusTeapot
rule := &model.ErrorPassthroughRule{
ID: 1, Name: "frame code rule", Enabled: true, Priority: 1,
Keywords: []string{code}, MatchMode: model.MatchModeAny,
Platforms: []string{model.PlatformOpenAI}, ResponseCode: &status, PassthroughBody: true,
}
return service.NewErrorPassthroughService(&errorPassthroughRepoStub{rules: []*model.ErrorPassthroughRule{rule}}, nil)
}
// A failed frame that triggers a failover is no longer written in-band, so its
// passthrough rule has to apply once the failover is exhausted. The rule is
// keyed on the frame's own code, which the generic failover envelope lacks.
func TestOpenAIMessagesFailoverExhaustedAppliesFailedFrameRule(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(1),
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
respond: func(call int) (*http.Response, error) {
failed := `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n"
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + failed))), nil
},
})
body := rec.Body.String()
t.Logf("status=%d body=%q", rec.Code, body)
require.Equal(t, 1, upstream.calls(), "body: %q", body)
require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body)
require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body)
require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body)
}
const preContentRateLimitFailed = `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}}` + "\n\n"
func requireFailedFrameRuleJSON(t *testing.T, rec *httptest.ResponseRecorder) {
t.Helper()
body := rec.Body.String()
t.Logf("status=%d content-type=%q body=%q", rec.Code, rec.Header().Get("Content-Type"), body)
require.Equal(t, http.StatusTeapot, rec.Code, "body: %q", body)
require.Contains(t, rec.Header().Get("Content-Type"), "application/json")
require.Equal(t, "upstream_error", gjson.Get(body, "error.type").String(), "body: %q", body)
require.Equal(t, "Rate limit reached for gpt-5.4", gjson.Get(body, "error.message").String(), "body: %q", body)
}
// The failed frame is the first event of the stream, so it triggers the
// failover before any output and used to reach the generic mapping unchecked.
func TestOpenAIMessagesFirstEventFailedFrameExhaustedAppliesRule(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(1),
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
respond: func(call int) (*http.Response, error) {
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentRateLimitFailed))), nil
},
})
require.Equal(t, 1, upstream.calls())
requireFailedFrameRuleJSON(t, rec)
}
func TestOpenAIMessagesNonStreamFailedFrameExhaustedAppliesRule(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(1),
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
requestBody: `{"model":"gpt-5.4","max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`,
respond: func(call int) (*http.Response, error) {
return preContentSSEResponse(io.NopCloser(strings.NewReader(preContentHandlerCreated + preContentRateLimitFailed))), nil
},
})
require.Equal(t, 1, upstream.calls())
requireFailedFrameRuleJSON(t, rec)
}
// A failover triggered by an HTTP status keeps the built-in exhaustion mapping:
// no passthrough rule is looked up for it.
func TestOpenAIMessagesHTTPStatusFailoverExhaustedIgnoresPassthroughRule(t *testing.T) {
rec, upstream := serveMessagesScenario(t, preContentFailoverScenario{
accounts: preContentAccounts(1),
passthrough: newFailedFrameCodeRule("rate_limit_exceeded"),
respond: func(call int) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusBadGateway,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.4"}}`)),
}, nil
},
})
body := rec.Body.String()
t.Logf("status=%d body=%q", rec.Code, body)
require.Equal(t, 1, upstream.calls(), "body: %q", body)
require.NotEqual(t, http.StatusTeapot, rec.Code, "body: %q", body)
require.Equal(t, "Upstream service temporarily unavailable", gjson.Get(body, "error.message").String(), "body: %q", body)
}
@@ -127,6 +127,8 @@ func TestOpenAIResponsesWebSocket_FirstFrameCaseVariantModelKeyRejected(t *testi
// 后续 turn 含重复 model 键(首个在白名单、末个不在):拒绝并关闭连接。
func TestOpenAIResponsesWebSocket_SubsequentTurnDuplicateModelKeysRejected(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
// 两种模式都在读取任何字段之前先做字段歧义检查(帧必须在兼容归一化等
// 重编码之前拦截),所以由歧义检查而不是白名单关闭连接,帧不到达上游。
t.Run(mode, func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
@@ -134,21 +136,21 @@ func TestOpenAIResponsesWebSocket_SubsequentTurnDuplicateModelKeysRejected(t *te
group: wsAllowlistGroup(true, "gpt-5.4"),
ingressMode: mode,
secondTurnCloseExpected: true,
closeReason: `declares field "model" more than once`,
})
})
}
}
// 重复但同值的 model 键不误伤,连接正常完成两个 turn。
func TestOpenAIResponsesWebSocket_DuplicateIdenticalModelKeysAllowed(t *testing.T) {
got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`,
secondPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(true, "gpt-5.4"),
// 重复但同值的 model 键:白名单本身放行(两个候选都在名单内),但字段歧义检查
// 拒绝——网关的 sjson 模型改写只改首个,改写后两者就会分叉(GHSA-p3r4-jcm3-2hph)。
func TestOpenAIResponsesWebSocket_DuplicateIdenticalModelKeysRejected(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(true, "gpt-5.4"),
firstFrameCloseExpected: true,
closeReason: `declares field "model" more than once`,
})
if len(got.clientEvents) != 2 {
t.Fatalf("expected two completed events, got %d", len(got.clientEvents))
}
}
// session.update 轮换绕过:首帧用白名单内模型建立会话,session.update 把会话
@@ -0,0 +1,128 @@
package handler
import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
)
const wsModelConflictCloseReason = "more than once"
// 没有开启白名单的分组:首帧里重复 model 键取值不一致(计费按第一个、上游可能
// 按最后一个绑定)必须以 1008 关闭,帧不到达上游。
func TestOpenAIResponsesWebSocket_FirstFrameConflictingModelKeysRejectedWithoutAllowlist(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
t.Run(mode, func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
firstFrameCloseExpected: true,
closeReason: wsModelConflictCloseReason,
})
})
}
}
// 大小写变体键同样会被 encoding/json 绑定到同一个字段。
func TestOpenAIResponsesWebSocket_FirstFrameConflictingCaseVariantModelKeyRejected(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","Model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: service.OpenAIWSIngressModePassthrough,
firstFrameCloseExpected: true,
closeReason: wsModelConflictCloseReason,
})
}
// 白名单开启且两个模型都在名单内:白名单放行,模型歧义检查仍要拒绝。
func TestOpenAIResponsesWebSocket_FirstFrameConflictingAllowlistedModelKeysRejected(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(true, "gpt-5.4-nano", "gpt-5.4"),
ingressMode: service.OpenAIWSIngressModePassthrough,
firstFrameCloseExpected: true,
closeReason: wsModelConflictCloseReason,
})
}
// 后续 turn 的帧同样检查。
func TestOpenAIResponsesWebSocket_SubsequentTurnConflictingModelKeysRejectedWithoutAllowlist(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
t.Run(mode, func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
secondPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
secondTurnCloseExpected: true,
closeReason: wsModelConflictCloseReason,
})
})
}
}
// 取值相同的重复键同样拒绝:网关的 sjson 改写(模型映射、推理强度降级)只改
// 首个,改写后两者就会分叉。首帧与后续 turn 都要关闭连接。
func TestOpenAIResponsesWebSocket_IdenticalDuplicateKeysRejectedWithoutAllowlist(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
t.Run(mode+"/first_frame", func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
firstFrameCloseExpected: true,
closeReason: `declares field "model" more than once`,
})
})
t.Run(mode+"/subsequent_turn", func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
secondPayload: `{"type":"response.create","model":"gpt-5.4","reasoning":{"effort":"xhigh","effort":"xhigh"},"stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
secondTurnCloseExpected: true,
closeReason: `declares field "reasoning.effort" more than once`,
})
})
}
}
// 非 model 字段同样参与计费与策略:首帧 service_tier、后续 turn 嵌套的
// reasoning.effort 取值不一致都必须关闭连接。
func TestOpenAIResponsesWebSocket_ConflictingBillingFieldsRejected(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
t.Run(mode+"/first_frame_service_tier", func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","service_tier":"flex","stream":false,"service_tier":"priority"}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
firstFrameCloseExpected: true,
closeReason: `declares field "service_tier" more than once`,
})
})
t.Run(mode+"/subsequent_turn_reasoning_effort", func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
secondPayload: `{"type":"response.create","model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
secondTurnCloseExpected: true,
closeReason: `declares field "reasoning.effort" more than once`,
})
})
}
}
// passthrough 原样转发 session.update 等非 response.create 事件:帧内重复字段
// 同样必须关闭连接,不能到达上游。
func TestOpenAIResponsesWebSocket_PassthroughSessionUpdateDuplicateRejected(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
midPayload: `{"type":"session.update","session":{"model":"gpt-5.4","model":"gpt-4.1"}}`,
group: wsAllowlistGroup(false),
ingressMode: service.OpenAIWSIngressModePassthrough,
midFrameCloseExpected: true,
closeReason: `declares field "session.model" more than once`,
})
}
@@ -0,0 +1,143 @@
//go:build unit
package handler
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/iotest"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
type nativeEndpointUpstream struct {
service.HTTPUpstream
mode string
paths []string
}
func (u *nativeEndpointUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
u.paths = append(u.paths, req.URL.Path)
if u.mode == "transport error" {
return nil, errors.New("synthetic upstream transport failure")
}
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}}
switch u.mode {
case "HTTP error":
response.StatusCode = http.StatusBadRequest
response.Body = io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"synthetic rejection"}}`))
case "body read error":
response.Body = io.NopCloser(iotest.ErrReader(errors.New("synthetic body read failure")))
default:
if gjson.GetBytes(body, "stream").Bool() {
response.Header.Set("Content-Type", "text/event-stream")
response.Body = io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion))
} else {
response.Body = io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"k3","content":[{"type":"text","text":"partial"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`))
}
}
return response, nil
}
func (u *nativeEndpointUpstream) DoWithTLS(req *http.Request, proxy string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
return u.Do(req, proxy, accountID, concurrency)
}
func TestOpenAINativeAnthropicEndpointDiagnostics(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, route := range []struct {
name string
path string
protocol string
platform string
}{
{"messages", "/v1/messages", service.APIProtocolAnthropic, service.PlatformKimi},
{"chat", "/v1/chat/completions", service.APIProtocolAnthropic, service.PlatformKimi},
{"responses", "/v1/responses", service.APIProtocolAnthropic, service.PlatformKimi},
{"adaptive messages", "/v1/messages", service.APIProtocolAdaptive, service.PlatformZhipu},
} {
for _, stream := range []bool{false, true} {
for _, mode := range []string{"transport error", "HTTP error", "body read error", "success"} {
t.Run(fmt.Sprintf("%s/stream=%t/%s", route.name, stream, mode), func(t *testing.T) {
upstream := &nativeEndpointUpstream{mode: mode}
cfg := &config.Config{Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{AllowInsecureHTTP: true}}}
gateway := service.NewOpenAIGatewayService(
nil, nil, nil, nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil, upstream,
nil, nil, nil, nil, nil, nil, nil, nil,
)
account := &service.Account{
ID: 9501, Platform: route.platform, Type: service.AccountTypeAPIKey,
Credentials: map[string]any{
"api_key": "test-key", "api_protocol": route.protocol,
"base_url": "http://anthropic.example",
"api_base_urls": map[string]any{
service.APIProtocolAnthropic: "http://anthropic.example",
service.APIProtocolChatCompletions: "http://chat.example",
},
},
}
model := "k3"
if route.protocol == service.APIProtocolAdaptive {
require.False(t, account.SupportsNativeCNResponses())
model = "glm-5.3"
}
request := map[string]any{"model": model, "stream": stream}
if route.path == "/v1/responses" {
request["input"] = "hello"
} else {
request["messages"] = []map[string]string{{"role": "user", "content": "hello"}}
request["max_tokens"] = 32
}
body, err := json.Marshal(request)
require.NoError(t, err)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, route.path, strings.NewReader(string(body)))
// The same Gin context can retain an earlier attempt's protocol.
service.SetActualOpenAIUpstreamEndpoint(c, EndpointChatCompletions)
var result *service.OpenAIForwardResult
switch route.path {
case "/v1/messages":
result, err = gateway.ForwardAsAnthropic(context.Background(), c, account, body, "", "")
case "/v1/chat/completions":
result, err = gateway.ForwardAsChatCompletions(context.Background(), c, account, body, "", "")
default:
result, err = gateway.Forward(context.Background(), c, account, body)
}
if mode == "success" {
require.NoError(t, err)
require.NotNil(t, result)
require.Equal(t, EndpointMessages, result.UpstreamEndpoint)
require.Contains(t, recorder.Body.String(), "partial")
} else {
require.Error(t, err)
if mode != "body read error" {
require.Nil(t, result, "error diagnostics must work without a forward result")
}
}
require.Len(t, upstream.paths, 1)
require.True(t, strings.HasSuffix(upstream.paths[0], EndpointMessages), "the request actually used native Anthropic: %v", upstream.paths)
// This is the endpoint reader used when writing operations errors and result-less usage.
require.Equal(t, EndpointMessages, GetUpstreamEndpoint(c, account.Platform))
require.Equal(t, EndpointMessages, service.GetActualOpenAIUpstreamEndpoint(c))
})
}
}
}
}
@@ -11,10 +11,13 @@ import (
var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`)
// Desktop injects page snapshots as standalone outputs, without a model tool call.
// Keep them as untrusted user text, including on history replay and mixed bootstrap turns.
func normalizeCodexPageContext(body []byte) ([]byte, bool) {
if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_") || !hasUniqueJSONMembers(body) {
// Codex injects external context as standalone outputs, without a model tool call.
// Use the legacy user-message representation for HTTP Responses interoperability.
func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
if !mayContainCodexCallOutputCandidate(body,
"codex_apps_open_page", "codex_apps_selected_page_part_",
"browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan",
) || !hasUniqueJSONMembers(body) {
return body, false
}
var request map[string]json.RawMessage
@@ -45,16 +48,21 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) {
continue
}
}
name, output := readString("name"), readString("output")
if !validCodexPageContext(name, output) {
name := readString("name")
var output *string
if json.Unmarshal(item["output"], &output) != nil || output == nil || !validCodexUntrustedContext(name, *output) {
continue
}
text := "<external_" + name + ">" + *output + "</external_" + name + ">"
if validCodexPageContext(name, *output) {
text = "<external_" + name + ">\n" + *output + "\n</external_" + name + ">"
}
message := map[string]any{
"type": "message",
"role": "user",
"content": []map[string]string{{
"type": "input_text",
"text": "<external_" + name + ">\n" + output + "\n</external_" + name + ">",
"text": text,
}},
}
encoded, err := json.Marshal(message)
@@ -79,6 +87,21 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) {
return encoded, true
}
func validCodexUntrustedContext(name, output string) bool {
switch name {
case "browser_info", "terminal_info", "goal_objective", "untrusted_context", "ide_context":
return strings.TrimSpace(output) != ""
case "untrusted_content":
// Codex's fallback for an unnamed context source can carry any text, including an empty value.
return true
case "proposed_plan":
// Codex splits an approved plan by byte length, so a chunk can be all whitespace.
return output != ""
default:
return validCodexPageContext(name, output)
}
}
func validCodexPageContext(name, output string) bool {
if name == "codex_apps_open_page" {
return validCodexPageSnapshot(output)
@@ -34,7 +34,7 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
require.Equal(t, 400, w.Code)
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
@@ -49,14 +49,254 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
require.False(t, item.Get("id").Exists())
}
require.Equal(t, "hello", gjson.GetBytes(got, "input.2.content").String())
again, changed := normalizeCodexPageContext(got)
again, changed := normalizeCodexUntrustedContext(got)
require.False(t, changed)
require.Equal(t, got, again)
}
var codexTextContextNamesForTest = []string{"browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"}
func TestNormalizeCodexTerminalInfoIssue8991(t *testing.T) {
body := []byte(`{"model":"deepseek-flash","input":[{"type":"function_call_output","namespace":"agent","name":"terminal_info","output":"retest context"}]}`)
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
require.Equal(t, 400, w.Code)
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.JSONEq(t, `{"model":"deepseek-flash","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"<external_terminal_info>retest context</external_terminal_info>"}]}]}`, string(got))
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.False(t, c.Writer.Written())
}
func TestNormalizeCodexTerminalInfoBoundaries(t *testing.T) {
for _, testCase := range []struct {
name string
key string
value any
}{
{"call id with surrounding whitespace", "call_id", " call_real "},
{"boolean call id", "call_id", false},
{"array call id", "call_id", []any{}},
{"object call id", "call_id", map[string]any{}},
{"namespace whitespace", "namespace", " agent "},
{"namespace case", "namespace", "Agent"},
{"boolean output", "output", false},
{"numeric output", "output", 42},
{"object output", "output", map[string]any{"text": "context"}},
{"name prefix", "name", "terminal_info_extra"},
{"name case", "name", "Terminal_info"},
{"unknown context", "name", "arbitrary_context"},
{"other type", "type", "custom_tool_call_output"},
} {
t.Run(testCase.name, func(t *testing.T) {
item := pageContextItem("terminal_info", "retest context")
item[testCase.key] = testCase.value
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
})
}
for _, body := range []string{
`{"input":[{"type":"function_call_output","namespace":"other","namespace":"agent","name":"terminal_info","output":"context"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"read_file","name":"terminal_info","output":"context"}]}`,
`{"input":[],"input":[{"type":"function_call_output","namespace":"agent","name":"terminal_info","output":"context"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"terminal_info","output":"context"}]} trailing`,
} {
got, changed := normalizeCodexUntrustedContext([]byte(body))
require.False(t, changed)
require.Equal(t, body, string(got))
}
}
func TestNormalizeCodexTerminalInfoEscapedName(t *testing.T) {
body := []byte(`{"input":[{"type":"function_call_output","namespace":"agent","name":"terminal_\u0069nfo","output":" context\n\t"}]}`)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "<external_terminal_info> context\n\t</external_terminal_info>", gjson.GetBytes(got, "input.0.content.0.text").String())
}
func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) {
body := pageContextRequest(t,
pageContextItem("terminal_info", "retest context"),
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info", "call_id": "call_real", "output": "real result"},
pageContextItem("read_file", "unrelated result"))
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String())
for _, path := range []string{"input.1", "input.2"} {
require.JSONEq(t, gjson.GetBytes(body, path).Raw, gjson.GetBytes(got, path).Raw)
}
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.Equal(t, 400, w.Code)
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
}
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
for _, name := range codexTextContextNamesForTest {
t.Run(name, func(t *testing.T) {
output := "external context\nline two"
if name == "ide_context" {
output = "# Context from my IDE setup:\n\n## Active file: main.go\n\n## Active selection of the file:\nfunc main() {}"
}
contextItem := map[string]any{"type": "function_call_output", "namespace": "agent", "name": name, "output": output}
body := pageContextRequest(t, contextItem,
map[string]any{"role": "user", "content": "continue"})
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
require.Equal(t, 400, w.Code)
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.False(t, c.Writer.Written())
item := gjson.GetBytes(got, "input.0")
require.Equal(t, "message", item.Get("type").String())
require.Equal(t, "user", item.Get("role").String())
require.Equal(t, "<external_"+name+">"+output+"</external_"+name+">", item.Get("content.0.text").String())
require.False(t, item.Get("call_id").Exists())
require.Equal(t, "continue", gjson.GetBytes(got, "input.1.content").String())
again, changed := normalizeCodexUntrustedContext(got)
require.False(t, changed)
require.Equal(t, got, again)
})
}
}
func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) {
for _, name := range codexTextContextNamesForTest {
for _, override := range []map[string]any{
{"call_id": "call_real"},
{"call_id": nil},
{"call_id": 42},
{"namespace": "other"},
{"namespace": nil},
{"namespace": 42},
{"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}},
{"output": nil},
} {
item := pageContextItem(name, "context")
for key, value := range override {
item[key] = value
}
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed, "name=%s override=%v", name, override)
require.Equal(t, body, got)
}
for _, field := range []string{"namespace", "output"} {
item := pageContextItem(name, "context")
delete(item, field)
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
}
}
// Recognized external context cannot make an unrelated tool result valid.
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
pageContextItem("read_file", "result"))
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.Equal(t, 400, w.Code)
// Keep historical calls, prior response and exact numeric metadata intact.
body = []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"goal_objective","output":"finish"}]}`)
got, changed = normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
for _, index := range []string{"input.0", "input.1"} {
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
}
}
func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) {
names := codexTextContextNamesForTest
for _, callID := range []string{"", " \t\n"} {
items := make([]any, 0, len(names))
for _, name := range names {
item := pageContextItem(name, "context for "+name)
item["call_id"] = callID
delete(item, "id")
items = append(items, item)
}
got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...))
require.True(t, changed)
require.Len(t, gjson.GetBytes(got, "input").Array(), len(names))
for i, item := range gjson.GetBytes(got, "input").Array() {
require.Equal(t, "user", item.Get("role").String())
require.Equal(t, "<external_"+names[i]+">context for "+names[i]+"</external_"+names[i]+">", item.Get("content.0.text").String())
}
}
}
func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) {
for _, name := range codexTextContextNamesForTest {
for _, body := range []string{
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`,
} {
got, changed := normalizeCodexUntrustedContext([]byte(body))
require.False(t, changed)
require.Equal(t, body, string(got))
}
}
}
func TestNormalizeCodexProposedPlanChunks(t *testing.T) {
chunks := []string{"# Plan\n", " \n\t", "1. Run tests."}
var items []any
for _, chunk := range chunks {
items = append(items, pageContextItem("proposed_plan", chunk))
}
got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...))
require.True(t, changed)
messages := gjson.GetBytes(got, "input").Array()
require.Len(t, messages, len(chunks))
for i, message := range messages {
require.Equal(t, "user", message.Get("role").String())
require.Equal(t, "<external_proposed_plan>"+chunks[i]+"</external_proposed_plan>", message.Get("content.0.text").String())
}
}
func TestNormalizeCodexAdditionalUntrustedContextBlankOutput(t *testing.T) {
for _, name := range codexTextContextNamesForTest {
for _, output := range []string{"", " \t"} {
body := pageContextRequest(t, pageContextItem(name, output))
got, changed := normalizeCodexUntrustedContext(body)
wantChange := name == "untrusted_content" || (name == "proposed_plan" && output != "")
require.Equal(t, wantChange, changed, "name=%s output=%q", name, output)
if wantChange {
require.Equal(t, "<external_"+name+">"+output+"</external_"+name+">", gjson.GetBytes(got, "input.0.content.0.text").String())
} else {
require.Equal(t, body, got)
}
}
}
}
func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) {
body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`)
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
@@ -66,7 +306,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T
badTool := pageContextItem("read_file", "result")
body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool)
got, changed = normalizeCodexPageContext(body)
got, changed = normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.True(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutputMissingCallID)
}
@@ -77,7 +317,7 @@ func TestNormalizeCodexPageContextMixedBootstrap(t *testing.T) {
{"type": "function_call_output", "namespace": "codex_app", "name": "automation_update", "output": "<heartbeat><automation_id>test</automation_id></heartbeat>"},
} {
body := pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), item)
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
got, _ = normalizeCodexAutomationBootstrap(got)
got, _ = normalizeCodexDelegationBootstrap(got)
@@ -89,7 +329,7 @@ func TestNormalizeCodexPageContextMultipart(t *testing.T) {
first := "Companion Page snapshot part 1 of 2:\n" + `{"page_id":"page1","document_view":"hello`
second := "Companion Page snapshot part 2 of 2:\n" + ` world"}`
body := pageContextRequest(t, pageContextItem("codex_apps_selected_page_part_1_of_2", first), pageContextItem("codex_apps_selected_page_part_2_of_2", second))
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Contains(t, gjson.GetBytes(got, "input.0.content.0.text").String(), first)
require.Contains(t, gjson.GetBytes(got, "input.1.content.0.text").String(), second)
@@ -119,7 +359,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
item := pageContextItem("codex_apps_open_page", `{"page_id":null}`)
item[tc.key] = tc.value
body := pageContextRequest(t, item)
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
})
@@ -128,7 +368,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","call_id":"real","call_id":"","output":"{\"page_id\":null}"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":null}"}]} trailing`,
} {
got, changed := normalizeCodexPageContext([]byte(body))
got, changed := normalizeCodexUntrustedContext([]byte(body))
require.False(t, changed)
require.Equal(t, body, string(got))
}
@@ -0,0 +1,165 @@
//go:build unit
package handler
// /v1/responses 透传账号的下游心跳换号回归。
//
// 透传流式路径(handleStreamingResponsePassthrough)在每次尝试进入流式循环时
// 都会新建一个 SSE 心跳器。第一次尝试真实写出心跳后遇到可换号的 event: error,
// 第二个账号立即以同样的错误失败,第三个账号成功:前一次尝试写出的心跳字节
// 不能被当成语义输出,否则第二次尝试会放弃换号,把错误直接写给客户端。
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
const openAIPassthroughKeepaliveSuccessSSE = "event: response.created\n" +
`data: {"type":"response.created","response":{"id":"resp_passthrough_ok","status":"in_progress","output":[]}}` + "\n\n" +
"event: response.completed\n" +
`data: {"type":"response.completed","response":{"id":"resp_passthrough_ok","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n"
const openAIPassthroughKeepaliveOverloadedSSE = "event: error\n" +
`data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded","status":529}}` + "\n\n"
type openAIPassthroughKeepaliveUpstream struct {
service.HTTPUpstream
mu sync.Mutex
calls []int64
responses []*http.Response
}
func (u *openAIPassthroughKeepaliveUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
u.mu.Lock()
defer u.mu.Unlock()
u.calls = append(u.calls, accountID)
if len(u.responses) == 0 {
return nil, io.ErrUnexpectedEOF
}
resp := u.responses[0]
u.responses = u.responses[1:]
return resp, nil
}
func (u *openAIPassthroughKeepaliveUpstream) callIDs() []int64 {
u.mu.Lock()
defer u.mu.Unlock()
return append([]int64(nil), u.calls...)
}
// openAIPassthroughKeepaliveWriter 在第一拍心跳写出时通知测试,测试据此
// 推进上游,不依赖 sleep 时序。
type openAIPassthroughKeepaliveWriter struct {
gin.ResponseWriter
once sync.Once
notify chan struct{}
}
func (w *openAIPassthroughKeepaliveWriter) Write(p []byte) (int, error) {
n, err := w.ResponseWriter.Write(p)
if bytes.Contains(p, []byte(": keepalive\n\n")) {
w.once.Do(func() { close(w.notify) })
}
return n, err
}
func newOpenAIPassthroughKeepaliveHandler(t *testing.T, upstream service.HTTPUpstream) *OpenAIGatewayHandler {
t.Helper()
newAccount := func(id int64, priority int) service.Account {
return service.Account{
ID: id, Name: "passthrough-keepalive", Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true,
Concurrency: 1, Priority: priority,
Credentials: map[string]any{"access_token": "test-token"},
Extra: map[string]any{"openai_passthrough": true},
}
}
accounts := []service.Account{newAccount(1, 0), newAccount(2, 1), newAccount(3, 2)}
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Gateway.StreamKeepaliveInterval = 1
gatewayService := service.NewOpenAIGatewayService(
openAIImagesFailoverAccountRepo{accounts: accounts}, nil, nil, nil, nil, nil, nil, cfg,
nil, nil, nil, nil, nil, upstream, nil, nil, nil, nil, nil, nil, nil, nil,
)
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
h := NewOpenAIGatewayHandler(
gatewayService,
service.NewConcurrencyService(nil),
billing,
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg),
nil, nil, nil, nil, cfg,
)
h.maxAccountSwitches = 2
return h
}
func newOpenAIPassthroughKeepaliveContext(t *testing.T) (*gin.Context, *httptest.ResponseRecorder, *openAIPassthroughKeepaliveWriter) {
t.Helper()
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
body := []byte(`{"model":"gpt-5.1","stream":true,"input":"hello"}`)
c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
groupID := int64(3135)
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
ID: 99, GroupID: &groupID,
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI},
User: &service.User{ID: 100},
})
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 100})
writer := &openAIPassthroughKeepaliveWriter{ResponseWriter: c.Writer, notify: make(chan struct{})}
c.Writer = writer
return c, rec, writer
}
func TestOpenAIGatewayHandlerResponsesPassthroughKeepaliveFailoverAcrossAttempts(t *testing.T) {
firstBody, firstWriter := io.Pipe()
sseHeader := func() http.Header { return http.Header{"Content-Type": []string{"text/event-stream"}} }
upstream := &openAIPassthroughKeepaliveUpstream{responses: []*http.Response{
{StatusCode: http.StatusOK, Header: sseHeader(), Body: firstBody},
{StatusCode: http.StatusOK, Header: sseHeader(), Body: io.NopCloser(strings.NewReader(openAIPassthroughKeepaliveOverloadedSSE))},
{StatusCode: http.StatusOK, Header: sseHeader(), Body: io.NopCloser(strings.NewReader(openAIPassthroughKeepaliveSuccessSSE))},
}}
h := newOpenAIPassthroughKeepaliveHandler(t, upstream)
c, rec, writer := newOpenAIPassthroughKeepaliveContext(t)
done := make(chan struct{})
go func() { h.Responses(c); close(done) }()
select {
case <-writer.notify:
case <-done:
t.Fatalf("handler 在第一拍心跳前返回: calls=%v body=%q", upstream.callIDs(), rec.Body.String())
case <-time.After(15 * time.Second):
t.Fatal("等待透传流第一拍心跳超时")
}
_, err := io.WriteString(firstWriter, openAIPassthroughKeepaliveOverloadedSSE)
require.NoError(t, err)
require.NoError(t, firstWriter.Close())
select {
case <-done:
case <-time.After(15 * time.Second):
t.Fatal("handler 未在后续尝试完成后返回")
}
body := rec.Body.String()
require.Equal(t, []int64{1, 2, 3}, upstream.callIDs(), "前一次尝试的心跳字节不得阻止第二次尝试换号: body=%q", body)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, body, ": keepalive\n\n", "第一次尝试必须真实写出心跳")
require.Equal(t, 1, strings.Count(body, "event: response.completed"), "成功流只允许一个 completed")
require.NotContains(t, body, "response.failed", "可换号的首输出前错误不得写给客户端")
require.NotContains(t, body, "Overloaded", "可换号的首输出前错误不得写给客户端")
}
@@ -1,7 +1,6 @@
package handler
import (
"fmt"
"net/http"
"github.com/Wei-Shaw/sub2api/internal/config"
@@ -26,18 +25,6 @@ func handleRequestBodyReadError(c *gin.Context, reqLog *zap.Logger, err error) b
return middleware2.RejectRequestBodyMemoryOverload(c, err)
}
func formatBodyLimit(limit int64) string {
const mb = 1024 * 1024
if limit >= mb {
return fmt.Sprintf("%dMB", limit/mb)
}
return fmt.Sprintf("%dB", limit)
}
func buildBodyTooLargeMessage(limit int64) string {
return fmt.Sprintf("Request body too large, limit is %s", formatBodyLimit(limit))
}
func readLenientJSONRequestBodyWithPrealloc(req *http.Request, cfg *config.Config) ([]byte, error) {
return pkghttputil.ReadLenientJSONRequestBodyWithPrealloc(req, gatewayMaxBodySize(cfg))
}
@@ -10,6 +10,7 @@ import (
"os"
"testing"
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
@@ -37,7 +38,7 @@ func TestRequestBodyLimitTooLarge(t *testing.T) {
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code)
require.Contains(t, recorder.Body.String(), buildBodyTooLargeMessage(limit))
require.Contains(t, recorder.Body.String(), pkghttputil.BodyTooLargeMessage(limit))
}
func TestHandleRequestBodyReadErrorCancellation(t *testing.T) {
@@ -16,11 +16,10 @@ import (
// logging request content.
func requestBodyReadFailure(reqLog *zap.Logger, req *http.Request, err error) (int, string) {
failure := pkghttputil.DescribeRequestBodyReadFailure(req, err)
if failure.Kind == pkghttputil.RequestBodyReadErrorMaxBytes {
return failure.Status, buildBodyTooLargeMessage(failure.MaxBytesLimit)
if failure.Kind != pkghttputil.RequestBodyReadErrorMaxBytes {
logRequestBodyReadFailure(reqLog, failure)
}
logRequestBodyReadFailure(reqLog, failure)
return failure.Status, failure.Message
return failure.Status, failure.ClientMessage()
}
func logRequestBodyReadFailure(reqLog *zap.Logger, failure pkghttputil.RequestBodyReadFailure) {
@@ -16,6 +16,7 @@ import (
"testing"
"testing/iotest"
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
@@ -47,7 +48,7 @@ func TestRequestBodyReadFailureKeepsBodyLimitMessageWithoutLogging(t *testing.T)
log, logs := newObservedLogger(t)
status, message := requestBodyReadFailure(log, nil, &http.MaxBytesError{Limit: 2 << 20})
require.Equal(t, http.StatusRequestEntityTooLarge, status)
require.Equal(t, buildBodyTooLargeMessage(2<<20), message)
require.Equal(t, pkghttputil.BodyTooLargeMessage(2<<20), message)
require.Empty(t, logs.All())
}
+42 -6
View File
@@ -50,6 +50,7 @@ type UsageHandler struct {
apiKeyService *service.APIKeyService
opsService *service.OpsService
settingService *service.SettingService
channelService *service.ChannelService
}
// NewUsageHandler creates a new UsageHandler
@@ -58,15 +59,51 @@ func NewUsageHandler(
apiKeyService *service.APIKeyService,
opsService *service.OpsService,
settingService *service.SettingService,
channelService *service.ChannelService,
) *UsageHandler {
return &UsageHandler{
usageService: usageService,
apiKeyService: apiKeyService,
opsService: opsService,
settingService: settingService,
channelService: channelService,
}
}
// userUsageLogs 将使用记录转换为普通用户 DTO。对于所属渠道开启了
// "向用户显示实际响应模型"的记录,额外填充 response_model。
// 渠道开关一次性从渠道内存缓存中批量读取,不产生额外数据库查询。
func (h *UsageHandler) userUsageLogs(c *gin.Context, records []service.UsageLog) []dto.UsageLog {
var exposed map[int64]bool
if h.channelService != nil && len(records) > 0 {
seen := make(map[int64]struct{}, 2)
ids := make([]int64, 0, 2)
for i := range records {
if records[i].ChannelID == nil {
continue
}
id := *records[i].ChannelID
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
ids = append(ids, id)
}
exposed = h.channelService.ResponseModelExposedChannels(c.Request.Context(), ids)
}
acceptLanguage := c.GetHeader("Accept-Language")
out := make([]dto.UsageLog, 0, len(records))
for i := range records {
item := dto.UsageLogFromService(&records[i]).Localized(acceptLanguage)
if records[i].ChannelID != nil && exposed[*records[i].ChannelID] {
item.ApplyResponseModel(&records[i])
}
out = append(out, *item)
}
return out
}
func (h *UsageHandler) parseUserUsageFilters(c *gin.Context, requireRange bool) (*userUsageFilters, bool) {
subject, ok := middleware2.GetAuthSubjectFromContext(c)
if !ok {
@@ -252,11 +289,7 @@ func (h *UsageHandler) List(c *gin.Context) {
return
}
out := make([]dto.UsageLog, 0, len(records))
for i := range records {
out = append(out, *dto.UsageLogFromService(&records[i]).Localized(c.GetHeader("Accept-Language")))
}
response.Paginated(c, out, result.Total, page, pageSize)
response.Paginated(c, h.userUsageLogs(c, records), result.Total, page, pageSize)
}
// ListErrors handles listing the current user's failed requests (redacted).
@@ -400,7 +433,7 @@ func (h *UsageHandler) GetByID(c *gin.Context) {
return
}
response.Success(c, dto.UsageLogFromService(record).Localized(c.GetHeader("Accept-Language")))
response.Success(c, &h.userUsageLogs(c, []service.UsageLog{*record})[0])
}
// Stats handles getting usage statistics
@@ -417,6 +450,9 @@ func (h *UsageHandler) Stats(c *gin.Context) {
return
}
stats.TotalAccountCost = nil
for i := range stats.Endpoints {
stats.Endpoints[i].AccountCost = 0
}
stats.UpstreamEndpoints = nil
stats.EndpointPaths = nil
@@ -64,7 +64,7 @@ func newDailyUsageTestRouter(usageRepo *dailyUsageRepoStub, apiKeyRepo *dailyUsa
gin.SetMode(gin.TestMode)
usageSvc := service.NewUsageService(usageRepo, nil, nil, nil)
apiKeySvc := service.NewAPIKeyService(apiKeyRepo, nil, nil, nil, nil, nil, nil)
handler := NewUsageHandler(usageSvc, apiKeySvc, nil, nil)
handler := NewUsageHandler(usageSvc, apiKeySvc, nil, nil, nil)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: userID})
@@ -81,7 +81,7 @@ func (s *userUsageRepoCapture) GetGroupStatsWithFilters(ctx context.Context, sta
func newUserUsageRequestTypeTestRouter(repo *userUsageRepoCapture) *gin.Engine {
gin.SetMode(gin.TestMode)
usageSvc := service.NewUsageService(repo, nil, nil, nil)
handler := NewUsageHandler(usageSvc, nil, nil, nil)
handler := NewUsageHandler(usageSvc, nil, nil, nil, nil)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 42})
@@ -27,7 +27,7 @@ func NewUserMsgQueueHelper(
pingFormat SSEPingFormat,
pingInterval time.Duration,
) *UserMsgQueueHelper {
if pingInterval <= 0 {
if pingInterval < 0 {
pingInterval = defaultPingInterval
}
return &UserMsgQueueHelper{
@@ -86,7 +86,7 @@ func (h *UserMsgQueueHelper) waitForLockWithPing(
streamStarted *bool,
reqLog *zap.Logger,
) (func(), error) {
needPing := isStream && h.pingFormat != ""
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
var flusher http.Flusher
if needPing {
@@ -196,7 +196,7 @@ func (h *UserMsgQueueHelper) ThrottleWithPing(
)
// 延迟期间发送 SSE ping(复用 waitForLockWithPing 的 ping 逻辑)
needPing := isStream && h.pingFormat != ""
needPing := isStream && h.pingFormat != "" && h.pingInterval > 0
var flusher http.Flusher
if needPing {
flusher, _ = c.Writer.(http.Flusher)
+13 -1
View File
@@ -348,7 +348,7 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
return nil, err
}
outRequestNo := fmt.Sprintf("%s%s%d", req.OrderID, alipayRefundRequestSep, time.Now().UnixNano())
outRequestNo := fmt.Sprintf("%s%s%s", req.OrderID, alipayRefundRequestSep, alipayRefundRequestNoSuffix(req.Amount))
result, err := alipayTradeRefund(ctx, client, alipay.TradeRefund{
OutTradeNo: req.OrderID,
RefundAmount: req.Amount,
@@ -374,6 +374,18 @@ func (a *Alipay) Refund(ctx context.Context, req payment.RefundRequest) (*paymen
}, nil
}
// alipayRefundRequestNoSuffix 生成跨重试稳定的 out_request_no 后缀。
// 支付宝把相同的 out_request_no 视为同一次退款请求;如果重试换号,
// "网关已受理但返回错误"后的重试会变成第二笔真实退款。
// 与 wxpayRefundID 一致,用金额区分同一订单的不同退款金额。
func alipayRefundRequestNoSuffix(amount string) string {
normalized := strings.NewReplacer(".", "", "-", "").Replace(strings.TrimSpace(amount))
if normalized == "" {
return "0"
}
return normalized
}
// QueryRefund 通过 alipay.trade.fastpay.refund.query 查询退款终态。refund_status 为 REFUND_SUCCESS
// 表示成功;退款发起超过宽限期仍查不到记录表示支付宝未受理或退款失败;其余情况视为仍在处理中。
func (a *Alipay) QueryRefund(ctx context.Context, req payment.RefundQueryRequest) (*payment.RefundResponse, error) {
@@ -480,6 +480,67 @@ func TestAlipayRefundRecordsOutRequestNoAsRefundID(t *testing.T) {
}
}
// out_request_no 必须跨重试稳定:支付宝把相同的 out_request_no 视为同一次退款请求。
// 如果重试生成新的请求号,一次"网关已受理但返回错误"的重试会退两次。
func TestAlipayRefundOutRequestNoIsStableAcrossRetries(t *testing.T) {
origRefund := alipayTradeRefund
t.Cleanup(func() { alipayTradeRefund = origRefund })
var outRequestNos []string
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
outRequestNos = append(outRequestNos, param.OutRequestNo)
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil
}
provider := &Alipay{client: &alipay.Client{}}
req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}
for i := 0; i < 2; i++ {
if _, err := provider.Refund(context.Background(), req); err != nil {
t.Fatalf("Refund() error = %v", err)
}
}
if len(outRequestNos) != 2 {
t.Fatalf("got %d refund calls, want 2", len(outRequestNos))
}
if outRequestNos[0] != "sub2_7-refund-1250" {
t.Fatalf("out_request_no = %q, want sub2_7-refund-1250", outRequestNos[0])
}
if outRequestNos[0] != outRequestNos[1] {
t.Fatalf("out_request_no changed across retries: %q != %q", outRequestNos[0], outRequestNos[1])
}
}
// 模拟支付宝的幂等语义:相同的 out_request_no 只产生一笔真实退款。
// 重试时如果请求号变了,钱会被退两次;稳定请求号下只退一次。
func TestAlipayRefundRetryDoesNotDoubleRefund(t *testing.T) {
origRefund := alipayTradeRefund
t.Cleanup(func() { alipayTradeRefund = origRefund })
const refundCents = 1250
refundedCents := 0
seen := make(map[string]struct{})
alipayTradeRefund = func(_ context.Context, _ *alipay.Client, param alipay.TradeRefund) (*alipay.TradeRefundRsp, error) {
if _, ok := seen[param.OutRequestNo]; !ok {
seen[param.OutRequestNo] = struct{}{}
refundedCents += refundCents
}
return &alipay.TradeRefundRsp{TradeNo: "2026101522001", FundChange: alipayFundChangeYes}, nil
}
provider := &Alipay{client: &alipay.Client{}}
req := payment.RefundRequest{OrderID: "sub2_7", Amount: "12.50", Reason: "r"}
for i := 0; i < 2; i++ {
if _, err := provider.Refund(context.Background(), req); err != nil {
t.Fatalf("Refund() error = %v", err)
}
}
if refundedCents != refundCents {
t.Fatalf("retry refunded %d cents, want %d (one refund only)", refundedCents, refundCents)
}
}
func TestAlipayQueryRefundMapsStatus(t *testing.T) {
origQuery := alipayTradeFastPayRefundQuery
t.Cleanup(func() { alipayTradeFastPayRefundQuery = origQuery })
@@ -31,6 +31,18 @@ func TestTransformClaudeToGemini_AttributionSystemText(t *testing.T) {
{"Codex GPT 5.6", "You are Codex, a coding agent based on GPT-5.6.\nKeep indentation.", "You are an AI agent.\nKeep indentation."},
{"Codex GPT 6", "You are Codex, based on GPT-6.", "You are an AI agent."},
{"Codex GPT 6 agent", "You are Codex, an agent based on GPT-6. Rest.", "You are an AI agent. Rest."},
{"Codex versionless", "You are Codex, a coding agent.", "You are an AI agent."},
{"Codex versionless instructions", "You are Codex, a coding agent. Keep all instructions.\n Preserve indentation.\n", "You are an AI agent. Keep all instructions.\n Preserve indentation.\n"},
{"Codex versionless whitespace", " \t\r\nYou are Codex, a coding agent.\r\n\tKeep indentation.", "You are an AI agent.\r\n\tKeep indentation."},
{"Codex versionless case", "you are codex, a coding agent. Rest.", "You are an AI agent. Rest."},
{"attribution before versionless", attribution + "\r\nYou are Codex, a coding agent. Rest.", "You are an AI agent. Rest."},
{"quoted versionless", `"You are Codex, a coding agent."`, `"You are Codex, a coding agent."`},
{"later versionless", "Example:\nYou are Codex, a coding agent.", "Example:\nYou are Codex, a coding agent."},
{"versionless mention", "Explain You are Codex, a coding agent.", "Explain You are Codex, a coding agent."},
{"versionless missing period", "You are Codex, a coding agent", "You are Codex, a coding agent"},
{"versionless longer sentence", "You are Codex, a coding agent helping with tests.", "You are Codex, a coding agent helping with tests."},
{"versionless longer word", "You are Codex, a coding agentic assistant.", "You are Codex, a coding agentic assistant."},
{"versionless period boundary", "You are Codex, a coding agent.example", "You are Codex, a coding agent.example"},
{"CLI comma", "You are GPT-5.6 running in the Codex CLI, a terminal-based coding assistant.", "You are an AI agent, a terminal-based coding assistant."},
{"Codex model suffix", "You are Codex, based on GPT-5.6-Codex. Rest.", "You are an AI agent. Rest."},
{"CLI GPT 5.6", "You are GPT-5.6 running in the Codex CLI. Rest.", "You are an AI agent. Rest."},
@@ -0,0 +1,68 @@
package antigravity
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestCarbonGenerationThinkingLevels(t *testing.T) {
for _, tc := range []struct {
name, body, level string
thoughts bool
}{
{"default", `{}`, "", false},
{"low", `{"output_config":{"effort":"low"}}`, "low", false},
{"medium", `{"output_config":{"effort":"medium"}}`, "medium", false},
{"high", `{"output_config":{"effort":"high"}}`, "high", false},
{"disabled wins", `{"thinking":{"type":"disabled"},"output_config":{"effort":"high"}}`, "low", false},
{"low budget", `{"thinking":{"type":"enabled","budget_tokens":1024}}`, "low", true},
{"medium budget", `{"thinking":{"type":"enabled","budget_tokens":4096}}`, "medium", true},
{"high budget", `{"thinking":{"type":"enabled","budget_tokens":32768}}`, "high", true},
{"adaptive default", `{"thinking":{"type":"adaptive"}}`, "", true},
{"effort wins", `{"thinking":{"type":"enabled","budget_tokens":32768},"output_config":{"effort":"medium"}}`, "medium", true},
} {
t.Run(tc.name, func(t *testing.T) {
var req ClaudeRequest
require.NoError(t, json.Unmarshal([]byte(tc.body), &req))
req.Model = "gemini-4-carbon"
req.MaxTokens = 1000
config := buildGenerationConfig(&req)
data, err := json.Marshal(config)
require.NoError(t, err)
require.NotContains(t, string(data), "thinkingBudget")
require.Equal(t, 1000, config.MaxOutputTokens, "Carbon budgets must not raise output limits")
if tc.level == "" && !tc.thoughts {
require.Nil(t, config.ThinkingConfig)
return
}
require.NotNil(t, config.ThinkingConfig)
require.Equal(t, tc.level, config.ThinkingConfig.ThinkingLevel)
require.Equal(t, tc.thoughts, config.ThinkingConfig.IncludeThoughts)
})
}
}
func TestCarbonTierPreservesUpstreamSelection(t *testing.T) {
for _, tier := range []string{"low", "medium", "high"} {
cfg := buildGenerationConfig(&ClaudeRequest{Model: "gemini-4-carbon-" + tier, Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 32768}, OutputConfig: &ClaudeOutputConfig{Effort: "low"}})
require.NotNil(t, cfg.ThinkingConfig)
require.True(t, cfg.ThinkingConfig.IncludeThoughts)
require.Empty(t, cfg.ThinkingConfig.ThinkingLevel)
require.Zero(t, cfg.ThinkingConfig.ThinkingBudget)
}
// Other models retain the existing budget behavior.
cfg := buildGenerationConfig(&ClaudeRequest{Model: "claude-sonnet-4-6", Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 4096}})
require.Equal(t, 4096, cfg.ThinkingConfig.ThinkingBudget)
require.Empty(t, cfg.ThinkingConfig.ThinkingLevel)
}
func TestCarbonTransformUsesMappedModelForThinking(t *testing.T) {
req := &ClaudeRequest{Model: "client-alias", MaxTokens: 4096, Messages: []ClaudeMessage{{Role: "user", Content: json.RawMessage(`"hello"`)}}, Thinking: &ThinkingConfig{Type: "enabled", BudgetTokens: 4096}}
data, err := TransformClaudeToGeminiWithOptions(req, "project", "gemini-4-carbon", TransformOptions{})
require.NoError(t, err)
require.Contains(t, string(data), `"thinkingLevel":"medium"`)
require.NotContains(t, string(data), `thinkingBudget`)
require.NotContains(t, string(data), `stopSequences`)
}
@@ -9,17 +9,23 @@ import (
// ClaudeRequest Claude Messages API 请求
type ClaudeRequest struct {
Model string `json:"model"`
Messages []ClaudeMessage `json:"messages"`
MaxTokens int `json:"max_tokens,omitempty"`
System json.RawMessage `json:"system,omitempty"` // string 或 []SystemBlock
Stream bool `json:"stream,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
Tools []ClaudeTool `json:"tools,omitempty"`
Thinking *ThinkingConfig `json:"thinking,omitempty"`
Metadata *ClaudeMetadata `json:"metadata,omitempty"`
Model string `json:"model"`
Messages []ClaudeMessage `json:"messages"`
MaxTokens int `json:"max_tokens,omitempty"`
System json.RawMessage `json:"system,omitempty"` // string 或 []SystemBlock
Stream bool `json:"stream,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
Tools []ClaudeTool `json:"tools,omitempty"`
Thinking *ThinkingConfig `json:"thinking,omitempty"`
Metadata *ClaudeMetadata `json:"metadata,omitempty"`
OutputConfig *ClaudeOutputConfig `json:"output_config,omitempty"`
}
// ClaudeOutputConfig carries the requested reasoning effort.
type ClaudeOutputConfig struct {
Effort string `json:"effort,omitempty"`
}
// ClaudeMessage Claude 消息
@@ -214,6 +220,7 @@ var geminiModels = []modelDef{
{ID: "gemini-3.8-flash-low", DisplayName: "Gemini 3.8 Flash Low", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
{ID: "gemini-3.8-flash-medium", DisplayName: "Gemini 3.8 Flash Medium", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
{ID: "gemini-3.8-flash-tiered", DisplayName: "Gemini 3.8 Flash", CreatedAt: "2026-09-02T00:00:00Z", IsReasoning: true},
{ID: "gemini-4-carbon", DisplayName: "Gemini 4 Carbon", CreatedAt: "2026-11-10T00:00:00Z", IsReasoning: true},
{ID: "gemini-4-argon-high", DisplayName: "Gemini 4 Argon (High)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
{ID: "gemini-4-argon-low", DisplayName: "Gemini 4 Argon (Low)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
{ID: "gemini-4-argon-medium", DisplayName: "Gemini 4 Argon (Medium)", CreatedAt: "2026-10-13T00:00:00Z", IsReasoning: true},
@@ -15,6 +15,7 @@ func TestDefaultModels_ContainsNewAndLegacyImageModels(t *testing.T) {
}
requiredIDs := []string{
"gemini-4-carbon",
"claude-fable-5-1",
"claude-fable-5",
"claude-opus-4-8",
@@ -80,6 +81,9 @@ func TestClaudeContentItem_ThinkingAlwaysHasSignature(t *testing.T) {
func TestIsGeminiReasoningModel_IncludesProAgent(t *testing.T) {
t.Parallel()
if !IsGeminiReasoningModel("gemini-4-carbon") {
t.Fatal("expected Carbon to be recognized as a Gemini reasoning model")
}
if !IsGeminiReasoningModel("gemini-pro-agent") {
t.Fatal("expected gemini-pro-agent to be recognized as a Gemini reasoning model")
}
@@ -84,8 +84,9 @@ type GeminiImageConfig struct {
// GeminiThinkingConfig Gemini thinking 配置
type GeminiThinkingConfig struct {
IncludeThoughts bool `json:"includeThoughts"`
ThinkingBudget int `json:"thinkingBudget,omitempty"`
IncludeThoughts bool `json:"includeThoughts"`
ThinkingBudget int `json:"thinkingBudget,omitempty"`
ThinkingLevel string `json:"thinkingLevel,omitempty"`
}
// GeminiToolDeclaration Gemini 工具声明
@@ -301,6 +301,7 @@ var systemIdentityOpeners = []*regexp.Regexp{
regexp.MustCompile(`(?i)^[ \t\r\n]*You are a Claude agent, built on Anthropic'?s Claude Agent SDK\.?`),
regexp.MustCompile(`(?i)^[ \t\r\n]*You are Claude Code, Anthropic'?s official CLI for Claude\.?`),
regexp.MustCompile(`(?i)^[ \t\r\n]*You are Codex,? (?:a coding agent |an agent )?based on GPT-[0-9]+(?:\.[0-9]+)*(?:-[a-z0-9]+)*\.?`),
regexp.MustCompile(`(?i)^[ \t\r\n]*You are Codex, a coding agent\.`),
regexp.MustCompile(`(?i)^[ \t\r\n]*You are GPT-[0-9]+(?:\.[0-9]+)*(?:-[a-z0-9]+)* running in the Codex CLI\.?`),
}
@@ -696,6 +697,45 @@ func isAntigravityOpusHighTierModel(model string) bool {
strings.HasPrefix(lower, "claude-opus-4-8")
}
// carbonThinkingConfig preserves the upstream default when no effort is specified.
// https://aistudio.google.com/docs/whats-new-gemini-4-carbon
func carbonThinkingConfig(req *ClaudeRequest, bareModel bool) *GeminiThinkingConfig {
cfg := &GeminiThinkingConfig{}
if req.Thinking != nil {
cfg.IncludeThoughts = req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive"
}
if bareModel {
if req.OutputConfig != nil {
switch strings.ToLower(strings.TrimSpace(req.OutputConfig.Effort)) {
case "none", "minimal", "low":
cfg.ThinkingLevel = "low"
case "medium":
cfg.ThinkingLevel = "medium"
case "high", "xhigh", "max":
cfg.ThinkingLevel = "high"
}
}
if req.Thinking != nil {
if req.Thinking.Type == "disabled" {
cfg.ThinkingLevel = "low"
} else if cfg.ThinkingLevel == "" && req.Thinking.Type == "enabled" && req.Thinking.BudgetTokens > 0 {
switch {
case req.Thinking.BudgetTokens <= 1024:
cfg.ThinkingLevel = "low"
case req.Thinking.BudgetTokens <= 8192:
cfg.ThinkingLevel = "medium"
default:
cfg.ThinkingLevel = "high"
}
}
}
}
if !cfg.IncludeThoughts && cfg.ThinkingLevel == "" {
return nil
}
return cfg
}
func buildGenerationConfig(req *ClaudeRequest) *GeminiGenerationConfig {
maxLimit := maxOutputTokensLimit(req.Model)
config := &GeminiGenerationConfig{
@@ -712,8 +752,16 @@ func buildGenerationConfig(req *ClaudeRequest) *GeminiGenerationConfig {
config.MaxOutputTokens = req.MaxTokens
}
// Carbon accepts thinking levels rather than token budgets. Tiered IDs, when
// supplied by the account catalog, already select the level upstream.
carbonModel := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(req.Model)), "models/")
isCarbon := carbonModel == "gemini-4-carbon" || carbonModel == "gemini-4-carbon-low" || carbonModel == "gemini-4-carbon-medium" || carbonModel == "gemini-4-carbon-high"
if isCarbon {
config.ThinkingConfig = carbonThinkingConfig(req, carbonModel == "gemini-4-carbon")
}
// Thinking 配置
if req.Thinking != nil && (req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive") {
if !isCarbon && req.Thinking != nil && (req.Thinking.Type == "enabled" || req.Thinking.Type == "adaptive") {
config.ThinkingConfig = &GeminiThinkingConfig{
IncludeThoughts: true,
}
@@ -376,24 +376,15 @@ func cleanJSONSchemaRecursive(value any) any {
}
}
// 8. [SAFETY] 处理缺失 items 的 Array (Gemini 严苛要求 array 必须声明 items Schema)
// 8. Gemini 只允许 array 携带 items,且 items 必须是非空 Schema 对象。
if t, _ := schemaMap["type"].(string); t == "array" {
itemsVal, hasItems := schemaMap["items"]
needDefaultItems := false
if !hasItems || itemsVal == nil {
needDefaultItems = true
} else if itemsMap, ok := itemsVal.(map[string]any); ok {
if len(itemsMap) == 0 {
needDefaultItems = true
}
} else if _, isBool := itemsVal.(bool); isBool {
needDefaultItems = true
}
if needDefaultItems {
if items, ok := schemaMap["items"].(map[string]any); !ok || len(items) == 0 {
schemaMap["items"] = map[string]any{
"type": "string",
}
}
} else {
delete(schemaMap, "items")
}
// 9. [SAFETY] Required 字段对齐
@@ -0,0 +1,323 @@
package apicompat
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestChatCacheWritePresenceAcrossAnthropicConverters(t *testing.T) {
for _, test := range []struct {
name string
details string
creation int
}{
{"missing write falls back", `"cache_creation_tokens":4`, 4},
{"zero write is authoritative", `"cache_write_tokens":0,"cache_creation_tokens":4`, 0},
{"null write is authoritative", `"cache_write_tokens":null,"cache_creation_tokens":4`, 0},
{"negative write clamps", `"cache_write_tokens":-2,"cache_creation_tokens":4`, 0},
{"positive write wins", `"cache_write_tokens":2,"cache_creation_tokens":4`, 2},
} {
t.Run(test.name, func(t *testing.T) {
var response ChatCompletionsResponse
payload := `{"id":"chat_cache","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":2,"prompt_tokens_details":{"cached_tokens":3,` + test.details + `}}}`
require.NoError(t, json.Unmarshal([]byte(payload), &response))
encoded, err := json.Marshal(response)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(encoded, &response))
if strings.Contains(test.details, `"cache_write_tokens":0`) {
require.Contains(t, string(encoded), `"cache_write_tokens":0`)
}
assertUsage := func(usage AnthropicUsage) {
require.Equal(t, 7-test.creation, usage.InputTokens)
require.Equal(t, 2, usage.OutputTokens)
require.Equal(t, 3, usage.CacheReadInputTokens)
require.Equal(t, test.creation, usage.CacheCreationInputTokens)
require.True(t, usage.CacheCreationInputTokensPresent)
require.True(t, usage.CacheReadInputTokensPresent)
require.Nil(t, usage.CacheCreation)
}
assertUsage(ChatCompletionsResponseToAnthropic(&response, "claude-sonnet-4").Usage)
converted := ChatCompletionsResponseToResponses(&response, "claude-sonnet-4", nil, nil, false, nil)
encoded, err = json.Marshal(converted)
require.NoError(t, err)
var decoded ResponsesResponse
require.NoError(t, json.Unmarshal(encoded, &decoded))
assertUsage(ResponsesToAnthropic(&decoded, "claude-sonnet-4").Usage)
for _, adapter := range []bool{false, true} {
state := NewChatCompletionsToAnthropicStreamState("claude-sonnet-4")
var events []AnthropicStreamEvent
chunk := &ChatCompletionsChunk{ID: "chat_cache", Usage: response.Usage}
if adapter {
responsesState := NewChatCompletionsToResponsesStreamState("claude-sonnet-4")
anthropicState := NewResponsesEventToAnthropicState()
responseEvents := ChatCompletionsChunkToResponsesEvents(chunk, responsesState)
responseEvents = append(responseEvents, FinalizeChatCompletionsResponsesStream(responsesState)...)
for _, event := range responseEvents {
events = append(events, ResponsesEventToAnthropicEvents(&event, anthropicState)...)
}
events = append(events, FinalizeResponsesAnthropicStream(anthropicState)...)
} else {
events = ChatCompletionsChunkToAnthropicEvents(chunk, state)
events = append(events, FinalizeChatCompletionsAnthropicStream(state)...)
}
deltas := 0
for _, event := range events {
if event.Type == "message_delta" {
require.NotNil(t, event.Usage)
assertUsage(*event.Usage)
deltas++
}
}
require.Equal(t, 1, deltas)
}
})
}
}
func TestAnthropicCacheCreationAggregatePresence(t *testing.T) {
for _, test := range []struct {
name string
snapshot string
want int
present bool
}{
{"contradictory aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 100, true},
{"explicit zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, true},
{"missing aggregate", `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false},
{"null aggregate", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false},
{"null TTL", `{"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":200}}`, 200, false},
} {
t.Run(test.name, func(t *testing.T) {
var usage AnthropicUsage
require.NoError(t, json.Unmarshal([]byte(test.snapshot), &usage))
require.Equal(t, test.present, usage.HasCacheCreationInputTokens())
response := AnthropicToResponsesResponse(&AnthropicResponse{Usage: usage})
require.Equal(t, test.want, response.Usage.CacheCreationInputTokens)
require.Equal(t, test.want, response.Usage.InputTokens)
state := NewAnthropicEventToResponsesState()
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
Type: "message_start", Message: &AnthropicResponse{ID: "msg_cache", Usage: usage},
}, state)
for range 2 {
var delta AnthropicUsage
require.NoError(t, json.Unmarshal([]byte(`{"cache_creation":{"ephemeral_1h_input_tokens":200}}`), &delta))
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &delta}, state)
require.Equal(t, test.want, state.CacheCreationInputTokens)
}
events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)
require.NotEmpty(t, events)
completed := events[len(events)-1].Response
require.NotNil(t, completed)
require.Equal(t, test.want, completed.Usage.CacheCreationInputTokens)
})
}
}
func TestAnthropicUsageJSONRoundtrip(t *testing.T) {
for _, test := range []struct {
name string
payload string
present bool
value int
}{
{"absent", `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, false, 0},
{"null", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, false, 0},
{"zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 0},
{"positive", `{"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 20},
} {
t.Run(test.name, func(t *testing.T) {
var usage AnthropicUsage
require.NoError(t, json.Unmarshal([]byte(test.payload), &usage))
for range 2 {
encoded, err := json.Marshal(usage)
require.NoError(t, err)
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal(encoded, &fields))
_, present := fields["cache_creation_input_tokens"]
require.Equal(t, test.present, present)
var roundtrip AnthropicUsage
require.NoError(t, json.Unmarshal(encoded, &roundtrip))
require.Equal(t, test.present, roundtrip.HasCacheCreationInputTokens())
require.Equal(t, test.value, roundtrip.CacheCreationInputTokens)
require.Equal(t, usage.CacheCreation, roundtrip.CacheCreation)
usage = roundtrip
}
})
}
}
func TestAnthropicUsageSyntheticJSONRoundtrip(t *testing.T) {
for _, test := range []struct {
name string
usage AnthropicUsage
present bool
}{
{"missing", AnthropicUsage{}, false},
{"inferred nonzero", AnthropicUsage{CacheCreationInputTokens: 25}, true},
{"explicit zero", AnthropicUsage{CacheCreationInputTokensPresent: true}, true},
} {
t.Run(test.name, func(t *testing.T) {
test.usage.InputTokens = 10
test.usage.OutputTokens = 7
test.usage.CacheReadInputTokens = 3
encoded, err := json.Marshal(test.usage)
require.NoError(t, err)
var roundtrip AnthropicUsage
require.NoError(t, json.Unmarshal(encoded, &roundtrip))
require.Equal(t, test.present, roundtrip.HasCacheCreationInputTokens())
require.Equal(t, test.usage.CacheCreationInputTokens, roundtrip.CacheCreationInputTokens)
require.Equal(t, 10, roundtrip.InputTokens)
require.Equal(t, 7, roundtrip.OutputTokens)
require.Equal(t, 3, roundtrip.CacheReadInputTokens)
})
}
}
func TestAnthropicUsageAdapterZeroContracts(t *testing.T) {
for _, test := range []struct {
name string
usage AnthropicUsage
present bool
}{
{"missing Responses usage", anthropicUsageFromResponsesUsage(nil), true},
{"explicit Responses totals", anthropicUsageFromResponsesUsage(&ResponsesUsage{}), true},
{"missing Chat usage", chatUsageToAnthropicUsage(nil), true},
{"explicit Chat totals", chatUsageToAnthropicUsage(&ChatUsage{}), true},
} {
t.Run(test.name, func(t *testing.T) {
encoded, err := json.Marshal(test.usage)
require.NoError(t, err)
var decoded AnthropicUsage
require.NoError(t, json.Unmarshal(encoded, &decoded))
require.Equal(t, test.present, decoded.HasCacheCreationInputTokens())
require.Zero(t, decoded.CacheCreationInputTokens)
})
}
responsesState := NewResponsesEventToAnthropicState()
startEvents := resToAnthHandleCreated(&ResponsesStreamEvent{}, responsesState)
chatState := NewChatCompletionsToAnthropicStreamState("claude-sonnet-4")
startEvents = append(startEvents, ensureCCAnthropicMessageStart(chatState)...)
for _, event := range startEvents {
encoded, err := json.Marshal(event)
require.NoError(t, err)
var decoded AnthropicStreamEvent
require.NoError(t, json.Unmarshal(encoded, &decoded))
require.NotNil(t, decoded.Message)
require.True(t, decoded.Message.Usage.HasCacheCreationInputTokens())
require.True(t, decoded.Message.Usage.CacheReadInputTokensPresent)
}
terminalEvents := FinalizeResponsesAnthropicStream(responsesState)
terminalEvents = append(terminalEvents, FinalizeChatCompletionsAnthropicStream(chatState)...)
usageEvents := 0
for _, event := range terminalEvents {
if event.Usage == nil {
continue
}
encoded, err := json.Marshal(event)
require.NoError(t, err)
var decoded AnthropicStreamEvent
require.NoError(t, json.Unmarshal(encoded, &decoded))
require.NotNil(t, decoded.Usage)
require.True(t, decoded.Usage.HasCacheCreationInputTokens())
require.Zero(t, decoded.Usage.CacheCreationInputTokens)
usageEvents++
}
require.Equal(t, 2, usageEvents)
}
func TestAnthropicCacheCreationPartialSnapshots(t *testing.T) {
state := NewAnthropicEventToResponsesState()
for index, snapshot := range []string{
`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`,
`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`,
`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`,
`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`,
`{"cache_creation_input_tokens":40}`,
`{"output_tokens":1}`,
`{"cache_creation_input_tokens":0}`,
`{"cache_creation":{"ephemeral_1h_input_tokens":200}}`,
`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":null}}`,
`{"cache_creation_input_tokens":100}`,
} {
var usage AnthropicUsage
require.NoError(t, json.Unmarshal([]byte(snapshot), &usage))
state.mergeCacheCreationUsage(usage)
require.Equal(t, []int{20, 50, 50, 50, 40, 40, 40, 40, 40, 100}[index], state.CacheCreationInputTokens)
}
}
func TestAnthropicConvertersRawCacheUsageLifecycle(t *testing.T) {
for _, test := range []struct {
name string
aggregate int
want []int
}{
{"zero aggregate derives partial TTL", 0, []int{20, 50, 50, 50, 30}},
{"positive aggregate survives placeholders", 40, []int{40, 40, 40, 40, 40}},
} {
for _, terminal := range []string{"message_stop", "eof"} {
t.Run(test.name+"/"+terminal, func(t *testing.T) {
state := NewAnthropicEventToResponsesState()
chatState := NewResponsesEventToChatState()
chatState.IncludeUsage = true
var completed *ResponsesResponse
var chatUsage *ChatUsage
consume := func(events []ResponsesStreamEvent) {
for _, event := range events {
if event.Type == "response.completed" {
completed = event.Response
}
for _, chunk := range ResponsesEventToChatChunks(&event, chatState) {
if chunk.Usage != nil {
chatUsage = chunk.Usage
}
}
}
}
start := AnthropicStreamEvent{Type: "message_start", Message: &AnthropicResponse{
ID: "msg_cache", Model: "claude-sonnet-4", Usage: AnthropicUsage{
InputTokens: 10, CacheReadInputTokens: 9,
CacheCreationInputTokens: test.aggregate, CacheCreationInputTokensPresent: true,
},
}}
consume(AnthropicEventToResponsesEvents(&start, state))
for index, snapshot := range []string{
`{"output_tokens":7,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":20}}`,
`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`,
`{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`,
`{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}`,
`{"cache_creation":{"ephemeral_5m_input_tokens":0}}`,
} {
var event AnthropicStreamEvent
require.NoError(t, json.Unmarshal([]byte(`{"type":"message_delta","usage":`+snapshot+`}`), &event))
consume(AnthropicEventToResponsesEvents(&event, state))
require.Equal(t, test.want[index], state.CacheCreationInputTokens, "snapshot %d", index)
require.Equal(t, 7, state.OutputTokens, "snapshot %d", index)
}
if terminal == "message_stop" {
consume(AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state))
} else {
consume(FinalizeAnthropicResponsesStream(state))
}
want := test.want[len(test.want)-1]
require.NotNil(t, completed)
require.NotNil(t, completed.Usage)
require.Equal(t, want, completed.Usage.CacheCreationInputTokens)
require.Equal(t, 19+want, completed.Usage.InputTokens)
require.Equal(t, 7, completed.Usage.OutputTokens)
require.Equal(t, 26+want, completed.Usage.TotalTokens)
require.NotNil(t, chatUsage)
require.Equal(t, 19+want, chatUsage.PromptTokens)
require.Equal(t, 7, chatUsage.CompletionTokens)
require.NotNil(t, chatUsage.PromptTokensDetails)
require.Equal(t, want, chatUsage.PromptTokensDetails.CacheCreationTokens)
require.Equal(t, 9, chatUsage.PromptTokensDetails.CachedTokens)
require.Empty(t, FinalizeAnthropicResponsesStream(state))
require.Empty(t, FinalizeResponsesChatStream(chatState))
})
}
}
}
@@ -0,0 +1,42 @@
//go:build unit
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestAnthropicUsageCacheReadPresenceRoundtrip(t *testing.T) {
for _, test := range []struct {
name string
payload string
present bool
value int
}{
{"missing", `{}`, false, 0},
{"null", `{"cache_read_input_tokens":null,"cached_tokens":null,"prompt_tokens_details":{"cached_tokens":null}}`, false, 0},
{"zero", `{"cache_read_input_tokens":0,"cached_tokens":0,"prompt_tokens_details":{"cached_tokens":0}}`, true, 0},
{"positive", `{"cache_read_input_tokens":20,"cached_tokens":20,"prompt_tokens_details":{"cached_tokens":20}}`, true, 20},
} {
t.Run(test.name, func(t *testing.T) {
var usage AnthropicUsage
require.NoError(t, json.Unmarshal([]byte(test.payload), &usage))
for range 2 {
require.Equal(t, test.present, usage.CacheReadInputTokensPresent)
require.Equal(t, test.present, usage.CachedTokensPresent)
require.Equal(t, test.value, usage.CacheReadInputTokens)
require.Equal(t, test.value, usage.CachedTokens)
if usage.PromptTokensDetails != nil {
require.Equal(t, test.present, usage.PromptTokensDetails.CachedTokensPresent)
require.Equal(t, test.value, usage.PromptTokensDetails.CachedTokens)
}
encoded, err := json.Marshal(usage)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(encoded, &usage))
}
})
}
}
@@ -0,0 +1,104 @@
//go:build unit
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestAnthropicUsageOutputTokensDetailsRoundtrip(t *testing.T) {
var usage AnthropicUsage
require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":12,"output_tokens":120,"output_tokens_details":{"thinking_tokens":40}}`), &usage))
require.NotNil(t, usage.OutputTokensDetails)
require.Equal(t, 40, usage.OutputTokensDetails.ThinkingTokens)
encoded, err := json.Marshal(usage)
require.NoError(t, err)
require.Contains(t, string(encoded), `"output_tokens_details":{"thinking_tokens":40}`)
encoded, err = json.Marshal(AnthropicUsage{InputTokens: 1, OutputTokens: 2})
require.NoError(t, err)
require.NotContains(t, string(encoded), "output_tokens_details")
}
func TestAnthropicThinkingTokensBecomeReasoningTokens(t *testing.T) {
for _, test := range []struct {
name string
details *AnthropicOutputTokensDetails
want int
}{
{"reported", &AnthropicOutputTokensDetails{ThinkingTokens: 40}, 40},
{"bounded by output_tokens", &AnthropicOutputTokensDetails{ThinkingTokens: 500}, 120},
{"reported zero", &AnthropicOutputTokensDetails{ThinkingTokens: 0}, 0},
{"absent", nil, 0},
} {
t.Run(test.name, func(t *testing.T) {
resp := &AnthropicResponse{
ID: "msg_thinking",
Type: "message",
Role: "assistant",
Model: "claude-sonnet-4-5",
StopReason: AnthropicStopReasonPtr("end_turn"),
Content: []AnthropicContentBlock{{Type: "text", Text: "ok"}},
Usage: AnthropicUsage{InputTokens: 12, OutputTokens: 120, OutputTokensDetails: test.details},
}
responses := AnthropicToResponsesResponse(resp)
chat := ResponsesToChatCompletions(responses, "claude-sonnet-4-5")
require.NotNil(t, chat.Usage)
require.Equal(t, 120, chat.Usage.CompletionTokens)
if test.want == 0 {
require.Nil(t, responses.Usage.OutputTokensDetails)
require.Nil(t, chat.Usage.CompletionTokensDetails)
return
}
require.NotNil(t, responses.Usage.OutputTokensDetails)
require.Equal(t, test.want, responses.Usage.OutputTokensDetails.ReasoningTokens)
require.NotNil(t, chat.Usage.CompletionTokensDetails)
require.Equal(t, test.want, chat.Usage.CompletionTokensDetails.ReasoningTokens)
})
}
}
func TestAnthropicStreamThinkingTokensUseLatestReportedValue(t *testing.T) {
for _, test := range []struct {
name string
delta string
want int
}{
{"delta reports thinking", `,"output_tokens_details":{"thinking_tokens":40}`, 40},
{"delta reports zero", `,"output_tokens_details":{"thinking_tokens":0}`, 0},
{"delta omits details", ``, 25},
} {
t.Run(test.name, func(t *testing.T) {
state := NewAnthropicEventToResponsesState()
var completed *ResponsesUsage
for _, payload := range []string{
`{"type":"message_start","message":{"id":"msg_s","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-5","usage":{"input_tokens":12,"output_tokens":1,"output_tokens_details":{"thinking_tokens":25}}}}`,
`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`,
`{"type":"content_block_stop","index":0}`,
`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":120` + test.delta + `}}`,
`{"type":"message_stop"}`,
} {
var event AnthropicStreamEvent
require.NoError(t, json.Unmarshal([]byte(payload), &event))
for _, out := range AnthropicEventToResponsesEvents(&event, state) {
if out.Type == "response.completed" {
completed = out.Response.Usage
}
}
}
require.NotNil(t, completed)
require.Equal(t, 120, completed.OutputTokens)
if test.want == 0 {
require.Nil(t, completed.OutputTokensDetails)
return
}
require.NotNil(t, completed.OutputTokensDetails)
require.Equal(t, test.want, completed.OutputTokensDetails.ReasoningTokens)
})
}
}
@@ -82,7 +82,7 @@ func AnthropicToResponsesWithOptions(req *AnthropicRequest, options AnthropicToR
// An explicit thinking disable takes precedence over output_config.effort.
effort := anthropicReasoningEffort(req)
if (openai.IsGPT61SolModelSpelling(req.Model) || openai.IsGPT61TerraModelSpelling(req.Model)) && req.OutputConfig != nil && req.OutputConfig.Effort == "max" && effort != "none" {
if (openai.GPT62ModelID(req.Model) != "" || openai.IsGPT61SolModelSpelling(req.Model) || openai.IsGPT61TerraModelSpelling(req.Model)) && req.OutputConfig != nil && req.OutputConfig.Effort == "max" && effort != "none" {
effort = "max"
}
out.Reasoning = &ResponsesReasoning{
@@ -206,6 +206,16 @@ func anthropicMsgToResponsesItems(m AnthropicMessage) ([]ResponsesInputItem, err
return anthropicUserToResponses(m.Content)
case "assistant":
return anthropicAssistantToResponses(m.Content)
case "system":
// Mid-conversation system turns (e.g. hook output) keep system-level
// authority: Responses uses developer for them, not user.
items, err := anthropicUserToResponses(m.Content)
for i := range items {
if items[i].Role == "user" {
items[i].Role = "developer"
}
}
return items, err
default:
return anthropicUserToResponses(m.Content)
}
@@ -29,6 +29,23 @@ func encodeAnthropicThinking(block AnthropicContentBlock) string {
return anthropicThinkingEnvelopePrefix + base64.RawStdEncoding.EncodeToString(payload)
}
func anthropicCacheCreationInputTokens(usage AnthropicUsage) int {
if usage.CacheCreationInputTokens > 0 {
return max(usage.CacheCreationInputTokens, 0)
}
if usage.CacheCreation != nil && (usage.CacheCreation.Ephemeral5mInputTokens != nil || usage.CacheCreation.Ephemeral1hInputTokens != nil) {
cacheCreationTokens := 0
if usage.CacheCreation.Ephemeral5mInputTokens != nil {
cacheCreationTokens += max(*usage.CacheCreation.Ephemeral5mInputTokens, 0)
}
if usage.CacheCreation.Ephemeral1hInputTokens != nil {
cacheCreationTokens += max(*usage.CacheCreation.Ephemeral1hInputTokens, 0)
}
return cacheCreationTokens
}
return max(usage.CacheCreationInputTokens, 0)
}
// AnthropicToResponsesResponse converts an Anthropic Messages response into a
// Responses API response. This is the reverse of ResponsesToAnthropic and
// enables Anthropic upstream responses to be returned in OpenAI Responses format.
@@ -130,24 +147,39 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse {
// Anthropic's input_tokens excludes cache_read/cache_creation, while OpenAI
// Responses' input_tokens is the total including cached tokens. Add them back
// when converting so downstream consumers see OpenAI semantics.
cacheCreationTokens := anthropicCacheCreationInputTokens(resp.Usage)
totalInputTokens := resp.Usage.InputTokens +
resp.Usage.CacheReadInputTokens +
resp.Usage.CacheCreationInputTokens
cacheCreationTokens
out.Usage = &ResponsesUsage{
InputTokens: totalInputTokens,
OutputTokens: resp.Usage.OutputTokens,
TotalTokens: totalInputTokens + resp.Usage.OutputTokens,
CacheCreationInputTokens: resp.Usage.CacheCreationInputTokens,
CacheCreationInputTokens: cacheCreationTokens,
}
if resp.Usage.CacheReadInputTokens > 0 {
out.Usage.InputTokensDetails = &ResponsesInputTokensDetails{
CachedTokens: resp.Usage.CacheReadInputTokens,
}
}
if details := resp.Usage.OutputTokensDetails; details != nil {
out.Usage.OutputTokensDetails = responsesReasoningTokensDetails(details.ThinkingTokens, resp.Usage.OutputTokens)
}
return out
}
// responsesReasoningTokensDetails reports Anthropic thinking tokens as
// Responses reasoning_tokens, bounded by the output total they belong to.
// Returns nil when there is nothing to report.
func responsesReasoningTokensDetails(thinkingTokens, outputTokens int) *ResponsesOutputTokensDetails {
reasoningTokens := min(max(thinkingTokens, 0), max(outputTokens, 0))
if reasoningTokens == 0 {
return nil
}
return &ResponsesOutputTokensDetails{ReasoningTokens: reasoningTokens}
}
// anthropicStopReasonToResponsesStatus maps Anthropic stop_reason to Responses status.
func anthropicStopReasonToResponsesStatus(stopReason string, blocks []AnthropicContentBlock) string {
switch stopReason {
@@ -220,8 +252,13 @@ type AnthropicEventToResponsesState struct {
// emitting the OpenAI Responses usage.
InputTokens int
OutputTokens int
ReasoningTokens int // output_tokens_details.thinking_tokens; a reported value (even 0) replaces the previous one
CacheReadInputTokens int
CacheCreationInputTokens int
CacheCreation AnthropicCacheCreation
cacheCreationInputTokensPresent bool
cacheCreationInputTokensFromDetails bool
StopReason string
}
@@ -233,6 +270,28 @@ func NewAnthropicEventToResponsesState() *AnthropicEventToResponsesState {
}
}
func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage AnthropicUsage) {
if usage.HasCacheCreationInputTokens() && (usage.CacheCreationInputTokens > 0 || state.CacheCreationInputTokens <= 0) {
state.CacheCreationInputTokens = max(usage.CacheCreationInputTokens, 0)
state.cacheCreationInputTokensPresent = true
state.cacheCreationInputTokensFromDetails = false
}
if usage.CacheCreation != nil {
if usage.CacheCreation.Ephemeral5mInputTokens != nil {
tokens := max(*usage.CacheCreation.Ephemeral5mInputTokens, 0)
state.CacheCreation.Ephemeral5mInputTokens = &tokens
}
if usage.CacheCreation.Ephemeral1hInputTokens != nil {
tokens := max(*usage.CacheCreation.Ephemeral1hInputTokens, 0)
state.CacheCreation.Ephemeral1hInputTokens = &tokens
}
}
if (!state.cacheCreationInputTokensPresent || state.cacheCreationInputTokensFromDetails || state.CacheCreationInputTokens <= 0) && (state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil) {
state.CacheCreationInputTokens = anthropicCacheCreationInputTokens(AnthropicUsage{CacheCreation: &state.CacheCreation})
state.cacheCreationInputTokensFromDetails = true
}
}
// AnthropicEventToResponsesEvents converts a single Anthropic SSE event into
// zero or more Responses SSE events, updating state as it goes.
func AnthropicEventToResponsesEvents(
@@ -299,9 +358,10 @@ func anthToResHandleMessageStart(evt *AnthropicStreamEvent, state *AnthropicEven
if evt.Message.Usage.CacheReadInputTokens > 0 {
state.CacheReadInputTokens = evt.Message.Usage.CacheReadInputTokens
}
if evt.Message.Usage.CacheCreationInputTokens > 0 {
state.CacheCreationInputTokens = evt.Message.Usage.CacheCreationInputTokens
if details := evt.Message.Usage.OutputTokensDetails; details != nil {
state.ReasoningTokens = details.ThinkingTokens
}
state.mergeCacheCreationUsage(evt.Message.Usage)
}
if state.CreatedSent {
@@ -560,16 +620,19 @@ func anthToResHandleContentBlockStop(evt *AnthropicStreamEvent, state *Anthropic
func anthToResHandleMessageDelta(evt *AnthropicStreamEvent, state *AnthropicEventToResponsesState) []ResponsesStreamEvent {
if evt.Usage != nil {
state.OutputTokens = evt.Usage.OutputTokens
if evt.Usage.OutputTokens > 0 {
state.OutputTokens = evt.Usage.OutputTokens
}
if evt.Usage.InputTokens > 0 {
state.InputTokens = evt.Usage.InputTokens
}
if evt.Usage.CacheReadInputTokens > 0 {
state.CacheReadInputTokens = evt.Usage.CacheReadInputTokens
}
if evt.Usage.CacheCreationInputTokens > 0 {
state.CacheCreationInputTokens = evt.Usage.CacheCreationInputTokens
if details := evt.Usage.OutputTokensDetails; details != nil {
state.ReasoningTokens = details.ThinkingTokens
}
state.mergeCacheCreationUsage(*evt.Usage)
}
if evt.Delta != nil && evt.Delta.StopReason != "" {
state.StopReason = evt.Delta.StopReason
@@ -713,6 +776,7 @@ func makeResponsesCompletedEvent(
CachedTokens: state.CacheReadInputTokens,
}
}
usage.OutputTokensDetails = responsesReasoningTokensDetails(state.ReasoningTokens, state.OutputTokens)
eventType := "response.completed"
if status == "incomplete" {
@@ -0,0 +1,271 @@
package apicompat
import (
"encoding/json"
"strings"
)
// ToolSearchToolName is Claude Code's client-executed tool-search tool. Under
// the native protocol it maps to the Responses `tool_search` tool, its
// tool_use to a `tool_search_call` and its tool_result to a
// `tool_search_output`; an upstream tool_search_call comes back under this name.
const ToolSearchToolName = "ToolSearch"
// emptyToolResultOutput is what convertToolResultOutput emits for a
// tool_result without text.
const emptyToolResultOutput = "(empty)"
// ApplyNativeToolSearch rewrites a Responses request produced by
// AnthropicToResponses so Claude Code's ToolSearch uses the native
// client-executed tool_search protocol of the ChatGPT/Codex backend.
//
// Deferred tools never reach the top-level tools: revealed definitions ride in
// the history's tool_search_output instead, so the top-level tools (the head of
// the prompt-cache prefix) stay identical before and after a reveal.
func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error {
declared := false
deferred := make(map[string]bool)
for _, t := range req.Tools {
if t.DeferLoading {
deferred[t.Name] = true
} else if t.Name == ToolSearchToolName {
declared = true
}
}
// The Responses API has no tool_choice value that forces tool_search or a
// tool declared only in tool_search_output, so a request forcing either
// keeps every tool and call as a plain function.
if !declared || forcesHiddenTool(req.ToolChoice, deferred) {
return nil
}
schemas := make(map[string]AnthropicTool, len(req.Tools))
kept := make([]AnthropicTool, 0, len(req.Tools))
for _, t := range req.Tools {
schemas[t.Name] = t
if t.DeferLoading {
continue
}
kept = append(kept, t)
}
tools := convertAnthropicToolsToResponses(kept)
for i, t := range kept {
if t.Name == ToolSearchToolName {
// Codex declares this tool without a name or strict.
tools[i] = ResponsesTool{
Type: "tool_search",
Execution: "client",
Description: t.Description,
Parameters: normalizeToolParameters(t.InputSchema),
}
}
}
out.Tools = tools
revealed := toolSearchReveals(req.Messages)
if len(revealed) == 0 {
return nil
}
var items []json.RawMessage
if err := json.Unmarshal(out.Input, &items); err != nil {
return err
}
rewritten := make([]json.RawMessage, 0, len(items))
var pendingText []string
flush := func(next json.RawMessage) (json.RawMessage, error) {
text := strings.Join(pendingText, "\n\n")
pendingText = nil
return userMessageWithLeadingText(next, text)
}
for _, raw := range items {
var item ResponsesInputItem
if err := json.Unmarshal(raw, &item); err != nil {
return err
}
if len(pendingText) > 0 && item.Type != "function_call_output" {
// A tool_search_output has no field for the result text, so it rides
// in the user message that follows the run of tool outputs.
merged, err := flush(raw)
if err != nil {
return err
}
if item.Type == "message" && item.Role == "user" {
raw = merged
} else {
rewritten = append(rewritten, merged)
}
}
names, isSearch := revealed[item.CallID]
if !isSearch {
rewritten = append(rewritten, raw)
continue
}
var native any
switch item.Type {
case "function_call":
native = map[string]any{
"type": "tool_search_call",
"call_id": item.CallID,
"execution": "client",
"status": "completed",
"arguments": jsonObjectOrEmpty(item.Arguments),
}
case "function_call_output":
loaded := make([]any, 0, len(names))
for _, name := range names {
t, ok := schemas[name]
if !ok {
continue
}
loaded = append(loaded, map[string]any{
"type": "function",
"name": name,
"description": t.Description,
"defer_loading": true,
"strict": false,
"parameters": normalizeToolParameters(t.InputSchema),
})
}
native = map[string]any{
"type": "tool_search_output",
"call_id": item.CallID,
"execution": "client",
"status": "completed",
"tools": loaded,
}
if item.Output != "" && item.Output != emptyToolResultOutput {
pendingText = append(pendingText, item.Output)
}
default:
rewritten = append(rewritten, raw)
continue
}
encoded, err := json.Marshal(native)
if err != nil {
return err
}
rewritten = append(rewritten, encoded)
}
if len(pendingText) > 0 {
tail, err := flush(nil)
if err != nil {
return err
}
rewritten = append(rewritten, tail)
}
input, err := json.Marshal(rewritten)
if err != nil {
return err
}
out.Input = input
return nil
}
// userMessageWithLeadingText returns next with a separate input_text part for
// text placed ahead of its existing parts when next is a user message, and
// otherwise a new user message holding text. Existing parts stay untouched.
func userMessageWithLeadingText(next json.RawMessage, text string) (json.RawMessage, error) {
lead, err := json.Marshal(ResponsesContentPart{Type: "input_text", Text: text})
if err != nil {
return nil, err
}
var msg ResponsesInputItem
if len(next) > 0 && json.Unmarshal(next, &msg) == nil && msg.Type == "message" && msg.Role == "user" {
var parts []json.RawMessage
if json.Unmarshal(msg.Content, &parts) == nil {
content, err := json.Marshal(append([]json.RawMessage{lead}, parts...))
if err != nil {
return nil, err
}
msg.Content = content
return json.Marshal(msg)
}
}
content, err := json.Marshal([]json.RawMessage{lead})
if err != nil {
return nil, err
}
return json.Marshal(ResponsesInputItem{Type: "message", Role: "user", Content: content})
}
func forcesHiddenTool(raw json.RawMessage, deferred map[string]bool) bool {
var choice struct {
Type string `json:"type"`
Name string `json:"name"`
}
if len(raw) == 0 || json.Unmarshal(raw, &choice) != nil {
return false
}
return choice.Type == "tool" && (choice.Name == ToolSearchToolName || deferred[choice.Name])
}
// toolSearchReveals maps each ToolSearch tool_use id in the history to the
// tool names its tool_result referenced, first occurrence first.
func toolSearchReveals(msgs []AnthropicMessage) map[string][]string {
reveals := make(map[string][]string)
for _, m := range msgs {
var blocks []AnthropicContentBlock
if json.Unmarshal(m.Content, &blocks) != nil {
continue
}
for _, b := range blocks {
switch {
case b.Type == "tool_use" && b.Name == ToolSearchToolName && b.ID != "":
reveals[toResponsesCallID(b.ID)] = nil
case b.Type == "tool_result":
id := toResponsesCallID(b.ToolUseID)
if _, isSearch := reveals[id]; !isSearch {
continue
}
var inner []AnthropicContentBlock
_ = json.Unmarshal(b.Content, &inner)
seen := make(map[string]bool)
for _, ib := range inner {
if ib.Type == "tool_reference" && ib.ToolName != "" && !seen[ib.ToolName] {
seen[ib.ToolName] = true
reveals[id] = append(reveals[id], ib.ToolName)
}
}
}
}
}
return reveals
}
// toolSearchCallToolUse turns an upstream tool_search_call back into the
// ToolSearch tool_use Claude Code executes; its call_id round-trips as the
// tool_use id that the next turn's tool_result answers.
func toolSearchCallToolUse(item ResponsesOutput) AnthropicContentBlock {
return AnthropicContentBlock{
Type: "tool_use",
ID: fromResponsesCallID(item.CallID),
Name: ToolSearchToolName,
Input: jsonObjectOrEmpty(item.Arguments),
}
}
// jsonObjectOrEmpty keeps raw when it is a JSON object; both tool_search_call
// arguments and tool_use input must be objects.
func jsonObjectOrEmpty(raw string) json.RawMessage {
var probe map[string]json.RawMessage
if json.Unmarshal([]byte(raw), &probe) != nil || probe == nil {
return json.RawMessage(`{}`)
}
return json.RawMessage(raw)
}
func resToAnthHandleToolSearchDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
events := closeCurrentBlock(state)
block := toolSearchCallToolUse(*evt.Item)
input := block.Input
block.Input = json.RawMessage(`{}`)
idx := state.ContentBlockIndex
state.HasToolCall = true
events = append(events,
AnthropicStreamEvent{Type: "content_block_start", Index: &idx, ContentBlock: &block},
AnthropicStreamEvent{Type: "content_block_delta", Index: &idx, Delta: &AnthropicDelta{Type: "input_json_delta", PartialJSON: string(input)}},
AnthropicStreamEvent{Type: "content_block_stop", Index: &idx},
)
state.ContentBlockIndex++
return events
}
@@ -0,0 +1,256 @@
//go:build unit
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
const toolSearchTestSchema = `{"type":"object","properties":{"query":{"type":"string"},"max_results":{"type":"number"}},"required":["query","max_results"]}`
func toolSearchTestRequest(t *testing.T, raw string) *AnthropicRequest {
t.Helper()
var req AnthropicRequest
require.NoError(t, json.Unmarshal([]byte(raw), &req))
return &req
}
func nativeToolSearchJSON(t *testing.T, req *AnthropicRequest) []byte {
t.Helper()
out, err := AnthropicToResponses(req)
require.NoError(t, err)
require.NoError(t, ApplyNativeToolSearch(req, out))
body, err := json.Marshal(out)
require.NoError(t, err)
return body
}
// Before the reveal Claude Code sends Bash + ToolSearch; after it, the revealed
// WebFetch schema joins tools[] with defer_loading:true and the history carries
// the ToolSearch call plus its tool_reference result.
const toolSearchBeforeReveal = `{"model":"gpt-6-astra","max_tokens":64,
"tools":[
{"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}},
{"name":"ToolSearch","description":"search deferred tools","input_schema":` + toolSearchTestSchema + `}],
"messages":[{"role":"user","content":"fetch the page"}]}`
const toolSearchAfterReveal = `{"model":"gpt-6-astra","max_tokens":64,
"tools":[
{"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}},
{"name":"ToolSearch","description":"search deferred tools","input_schema":` + toolSearchTestSchema + `},
{"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object","properties":{"url":{"type":"string"}},"required":["url"]},"defer_loading":true}],
"messages":[
{"role":"user","content":"fetch the page"},
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"select:WebFetch","max_results":5}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search","content":[{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"Unknown"}]}]}]}`
func TestApplyNativeToolSearch_TopLevelToolsStableAcrossReveal(t *testing.T) {
before := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchBeforeReveal))
after := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchAfterReveal))
require.JSONEq(t, gjson.GetBytes(before, "tools").Raw, gjson.GetBytes(after, "tools").Raw,
"top-level tools must not change when a deferred tool is revealed (prompt cache prefix)")
tools := gjson.GetBytes(after, "tools").Array()
require.Len(t, tools, 2)
require.Equal(t, "function", tools[0].Get("type").String())
require.Equal(t, "Bash", tools[0].Get("name").String())
search := tools[1]
require.Equal(t, "tool_search", search.Get("type").String())
require.Equal(t, "client", search.Get("execution").String())
require.Equal(t, "search deferred tools", search.Get("description").String())
require.JSONEq(t, toolSearchTestSchema, search.Get("parameters").Raw)
require.False(t, search.Get("name").Exists(), "tool_search carries no function name")
require.False(t, search.Get("strict").Exists(), "tool_search is declared without strict")
}
func TestApplyNativeToolSearch_HistoryMapsToNativeItems(t *testing.T) {
body := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchAfterReveal))
input := gjson.GetBytes(body, "input").Array()
require.Len(t, input, 3)
call := input[1]
require.Equal(t, "tool_search_call", call.Get("type").String())
require.Equal(t, "toolu_search", call.Get("call_id").String())
require.Equal(t, "client", call.Get("execution").String())
require.Equal(t, "completed", call.Get("status").String())
require.True(t, call.Get("arguments").IsObject(), "tool_search_call arguments are a JSON object")
require.Equal(t, "select:WebFetch", call.Get("arguments.query").String())
output := input[2]
require.Equal(t, "tool_search_output", output.Get("type").String())
require.Equal(t, "toolu_search", output.Get("call_id").String())
require.Equal(t, "client", output.Get("execution").String())
require.Equal(t, "completed", output.Get("status").String())
revealed := output.Get("tools").Array()
require.Len(t, revealed, 1, "duplicate and unknown references are dropped")
require.Equal(t, "function", revealed[0].Get("type").String())
require.Equal(t, "WebFetch", revealed[0].Get("name").String())
require.Equal(t, "fetch a url", revealed[0].Get("description").String())
require.True(t, revealed[0].Get("defer_loading").Bool())
require.False(t, revealed[0].Get("strict").Bool())
require.True(t, revealed[0].Get("strict").Exists())
require.Equal(t, "url", revealed[0].Get("parameters.required.0").String())
}
func TestApplyNativeToolSearch_NoToolSearchDeclaredKeepsFunctionTools(t *testing.T) {
req := toolSearchTestRequest(t, toolSearchAfterReveal)
tools := req.Tools[:0:0]
for _, tool := range req.Tools {
if tool.Name != "ToolSearch" {
tools = append(tools, tool)
}
}
req.Tools = tools
body := nativeToolSearchJSON(t, req)
var names []string
for _, tool := range gjson.GetBytes(body, "tools").Array() {
require.Equal(t, "function", tool.Get("type").String())
names = append(names, tool.Get("name").String())
}
require.Equal(t, []string{"Bash", "WebFetch"}, names)
require.NotContains(t, string(body), "tool_search_call")
}
func TestApplyNativeToolSearch_ForcedHiddenToolLeavesRequestUntouched(t *testing.T) {
for _, name := range []string{"ToolSearch", "WebFetch"} {
for _, raw := range []string{toolSearchBeforeReveal, toolSearchAfterReveal} {
req := toolSearchTestRequest(t, raw)
if name == "WebFetch" {
req.Tools = append(req.Tools, AnthropicTool{Name: "WebFetch", InputSchema: json.RawMessage(`{"type":"object"}`), DeferLoading: true})
}
req.ToolChoice = json.RawMessage(`{"type":"tool","name":"` + name + `"}`)
want, err := AnthropicToResponses(req)
require.NoError(t, err)
wantBody, err := json.Marshal(want)
require.NoError(t, err)
require.Equal(t, string(wantBody), string(nativeToolSearchJSON(t, req)), name)
require.NotContains(t, string(wantBody), "tool_search", name)
}
}
}
func TestApplyNativeToolSearch_OtherToolChoicesKeepNativeMapping(t *testing.T) {
for _, choice := range []string{
`{"type":"tool","name":"Bash"}`,
`{"type":"auto"}`,
`{"type":"any"}`,
} {
req := toolSearchTestRequest(t, toolSearchAfterReveal)
req.ToolChoice = json.RawMessage(choice)
body := nativeToolSearchJSON(t, req)
require.Equal(t, "tool_search", gjson.GetBytes(body, "tools.1.type").String(), choice)
require.Contains(t, string(body), "tool_search_output", choice)
}
}
func toolSearchResultRequest(t *testing.T, result string, trailing string) *AnthropicRequest {
t.Helper()
return toolSearchTestRequest(t, `{"model":"gpt-6-astra","max_tokens":64,
"tools":[
{"name":"ToolSearch","description":"search deferred tools","input_schema":`+toolSearchTestSchema+`},
{"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object"},"defer_loading":true}],
"messages":[
{"role":"user","content":"fetch the page"},
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"x","max_results":5}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search",`+result+`}`+trailing+`]}]}`)
}
func TestApplyNativeToolSearch_ResultTextRidesInFollowingUserMessage(t *testing.T) {
cases := []struct {
name, result, trailing, wantText, wantUser string
wantTools int
}{
{"error", `"is_error":true,"content":"<tool_use_error>InputValidationError</tool_use_error>"`, "", "<tool_use_error>InputValidationError</tool_use_error>", "", 0},
{"no match string", `"content":"No matching deferred tools found"`, "", "No matching deferred tools found", "", 0},
{"text with reference", `"content":[{"type":"text","text":"found one"},{"type":"tool_reference","tool_name":"WebFetch"}]`, "", "found one", "", 1},
{"separate part ahead of following text", `"content":"No matching deferred tools found"`, `,{"type":"text","text":"retry"}`, "No matching deferred tools found", "retry", 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
body := nativeToolSearchJSON(t, toolSearchResultRequest(t, tc.result, tc.trailing))
input := gjson.GetBytes(body, "input").Array()
require.Len(t, input, 4)
require.Equal(t, "tool_search_call", input[1].Get("type").String())
require.Equal(t, "tool_search_output", input[2].Get("type").String())
require.Len(t, input[2].Get("tools").Array(), tc.wantTools)
require.Equal(t, "message", input[3].Get("type").String())
require.Equal(t, "user", input[3].Get("role").String())
parts := input[3].Get("content").Array()
require.Equal(t, tc.wantText, parts[0].Get("text").String())
if tc.wantUser == "" {
require.Len(t, parts, 1)
return
}
require.Len(t, parts, 2)
require.Equal(t, `{"type":"input_text","text":"`+tc.wantUser+`"}`, parts[1].Raw)
})
}
t.Run("reference only adds no message", func(t *testing.T) {
body := nativeToolSearchJSON(t, toolSearchResultRequest(t, `"content":[{"type":"tool_reference","tool_name":"WebFetch"}]`, ""))
require.Len(t, gjson.GetBytes(body, "input").Array(), 3)
})
}
func TestResponsesToAnthropic_RestoresToolSearchCall(t *testing.T) {
var resp ResponsesResponse
require.NoError(t, json.Unmarshal([]byte(`{"id":"resp_1","status":"completed","output":[
{"type":"tool_search_call","call_id":"call_search","execution":"client","status":"completed","arguments":{"query":"select:WebFetch","max_results":5}}]}`), &resp))
out := ResponsesToAnthropic(&resp, "gpt-6-astra")
require.Len(t, out.Content, 1)
block := out.Content[0]
require.Equal(t, "tool_use", block.Type)
require.Equal(t, "call_search", block.ID)
require.Equal(t, "ToolSearch", block.Name)
require.JSONEq(t, `{"query":"select:WebFetch","max_results":5}`, string(block.Input))
require.Equal(t, "tool_use", AnthropicStopReasonString(out.StopReason))
}
func TestResponsesEventToAnthropic_RestoresToolSearchCall(t *testing.T) {
state := NewResponsesEventToAnthropicState()
var events []AnthropicStreamEvent
for _, raw := range []string{
`{"type":"response.created","response":{"id":"resp_1","model":"gpt-6-astra"}}`,
`{"type":"response.output_item.added","output_index":0,"item":{"type":"tool_search_call","call_id":"call_search","execution":"client"}}`,
`{"type":"response.output_item.done","output_index":0,"item":{"type":"tool_search_call","call_id":"call_search","execution":"client","status":"completed","arguments":{"query":"docs","max_results":5}}}`,
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`,
} {
var evt ResponsesStreamEvent
require.NoError(t, json.Unmarshal([]byte(raw), &evt))
events = append(events, ResponsesEventToAnthropicEvents(&evt, state)...)
}
var start, delta, stop *AnthropicStreamEvent
for i := range events {
switch events[i].Type {
case "content_block_start":
start = &events[i]
case "content_block_delta":
delta = &events[i]
case "content_block_stop":
stop = &events[i]
}
}
require.NotNil(t, start)
require.Equal(t, "tool_use", start.ContentBlock.Type)
require.Equal(t, "call_search", start.ContentBlock.ID)
require.Equal(t, "ToolSearch", start.ContentBlock.Name)
require.NotNil(t, delta)
require.Equal(t, "input_json_delta", delta.Delta.Type)
require.JSONEq(t, `{"query":"docs","max_results":5}`, delta.Delta.PartialJSON)
require.NotNil(t, stop)
require.Equal(t, *start.Index, *stop.Index)
last := events[len(events)-2]
require.Equal(t, "message_delta", last.Type)
require.Equal(t, "tool_use", last.Delta.StopReason)
}
@@ -0,0 +1,32 @@
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// A system message in the middle of an Anthropic conversation (e.g. hook
// output) must reach Responses as a developer item, not as user input.
func TestAnthropicToResponses_MidConversationSystemBecomesDeveloper(t *testing.T) {
out, err := AnthropicToResponses(&AnthropicRequest{
Model: "gpt-5.2",
MaxTokens: 64,
Messages: []AnthropicMessage{
{Role: "user", Content: json.RawMessage(`"hi"`)},
{Role: "system", Content: json.RawMessage(`[{"type":"text","text":"hook output"}]`)},
{Role: "system", Content: json.RawMessage(`"extra context"`)},
},
})
require.NoError(t, err)
input := gjson.ParseBytes(out.Input).Array()
require.Len(t, input, 3)
require.Equal(t, "user", input[0].Get("role").String())
require.Equal(t, "developer", input[1].Get("role").String())
require.Equal(t, "hook output", input[1].Get("content.0.text").String())
require.Equal(t, "developer", input[2].Get("role").String())
require.Equal(t, "extra context", input[2].Get("content.0.text").String())
}
@@ -411,6 +411,7 @@ func ChatCompletionsResponseToAnthropic(resp *ChatCompletionsResponse, model str
Type: "message",
Role: "assistant",
Model: model,
Usage: chatUsageToAnthropicUsage(nil),
}
if resp != nil {
@@ -517,21 +518,13 @@ func chatFinishReasonToAnthropicStopReason(reason string, blocks []AnthropicCont
// usage shape. Mirrors ChatUsageToResponsesUsage + anthropicUsageFromResponsesUsage.
func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage {
if usage == nil {
return AnthropicUsage{}
return AnthropicUsage{CacheCreationInputTokensPresent: true, CacheReadInputTokensPresent: true}
}
cachedTokens := 0
cacheCreationTokens := 0
cacheCreationTokens := usage.PromptTokensDetails.cacheCreationInputTokens()
if usage.PromptTokensDetails != nil {
cachedTokens = usage.PromptTokensDetails.CachedTokens
// cache_write_tokens and cache_creation_tokens are alternate spellings of
// the same quantity, not additive; the double-conversion path
// (ChatUsageToResponsesUsage) prefers write and falls back to creation.
if usage.PromptTokensDetails.CacheWriteTokens > 0 {
cacheCreationTokens = usage.PromptTokensDetails.CacheWriteTokens
} else {
cacheCreationTokens = usage.PromptTokensDetails.CacheCreationTokens
}
}
inputTokens := usage.PromptTokens - cachedTokens - cacheCreationTokens
@@ -540,10 +533,12 @@ func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage {
}
return AnthropicUsage{
InputTokens: inputTokens,
OutputTokens: usage.CompletionTokens,
CacheReadInputTokens: cachedTokens,
CacheCreationInputTokens: cacheCreationTokens,
InputTokens: inputTokens,
OutputTokens: usage.CompletionTokens,
CacheReadInputTokens: cachedTokens,
CacheCreationInputTokens: cacheCreationTokens,
CacheCreationInputTokensPresent: true,
CacheReadInputTokensPresent: true,
}
}
@@ -714,10 +709,12 @@ func FinalizeChatCompletionsAnthropicStream(state *ChatCompletionsToAnthropicStr
StopReason: stopReason,
},
Usage: &AnthropicUsage{
InputTokens: state.InputTokens,
OutputTokens: state.OutputTokens,
CacheReadInputTokens: state.CacheReadInputTokens,
CacheCreationInputTokens: state.CacheCreationInputTokens,
InputTokens: state.InputTokens,
OutputTokens: state.OutputTokens,
CacheReadInputTokens: state.CacheReadInputTokens,
CacheCreationInputTokens: state.CacheCreationInputTokens,
CacheCreationInputTokensPresent: true,
CacheReadInputTokensPresent: true,
},
},
AnthropicStreamEvent{Type: "message_stop"},
@@ -741,7 +738,7 @@ func ensureCCAnthropicMessageStart(state *ChatCompletionsToAnthropicStreamState)
Content: []AnthropicContentBlock{},
Model: state.Model,
StopReason: nil, // JSON null; never ""
Usage: AnthropicUsage{InputTokens: 0, OutputTokens: 0},
Usage: chatUsageToAnthropicUsage(nil),
},
}}
}
@@ -61,6 +61,7 @@ func ResponsesToChatCompletionsRequestWithOptions(req *ResponsesRequest, opts *R
Stream: req.Stream,
ServiceTier: req.ServiceTier,
ParallelToolCalls: req.ParallelToolCalls,
Stop: req.Stop,
}
if req.Reasoning != nil {
out.ReasoningEffort = req.Reasoning.Effort
@@ -1537,9 +1538,10 @@ func ChatUsageToResponsesUsage(usage *ChatUsage) *ResponsesUsage {
return nil
}
out := &ResponsesUsage{
InputTokens: usage.PromptTokens,
OutputTokens: usage.CompletionTokens,
TotalTokens: usage.TotalTokens,
InputTokens: usage.PromptTokens,
OutputTokens: usage.CompletionTokens,
TotalTokens: usage.TotalTokens,
CacheCreationInputTokens: usage.PromptTokensDetails.cacheCreationInputTokens(),
}
if out.TotalTokens == 0 {
out.TotalTokens = out.InputTokens + out.OutputTokens
@@ -1551,10 +1553,9 @@ func ChatUsageToResponsesUsage(usage *ChatUsage) *ResponsesUsage {
CacheCreationTokens: usage.PromptTokensDetails.CacheCreationTokens,
CacheWriteTokens: usage.PromptTokensDetails.CacheWriteTokens,
}
if usage.PromptTokensDetails.CacheWriteTokens > 0 {
out.CacheCreationInputTokens = usage.PromptTokensDetails.CacheWriteTokens
} else {
out.CacheCreationInputTokens = usage.PromptTokensDetails.CacheCreationTokens
if out.CacheCreationInputTokens == 0 {
out.InputTokensDetails.CacheCreationTokens = 0
out.InputTokensDetails.CacheWriteTokens = 0
}
}
return out
@@ -445,6 +445,38 @@ func TestChatCompletionsToResponses_ResponseFormatJsonSchema(t *testing.T) {
}`, string(resp.Text.Format))
}
func TestChatCompletionsToResponses_ResponseFormatJsonSchemaDefaultsStrictFalse(t *testing.T) {
req := &ChatCompletionsRequest{
Model: "gpt-4o",
Messages: []ChatMessage{{Role: "user", Content: json.RawMessage(`"Return structured JSON"`)}},
ResponseFormat: json.RawMessage(`{
"type":"json_schema",
"json_schema":{
"name":"answer",
"schema":{
"type":"object",
"properties":{"ok":{"type":"boolean"}},
"required":["ok"]
}
}
}`),
}
resp, err := ChatCompletionsToResponses(req)
require.NoError(t, err)
require.NotNil(t, resp.Text)
assert.JSONEq(t, `{
"type":"json_schema",
"name":"answer",
"schema":{
"type":"object",
"properties":{"ok":{"type":"boolean"}},
"required":["ok"]
},
"strict":false
}`, string(resp.Text.Format))
}
func TestChatCompletionsToResponses_ImageURL(t *testing.T) {
content := `[{"type":"text","text":"Describe this"},{"type":"image_url","image_url":{"url":"data:image/png;base64,abc123"}}]`
req := &ChatCompletionsRequest{
@@ -23,6 +23,11 @@ func chatResponseFormatToResponsesTextFormat(raw json.RawMessage) json.RawMessag
return raw
}
schema["type"] = rawJSONString("json_schema")
// Chat Completions defaults strict to false while Responses defaults to strict,
// so make the intended mode explicit to avoid the upstream rejecting the schema.
if _, ok := schema["strict"]; !ok {
schema["strict"] = json.RawMessage("false")
}
out, err := json.Marshal(schema)
if err != nil {
@@ -1,6 +1,7 @@
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
@@ -97,3 +98,101 @@ func TestAnthropicToResponsesResponse_CacheCreation(t *testing.T) {
assert.Equal(t, 20, out.Usage.InputTokens, "total = input(10) + cache_read(4) + cache_creation(6)")
assert.Equal(t, 6, out.Usage.CacheCreationInputTokens, "cache creation must round-trip")
}
func TestAnthropicUsageDecodesCacheCreationBreakdown(t *testing.T) {
var usage AnthropicUsage
require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":7}}`), &usage))
require.NotNil(t, usage.CacheCreation)
require.NotNil(t, usage.CacheCreation.Ephemeral5mInputTokens)
require.NotNil(t, usage.CacheCreation.Ephemeral1hInputTokens)
assert.Equal(t, 0, *usage.CacheCreation.Ephemeral5mInputTokens)
assert.Equal(t, 7, *usage.CacheCreation.Ephemeral1hInputTokens)
}
func TestAnthropicToResponsesResponse_UsesCacheCreationBreakdown(t *testing.T) {
fiveMinutes := 2
oneHour := 3
resp := AnthropicResponse{Usage: AnthropicUsage{
InputTokens: 10,
CacheCreation: &AnthropicCacheCreation{
Ephemeral5mInputTokens: &fiveMinutes,
Ephemeral1hInputTokens: &oneHour,
},
}}
out := AnthropicToResponsesResponse(&resp)
require.NotNil(t, out.Usage)
assert.Equal(t, 15, out.Usage.InputTokens)
assert.Equal(t, 5, out.Usage.CacheCreationInputTokens)
}
func TestAnthropicEventToResponsesEvents_MergesCacheCreationBreakdown(t *testing.T) {
tests := []struct {
name string
delta string
want5m int
want1h int
wantTotal int
}{
{"explicit_1h_zero", `{"cache_creation":{"ephemeral_1h_input_tokens":0}}`, 2, 0, 2},
{"explicit_5m_zero", `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, 0, 3, 3},
{"omitted_details", `{}`, 2, 3, 5},
{"empty_details", `{"cache_creation":{}}`, 2, 3, 5},
{"legacy_aggregate_after_details", `{"cache_creation_input_tokens":99}`, 2, 3, 99},
{"explicit_both_zero", `{"cache_creation_input_tokens":99,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}`, 0, 0, 99},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var startUsage, deltaUsage AnthropicUsage
require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_read_input_tokens":4,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}`), &startUsage))
require.NoError(t, json.Unmarshal([]byte(test.delta), &deltaUsage))
state := NewAnthropicEventToResponsesState()
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
Type: "message_start",
Message: &AnthropicResponse{ID: "msg_test", Usage: startUsage},
}, state)
assert.Equal(t, 5, state.CacheCreationInputTokens)
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &deltaUsage}, state)
require.NotNil(t, state.CacheCreation.Ephemeral5mInputTokens)
require.NotNil(t, state.CacheCreation.Ephemeral1hInputTokens)
assert.Equal(t, test.want5m, *state.CacheCreation.Ephemeral5mInputTokens)
assert.Equal(t, test.want1h, *state.CacheCreation.Ephemeral1hInputTokens)
assert.Equal(t, test.wantTotal, state.CacheCreationInputTokens)
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7},
}, state)
events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)
require.Len(t, events, 1)
require.Equal(t, "response.completed", events[0].Type)
require.NotNil(t, events[0].Response)
usage := events[0].Response.Usage
require.NotNil(t, usage)
assert.Equal(t, test.wantTotal, usage.CacheCreationInputTokens)
assert.Equal(t, 14+test.wantTotal, usage.InputTokens)
assert.Equal(t, 7, usage.OutputTokens)
assert.Equal(t, 21+test.wantTotal, usage.TotalTokens)
})
}
}
func TestAnthropicEventToResponsesEvents_CacheCreationLegacyFallback(t *testing.T) {
state := NewAnthropicEventToResponsesState()
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
Type: "message_start",
Message: &AnthropicResponse{Usage: AnthropicUsage{InputTokens: 10, CacheCreationInputTokens: 5}},
}, state)
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
Type: "message_delta", Usage: &AnthropicUsage{CacheCreationInputTokens: 6, CacheCreation: &AnthropicCacheCreation{}},
}, state)
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7}}, state)
assert.Nil(t, state.CacheCreation.Ephemeral5mInputTokens)
assert.Nil(t, state.CacheCreation.Ephemeral1hInputTokens)
events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)
require.Len(t, events, 1)
require.NotNil(t, events[0].Response)
require.NotNil(t, events[0].Response.Usage)
assert.Equal(t, 6, events[0].Response.Usage.CacheCreationInputTokens)
assert.Equal(t, 16, events[0].Response.Usage.InputTokens)
}
@@ -0,0 +1,24 @@
package apicompat
import "strings"
// IsServerSideSearchCall reports whether a Responses output item is a search
// that the xAI server runs itself, so the client has nothing to execute.
//
// xAI documents the Responses API form of X Search as a custom_tool_call whose
// call_id starts with xs_, and attachment search as one whose call_id starts
// with as_; both are "handled by the xAI server"
// (https://docs.x.ai/developers/tools/tool-usage-details, "Using Responses API"
// table; https://docs.x.ai/developers/tools/x-search, "How X Search Works").
// A custom_tool_call without these prefixes is a client tool call.
//
// This is the only place the prefix rule lives. Converters that turn
// custom_tool_call items into client tool calls skip items for which it
// returns true when the caller says the upstream is xAI, and Grok search
// counting includes them.
func IsServerSideSearchCall(itemType, callID string) bool {
if itemType != "custom_tool_call" {
return false
}
return strings.HasPrefix(callID, "xs_") || strings.HasPrefix(callID, "as_")
}
@@ -0,0 +1,189 @@
package apicompat
import (
"testing"
"github.com/stretchr/testify/require"
)
// serverSideSearchStream is the event sequence of one custom_tool_call item
// followed by a text answer, in the shape xAI documents for X Search.
func serverSideSearchStream(callID, name string) []*ResponsesStreamEvent {
item := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_1", CallID: callID, Name: name, Input: `{"query":"q"}`, Status: "completed"}
added := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_1", CallID: callID, Name: name}
message := ResponsesOutput{Type: "message", ID: "msg_1", Role: "assistant", Content: []ResponsesContentPart{{Type: "output_text", Text: "found it"}}}
return []*ResponsesStreamEvent{
{Type: "response.created", Response: &ResponsesResponse{ID: "resp_1"}},
{Type: "response.output_item.added", OutputIndex: 0, Item: &added},
{Type: "response.custom_tool_call_input.delta", OutputIndex: 0, ItemID: "ctc_1", Delta: `{"query":"q"}`},
{Type: "response.custom_tool_call_input.done", OutputIndex: 0, ItemID: "ctc_1", Input: `{"query":"q"}`},
{Type: "response.output_item.done", OutputIndex: 0, Item: &item},
{Type: "response.output_text.delta", OutputIndex: 1, Delta: "found it"},
{Type: "response.output_item.done", OutputIndex: 1, Item: &message},
{Type: "response.completed", Response: &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{item, message}}},
}
}
func anthropicEventsOf(events []*ResponsesStreamEvent, xai bool) []AnthropicStreamEvent {
state := NewResponsesEventToAnthropicState()
state.XAIServerSideSearch = xai
var out []AnthropicStreamEvent
for _, event := range events {
out = append(out, ResponsesEventToAnthropicEvents(event, state)...)
}
return out
}
func chatChunksOf(events []*ResponsesStreamEvent, xai bool) []ChatCompletionsChunk {
state := NewResponsesEventToChatState()
state.XAIServerSideSearch = xai
var out []ChatCompletionsChunk
for _, event := range events {
out = append(out, ResponsesEventToChatChunks(event, state)...)
}
return out
}
func anthropicToolUseStarts(events []AnthropicStreamEvent) int {
count := 0
for _, event := range events {
if event.Type == "content_block_start" && event.ContentBlock != nil && event.ContentBlock.Type == "tool_use" {
count++
}
}
return count
}
func anthropicStopReason(events []AnthropicStreamEvent) string {
for _, event := range events {
if event.Type == "message_delta" && event.Delta != nil {
return event.Delta.StopReason
}
}
return ""
}
func chatToolCallChunks(chunks []ChatCompletionsChunk) int {
count := 0
for _, chunk := range chunks {
for _, choice := range chunk.Choices {
count += len(choice.Delta.ToolCalls)
}
}
return count
}
func chatFinishReason(chunks []ChatCompletionsChunk) string {
for _, chunk := range chunks {
for _, choice := range chunk.Choices {
if choice.FinishReason != nil {
return *choice.FinishReason
}
}
}
return ""
}
func TestResponsesEventToAnthropicEvents_ServerSideSearchIsNotToolUse(t *testing.T) {
for _, tt := range []struct {
name, callID, toolName string
xai bool
wantToolUse int
wantStop string
}{
{"x search", "xs_123", "x_keyword_search", true, 0, "end_turn"},
{"attachment search", "as_456", "attachment_search", true, 0, "end_turn"},
{"client custom tool", "call_9", "exec", true, 1, "tool_use"},
{"x search call id on a non-xAI upstream", "xs_123", "x_keyword_search", false, 1, "tool_use"},
{"attachment search call id on a non-xAI upstream", "as_456", "attachment_search", false, 1, "tool_use"},
} {
t.Run(tt.name, func(t *testing.T) {
events := anthropicEventsOf(serverSideSearchStream(tt.callID, tt.toolName), tt.xai)
require.Equal(t, tt.wantToolUse, anthropicToolUseStarts(events))
require.Equal(t, tt.wantStop, anthropicStopReason(events))
})
}
}
func TestResponsesEventToAnthropicEvents_ServerSideSearchKeepsClientToolCall(t *testing.T) {
stream := serverSideSearchStream("xs_123", "x_keyword_search")
client := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_2", CallID: "call_9", Name: "exec", Input: "dir"}
clientAdded := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_2", CallID: "call_9", Name: "exec"}
mixed := append([]*ResponsesStreamEvent{}, stream[:len(stream)-1]...)
mixed = append(mixed,
&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: 2, Item: &clientAdded},
&ResponsesStreamEvent{Type: "response.custom_tool_call_input.delta", OutputIndex: 2, ItemID: "ctc_2", Delta: "dir"},
&ResponsesStreamEvent{Type: "response.output_item.done", OutputIndex: 2, Item: &client},
&ResponsesStreamEvent{Type: "response.completed", Response: &ResponsesResponse{ID: "resp_1", Status: "completed"}},
)
events := anthropicEventsOf(mixed, true)
require.Equal(t, 1, anthropicToolUseStarts(events))
require.Equal(t, "tool_use", anthropicStopReason(events))
}
func TestResponsesEventToChatChunks_ServerSideSearchIsNotToolCall(t *testing.T) {
for _, tt := range []struct {
name, callID, toolName string
xai bool
wantToolCalls int
wantFinish string
}{
{"x search", "xs_123", "x_keyword_search", true, 0, "stop"},
{"attachment search", "as_456", "attachment_search", true, 0, "stop"},
{"client custom tool", "call_9", "exec", true, 2, "tool_calls"},
{"x search call id on a non-xAI upstream", "xs_123", "x_keyword_search", false, 2, "tool_calls"},
{"attachment search call id on a non-xAI upstream", "as_456", "attachment_search", false, 2, "tool_calls"},
} {
t.Run(tt.name, func(t *testing.T) {
chunks := chatChunksOf(serverSideSearchStream(tt.callID, tt.toolName), tt.xai)
// A client call is announced once and then carries its input delta.
require.Equal(t, tt.wantToolCalls, chatToolCallChunks(chunks))
require.Equal(t, tt.wantFinish, chatFinishReason(chunks))
})
}
}
func TestBufferedResponseAccumulator_ServerSideSearchIsNotRebuiltAsFunctionCall(t *testing.T) {
rebuild := func(callID, name string, xai bool) []ResponsesOutput {
acc := NewBufferedResponseAccumulator()
acc.XAIServerSideSearch = xai
for _, event := range serverSideSearchStream(callID, name) {
if event.Type == "response.completed" {
continue
}
acc.ProcessEvent(event)
}
resp := &ResponsesResponse{ID: "resp_1", Status: "completed"}
acc.SupplementResponseOutput(resp)
return resp.Output
}
client := rebuild("call_9", "exec", true)
require.Equal(t, "function_call", client[len(client)-1].Type)
require.Equal(t, "call_9", client[len(client)-1].CallID)
for _, callID := range []string{"xs_123", "as_456"} {
notXAI := rebuild(callID, "x_keyword_search", false)
require.Equal(t, "function_call", notXAI[len(notXAI)-1].Type, "without the xAI switch the item is rebuilt as before")
output := rebuild(callID, "x_keyword_search", true)
for _, item := range output {
require.NotEqual(t, "function_call", item.Type, "a server-side search is not a client function call")
}
last := output[len(output)-1]
require.Equal(t, "custom_tool_call", last.Type)
require.Equal(t, callID, last.CallID)
require.Equal(t, `{"query":"q"}`, last.Input)
resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: output}
message := ResponsesToAnthropic(resp, "m")
require.Equal(t, "end_turn", *message.StopReason)
for _, block := range message.Content {
require.NotEqual(t, "tool_use", block.Type)
}
chat := ResponsesToChatCompletions(resp, "m")
require.Empty(t, chat.Choices[0].Message.ToolCalls)
require.Equal(t, "stop", chat.Choices[0].FinishReason)
}
}
@@ -0,0 +1,30 @@
package apicompat
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestIsServerSideSearchCall(t *testing.T) {
tests := []struct {
name string
itemType string
callID string
want bool
}{
{"x search", "custom_tool_call", "xs_123", true},
{"attachment search", "custom_tool_call", "as_456", true},
{"padded call id is not a prefix match", "custom_tool_call", " xs_123", false},
{"client custom tool", "custom_tool_call", "call_9", false},
{"prefix is not a substring", "custom_tool_call", "call_xs_9", false},
{"no call id", "custom_tool_call", "", false},
{"function call keeps its client meaning", "function_call", "xs_123", false},
{"other server-side item types are separate items", "x_search_call", "xs_123", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, IsServerSideSearchCall(tt.itemType, tt.callID))
})
}
}
@@ -20,6 +20,7 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo
Type: "message",
Role: "assistant",
Model: model,
Usage: anthropicUsageFromResponsesUsage(nil),
}
var blocks []AnthropicContentBlock
@@ -52,9 +53,24 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo
Type: "tool_use",
ID: fromResponsesCallID(item.CallID),
Name: item.Name,
Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments),
Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments),
})
case "custom_tool_call":
if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) {
continue
}
blocks = append(blocks, AnthropicContentBlock{
Type: "tool_use",
ID: fromResponsesCallID(item.CallID),
Name: item.Name,
Input: anthropicToolUseInput(item.Type, item.Name, item.Input),
})
case "tool_search_call":
blocks = append(blocks, toolSearchCallToolUse(item))
case "web_search_call":
if item.Status != "completed" {
continue
}
toolUseID := "srvtoolu_" + item.ID
query := ""
if item.Action != nil {
@@ -67,11 +83,10 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo
Name: "web_search",
Input: inputJSON,
})
emptyResults, _ := json.Marshal([]struct{}{})
blocks = append(blocks, AnthropicContentBlock{
Type: "web_search_tool_result",
ToolUseID: toolUseID,
Content: emptyResults,
Content: webSearchCallResults(&item),
})
}
}
@@ -92,7 +107,7 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo
func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage {
if usage == nil {
return AnthropicUsage{}
return AnthropicUsage{CacheCreationInputTokensPresent: true, CacheReadInputTokensPresent: true}
}
cachedTokens := 0
@@ -106,10 +121,12 @@ func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage {
}
return AnthropicUsage{
InputTokens: inputTokens,
OutputTokens: usage.OutputTokens,
CacheReadInputTokens: cachedTokens,
CacheCreationInputTokens: usage.CacheCreationInputTokens,
InputTokens: inputTokens,
OutputTokens: usage.OutputTokens,
CacheReadInputTokens: cachedTokens,
CacheCreationInputTokens: usage.CacheCreationInputTokens,
CacheCreationInputTokensPresent: true,
CacheReadInputTokensPresent: true,
}
}
@@ -139,6 +156,26 @@ func containsAnthropicToolUseBlock(blocks []AnthropicContentBlock) bool {
return false
}
// anthropicToolUseInput returns the input of a non-streaming tool_use block,
// which must be a JSON object. An object is kept as it is. A function_call whose
// arguments are not an object (truncated by max_output_tokens, or empty) gets {};
// a custom_tool_call's free-form input is wrapped in the same {"input": ...}
// shape that downgrades a custom tool to a function tool, so that
// extractCustomToolCallInput gives the text back; an empty custom input is {} as
// it is in the streamed tool_use.
func anthropicToolUseInput(itemType, name, raw string) json.RawMessage {
if trimmed := strings.TrimSpace(raw); strings.HasPrefix(trimmed, "{") && json.Valid([]byte(trimmed)) {
return sanitizeAnthropicToolUseInput(name, raw)
}
if itemType == "custom_tool_call" && raw != "" {
wrapped, err := json.Marshal(map[string]string{"input": raw})
if err == nil {
return wrapped
}
}
return json.RawMessage("{}")
}
func sanitizeAnthropicToolUseInput(name string, raw string) json.RawMessage {
if name != "Read" || raw == "" {
return json.RawMessage(raw)
@@ -190,6 +227,11 @@ type ResponsesEventToAnthropicState struct {
PendingThinkingSignature string
HasToolCall bool
// XAIServerSideSearch is set by callers whose upstream is xAI. A
// custom_tool_call that IsServerSideSearchCall then never becomes a tool_use
// block, because xAI runs it itself.
XAIServerSideSearch bool
// OutputIndexToBlockIdx maps Responses output_index → Anthropic content block index.
OutputIndexToBlockIdx map[int]int
@@ -282,10 +324,12 @@ func FinalizeResponsesAnthropicStream(state *ResponsesEventToAnthropicState) []A
StopReason: stopReason,
},
Usage: &AnthropicUsage{
InputTokens: state.InputTokens,
OutputTokens: state.OutputTokens,
CacheReadInputTokens: state.CacheReadInputTokens,
CacheCreationInputTokens: state.CacheCreationInputTokens,
InputTokens: state.InputTokens,
OutputTokens: state.OutputTokens,
CacheReadInputTokens: state.CacheReadInputTokens,
CacheCreationInputTokens: state.CacheCreationInputTokens,
CacheCreationInputTokensPresent: true,
CacheReadInputTokensPresent: true,
},
},
AnthropicStreamEvent{Type: "message_stop"},
@@ -333,8 +377,10 @@ func resToAnthHandleCreated(evt *ResponsesStreamEvent, state *ResponsesEventToAn
Model: state.Model,
StopReason: nil,
Usage: AnthropicUsage{
InputTokens: 0,
OutputTokens: 0,
InputTokens: 0,
OutputTokens: 0,
CacheCreationInputTokensPresent: true,
CacheReadInputTokensPresent: true,
},
},
}}
@@ -349,6 +395,9 @@ func resToAnthHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE
// function_call 与 custom_tool_call(custom/freeform 工具,如新版 apply_patch)
// 同样映射为 Anthropic 的 tool_use 块。
case "function_call", "custom_tool_call":
if state.XAIServerSideSearch && IsServerSideSearchCall(evt.Item.Type, evt.Item.CallID) {
return nil
}
var events []AnthropicStreamEvent
events = append(events, closeCurrentBlock(state)...)
@@ -623,6 +672,10 @@ func resToAnthHandleOutputItemDone(evt *ResponsesStreamEvent, state *ResponsesEv
if evt.Item.Type == "web_search_call" && evt.Item.Status == "completed" {
return resToAnthHandleWebSearchDone(evt, state)
}
// The native tool_search_call carries its arguments only on done.
if evt.Item.Type == "tool_search_call" {
return resToAnthHandleToolSearchDone(evt, state)
}
// Capture encrypted_content on reasoning item done (often only present here).
if evt.Item.Type == "reasoning" {
@@ -670,9 +723,6 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve
state.ContentBlockIndex++
// Emit web_search_tool_result block (start + stop).
// Content is empty because OpenAI does not expose individual search results;
// the model consumes them internally and produces text output.
emptyResults, _ := json.Marshal([]struct{}{})
idx2 := state.ContentBlockIndex
events = append(events, AnthropicStreamEvent{
Type: "content_block_start",
@@ -680,7 +730,7 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve
ContentBlock: &AnthropicContentBlock{
Type: "web_search_tool_result",
ToolUseID: toolUseID,
Content: emptyResults,
Content: webSearchCallResults(evt.Item),
},
})
events = append(events, AnthropicStreamEvent{
@@ -768,10 +818,12 @@ func resToAnthHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo
StopReason: stopReason,
},
Usage: &AnthropicUsage{
InputTokens: state.InputTokens,
OutputTokens: state.OutputTokens,
CacheReadInputTokens: state.CacheReadInputTokens,
CacheCreationInputTokens: state.CacheCreationInputTokens,
InputTokens: state.InputTokens,
OutputTokens: state.OutputTokens,
CacheReadInputTokens: state.CacheReadInputTokens,
CacheCreationInputTokens: state.CacheCreationInputTokens,
CacheCreationInputTokensPresent: true,
CacheReadInputTokensPresent: true,
},
},
AnthropicStreamEvent{Type: "message_stop"},
@@ -0,0 +1,80 @@
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestAnthropicToolUseInput(t *testing.T) {
tests := []struct {
name string
itemType string
raw string
want string
}{
{"object kept", "function_call", "{\"a\":1}", "{\"a\":1}"},
{"object with padding kept", "function_call", " {\"a\": 1}\n", " {\"a\": 1}\n"},
{"truncated function arguments", "function_call", "{\"a\":1", "{}"},
{"empty function arguments", "function_call", "", "{}"},
{"non-object function arguments", "function_call", "[1]", "{}"},
{"custom input wrapped", "custom_tool_call", "dir /b", "{\"input\":\"dir /b\"}"},
{"empty custom input is an empty object", "custom_tool_call", "", "{}"},
{"custom input that is an object kept", "custom_tool_call", "{\"a\":1}", "{\"a\":1}"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := anthropicToolUseInput(tc.itemType, "exec", tc.raw)
require.Equal(t, tc.want, string(got))
require.True(t, json.Valid(got))
})
}
}
// The wrapper must round-trip through the helper that undoes the custom tool
// downgrade, including text that is itself valid JSON or has outer whitespace.
func TestAnthropicToolUseInputCustomRoundTrip(t *testing.T) {
for _, text := range []string{"dir", " padded text\n", "", "\"quoted\"", "[1,2]", "line1\nline2"} {
wrapped := anthropicToolUseInput("custom_tool_call", "exec", text)
require.Equal(t, text, extractCustomToolCallInput(string(wrapped)), text)
}
}
func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) {
resp := &ResponsesResponse{ID: "resp_1", Status: "incomplete", IncompleteDetails: &ResponsesIncompleteDetails{Reason: "max_output_tokens"}, Output: []ResponsesOutput{
{Type: "reasoning", Summary: []ResponsesSummary{{Type: "summary_text", Text: "plan"}}},
{Type: "function_call", CallID: "call_1", Name: "get", Arguments: "{\"a\":1"},
{Type: "custom_tool_call", CallID: "call_2", Name: "exec", Input: "dir"},
}, RenderCustomToolCalls: true}
out := ResponsesToAnthropic(resp, "m")
body, err := json.Marshal(out)
require.NoError(t, err)
require.Len(t, out.Content, 3)
require.Equal(t, "thinking", out.Content[0].Type)
require.Equal(t, "{}", string(out.Content[1].Input))
require.Equal(t, "{\"input\":\"dir\"}", string(out.Content[2].Input))
require.Equal(t, "max_tokens", *out.StopReason, string(body))
}
func TestResponsesToChatCompletionsRendersCustomToolCall(t *testing.T) {
resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{
{Type: "custom_tool_call", CallID: "call_1", Name: "exec", Input: "dir"},
}, RenderCustomToolCalls: true}
out := ResponsesToChatCompletions(resp, "m")
require.Len(t, out.Choices[0].Message.ToolCalls, 1)
require.Equal(t, "dir", out.Choices[0].Message.ToolCalls[0].Function.Arguments)
require.Equal(t, "tool_calls", out.Choices[0].FinishReason)
}
// An output the upstream delivered keeps custom_tool_call items unrendered.
func TestResponsesToAnthropicAndChatSkipDeliveredCustomToolCall(t *testing.T) {
resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{
{Type: "custom_tool_call", CallID: "xs_123", Name: "x_keyword_search", Input: "{}"},
}}
require.Len(t, ResponsesToAnthropic(resp, "m").Content, 1)
require.Equal(t, "text", ResponsesToAnthropic(resp, "m").Content[0].Type)
chat := ResponsesToChatCompletions(resp, "m")
require.Empty(t, chat.Choices[0].Message.ToolCalls)
require.Equal(t, "stop", chat.Choices[0].FinishReason)
}
Loaded 100 of 668 files, more files were not shown because too many files have changed in this diff. Show more