Compare commits

..
362 Commits
Author SHA1 Message Date
Wesley Liddick eb413d9b39 Merge pull request #9258 from zriyox/fix/payment-expired-order-recovery
fix(payment): 过期订单收到支付成功回调后照常入账;过期前查单失败不再直接置为过期
2026-12-04 23:42:23 +08:00
Wesley Liddick c589c121ec Merge pull request #9255 from zanyatta/fix/xai-input-too-large
fix(grok): keep xAI context-window refusals as context_length_exceeded
2026-12-04 23:41:22 +08:00
Wesley Liddick 3f99496496 Merge pull request #9254 from Sjeary/fix/users-mobile-layout
fix: 修复手机端用户管理页面溢出和菜单裁切的问题
2026-12-04 23:41:19 +08:00
Wesley Liddick 4f621a5a10 Merge pull request #9251 from dzolv/fix/gemini-list-models-pagination
fix(gemini): forward pageSize and pageToken on /v1beta/models
2026-12-04 23:41:15 +08:00
Wesley Liddick 2f39007e86 Merge pull request #9214 from dzolv/fix/ws-http-bridge-window-and-delegation
fix(openai): ignore standalone named delegation in continuation checks and reset WS HTTP bridge on window rollover
2026-12-04 23:41:10 +08:00
Wesley Liddick 9ac8925fe9 Merge pull request #8560 from weicheng59/fix/openai-capacity-shed-strip-retry-after
fix(openai): preserve WebSocket retries on capacity shedding
2026-12-04 23:41:07 +08:00
shaw 6ba762f3bf fix(grok): restore strconv import after merging main 2026-12-04 23:37:52 +08:00
shaw bfceebe029 Merge remote-tracking branch 'origin/main' into pr-9255-fix 2026-12-04 23:34:29 +08:00
zriyox 82302dbfca fix(payment): 过期订单收到支付成功回调后照常入账;过期前查单失败不再直接置为过期
- toPaid 对 EXPIRED 订单不再限制 5 分钟宽限,和 CANCELLED 一致:回调已验签且上游确认已付,就恢复并发货。
- ExpireTimedOutOrders 在上游查单报错时保留 PENDING,下一轮重查;超过过期时间 1 小时仍查不通才置为过期。
2026-12-04 07:29:50 -08:00
Wesley Liddick af6a5c3d0c Merge pull request #9253 from Wei-Shaw/fix/9156-gpt-image-26-unified-generations
fix(openai): support image/mask/markup inputs on unified /v1/images/generations
2026-12-04 21:53:49 +08:00
Wesley Liddick cd412f6c09 Merge pull request #9252 from Wei-Shaw/fix/9183-capacity-shed-long-retry-after
fix(openai): skip same-account overload retries when Retry-After exceeds budget
2026-12-04 21:53:43 +08:00
shaw a562e77638 Merge remote-tracking branch 'origin/main' into fix/9156-gpt-image-26-unified-generations 2026-12-04 21:38:25 +08:00
shaw c7ae3a36e4 Merge remote-tracking branch 'origin/main' into fix/9183-capacity-shed-long-retry-after 2026-12-04 21:38:21 +08:00
Wesley Liddick a2cd083dce Merge pull request #9256 from Wei-Shaw/fix/ws-bridge-reconcile-8302
fix(openai-ws): reconcile HTTP bridge parent check with history limit and sticky continuations
2026-12-04 21:36:46 +08:00
shawandDevin 4e694a3745 fix(openai-ws): reconcile HTTP bridge parent check with history limit and sticky continuations
Follow-up to #8302 (f7ec8b3ce).

Placing the unresolved `previous_response_id` 1008 rejection at the top of the
HTTP bridge turn loop ran before `hooks.BeforeTurn` and before the `historyLost`
1013 (`StatusTryAgainLater`) check from #9203, and rejected valid turn-1 sticky
API-key continuations (`store != false` bound in `stateStore`) as well as Grok
HTTP bridge turns.

Move the 1008 check after `BeforeTurn` and `historyLost`, allow turn-1 API-key
continuations bound to the selected account when `store != false`, and preserve
Grok HTTP bridge handling while keeping all #8302 unresolved-parent cases closed
with 1008.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-04 18:24:50 +08:00
shawandDevin c3f1b4bc75 fix(openai): tighten null/empty image field checks and model_not_found 404 guard
- Ignore explicit JSON `null` values on `mask` and native image options so
  prompt-only requests with null placeholders stay on basic capability.
- Reject empty objects/strings inside `images[]`, `image`, and `mask` instead of
  silently dropping malformed image entries.
- Skip same-account `/images/edits` -> `/images/generations` retry when a 404 is
  explicitly `model_not_found` so account failover runs without an extra round-trip.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-04 17:31:39 +08:00
shawandDevin 332f45f858 fix(openai): guard 429-wrapped capacity shed against long Retry-After window
When a capacity-shed event (`slow_down` / `server_is_overloaded`) arrives with a
429 status and an explicit `Retry-After` exceeding the 8s same-account budget,
skip opening the 2-minute OAuth 429 retry deadline window as well, and emit
`upstream_retry_after` across WebSocket, Embeddings, and AlphaSearch logs.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-04 17:27:09 +08:00
Sjeary 8baebfee07 merge: sync upstream and retain DOMPurify 3.5.1 2026-12-04 01:18:32 -08:00
zanyatta 44ac31a891 fix(grok): keep xAI context-window refusals as context_length_exceeded
xAI rejects an oversized prompt with HTTP 400
{"code":"invalid-argument","error":"Failed to start sampling: [input_too_large] The prompt is too long for this model’s context window (612345 tokens > 500000 tokens)"}.
The shared extractor cannot read this flat body, so Responses clients got the
generic "Upstream rejected the request" and could not tell an oversized
prompt from any other rejected request.

For Grok accounts, a 400 that carries the explicit [input_too_large] tag is now
returned as 400 {"error":{"type":"invalid_request_error",
"code":"context_length_exceeded","message":...}}. Token counts are copied only
when the upstream message states them. X-Grok-Context-Window is forwarded from
the upstream when it is a positive integer, otherwise taken from the stated
limit, otherwise omitted. Other 400s keep their existing shape, and the error
still does not fail over or cool down the account.
2026-12-04 08:54:00 +00:00
shawandDevin 547c35acf5 fix(openai): support image/mask/markup inputs on unified /v1/images/generations
GPT Image 2.6 callers using the unified `/v1/images/generations` protocol pass
reference `images` / `image`, `mask`, and `markup` directly on `generations`
rather than `/v1/images/edits`. Previously, input-image parsing and Codex OAuth
payload construction were gated behind `IsEdits()`, silently dropping image
inputs (and skipping image moderation) on `/v1/images/generations`.

- Parse, validate, moderate, and forward `images`/`image`, `mask`, and `markup`
  on `/v1/images/generations` (JSON and multipart) as well as `/v1/images/edits`.
- Recognize bare `gpt-image-2.6` and `gpt-image-2.6-*` snapshots consistently in
  direct routing, Responses-fallback guard, and fallback pricing.
- Automatically fall forward from `/backend-api/codex/images/edits` to
  `/backend-api/codex/images/generations` when upstream returns 404/405.

Fixes #9156

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-04 16:44:02 +08:00
shawandDevin d07f63ddf8 fix(openai): skip same-account overload retries when Retry-After exceeds budget
When an OpenAI upstream sheds capacity (`server_is_overloaded` / `slow_down`)
and advertises an explicit `Retry-After` longer than the per-retry delay cap
(8s, e.g. 315-369s in #9183), replaying a single-credential account every 8s
cannot satisfy the upstream window and delays switching to healthy accounts.

Switch non-pool accounts immediately on long capacity-shed `Retry-After` hints
while keeping short/unspecified blips and pool-mode relays retryable, preserve
request-scoped transient semantics (no persistent account cooldown), and log
`upstream_retry_after` on retry and switch events.

Fixes #9183

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-04 16:30:39 +08:00
Wesley Liddick f7ec8b3cee Merge pull request #8302 from xz-dev/fix/http-bridge-unresolved-previous-response-id
fix(openai-ws): reject unresolved previous_response_id on HTTP bridge
2026-12-04 15:20:56 +08:00
Wesley Liddick 484625a239 Merge pull request #9236 from r266-tech/codex/antigravity-retry-after
fix(antigravity): honor Retry-After for upstream 429s
2026-12-04 15:20:47 +08:00
Wesley Liddick 57ddb49706 Merge pull request #9217 from debug-zhang/fix/5010-proxy-circuit-diagnosis
fix(openai): scope stream circuit per account and cache no-account diagnostics
2026-12-04 15:20:37 +08:00
Wesley Liddick d63c48cf62 Merge pull request #9224 from debug-zhang/fix/8966-reasoning-only-completed
fix(openai): treat reasoning-only responses.completed as empty
2026-12-04 15:20:27 +08:00
Wesley Liddick 49ef0328a5 Merge pull request #9078 from xidongyuandong/fix/codex-catalog-auto-refresh-v0.2.25
fix(codex): use automatic identity for catalog downloads
2026-12-04 15:20:17 +08:00
Wesley Liddick 7a09fbf167 Merge pull request #9223 from r266-tech/codex/ccswitch-codex-transport
feat(keys): choose Codex transport for CC Switch imports
2026-12-04 15:20:08 +08:00
Wesley Liddick ec68ce4f87 Merge pull request #9247 from Sjeary/fix/users-global-usage-sort
fix: 修复用户管理用量排序仅作用于当前页的问题
2026-12-04 15:19:59 +08:00
Wesley Liddick 5720d10c38 Merge pull request #9146 from erywim/fix/balance-low-notify-dedup
fix(billing): notify again when a new deduction crosses the balance threshold
2026-12-04 15:19:49 +08:00
Wesley Liddick 725b235f97 Merge pull request #9225 from debug-zhang/fix/3210-api-key-existence-oracle
fix(security): hide custom api key existence in creation errors
2026-12-04 15:19:40 +08:00
Wesley Liddick f8c9792d7b Merge pull request #9250 from HuntercodeT/fix/deps-dompurify-3.5.0
fix(deps): bump dompurify to 3.5.0 for GHSA-hrxw-jjj6-2g2j
2026-12-04 15:19:04 +08:00
Sjeary d35839def7 fix: upgrade DOMPurify to patched 3.5.0 2026-12-03 20:33:48 -08:00
Sjeary 6be2403d7a fix: prevent overflow in mobile user management 2026-12-03 20:18:44 -08:00
dzolv 08fdfa61d8 fix(gemini): forward pageSize and pageToken on /v1beta/models 2026-12-04 10:44:00 +08:00
HuntercodeT c7af427fb8 fix(deps): bump dompurify to 3.5.0 for GHSA-hrxw-jjj6-2g2j
Raise the direct dependency and the pnpm override floor to 3.5.0, the first release patched for GHSA-hrxw-jjj6-2g2j (CVE-2026-144292). pnpm 9 resolves the direct dependency and the transitive copies to 3.5.1. The regenerated lockfile changes only DOMPurify entries.
2026-12-04 10:26:50 +08:00
Sjeary c2acc48d5d fix: sort admin user usage before pagination 2026-12-03 08:11:03 -08:00
debug-zhang 470dba8363 fix(openai): treat reasoning-only responses.completed as empty
Root cause: openAIResponsesCompletedEventIsEmpty classified a terminal
response.completed as non-empty whenever usage reported any tokens, so a
stream whose output held only reasoning items (reasoning tokens, no message
text or tool call) was recorded as a successful empty turn (issue #8966).

Change: classify emptiness by the terminal output items instead of usage.
Message items count only with visible text or a refusal; function_call,
custom_tool_call, tool_search_call, image_generation_call and any unknown
item type count as visible products; reasoning-only output is empty. When
output is missing, null, non-array or empty and usage exists, the previous
usage fallback still applies, so partial terminal events are not failed over.
The failover message now says "no visible output".

Tests: table cases for reasoning-only completed (inline and accumulated
usage), message text/refusal, empty message content, tool calls, image
generation, top-level output and malformed output fallback; stream-level
tests assert reasoning-only completed produces UpstreamFailoverError while
reasoning plus message text completes normally.
2026-12-03 21:37:19 +08:00
Wesley Liddick 874e1b337a Merge pull request #9158 from feeeei/feat/chat-completions-anthropic-auto-cache
feat(gateway): enable top-level auto cache_control for chat completions to Anthropic
2026-12-03 17:50:23 +08:00
Wesley Liddick 9172ba8b95 Merge pull request #9033 from feeeei/fix/codex-heartbeat-and-external-message-namespace
fix(openai): 兼容长对话 Codex 定时 heartbeat 归一化并保留 ExternalMessage namespace
2026-12-03 17:50:18 +08:00
Wesley Liddick 708d833d6b Merge pull request #9241 from feeeei/perf/openai-responses-large-body-zero-copy
perf(openai): 大请求体流式零拷贝内容会话哈希与入口/转发扫描合并优化
2026-12-03 17:50:14 +08:00
Wesley Liddick 806534e5ca Merge pull request #9218 from debug-zhang/fix/7435-audit-inline-base64
perf(securityaudit): strip inline image payloads before prompt guard scan
2026-12-03 16:50:34 +08:00
Wesley Liddick 9c72aca60c Merge pull request #9208 from cyhhao/fix/ws-previous-response-fail-loud
fix(openai-ws): fail loudly on missing or incomplete previous_response_id continuation
2026-12-03 16:50:29 +08:00
Wesley Liddick 4644600eb1 Merge pull request #9230 from debug-zhang/fix/5252-codex-models-fallback
fix(openai): fall back to a local Codex models manifest
2026-12-03 16:50:22 +08:00
Wesley Liddick acec49eaaf Merge pull request #9237 from pood1e/fix/pool-mode-local-state
fix(ratelimit): keep pool-mode accounts off model and transport cooldowns
2026-12-03 16:50:16 +08:00
shaw 39b0022a6f style(securityaudit): discard strings.Builder write results for errcheck 2026-12-03 16:34:55 +08:00
shaw 6db1e10ef0 fix(securityaudit): pin the header offset regression, document the residual, precheck signatures
- The non-ASCII header test now reproduces the case-folded offset bug.
- Add a mixed fake/real data URI test.
- Check the image signature on the first bytes before decoding the whole
  payload, and stop pre-growing the output buffer to the input size.
- Describe the accepted residual accurately.
2026-12-03 16:15:35 +08:00
shaw e7bf4232cf fix(openai-ws): keep fail-loud for unbound API-key continuations; add replay regression test
Drop the API-key exemption: the HTTP path also rejects a previous_response_id
whose owner record expired, and the HTTP bridge would strip the id silently.
Only the per-selection strict affinity re-evaluation remains, now pinned by
a regression test for a current-turn failover replay after a continuation.
2026-12-03 16:06:59 +08:00
shaw 2ecf932f87 fix(ratelimit): honor explicit temp-unschedulable rules on pool-mode model-not-found
Pool mode only skips the default model cooldown; a rule the admin configured
still applies, mirroring the pool-mode branch of HandleUpstreamError.
2026-12-03 16:04:47 +08:00
shaw 800ebceb0f fix(securityaudit): keep data URI headers visible and require complete image files
- Only the payload of a verified image is replaced; the media type and
  parameters stay in the scan so prose cannot be smuggled through them.
- The payload is located by regexp submatch indices instead of a
  case-folded copy, so non-ASCII header characters cannot shift it.
- The whole payload must strictly decode to a PNG/JPEG/GIF/WEBP file with
  its trailer; padding is only accepted at the end.
- Skip the regexp entirely when the text has no ;base64, marker.
2026-12-03 16:03:33 +08:00
shaw b55a546fa5 fix(openai): expand wildcard-only fallback allowlists against servable models
Use the configured-manifest candidate set (mapping keys, plus the default
catalog only when an account serves unmapped models) and tag the fallback
log with the group.
2026-12-03 16:01:17 +08:00
shaw da03c58cf2 fix(securityaudit): only strip verified inline images and never truncate audit text
- Drop the per-segment 64K truncation: everything forwarded upstream must be
  audited, and over-long prompts keep the existing fail-closed timeout path.
- Strip a data URI only when its payload uses the standard base64 alphabet,
  is at least 256 characters, and decodes to a PNG/JPEG/GIF/WEBP signature.
  Prose dressed up as a data URI (hyphens, spaces, plain letter runs, SVG
  markup) stays in the scan.
2026-12-03 15:53:27 +08:00
Wesley Liddick f4b6acf2f9 Merge pull request #9239 from magisk-k/fix/openai-ws-concurrency-queue
fix(openai): queue WebSocket turns for user concurrency slots
2026-12-03 15:49:22 +08:00
Wesley Liddick ad6c1ba138 Merge pull request #9213 from magisk-k/feat/codex-ws-max-message-bytes
feat(openai): follow the upstream WebSocket message limit for HTTP bridging
2026-12-03 15:49:16 +08:00
Wesley Liddick e4a0116fd2 Merge pull request #9231 from debug-zhang/fix/6182-selection-failure-diagnostics
fix(observability): attribute selection model cooldown failures by reason
2026-12-03 15:49:10 +08:00
Wesley Liddick 0a30b2e5b2 Merge pull request #9219 from debug-zhang/fix/8370-compat-account-error-policy
fix(gateway): map non-failover upstream errors in compat paths
2026-12-03 15:49:05 +08:00
Wesley Liddick 8c3de07b8e Merge pull request #9222 from debug-zhang/fix/5165-stream-failed-diagnostics
fix(openai): record stream failures after output
2026-12-03 15:48:59 +08:00
Wesley Liddick 38f0461163 Merge pull request #9233 from Ming-Sir-69/fix/antigravity-quota-auth-status
fix(antigravity): avoid false reauthorization prompts on quota reads
2026-12-03 15:48:53 +08:00
Wesley Liddick 8cbd513c27 Merge pull request #9232 from yakwu/feat/proxy-search-by-ip
feat(proxies): support searching proxies by IP/host in admin proxy list
2026-12-03 15:48:48 +08:00
Wesley Liddick db62b187dc Merge pull request #9221 from debug-zhang/fix/7867-user-last-used-query
perf(user): fetch latest usage timestamp with an index-backed lateral probe
2026-12-03 15:48:41 +08:00
shaw cff176dfd7 fix(openai): keep the local Codex models fallback inside the group allowlist
The fallback list now passes through FilterCodexModelIDsForGroup, the same
listing filter /v1/models uses. A wildcard-only allowlist expands its
patterns against account mappings and the default catalog instead of
falling through to the unfiltered default catalog. Serving the fallback is
logged with the upstream error, since clients only see a 200.
2026-12-03 15:48:24 +08:00
shaw 5746b50e8b fix(openai-ws): re-evaluate continuation affinity per selection and forward API-key continuations
- A current-turn failover replay clears previous_response_id because the
  retry payload already carries the full input; the strict affinity check is
  now computed on every selection so that replay is no longer rejected with
  previous_response_not_found.
- API-key accounts resolve previous_response_id upstream, matching the HTTP
  path; a missing local binding forwards the id unchanged instead of failing
  loudly. OAuth-like accounts keep the fail-loud behavior.
2026-12-03 15:43:54 +08:00
shaw 4b43302f59 fix(ratelimit): keep pool-mode model-not-found failover and proxy-auth cooldown
A pool-mode account hitting a deterministic model-not-found must still fail
the current attempt over (404 is not in the generic failover set), only the
30-minute model cooldown is skipped. Rejected proxy credentials are a local
configuration fault, so only reachability failures skip the transport
cooldown for pool-mode accounts.
2026-12-03 15:39:05 +08:00
feeeei 2c922cf496 perf(openai): 合并大请求体入口与转发链路的重复扫描和校验 2026-12-03 14:57:26 +08:00
feeeei 6744f02164 perf(openai): 流式零拷贝计算内容会话哈希并消除 input 整段拷贝 2026-12-03 14:56:18 +08:00
Wesley Liddick 524e8df850 Merge pull request #9166 from Imccccc/upstream/vertex-messages-claude-code
fix(gemini): Claude Code on Vertex accounts: cache usage, thought signatures, tool result order, finish reasons
2026-12-03 14:38:56 +08:00
dzolv 57a990fafa fix(openai): keep HTTP handler missing-call-id validation and scope handshake window_id 2026-12-03 11:05:52 +08:00
magisk-k 7e0edb310f fix(openai): queue WebSocket turns for user concurrency slots
WebSocket turns closed the connection with 1013 as soon as the user was
at its concurrency limit, after the client had already uploaded the full
request. Clients such as Codex then retry and eventually switch the
session to HTTP, which resends the whole context on every turn.

Wait in the same bounded per-user queue as HTTP requests instead. The
wait is 60 seconds, longer than the HTTP wait because a rejected
WebSocket turn is more expensive. Timeouts, a full queue and a closed
connection still end with 1013.
2026-12-03 02:53:31 +00:00
pood1eandClaude Opus 5.5 76ddf1e782 fix(ratelimit): keep pool-mode accounts off model and transport cooldowns
Pool mode promises that upstream errors leave local account state alone
and are retried on the same account. Two paths still marked it:

- HandleUpstreamModelNotFound put a 30-minute model rate limit on the
  account for a 404 model_not_found, although HandleUpstreamError and
  HandleTempUnschedulable already skip pool-mode accounts without custom
  error codes. The OpenAI fast path calls it first, so the skip never
  applied there.
- tempUnscheduleOpenAITransportError marked the account unschedulable
  after a transport error.

A pool-mode upstream that restarts briefly answers 404 for its models
and refuses connections; the account then stayed blocked for up to 30
minutes after the upstream recovered. Custom error codes still opt a
pool-mode account into the model rate limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 17:38:26 -08:00
Weicheng Yu 7aceae8025 Merge upstream main and narrow OpenAI capacity-shed fixes
Keep upstream HTTP Retry-After handling. Retain client frame cleanup and
bounded same-account retries for replay-safe WebSocket failures, with
regression coverage. Drop unrelated allocation test changes.
2026-12-03 09:23:26 +08:00
r266-tech 9b3717b55e fix(antigravity): honor Retry-After for upstream 429s 2026-12-02 11:51:28 -08:00
Ming-Sir-69 542d678dee fix(antigravity): honor the OAuth expiry margin in quota checks 2026-12-02 22:50:35 +08:00
Yakun Wu 11c58d92d0 feat(proxies): support searching proxies by IP/host in admin proxy list 2026-12-02 22:49:10 +08:00
Ming-Sir-69 3fcd1c15b9 fix(antigravity): scope quota cache to the access token 2026-12-02 22:42:14 +08:00
Ming-Sir-69 272b331868 fix(antigravity): distinguish expired access from reauthorization 2026-12-02 22:27:53 +08:00
debug-zhang ca39c9c097 fix(observability): attribute selection model cooldown failures by reason
Root cause: selection failure diagnostics collapsed every persisted model
cooldown into a single model_rate_limited counter, so the operator could not
tell an upstream 404 model_not_found, a real upstream 429, a plan-gated or
temp-unschedulable cooldown, or legacy data apart. The decision log also had no
request_id to join the failure with the request.

Change:
- read the persisted cooldown reason from the account model_rate_limits
  snapshot through a diagnostics-only helper; selection behavior is unchanged
- keep only existing reason values (bounded allowlist), classify structured
  rule reasons, and bucket empty/unknown reasons as "other"
- add per-reason counts to selectionFailureStats and openAISelectionFilterStats
- append model_rate_limited_reasons=<reason:count,...> after the legacy
  summary while keeping the aggregate model_rate_limited=<n> token intact for
  the no_account_error regex and the existing 429 upgrade
- include request_id in the SelectAccountDetailed log line

Tests:
- breakdown across upstream_404_model_not_found, image 429 cooldown,
  empty/other, scheduling-threshold JSON and temp-unschedulable JSON
- OpenAI load-aware no-account error carries the model cooldown breakdown
- legacy summary is byte-identical without a breakdown
- handler regex still upgrades the aggregate count to 429
- go build ./... and go test ./internal/service/ pass
2026-12-02 21:53:46 +08:00
debug-zhang aede013903 fix(openai): fall back to a local Codex models manifest
Root cause: Codex /models requests always fetch the manifest from a
scheduled upstream. Custom API-key upstreams that do not implement
/v1/models return 5xx, an empty catalog, or a non-standard body, so the
gateway exhausts account failover and returns 502 even when the group
can describe its models locally.

Change: generate a local Codex manifest when every candidate fails (or
the account switch budget is exhausted) and when an upstream returns an
empty manifest. Sources follow the group's models_list_config, then the
group accounts' model_mapping keys, then the default OpenAI catalog, with
the same retired-model filter as /v1/models. The local list only replaces
the upstream error when it is non-empty, keeps ETag/304 revalidation, and
leaves successful upstream manifests untouched. Pinned discovery mode
keeps its explicit FallbackToScheduler contract.

Tests: cover 5xx/empty/non-JSON upstream fallback, all-candidates-failed
fallback, source priority, upstream success regression, ETag
revalidation, and preserving the original error when the local list is
empty.
2026-12-02 21:16:00 +08:00
Wesley Liddick 667902572f Merge pull request #9162 from GrantElizabeth/fix/simple-mode-group-isolation
fix(scheduler): 支持 Simple 模式按 API Key 分组隔离账号
2026-12-02 19:59:08 +08:00
debug-zhang ff06dab68d fix(openai): scope stream circuit per account and cache no-account diagnostics
Root cause:
- The OpenAI proxy stream circuit was keyed only on proxy_id. One account
  whose Responses SSE streams kept disconnecting quarantined every healthy
  account sharing that egress proxy, emptying the pool for 10 minutes (#5010).
- Every 'no available accounts' response called
  DiagnoseModelAvailabilityForPlatform, which ran a candidates query per
  request; retrying clients turned that into a database query storm.

Change:
- Key the circuit on (account_id, proxy_id) and pass the owning account at
  every record/clear/check call site. The failure threshold (2 in 60s) and
  10-minute quarantine TTL are unchanged, as is fail-open selection.
- Add a bounded in-process TTL (5s) cache with singleflight for the model
  availability diagnosis on both gateway services. Keys include platform,
  group, model and, for the context-sensitive generic check, request-scoped
  composite-route/thinking inputs. Lookup failures are not cached so callers
  keep the conservative 503 fallback and retry the database.
- Update the circuit config doc comment and the scheduler tests that relied
  on proxy-wide quarantine.

Tests:
- go test ./internal/service -run 'TestOpenAIProxyStream' -count=1
- go test -tags=unit ./internal/service -run 'TestDiagnoseModelAvailabilityForPlatform|TestOpenAIDiagnoseModelAvailability|TestGatewayDiagnoseModelAvailability|TestModelAvailabilityDiagnosisCache|TestOpenAIProxyStream|TestOpenAIGatewayService_SelectAccountWithScheduler_(SkipsQuarantinedSharedProxy|QuarantinedAccountKeepsPeerOnSharedProxy|FailsOpenWhenAllProxiesQuarantined)|TestSelectAccountWithSchedulerForImages_UnspecifiedSizePrefersHealthyProxyOverQuarantinedUnrestricted' -count=1
- go test -tags=unit ./internal/handler -run 'TestClassifyNoAccount|TestClassifySelectionFailure|TestGPT55Retirement' -count=1
- go build ./... and gofmt -l are clean.
2026-12-02 19:30:02 +08:00
shaw 29f6ae68a6 Merge origin/main into PR #9162 2026-12-02 19:05:44 +08:00
r266-tech 6d345a4ec0 feat(keys): choose Codex transport for CC Switch imports 2026-12-02 02:28:06 -08:00
shaw 4f41f253f4 chore: release v0.2.27 2026-12-02 16:28:35 +08:00
dzolv 905893ca9e fix(openai): ignore standalone named delegation in continuation checks and reset WS HTTP bridge on window rollover 2026-12-02 16:23:39 +08:00
magisk-k 989a491859 feat(openai): follow the upstream WebSocket message limit for HTTP bridging
The ChatGPT Codex backend announces the largest WebSocket message it
accepts in x-codex-websocket-max-message-bytes (currently 128 MiB). The
gateway ignored it and bridged every session whose first message reached
a fixed 15 MiB to HTTP, after which each turn replays the full input to
the upstream instead of continuing incrementally over WebSocket.

Record the announced limit per account on every successful upstream
handshake and derive the bridge threshold from it, minus a margin for
fields the gateway adds. http_bridge_threshold_bytes now defaults to 0
(follow the upstream); an explicit value caps the upstream limit, and the
15 MiB default still applies until a limit is known.

Also announce the gateway's client read limit in the same header on the
client handshake, so Codex clients stop before uploading a message the
gateway would reject.
2026-12-02 08:20:39 +00:00
shaw ce7940a900 chore: update sponsors 2026-12-02 16:18:57 +08:00
Wesley Liddick 380ab13810 Merge pull request #9191 from lyen1688/feat/risk-control-excluded-accounts-fastpath
风控内容审计新增排除账户豁免机制并优化同步前置拦截性能
2026-12-02 16:09:57 +08:00
shaw 24b70236d5 fix(risk-control): audit follow-up for #9191
- Excluded accounts no longer suppress image_safety / cyber_policy evidence,
  ban counting or notifications; those are upstream verdicts, not our audit.
- Sampled multi-image inputs (more images than the audit sends) skip the clean
  cache and singleflight so one clean random sample cannot pin the verdict.
- Account search truncates by rune and drops invalid UTF-8 so PG does not
  reject the pattern with a 500.
- Account directory lookups are part of ContentModerationRepository instead of
  a runtime type assertion; lookup errors now propagate from Get/UpdateConfig.
- Remove the never-set BodyValidated flag and the frontend id-only fallback.
2026-12-02 15:53:42 +08:00
shaw aa25d20690 Merge origin/main into PR #9191 2026-12-02 15:34:05 +08:00
Wesley Liddick edba3eb7eb Merge pull request #9211 from Wei-Shaw/fix/release-version-before-tag
fix(release): require the tagged commit to carry the release VERSION
2026-12-02 15:29:07 +08:00
shaw ec0e489ab7 fix(release): require the tagged commit to carry the release VERSION
The sync-version-file job committed the VERSION bump to main only after
publishing, so every tag pointed at a commit whose VERSION was the previous
release (v0.2.19 through v0.2.26). Published artifacts were unaffected because
prepare rewrites VERSION from the tag, but source builds of a tag (go build,
GitHub source archives, Docker builds without .git) reported the old version.

prepare now fails before building or publishing when VERSION at the tag does
not match the tag version. A manual run with allow_version_mismatch=true
downgrades this to a warning for re-releasing older tags. The post-release
sync job is removed: the VERSION bump is committed before tagging instead.
2026-12-02 15:22:58 +08:00
Wesley Liddick ce3a27912e Merge pull request #9147 from erywim/fix/sanitize-safety-review-details
fix(openai): strip safety review details from client-visible failed events
2026-12-02 12:52:39 +08:00
cyh 622ad49022 fix(openai-ws): fail loudly on missing or incomplete previous_response_id continuation 2026-12-02 12:41:11 +08:00
shaw a64db2860b test: pass the replay collector argument added by #9203(audit follow-up for #9147) 2026-12-02 12:37:30 +08:00
shaw ea2df1442b Merge origin/main into PR #9147 2026-12-02 12:35:49 +08:00
Wesley Liddick 97b70cca2a Merge pull request #9203 from HuntercodeT/fix/ws-http-bridge-history-bounds
fix(openai): bound WebSocket HTTP bridge replay history
2026-12-02 12:35:38 +08:00
Wesley Liddick 6bc40957cf Merge pull request #9199 from magisk-k/fix/codex-models-etag-metadata
fix(openai): keep Codex catalog ETag in sync with codex.response.metadata
2026-12-02 12:35:34 +08:00
Wesley Liddick 51455623ce Merge pull request #9197 from debug-zhang/fix/9163-retry-after
fix(gateway): return Retry-After on rate-limit and pool-cooldown errors
2026-12-02 12:35:30 +08:00
Wesley Liddick 4bd5fa6480 Merge pull request #9149 from r266-tech/fix/alpha-search-apikey-400-failover
fix(openai): fail over standalone alpha search on API-key upstream 400
2026-12-02 12:35:25 +08:00
Wesley Liddick 4cfeeb2396 Merge pull request #9135 from NDCCCCCC/pr/account-threshold-ui
feat(accounts): 让所有受支持平台都能配置账号级自动停调阈值
2026-12-02 12:35:21 +08:00
shaw c101515d0a Merge origin/main into PR #9199 2026-12-02 12:06:32 +08:00
shaw 63cfafbac3 Merge origin/main into PR #9135 2026-12-02 12:06:32 +08:00
shaw 15aec090c2 Merge origin/main into PR #9149 2026-12-02 12:06:31 +08:00
shaw a08eb02ff8 Merge origin/main into PR #9197 2026-12-02 12:06:30 +08:00
shaw 9f1ec1f69e Merge origin/main into PR #9203 2026-12-02 12:06:29 +08:00
shaw b88a4f4cf9 Merge origin/main into PR #9147 2026-12-02 12:06:28 +08:00
Wesley Liddick 4c953d9252 Merge pull request #9205 from fengshao1227/fix/openai-manual-reset-earliest-credit
fix(openai): spend the earliest-expiring reset credit on manual reset
2026-12-02 12:06:06 +08:00
Wesley Liddick debe9e3e21 Merge pull request #9204 from fengshao1227/docs/antigravity-forward-env-passthrough
fix(deploy): pass Antigravity endpoint and 429 cooldown env through Compose
2026-12-02 12:06:02 +08:00
Wesley Liddick d036368c8e Merge pull request #9201 from Ikhdev1/ikhdev1/update-x-image-v045
CVE fix(deps): update golang.org/x/image to v0.45.0
2026-12-02 12:05:59 +08:00
Wesley Liddick b7b5321a6a Merge pull request #9200 from magisk-k/feat/codex-keep-hidden-auto-modes
feat(groups): add switch to keep upstream-hidden Codex automatic modes
2026-12-02 12:05:54 +08:00
Wesley Liddick 2d597faf60 Merge pull request #9198 from debug-zhang/fix/8933-http2-stream-limit
fix(gateway): retry OpenAI upstream once after a pre-output connection reset
2026-12-02 12:05:51 +08:00
Wesley Liddick 252e394f5c Merge pull request #9195 from debug-zhang/fix/8842-scheduler-cache-write
perf(scheduler): skip rewriting unchanged accounts in scheduler cache
2026-12-02 12:05:47 +08:00
Wesley Liddick cdbfa172e3 Merge pull request #9190 from pood1e/feat/openai-chat-session-id
feat(openai): let API-key accounts send an isolated session ID on Chat Completions
2026-12-02 12:05:42 +08:00
Wesley Liddick 120f4eeac8 Merge pull request #9187 from SomeoneKong/fix/content-moderation-worker-stop
fix(content-moderation): add Stop so background workers can be shut down
2026-12-02 12:05:38 +08:00
Wesley Liddick 5e68375f0c Merge pull request #9181 from feeeei/fix/gemini-4-argon-carbon-regular-pricing
fix(billing): update Gemini 4 Argon and Carbon to regular pricing
2026-12-02 12:05:34 +08:00
Wesley Liddick a07fa27e29 Merge pull request #9179 from SipengXie2024/fix/antigravity-keep-system-notices-in-place
fix(antigravity): keep mid-conversation system messages in place so the prompt prefix stays cacheable
2026-12-02 12:05:30 +08:00
Wesley Liddick 0e8cb91137 Merge pull request #9176 from r266-tech/codex/export-image-usage-costs
fix(usage): export numeric image cost breakdowns in admin Excel
2026-12-02 12:05:26 +08:00
Wesley Liddick ade6442b58 Merge pull request #9173 from HuntercodeT/fix/ws-codex-string-input
fix(openai): convert string input to a message list on Codex WS upstream
2026-12-02 12:05:21 +08:00
Wesley Liddick 988569acde Merge pull request #9171 from debug-zhang/fix/codex-removed-config-keys
fix(frontend): drop Codex config keys removed upstream
2026-12-02 12:05:17 +08:00
Wesley Liddick e7bf40dedf Merge pull request #9167 from Imccccc/upstream/vertex-tool-schema
fix(gemini): send only Vertex Schema fields in tool parameters
2026-12-02 12:05:13 +08:00
Wesley Liddick 8a8f1c135e Merge pull request #9160 from r266-tech/codex/antigravity-channel-pricing-sync
fix(channels): include mapped Gemini models in Antigravity pricing sync
2026-12-02 12:05:09 +08:00
Wesley Liddick 35eaa252b3 Merge pull request #9154 from r266-tech/codex/usage-display-state
fix(frontend): keep usage displays tied to the current request
2026-12-02 12:05:05 +08:00
Wesley Liddick 9e7647ec90 Merge pull request #9150 from r266-tech/codex/preserve-antigravity-import-options
fix(accounts): preserve Antigravity options on refresh token import
2026-12-02 12:05:01 +08:00
Wesley Liddick 6c55134201 Merge pull request #9140 from fengshao1227/fix/responses-anthropic-budget-below-max-tokens
fix(apicompat): keep max_tokens above the Responses thinking budget
2026-12-02 12:04:57 +08:00
Wesley Liddick 1d746382e9 Merge pull request #9138 from fengshao1227/fix/websearch-test-surface-provider-errors
fix(websearch): show why the admin web search test failed
2026-12-02 12:04:52 +08:00
Wesley Liddick a4d580691f Merge pull request #9137 from fengshao1227/fix/tavily-bearer-auth
fix(websearch): authenticate Tavily with a Bearer header
2026-12-02 12:04:47 +08:00
Wesley Liddick 8ff16c5cc0 Merge pull request #9073 from mengkzhaoyun/fix/grok-scheduler-tier-projection
fix(scheduler): preserve resolved Grok subscription_tier in metadata projection
2026-12-02 12:04:43 +08:00
shaw 2934284844 fix: drop bridge history when end-of-turn resize does not fit(audit follow-up for #9203)
Retaining a turn can need more budget than the turn held because the replay
and failover sequences get separate header arrays. When that growth does not
fit, drop the history instead of keeping it under-accounted. Count a shared
body only when both pointer and length match, and skip the common prefix by
index so the lookup set covers only the diverging tail.
2026-12-02 12:04:31 +08:00
shaw 1a55e82973 fix: strip safety review details using the resolved SSE event type(audit follow-up for #9147)
SSE data lines may omit "type"; the HTTP SSE path already resolved the event
type from the event: line, so strip with that instead of re-reading the
payload.
2026-12-02 12:04:31 +08:00
shaw 71436d44cc fix: keep existing 400 classification before alpha search API-key failover(audit follow-up for #9149) 2026-12-02 11:50:32 +08:00
shaw 9e63d8b986 fix: 非续接未缓存轮保留 failover 输入并去重共享历史字节(audit follow-up for #9203) 2026-12-02 11:48:59 +08:00
shaw d6f167622d fix: 在 WS ingress/桥接/passthrough/HTTP+WS上游路径剥离安全审查详情(audit follow-up for #9147) 2026-12-02 11:47:41 +08:00
shaw 0dba88681b fix: hide create-account scheduling threshold unless submit writes it and reset it on close(audit follow-up for #9135) 2026-12-02 11:45:21 +08:00
shaw 385e07ca85 fix: shorten Codex models ETag mapping TTL and clear it for upstream-less manifests(audit follow-up for #9199) 2026-12-02 11:44:07 +08:00
shaw 8aa5c2a4ba fix: omit Retry-After hint when any supporting account is not in persisted cooldown(audit follow-up for #9197) 2026-12-02 11:42:27 +08:00
debug-zhang c678e772af fix(security): hide custom api key existence in creation errors
Root cause:
- POST create with custom_key returned API_KEY_EXISTS (409) when the key
  already existed, letting authenticated callers confirm that a guessed key
  belongs to someone else and then use it.
- Malformed keys returned distinct API_KEY_TOO_SHORT / API_KEY_INVALID_CHARS
  errors, so the collision error could be told apart from other failures.

Change:
- Add ErrAPIKeyUnavailable (400, API_KEY_UNAVAILABLE, generic message) and
  return it for malformed custom keys and collisions alike, including a
  unique-constraint race on insert.
- Keep detailed reasons in server logs only; keep the failed-attempt counter
  on collisions and the internal ErrAPIKeyExists for repository translation.
- Normal custom-key creation (including reusing a soft-deleted key whose
  credential was tombstoned) and generated keys are unchanged.

Tests:
- go build ./...
- go test -tags=unit ./internal/service -count=1
- go test -tags=unit ./internal/repository -run TestAPIKeyRepository
- go test -tags=unit ./internal/handler -run TestValidateAPIKey
2026-12-02 10:24:26 +08:00
debug-zhang ebc32f90fb fix(gateway): map non-failover upstream errors in compat paths
Root cause: PR #8385 applied the account error policy to the Chat
Completions and Responses compatibility paths, but statuses outside the
failover whitelist (for example 410 Gone from a migrated upstream base
URL) still fell through to writeGatewayCCError/writeResponsesError with
the upstream status and raw message. Global passthrough rules were not
consulted either, so the client saw a bare 410 and the upstream
migration hint.

Change:
- Apply applyErrorPassthroughRule before writing the non-failover error,
  so configured rules can remap status and message.
- Record the original upstream status plus an http_error Ops event, then
  collapse unknown 4xx statuses (notably 410) into a generic 502
  "Upstream request failed", matching /v1/messages and avoiding exposure
  of upstream migration hints. 400/404/413/422 keep their request-level
  status and sanitized message.
- Leave 410 out of shouldFailoverUpstreamError to avoid changing retry
  semantics.

Tests: extend the compat account policy regression to assert 410 -> 502
without the upstream message, request-level 4xx passthrough and Ops
bookkeeping; add a passthrough-rule remap case for both entrypoints.

Validation:
- go build ./...
- go test -tags=unit ./internal/service -count=1
- go test -tags=unit ./internal/service -run 'TestAnthropicCompat(AccountErrorPolicy|NonFailoverErrorAppliesPassthroughRule)$' -count=1
2026-12-02 10:24:12 +08:00
li 7613baf97c fix(openai): spend the earliest-expiring reset credit on manual reset
The automatic reset sorts the available credits by expiry and consumes the
first one by id, but the admin reset button sent no credit_id and let
upstream pick. Upstream can then spend a later credit and leave the one
closest to expiry to lapse, while the account list shows that earliest
expiry next to the button.

ResetCredit now reads the credit list first and targets the credit that
expires first. When the list cannot name it (request failed, a credit
without expiry or id, fewer credits listed than available, unparsable
expiry) the request stays untargeted as before.
2026-12-02 10:19:35 +08:00
debug-zhang 33472b553a perf(securityaudit): strip inline image payloads before prompt guard scan
Root cause: structured input_image parts are skipped during extraction, but an
image serialized as JSON into a plain input_text kept its base64 data URI in
the scan text. A single 384x384 PNG data URI (~590k chars) was split into
hundreds of guard chunks that all shared the same audit deadline, so the
request ended in prompt_guard_unavailable.

Change:
- Replace data:image/...;base64,... data URIs (plain and JSON-escaped, with
  optional media parameters) with "[image data omitted]" while extracting
  prompt text; the surrounding text and the message itself are preserved.
- Cap every extracted text segment at 65536 runes and mark the cut with
  "[truncated]" so one client-controlled field cannot expand without bound.
- Structured input_image parts remain skipped.

Tests: a synthetic 384x384 PNG data URI embedded in a serialized history JSON
now produces one guard chunk and a single scanner call. JSON-escaped data URIs,
rune-boundary truncation, structured image skipping, and normal long-text
chunking are covered in prompt_inline_data_test.go.
2026-12-02 10:16:15 +08:00
debug-zhang 337e33bda5 fix(openai): record stream failures after output
Root cause: once semantic output is committed, failover replay is unsafe, so
the stream is forwarded as-is. Only explicit response.failed events were
recorded (PR #6736); bare error frames and the synthesized terminal failure
they produce had no ops upstream-error record, leaving post-output capacity
failures invisible in ops_error_logs.

Change: record after-output terminal failures in both the native and
passthrough Responses stream handlers with kind stream_failed_after_output,
passing the raw upstream payload and upstream request ID. A bare error is
recorded when the authoritative response.failed arrives, or at EOF when the
Codex terminal synthesis is used; one record per stream avoids duplicates.
No failover, replay, or client-visible error shape is changed.

Tests: new TestOpenAIStreamBareErrorAfterOutputIsRecorded covers OAuth
native/passthrough synthesis and the API-key forwarded-error path; the
existing after-output processing-failure test now asserts the new kind.
Also ran go build ./... and go test ./internal/service/ -count=1.
2026-12-02 10:15:47 +08:00
debug-zhang d762d5fa8a perf(user): fetch latest usage timestamp with an index-backed lateral probe
Root cause: GetLatestUsedAtByUserIDs aggregated every historical usage_logs
row for the requested users (MAX(created_at) ... GROUP BY user_id). The
existing idx_usage_logs_user_created(user_id, created_at) index could not be
used to early-stop, so the admin user list paid O(history) per page and took
9-10s on million-row tables.

Change: probe only the newest row per requested user with
unnest($1::bigint[]) CROSS JOIN LATERAL (SELECT created_at FROM usage_logs
WHERE user_id = u.user_id ORDER BY created_at DESC LIMIT 1). Each inner
subquery is a single backward index scan on idx_usage_logs_user_created,
making the lookup O(page size * log n). The inner join preserves the previous
semantics: users without usage rows are absent from the returned map, and
timestamps are still normalized to UTC. GetLatestUsedAtByUserID keeps reusing
the batch function.

Tests: new sqlmock unit tests assert the lateral/ORDER BY ... LIMIT 1 query
shape, per-user latest result, missing-user omission, UTC normalization, empty
input short-circuit, no-rows, singleton reuse and error propagation. The
integration suite extends GetLatestUsedAtByUserIDs coverage with out-of-order
inserts across multiple users, a user without usage, and empty input.
2026-12-02 10:09:39 +08:00
li 9f6e0f76ba fix(deploy): pass Antigravity endpoint and 429 cooldown env through Compose
GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL and
GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS are read with os.Getenv, but the
Compose files only interpolate an explicit list of variables. Setting either
one in deploy/.env therefore never reached the container.

Register both in .env.example (empty, so the built-in behavior is unchanged),
pass them through every Compose file, and document the
gateway.antigravity_fallback_cooldown_minutes key they fall back to. The
existing docker-compose gateway env test now covers both variables.
2026-12-02 10:03:41 +08:00
Wesley Liddick 6ddd0fe8d4 Merge pull request #9194 from debug-zhang/fix/8609-codex-agent-context
fix(codex): normalize agent context outputs without call_id
2026-12-02 10:03:36 +08:00
shaw f84d1d3eb2 fix(codex): keep browser_tabs tag and name unknown agent context
Rebasing onto #9152 made browser_tabs a known context name; add it to the
known list so it keeps its <external_browser_tabs> tag and empty-output
check instead of falling to the generic branch.

Render unknown agent context names the way Codex renders context it does
not send as a tool output, <external_{name}>, when the name has the shape
Codex derives names in ([A-Za-z0-9_]{1,128}). Other names still use the
generic <external_agent_context> tag, so a client supplied name is never
embedded unchecked.
2026-12-02 09:47:40 +08:00
shaw b20c5d0e78 Merge remote-tracking branch 'origin/main' into pr9194
# Conflicts:
#	backend/internal/handler/openai_page_context.go
2026-12-02 09:47:11 +08:00
HuntercodeT c5b12503bb fix(openai): bound WebSocket HTTP bridge replay history 2026-12-02 09:28:53 +08:00
Wesley Liddick 7d32ba27f7 Merge pull request #9152 from pangxin12345/fix/codex-browser-tabs-context
fix(openai): normalize standalone browser tabs context
2026-12-02 09:25:01 +08:00
Ikhdev1 799aee99fd fix(deps): update golang.org/x/image to v0.45.0 2026-12-01 19:24:11 +03:00
magisk-k 79f84cb2aa feat(groups): add switch to keep upstream-hidden Codex automatic modes
Codex manifests fetched from upstream carry automatic modes such as
codex-auto-review, which upstream already hides from the model picker and
Codex uses to review approvals. The gateway removes every automatic mode the
group model list does not select, so Codex falls back to the main model for
reviews and the forwarded manifest always differs from upstream.

Add keep_hidden_auto_modes to the group Codex manifest config. When enabled,
automatic modes that upstream marks as hidden are forwarded byte-for-byte;
visible ones are still removed unless selected, and explicit selections keep
listing them in the picker. The switch is off by default, so existing groups
behave as before, and the admin group dialog exposes it next to the pinned
accounts settings.
2026-12-01 15:47:27 +00:00
magisk-k 56e27df2d7 fix(openai): keep Codex catalog ETag in sync with codex.response.metadata
Codex caches the /models catalog together with its ETag and, on every
Responses WebSocket turn, compares that ETag with the x-models-etag header
of the codex.response.metadata event. Upstream reports the ETag of its own
catalog, but the gateway serves a group-specific manifest whose ETag changes
as soon as group policy adjusts it, so Codex re-downloaded the full catalog
on every turn.

Record, per group, which served ETag corresponds to each upstream catalog
ETag, and translate the metadata header when relaying WebSocket events in
both ctx_pool and passthrough modes. Unknown values are removed so clients
fall back to their regular catalog cache TTL. Pinned manifests keep the
upstream ETags of every merged account, and generated manifests now use weak
ETags so the value still matches behind a compressing reverse proxy.
2026-12-01 15:35:35 +00:00
debug-zhang cbde784ed0 fix(gateway): retry OpenAI upstream once after a pre-output connection reset
Root cause: an upstream HTTP/2 connection multiplexes many in-flight
requests. When a CDN resets that TCP connection, every stream multiplexed
on it fails at once. Before any byte reached the client the gateway either
returned 502 (reset before response headers) or a failover error that
switched accounts (reset while reading the stream). The upstream keeps
reading the request and bills it in full, so the request is charged
upstream while the gateway records zero usage downstream.

Change: Forward now treats a connection reset / unexpected EOF on an
established upstream connection as a transport incident, not an account
failure. When the client is still connected, the request body is
replayable and this attempt wrote no client-visible byte (semantic output
accounting; keepalive comments excluded), it rebuilds the request and
replays it once on the same account. The replay never touches
failover/account-health or sticky-session accounting; if it fails again
the original failover error is returned and the existing path runs.
Timeouts, context cancellation, client disconnects, dial failures and
plugin hand-offs that may already have executed upstream are never
replayed. Stream read errors expose a new ConnectionResetBeforeOutput
marker so Forward can distinguish this window from other failovers.

Tests: new openai_upstream_connection_reset_retry_test.go covers a reset
before any client output (both the pre-header transport form and the
stream-read form) retried once and succeeding, a second reset not
starting a third attempt, a reset after client output not retried,
timeout/cancel not retried, a non-replayable body not retried, the reset
classifier, and the marker only being set before output.
2026-12-01 23:31:31 +08:00
debug-zhang e7f32da0a8 fix(gateway): return Retry-After on rate-limit and pool-cooldown errors
Root cause: downstream 429/503 responses carried no Retry-After. The
no-account classifier had no recovery time at all; the earliest account
cooldown only existed inside scheduler log lines; and upstream error paths
either dropped the provider's response headers (shouldDisable failures,
final compat write) or copied Retry-After verbatim, including capacity-shed
windows that clients would honor by sleeping for minutes.

Change:
- Diagnose the earliest cooldown among model-capable accounts (account
  rate limit, overload, temporary unschedulable, and per-model rate limit)
  and expose it as ModelAvailabilityDiagnosis.RetryAfterSeconds, capped by
  the new gateway.retry_after_max_seconds option (default 300s).
- Emit Retry-After for 429/503 no-account classifications only when a
  recovery time is known; 404 model_not_found and unknown values omit it.
- Forward upstream Retry-After / retry-after-ms (header or body) only for
  explicit 429 rate limits, converting to integer seconds with a ceiling
  and the same cap. Capacity-shed/server_is_overloaded and generic 5xx
  hints stay dropped to stay compatible with #8560/#8938.
- Preserve upstream response headers on failover errors and route every
  failover-exhaustion path through the gated helper instead of copying
  arbitrary Retry-After values.
- Status codes, error types, and messages are unchanged.

Tests:
- service: retry-after parsing (header, retry-after-ms rounding, body
  fields), cap/default/config override, capacity-shed rejection, non-429
  statuses ignored, cooldown computation and unknown recovery.
- handler: no-account 429/503 emit the diagnosed value, unknown recovery
  and model_not_found omit it, failover exhaustion forwards upstream 429
  hints (including body retry-after-ms) and omits capacity-shed hints.
2026-12-01 23:19:41 +08:00
debug-zhang c15bfc71cf perf(scheduler): skip rewriting unchanged accounts in scheduler cache
Root cause: writeAccountIDs unconditionally SET every account payload and
metadata record on each scheduler refresh. After 0.2.26 stopped embedding
expanded group objects the payload is smaller, but refreshes driven by
snapshots or account updates still rewrote all keys even when their content
was identical, amplifying AOF and replication traffic when several instances
share one Redis.

Change: read the previous full and metadata payloads with one chunked MGET
per write chunk and compare bytes before writing. Only payloads that changed
are SET; unchanged accounts are still returned in the account ID list so
bucket membership is unchanged. Platform revisions advance only when a
payload was actually written and stay in the last writing chunk, after all
metadata writes. The fallback path used when the read fails keeps the
original unconditional write and SET ... GET platform-change detection
(fail-open). Redis remains the source of truth; no in-process caching is
added.

Tests: new unit tests cover repeated identical writes issuing no SET and no
revision, changed payloads being rewritten, per-chunk skipping, platform
changes still advancing the global revision, and the MGET-failure fallback.
Existing scheduler cache revision tests were updated for the read-first write
layout. Validated with go build ./..., go test -tags=unit
./internal/repository/, and gofmt.
2026-12-01 23:02:02 +08:00
debug-zhang 638b48c876 fix(codex): normalize agent context outputs without call_id
Root cause: normalizeCodexUntrustedContext only rewrote function_call_output
items whose name matched a fixed list of Codex context tools. Newer Codex
clients send page/tab context under new names (for example browser_tabs), so
the item kept its missing call_id and validateFunctionCallOutputRequest
rejected the whole request with HTTP 400.

Change: gate agent context by namespace == "agent" and a missing or blank
call_id instead of an enumerated name list. Known context names keep their
existing tags and format checks; any other agent-namespace name is rendered
under the generic <external_agent_context> tag so client-supplied names are
never interpolated into tags unchecked. Items with a call_id, without the
agent namespace, with a non-string output, or with duplicate members are left
untouched and keep the original validation path. A zero-copy namespace probe
replaces the name-literal fast path.

Tests: add browser_tabs, unknown/renamed agent context names, escaped
namespace, blank call_id, real tool outputs still rejected (400), and
call_id regression cases; adapt existing unrelated-tool-result fixtures to
model real tool outputs without the agent namespace. Full handler and service
unit packages pass; go build and gofmt are clean.
2026-12-01 23:00:00 +08:00
lyen1688 bf88f07f46 feat(risk-control): 内容审计新增排除账户豁免机制并优化同步前置拦截性能 2026-12-01 22:20:36 +08:00
pood1eandClaude Opus 5.5 ed3317d02b feat(openai): let API-key accounts send an isolated session ID on Chat Completions
Self-hosted routers such as vllm-router keep a session on one decode
replica by the X-Session-ID header, but the Chat Completions outbound path
forwards only accept-language and user-agent from the client. The new
account extra key `openai_chat_session_id` makes that path send the
client's session as X-Session-ID, isolated per API key with
isolateOpenAIUpstreamSessionID. The session comes from the same sources
as x-opencode-session: client session headers first, then the
prompt_cache_key or metadata.user_id remembered before protocol
conversion, so /v1/responses and /v1/messages requests converted to Chat
Completions keep their sessions. Account header overrides still apply
last, and accounts without the key send the same headers as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:53:38 -08:00
someonekongandClaude Opus 5.5 854b16dfe8 fix(content-moderation): add Stop so background workers can be shut down
NewContentModerationService starts 32 workers and a cleanup goroutine that
loop forever with no way to stop them. Production keeps one service for the
process lifetime, but the service package tests construct it in 27 places and
every one leaks its goroutines until the test binary exits. The workers call
time.Now() every second, so tests that later switch time.Local through
timezone.Init race with them; under -race the test binary has segfaulted on
the torn time.Local.

Add Stop: it closes a stop channel, waits for the workers and the cleanup
goroutine, then waits for an in-flight runtime snapshot refresh by taking
runtimeRefreshMu. Workers finish the task they hold before exiting; idle
waits, the configuration back-off and the cleanup timer all wake on the stop
channel. Stop is idempotent and safe on services that started no goroutines.
Production wiring does not call it, so runtime behaviour is unchanged.

Tests that construct a service with workers register t.Cleanup(svc.Stop), and
the stale-scope cyber test stops the workers before it rewrites the snapshot
TTL they read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:35:57 +08:00
Sterbennicht ee99ee1e23 fix(openai-ws): reject unresolved previous_response_id on HTTP bridge
On the http_bridge path, a response.create whose previous_response_id
cannot be resolved on this connection was silently stripped of the id
and posted as a delta-only request, losing the entire prior context.
Fail closed instead: close the socket with 1008 and tell the client to
resend the full input without previous_response_id.

The bridge tracks the last completed turn's response id; a parent is
resolvable only when it matches that id and a non-empty replay history
exists. Covers fresh connections, id mismatches, empty replay, missing
upstream response ids, and failed parent turns.
2026-12-01 16:22:57 +08:00
feeeei e141954afc fix(billing): update Gemini 4 Argon and Carbon to regular pricing 2026-12-01 14:10:46 +08:00
SipengXie2024 8a1ca956fd fix(antigravity): keep mid-conversation system messages in place so the prompt prefix stays cacheable
Claude Code sends {role: "system"} messages inside messages: one with the
environment after the first user message, and a notice after every tool
result, which stays in the history. buildContents moved all of them to the
end of systemInstruction. systemInstruction precedes the contents, so every
tool round changed the start of the prompt and Gemini's implicit prefix cache
matched only the tools and the fixed system prompt: in a Claude Code tool loop
on gemini-4-neon cache_read stayed at about 34k tokens of a 100k-200k token
conversation (9.4% of input tokens over 3947 requests).

System messages before the first model turn still go to systemInstruction.
Later ones stay at their position as <system-reminder> text at the end of the
user turn they follow; one that follows a model turn joins the next user turn
after its tool results, so a functionCall is still followed directly by its
functionResponse. System message text is trimmed in both wire forms, since
Claude Code sends the newest one as cache_control blocks and the same message
as a string once it is history.
2026-12-01 04:30:05 +00:00
r266-tech 2c09c5cc29 fix(usage): export numeric image cost breakdowns in admin Excel 2026-11-30 19:01:19 -08:00
HuntercodeT 7e563855f0 test(openai): check type assertions in WS string input tests 2026-12-01 10:03:04 +08:00
HuntercodeT 0e35d49c99 fix(openai): convert string input to a message list on Codex WS upstream
The ChatGPT codex backend rejects a string `input` with
"Input must be a list". The HTTP path already converts it in
applyCodexOAuthTransform (#919), but the Responses WebSocket ingress
forwarded the client frame unchanged, so the same request succeeded over
HTTP and failed over WS. Clients that treat a failed WS turn as "WS
unsupported" then fall back to HTTP for the whole provider.

Convert only the copy written to the native upstream WS, using the same
rule as the HTTP path. The session's stored client payloads and the
http_bridge path are unchanged.
2026-12-01 09:40:42 +08:00
debug-zhang 5620cd6bac fix(frontend): drop Codex config keys removed upstream
Codex 0.17x reports `disable_response_storage` and
`windows_wsl_setup_acknowledged` as unknown configuration fields, and
rejects the top-level `network_access = "enabled"` because the key only
exists as a boolean under [sandbox_workspace_write].

Remove the two removed keys from every generated config.toml and express
the network intent with the supported sandbox table. The commented Grok
template drops the same stale lines.
2026-11-30 22:19:00 +08:00
changjingandClaude Opus 5.5 04aa0974a8 fix(gemini): send no foreign thinking signature from history on any account
Forward carried only marked thinking signatures (vertex-thought-v1:) for
Vertex accounts. For every other Gemini account it carried any real
thinking signature from history. Those accounts render responses with the
compat emitter, which never sends a thinking signature, so the only real
thinking signatures in their history are foreign: after a switch from a
Claude model in the same session, Anthropic signatures. They reached
Gemini as thoughtSignature, Gemini answered with a signature 400, and the
signature retry ran on every request of the session. main sends none.

Failure modes this commit guards against:
- An AI Studio (or OAuth) account sends an Anthropic thinking signature on
  a functionCall part or on a text part.
- The first request and the signature retry follow different rules.
- Vertex changes: marked signatures still go back without the marker, and
  unmarked ones are still not carried.
- tool_use.signature handling changes.

Changes:
- Forward builds the request with markedThinkingSignatures on for every
  account, on the first request and on the signature retry. Only the
  Vertex renderer emits marked signatures, so other accounts carry no
  thinking signature, as on main. A functionCall without a signature still
  gets the dummy.

Tests:
- New TestGeminiCompatForward_AIStudioSendsNoThinkingSignatureFromHistory:
  an AI Studio account with Anthropic thinking signatures before a call
  and before text. Upstream gets the dummy on the call, no signature on
  the text, and no Anthropic signature. It fails on the parent commit. For
  the same request, the upstream body is byte-identical to main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:22:48 +08:00
changjingandClaude Opus 5.5 e93012e94e fix(antigravity): keep the text-part rule for signature-only parts
The Vertex renderer commit let a non-thought part that carries only a
thoughtSignature (an empty text part, or a part with no text key) reach
the text path. On the Vertex path the text-part signature is dropped
since then, so the change has no effect there. On the antigravity
platform it added an empty thinking block for such a part: a stream whose
signature arrives in an empty final part ended [text, thinking("")], and
Claude Code reports an empty result for a turn that ends with a thinking
block. main renders [text].

Failure modes this commit guards against:
- Antigravity (zero options): "Hello world" followed by an empty final
  part with a signature, or a part with only a signature, renders an
  extra empty thinking block (stream with the signature in its own chunk,
  and non-stream).
- Vertex options (marker prefix, text signatures dropped): the output
  changes. A scratch probe over 8 part shapes (signature-only part before
  text, after text, after thinking, between text and a call, after a
  call; signed text; signed image), stream and non-stream, gives the same
  bytes before and after this commit. With zero options the same probe
  gives the bytes of main.

Changes:
- StreamingProcessor and NonStreamingProcessor: the text branch runs
  again only for a part with text or a thought part, as on main.

Tests:
- New TestSignatureOnlyTextPartAddsNoBlock: [text] for both tail shapes,
  stream (two chunks) and non-stream, with zero options and with the
  Vertex options. The zero-option cases fail on the parent commit.
- TestProcessorsKeepSignatureOnlyPartsAndEmptyToolInput loses its two
  signature-only cases and becomes
  TestProcessorsKeepEmptyToolInputAndImageSignature.
- TestDropTextSignatures: with the drop off, a trailing empty signed part
  now gives [text].
- TestThinkingSignaturePrefixMarksOnlyThinkingBlocks: the carried text
  signature now comes from a signed non-empty text part, so the test still
  checks that the carrier thinking block gets the prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:18:55 +08:00
changjing b089e60895 fix(gemini): send only Vertex Schema fields in tool parameters
Vertex rejects a function declaration whose parameters carry a keyword
outside its Schema type: a live call with propertyNames returns
400 Unknown name "propertyNames" on every Gemini 4 model. zod-generated MCP
tool schemas emit propertyNames for records, and Claude Code adds a deferred
tool to tools[] once ToolSearch loads it, so every later request in the
session fails with a 400.

The cleaner now keeps only the fields of the Vertex v1 Schema type
(https://docs.cloud.google.com/vertex-ai/docs/reference/rest/v1/Schema).
The keywords it already dropped stay dropped. oneOf becomes anyOf when the
node has no anyOf. A format value stays only when the reference lists it for
the node's type. Every other dropped keyword is appended to the node's
description as "[Constraint: key: value, ...]", in key order, the same hint
shape as the antigravity schema cleaner. No tool is removed.

Failure modes this commit guards against:
- A non-Vertex keyword (propertyNames, not, if/then/else, allOf,
  prefixItems, contains, uniqueItems, multipleOf, exclusiveMaximum,
  unevaluated*, dependentSchemas, dependencies, ...) reaches parameters at
  any depth and Vertex returns 400.
- oneOf is sent under its own name, or its branches are lost.
- A format the reference does not list (uri, uuid) is sent, or a listed one
  (date, date-time, int64, double) is dropped.
- A dropped constraint disappears without a trace for the model.
- A property whose name equals a keyword (not, format, propertyNames) is
  dropped.
- The same schema gives different request bytes on two turns, which breaks
  implicit prefix caching.
- A tool is removed from functionDeclarations.

Test changes:
- TestCleanToolSchema_PreservesNestedOneOfCombinator becomes
  TestCleanToolSchema_MapsNestedOneOfToAnyOf: oneOf is not a Vertex Schema
  field, so the branches now arrive under anyOf.
- TestCleanToolSchema_TraversesRetainedSchemaValuedKeywords becomes
  TestCleanToolSchema_DropsNonVertexSchemaValuedKeywordsIntoDescription:
  additionalItems, unevaluatedItems, unevaluatedProperties and dependencies
  are not Vertex Schema fields, so they move into the description hint.
- New: gemini_messages_tool_schema_test.go.
2026-11-30 17:59:58 +08:00
changjing a1c77909ed fix(gemini): end a Vertex text turn with its text, not an empty thinking block
Gemini 3 and later put a thoughtSignature on the last part of a turn. When
that part is text (or an empty text part, as streaming does), the
antigravity processors emit an empty thinking block after the text only to
carry the signature. A final Vertex turn then ends [text, thinking("")],
and Claude Code reports an empty result for it, because it reads the last
block. Headless callers that read the result get "".

Vertex enforces signatures only on functionCall parts. A missing signature
on a text part causes no error ("The API does not strictly enforce
validation for signatures in non-functionCall parts"), see
https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thought-signatures
So on the Vertex-account path the text-part signature is dropped.

Failure modes this commit guards against:
- A Vertex text turn with a signature on its text part, or in a trailing
  empty text part, ends with an empty thinking block (stream and
  non-stream).
- An empty thinking block is emitted between text and a function call, or
  after a function call, only to carry a text-part signature.
- A real thinking block loses its signature (signature_delta), or loses the
  vertex-thought-v1 marker.
- A function call loses tool_use.signature.
- Text is lost or reordered when its signature is dropped.
- The antigravity platform output changes: it must still emit the empty
  thinking block with the raw signature.

Changes:
- pkg/antigravity: ResponseTransformOptions.DropTextSignatures and
  StreamingProcessor.SetDropTextSignatures. When set, a non-thought text
  part is processed without its signature. The zero value keeps today's
  output.
- streamGeminiSSEAsClaude takes antigravity.ResponseTransformOptions
  instead of the prefix string, so stream and non-stream use one option
  set. The antigravity platform passes the zero value.
- G: geminiVertexResponseOptions (the vertex-thought-v1 marker plus
  DropTextSignatures) for the Vertex stream and non-stream renderers, the
  same switch as the marker.

Tests (go test -tags=unit):
- pkg/antigravity TestDropTextSignatures: 5 cases, stream and non-stream,
  drop on and off. Text-part signature, trailing empty part, real thinking
  plus signed text, signed text before a function call, and text split
  around a signed part. With the drop on, there is no empty thinking
  block; thinking and tool_use signatures stay, and the text stays in
  order. With it off, the output is today's.
- service TestGeminiCompatForward_VertexTextPartSignatures: a real Forward,
  stream and non-stream. A text turn renders [thinking(marker+sig), text
  "PROBE_DONE"] with no text signature; a call turn renders [text,
  tool_use(SIG_CALL)] with no empty thinking.
- service TestAntigravityClaudeStreamKeepsTextSignatureCarrier: the
  antigravity handler still emits [text, thinking] with the raw signature.
- Updated to the new rule: the Vertex render test no longer expects the
  trailing SIG_TAIL thinking block after tool_use. The Vertex signature
  test now gets its marked signature from a thought part, and checks that
  the text-part signature is not sent.
2026-11-30 17:58:30 +08:00
changjing de1967bee3 fix(gemini): send Vertex only the thinking signatures that the Vertex path emitted
After a switch from Claude to Gemini in the middle of a session, the history
holds thinking blocks with Anthropic signatures. The converter carries any
real thinking signature as thoughtSignature, so Vertex gets a foreign
signature, answers with a signature 400, and Forward retries with the
thinking blocks downgraded. That costs one extra upstream call on every
request for the rest of the session. tool_use.signature is not affected:
Anthropic tool_use blocks carry no signature.

Failure modes this commit guards against:
- A thinking signature from another upstream (no marker) reaches Vertex as
  thoughtSignature on a text or functionCall part.
- A thinking signature that the Vertex path emitted no longer round-trips:
  the marker reaches Vertex, or the signature is dropped.
- A marker in front of an empty or skip_thought_signature_validator
  signature is carried.
- tool_use.signature changes on the Vertex path.
- The Vertex response sends a thinking signature without the marker, or
  marks tool_use.signature.
- The signature-error retry rebuilds the request without the rule.
- The antigravity platform changes: its /v1/messages responses and its
  compat path (which uses the same converter) must keep raw signatures.

Changes:
- Vertex responses (stream and non-stream) send thinking-block signatures
  as "vertex-thought-v1:" + signature. tool_use signatures stay raw.
- pkg/antigravity: StreamingProcessor.SetThinkingSignaturePrefix and
  TransformGeminiToClaudeWithOptions(ResponseTransformOptions). The zero
  value keeps today's output; the antigravity callers do not set them.
- convertClaudeMessagesToGeminiRequest(body, model, markedThinkingSignatures):
  Forward sets it for Vertex accounts, on the first request and on the
  signature retry. With it set, a thinking signature is carried only when it
  has the marker, and without the marker. Without the marker the block falls
  back to today's handling: no signature on text, the dummy on a call.
  convertClaudeMessagesToGeminiGenerateContent keeps the old behaviour for
  every other caller.

Histories written by the Vertex path before this commit carry unmarked
signatures. They now fall back the same way, which costs only reasoning
continuity on those old turns.

Test changes: three assertions in gemini_messages_vertex_render_test.go now
expect the marker on thinking signatures. tool_use.signature assertions are
unchanged.
New: gemini_messages_vertex_signature_test.go,
pkg/antigravity/thinking_signature_prefix_test.go.
2026-11-30 17:58:30 +08:00
changjing 0f64666b67 fix(antigravity): map Gemini safety and invalid-output finish reasons for Claude clients
The antigravity response processors, which now also render Vertex
/v1/messages responses, mapped every finish reason except MAX_TOKENS to
end_turn (or tool_use). A blocked or broken turn then looked like a
successful empty answer: Claude Code ends the turn and the run reports
success.

Failure modes this commit guards against:
- SAFETY, PROHIBITED_CONTENT, SPII, BLOCKLIST, IMAGE_SAFETY or RECITATION
  ends as end_turn. It is now stop_reason "refusal", in stream and
  non-stream.
- A prompt blocked by promptFeedback.blockReason, with no candidates, ends
  as end_turn. It is now "refusal".
- MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS or
  MALFORMED_RESPONSE with no text and no tool_use ends as an empty
  end_turn. Thinking blocks do not count as content: with thinking on, a
  thought summary comes before almost every invalid call. The stream now
  ends with an SSE error event of type api_error, which Claude Code
  retries. Non-stream returns ErrMalformedFunctionCall or
  ErrInvalidOutputWithoutContent, which callers write as a 502.
- The same reasons after text or a tool call must still end normally
  (end_turn, or tool_use after a call). Non-stream MALFORMED_FUNCTION_CALL
  with text now gives end_turn too; the antigravity collect path still
  fails it before conversion, as before.
- After the error event, no later chunk may emit content, message_delta or
  message_stop, and the usage must still be collected for billing.
- STOP, MAX_TOKENS, OTHER and tool calls without a refusal reason keep
  their mapping. A refusal reason wins over tool_use.

Only the mapping changes; no safetySettings are added. Effects on the other
antigravity paths:
- Claude, chat-completions and responses non-stream now return 502 for
  UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS and MALFORMED_RESPONSE without
  text or tool calls, where they returned an empty 200 before.
- The chat-completions and responses stream adapters buffer the error event
  like the empty end_turn before it, so they still report an empty stream.
- Not mapped, and so still end_turn: MODEL_ARMOR, IMAGE_PROHIBITED_CONTENT,
  IMAGE_RECITATION, IMAGE_OTHER, NO_IMAGE and CONTINUATION.

Tests: pkg/antigravity/finish_reason_test.go (stream and non-stream per
reason), gemini_messages_vertex_finish_test.go (Vertex /v1/messages through
Forward).
2026-11-30 17:58:30 +08:00
changjing 069e75c47e fix(gemini): keep tool result order, errors, documents and thinking signatures in history
Four request-side defects in convertClaudeMessagesToGeminiContents. They
apply to every caller of the Gemini compat converter, including the
antigravity compat path for gemini-* models.

Failure modes this commit guards against:
- Two parallel calls of the same tool get each other's results. Claude Code
  sends tool results in completion order, and Vertex v1 matches a
  functionResponse to its functionCall by position, because ids are stripped
  (Vertex documents them for v1beta1 only, and the compat path calls /v1).
- A result whose tool_use_id is not in the previous model turn lands among
  the known results.
- Reordering moves other parts of the user message.
- is_error is dropped, so the model cannot tell a failed call from output.
- A PDF read by Claude Code arrives as a document block inside tool_result
  and is dropped. The "PDF file read: ..." text must also stay.
- A top-level base64 document is sent as JSON text with the base64 inside,
  and a text-source document is not sent as plain text.
- A real thinking signature from history is dropped. An empty or
  skip_thought_signature_validator signature must not be attached,
  tool_use.signature must win over a thinking signature, and a parallel
  sibling call must keep the dummy signature, also when the first call has
  its own signature.
- A signature-only thinking block that follows a text block is lost. The
  antigravity processors emit a text part's signature this way (text first,
  then an empty thinking block with the signature), and a signature from a
  final empty text part the same way at the end of the message. Such a
  block is the text's own signature, so it also replaces a signature that
  the text got from an earlier thinking block.

Changes:
- Results: each user message's functionResponse parts are reordered, in
  place, to the call order of the previous model turn by tool_use_id.
  Unknown ids go after the known ones. Other parts keep their positions.
  stripGeminiFunctionIDs stays.
- is_error: response is {"error": text}; otherwise {"content": text} as
  before.
- Documents: a base64 document becomes inlineData, a text-source document a
  text part, other sources keep the JSON-text fallback. Inside tool_result,
  base64 documents travel with images: in functionResponse.parts on models
  with multimodal function responses (Gemini 3+), else as trailing parts.
- Signatures: the shape of upstream PR #8545, made stricter. A real
  signature on a thinking block goes to the very next text or functionCall
  part only. If that part has its own signature, the carried one is
  dropped, so later parallel calls keep the dummy. A signature-only
  thinking block right after a text part goes back to that text part.
  ensureGeminiFunctionCallThoughtSignatures stays as the fallback.
- After a switch from Claude in the same session, Anthropic thinking
  signatures in history now reach Vertex in place of the dummy. Vertex then
  answers with a signature error, and the existing signature retry in
  Forward downgrades the thinking blocks and sends the request again.

Tests: gemini_messages_history_test.go replays the block shapes of a
captured Claude Code session (signature echoes, out-of-order parallel
results, a PDF read, an error result, a tool_reference result).
2026-11-30 17:58:30 +08:00
changjing d6585a2cad fix(gemini): render Vertex /v1/messages responses with the antigravity processors
Vertex accounts (service account JSON and API key) on /v1/messages keep the
Gemini compat request converter and the Vertex transport. Their responses are
now rendered by pkg/antigravity's StreamingProcessor (stream) and
NonStreamingProcessor (non-stream), the same processors that the antigravity
compat path already uses for gemini-* models. Both read plain Vertex
responses with no v1internal wrapper. Other account types keep the compat
emitters unchanged.

Failure modes this commit guards against:
- The client usage carries no cache_read_input_tokens when Vertex reports
  cachedContentTokenCount. Claude Code then starts auto-compaction late or
  never, and long sessions fail.
- The thoughtSignature of a functionCall part does not reach
  tool_use.signature, so the next turn falls back to the dummy signature.
- The signature of a thought part is not sent as a signature_delta.
- A signature that arrives in a final empty text part is lost. Vertex
  documents that a stream can return the signature this way. The
  antigravity processors had the trailing-signature branch, but processPart
  never reached it for an empty text part.
- Non-stream: no thought text (includeThoughts was set for stream only), no
  signatures, and a call without args has no input object.
- A text chunk that is a prefix of earlier text is dropped as a duplicate.
- Web search grounding sources (groundingMetadata) never reach the client.
- Billing drifts: the recorded usage must still come from the upstream
  usageMetadata (input minus cached, cache read, output plus thoughts, image
  output tokens), and image outputs must still be counted.
- An empty upstream stream must fail over before a byte reaches the client.
- A client that leaves before any usage arrives must stay unbilled, as in
  the compat stream handler.
- Non-Vertex accounts must keep the compat emitter.

Changes:
- AntigravityGatewayService.handleClaudeStreamingResponse becomes a thin
  wrapper around streamGeminiSSEAsClaude(cfg, observeLine). The antigravity
  path passes its own config and line observer, so its behaviour does not
  change.
- GeminiMessagesCompatService.Forward: for Vertex accounts, the stream is
  rendered by streamGeminiSSEAsClaude, and the non-stream body by
  antigravity.TransformGeminiToClaude. Model, image and usage observation
  per upstream payload stay as in the compat emitters, so billing keeps its
  source. includeThoughts is also requested for non-stream calls.
- pkg/antigravity: a tool_use with no args serializes "input": {}, and a part
  that carries only a thoughtSignature reaches the trailing-signature path.
  An image part keeps today's behaviour.

The non-stream path keeps upstream generateContent, so the existing Vertex
endpoint tests still apply unchanged.

Behaviour changes beyond the fixes:
- The signature-only part fix is in pkg/antigravity, so the antigravity
  platform's own Claude responses now also carry such a signature as an
  empty thinking block, where it was dropped before.
- Vertex image models on /v1/messages now return generated images as
  markdown data-URL text, as the antigravity processors render them. The
  compat emitter did not forward images on this endpoint.

Tests: gemini_messages_vertex_render_test.go (Forward with a Vertex API key
account and scripted Vertex chunks), pkg/antigravity/signature_part_test.go.
2026-11-30 17:58:30 +08:00
mengkzhaoyun 50eb7befec fix(scheduler): preserve resolved Grok subscription_tier in metadata projection 2026-11-30 17:19:10 +08:00
r266-tech 527c37ac26 fix(channels): include mapped Gemini models in Antigravity pricing sync 2026-11-29 21:13:03 -08:00
feeeei c1b4041f35 feat(gateway): enable top-level auto cache_control for chat completions to Anthropic
Add top-level CacheControl to apicompat.AnthropicRequest and inject {"type":"ephemeral"} on Chat Completions to Anthropic API-key forwarding paths for Claude models, respecting explicit client cache_control overrides and null/false opt-out. Also count top-level cache_control objects toward Anthropic's 4-breakpoint limit in enforceCacheControlBlockLimit.
2026-11-30 11:22:22 +08:00
GrantElizabeth 5c69258b3f fix(scheduler): support opt-in group isolation in simple mode 2026-11-30 10:36:30 +08:00
r266-tech ef3649aafe fix(frontend): keep usage displays tied to the current request 2026-11-30 03:36:50 +09:00
一叶飘零andClaude Opus 4.6 2eb3170504 fix: use checked type assertion to pass errcheck lint
The golangci-lint CI job fails because check-type-assertions is enabled
and version.Load().(string) uses the unchecked single-value form.
Switch to the two-value form so the linter is satisfied.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-11-30 01:47:41 +08:00
pangxin12345 bc1a717083 fix(openai): normalize standalone browser tabs context
The Codex desktop in-app browser sends the open tabs as an agent-namespace
function_call_output named browser_tabs without a call_id. It is not on the
untrusted-context allowlist, so HTTP Responses requests are rejected with
"function_call_output requires call_id". Add it next to browser_info and
terminal_info so it is rewritten into a user message like the others.
2026-11-29 19:39:24 +08:00
r266-tech cd73d7975e fix(accounts): preserve Antigravity options on refresh token import 2026-11-29 13:32:29 +09:00
r266-techandClaude Opus 5.5 df3c428142 fix(openai): fail over standalone alpha search on API-key upstream 400
Some OpenAI-compatible relays reject the standalone Codex search endpoint
with HTTP 400 while serving /v1/responses normally. The 400 was passed
straight to the client, so search failed even when another account in the
group could serve it.

For API-key accounts, a 400 from /v1/alpha/search now fails over to the
next eligible account without account-health side effects or same-account
retries. When failover is exhausted the last upstream status and body are
returned unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 11:24:35 +09:00
Erywim 58b026c0b1 fix(billing): alert again when a new deduction crosses the balance threshold 2026-11-29 01:28:49 +08:00
Erywim a622eca4f9 fix(openai): strip safety review details from client-visible failed events 2026-11-29 01:19:19 +08:00
github-actions[bot] f53641e53c chore: sync VERSION to 0.2.26 [skip ci] 2026-11-28 08:23:23 +00:00
shaw 9494105c7e Revert "Merge pull request #7672 from william-drakemond/fix/updater-require-checksum"
This reverts commit 2b47d8a36c, reversing
changes made to e38f8ad784.
2026-11-28 16:14:12 +08:00
li e40a84edac fix(apicompat): keep max_tokens above the Responses thinking budget
ResponsesToAnthropicRequest defaults max_tokens to 8192 when the
Responses request has no max_output_tokens, and turns any effort above
low into thinking.type=enabled with an effort-derived budget: 10240 for
high, 32768 for xhigh/max. Anthropic requires max_tokens to be greater
than budget_tokens, so every effort above medium was rejected with
"budget_tokens must be less than max_tokens". Codex never sends
max_output_tokens, so its users could not work around it.

After the conversion, raise max_tokens to budget_tokens + 1000 when an
enabled budget does not fit, the same rule and padding the Antigravity
transformer applies in ensureMaxTokensGreaterThanBudget. Requests that
already fit, adaptive thinking, and requests without thinking are
unchanged.

Fixes #6569
2026-11-28 15:25:28 +08:00
li 1e8f5f3c39 fix(websearch): show why the admin web search test failed
The admin "Test" button for web search emulation always showed
"internal error". Manager.TestSearch dropped every provider's error with
a bare `continue` and returned "no available provider", and the handler
passed that plain error to response.ErrorFrom, which maps it to a 500
with the generic message. A wrong key, an exhausted plan, a proxy
failure and an unsaved config all looked the same.

Keep each provider's error in TestSearch and join them when every
provider fails, and return the cause from the handler as a 400, the
same way the SMTP connection test already does. TestSearch is admin
only; the production SearchWithBestProvider path is unchanged.

Refs #7201
2026-11-28 14:45:25 +08:00
li 80ba2fca9a fix(websearch): authenticate Tavily with a Bearer header
Tavily's /search endpoint documents a single credential scheme,
`Authorization: Bearer <key>`, and its official Python/JS SDKs send only
that header. The provider still put the key in an `api_key` body field
and sent no Authorization header, so web search emulation through
Tavily relied on an undocumented contract. Brave and Exa in the same
package already send their keys as headers.

Send the key as a Bearer token and drop it from the request body. The
old unit test only marshalled the request struct and asserted the body
`api_key`, so it locked in the stale contract without exercising
Search(); replace it with a test that drives Search() through a
recording transport and checks the outgoing headers and body.

Refs #7201
2026-11-28 14:41:57 +08:00
Wesley Liddick cd3a998434 Merge pull request #9132 from william-drakemond/pr/aistudio-thought-signature
fix(openai): 为发往 AI Studio 的历史 tool_calls 补齐 Gemini thought_signature / Add Gemini thought signatures to AI Studio tool-call history
2026-11-28 13:06:33 +08:00
Wesley Liddick 122cda9896 Merge pull request #9131 from william-drakemond/pr/chat-stream-null-tool-index
fix(apicompat): 无 index 的并行 tool_calls 不再合并为同一项 / Keep index-less parallel tool calls separate
2026-11-28 13:06:26 +08:00
Wesley Liddick 8d5b3fda3c Merge pull request #9130 from william-drakemond/pr/merge-assistant-commentary-after-tool-calls
fix(apicompat): 合并紧跟在 tool_call 后的 assistant 文本消息 / Merge assistant commentary after tool calls
2026-11-28 13:06:19 +08:00
Wesley Liddick 86bae77dab Merge pull request #9129 from william-drakemond/pr/responses-input-object-arguments
fix(apicompat): ResponsesInputItem.Arguments 兼容 JSON 对象格式 / Accept JSON object arguments in ResponsesInputItem
2026-11-28 13:06:12 +08:00
Wesley Liddick a233668015 Merge pull request #9127 from fengshao1227/fix/antigravity-quota-exhausted-switch-immediately
fix(antigravity): QUOTA_EXHAUSTED 429 立即冷却并切换账号,不再同号退避重试
2026-11-28 13:06:05 +08:00
Wesley Liddick 2eaf0e645d Merge pull request #9126 from fengshao1227/fix/pending-oauth-form-always-verify-email
fix(auth): 第三方首登建号表单不再按全局邮箱验证开关隐藏验证码
2026-11-28 13:05:56 +08:00
Wesley Liddick 5b2498bac9 Merge pull request #9125 from fengshao1227/fix/anthropic-message-start-output-usage-v2
fix(gateway): 原生 Anthropic 流保留 message_start 已上报的 output_tokens
2026-11-28 13:05:49 +08:00
Wesley Liddick 60793b1bde Merge pull request #9124 from fengshao1227/fix/chat-bridge-incomplete-terminal-event
fix(apicompat): Chat→Responses 流在 length 截断时以 response.incomplete 收尾
2026-11-28 13:05:41 +08:00
Wesley Liddick 8fbc096757 Merge pull request #8704 from yakwu/fix/usage-tooltip-viewport-clamp
fix(frontend): keep info tooltips inside the viewport on mobile
2026-11-28 13:05:34 +08:00
Wesley Liddick 099818d164 Merge pull request #8244 from AndersonBY/codex/antigravity-quota-precision
fix(antigravity): preserve fractional quota utilization
2026-11-28 13:05:25 +08:00
ninedrunk f34df0e313 feat(accounts): 让所有受支持平台都能配置账号级自动停调阈值
后端已对 AllowedSchedulingThresholdPlatforms 中所有平台支持账号级
account_scheduling_threshold 覆盖,系统设置页也通过
SCHEDULING_THRESHOLD_PLATFORMS 展示了完整清单。

但账号编辑弹窗把 override 支持平台硬编码为 openai / anthropic / grok,
导致 Kimi / Zhipu GLM / MiniMax / OpenCode Go / Command Code 账号
即使后端完全支持,也没有 UI 可以配置账号级阈值。
创建账号弹窗则完全没有该选项。

改动:
- 编辑弹窗改为从 SCHEDULING_THRESHOLD_PLATFORMS 派生支持平台,
  消除前后端清单漂移;
- 创建账号弹窗新增同样的账号级阈值覆盖入口;
- 沿用 credentials.account_scheduling_threshold 键及原有语义。

不改动后端逻辑,不影响现有平台行为。
2026-11-28 12:52:13 +08:00
William Drake efda6f6fb0 fix(openai): add Gemini thought signatures to AI Studio tool-call history
Google AI Studio rejects replayed function calls without a thought signature (400 "Function call is missing a thought_signature in functionCall parts"). The signature arrives in tool_calls[].extra_content.google, which Codex Responses history cannot preserve, so follow-up turns after tool calls fail when routed to AI Studio.

Before a Chat Completions request goes to generativelanguage.googleapis.com, give each assistant tool call without an existing thought_signature the dummy value skip_thought_signature_validator (matching the native Gemini path). Signatures embedded in Unity/LiteLLM "__thought__" call-id suffixes are not reused because they are issued by a different Google backend and fail with INVALID_THOUGHT_SIGNATURE; the call id itself is kept intact so tool outputs still match. Other upstreams are byte-for-byte unchanged.
2026-11-27 16:21:34 -07:00
William Drake bb58d8103e fix(apicompat): accept JSON object arguments in ResponsesInputItem 2026-11-27 16:21:12 -07:00
William Drake 63b5e11e04 fix(apicompat): merge assistant commentary after tool calls 2026-11-27 16:21:07 -07:00
William Drakemond 59caf6d08b fix(apicompat): keep index-less parallel tool calls separate
Google AI Studio OpenAI-compatible streams send parallel tool calls
without an index, each whole in its own chunk with its own id. A missing
index defaulted to 0, so both calls merged into one item with arguments
like {"cmd":"ls"}{"cmd":"date"} and the stream failed with
invalid tool call arguments (502). Without an index, continue the last
call when the delta has no id or the same id, otherwise open the next
contiguous slot. Indexed streams are unchanged.
2026-11-27 16:21:02 -07:00
Anderson cd65afc0fd merge current upstream main into quota precision fix 2026-11-28 00:23:00 +08:00
li c2f3bcfe3f fix(antigravity): QUOTA_EXHAUSTED 429 立即冷却并切换账号,不再同号退避重试
classifyAntigravity429 已把配额耗尽识别为 antigravity429QuotaExhausted,但
handleSmartRetry 只在 overages 分支用到它;积分不可用或积分重试失败后,因
parseAntigravitySmartRetryInfo 只认 RATE_LIMIT_EXCEEDED,函数返回 Continue,
antigravityRetryLoop 在同一个已耗尽账号上再做 2 次指数退避(1s+2s 和两次
必然失败的上游请求),开启 overages 时还会逐次重复积分重试。

现在该情形按重试用尽时的同一套规则冷却账号(handleError,按 quotaResetDelay
写模型级限流),清理粘性会话并返回 AntigravityAccountSwitchError,与
RATE_LIMIT_EXCEEDED 长延迟分支一致;同时记录 failover 运维事件保留 429 原因。

- 把循环末尾"裸 429 认领 + 冷却"提为 applyAntigravity429Cooldown 共用,
  message-only 的 QUOTA_EXHAUSTED(同属裸 429)仍遵守每请求最多冷却一个账号。
- Claude 路径签名/budget 修正二次重试收到切换信号时转为 failover(新增
  antigravityRetrySwitchToFailover,与 Gemini 路径一致),不再吞掉后返回原始 400。

既有用例 429WithResetDelay_CoolsEveryAccount 断言循环返回 429 响应,改为断言
返回切换信号且每个账号冷却一次,用例本意不变。

Refs #8978
2026-11-27 19:33:54 +08:00
li 418bcedbbd fix(auth): 第三方首登建号表单不再按全局邮箱验证开关隐藏验证码
后端 createPendingOAuthAccount → RegisterOAuthEmailAccount → VerifyOAuthEmailCode
无条件要求本地邮箱验证码(注释写明有意独立于全局 email_verify_enabled),
发码端点 SendPendingOAuthVerifyCode 同样不看该开关。共享表单
PendingOAuthCreateAccountForm 却在全局开关关闭时隐藏发码入口并把验证码
清空提交,导致微信、OIDC、钉钉首登(及需邀请码时的 Linux DO)在关闭邮箱
验证后一律返回 EMAIL_VERIFY_REQUIRED,用户无法完成建号。

门控源自 aea2950b1:后端只给 Linux DO 加了关闭验证时直接登录的分支,
却把门控加在了所有提供方共用的表单上。去掉该门控,始终显示发码入口
并提交用户填写的验证码;普通注册页 RegisterView 不受影响。

原用例把"关闭时隐藏控件、提交空验证码"写成了预期,改为断言控件仍在、
可发码、提交携带验证码。

Fixes #9103
2026-11-27 19:19:03 +08:00
li 289791ab2b fix(gateway): 原生 Anthropic 流保留 message_start 已上报的 output_tokens
/v1/messages 的通用解析 extractSSEUsagePatch 与透传解析 parseSSEUsagePassthrough
在 message_start 分支都不读 usage.output_tokens,只靠后续 message_delta。
上游在 message_delta 前 EOF / 读错误 / 超时时,已观测到的输出用量被记成 0,
造成少计费。Antigravity 解析器与兼容路径的 mergeAnthropicUsage 早已对
message_start 读取 output_tokens > 0,本次对齐这两处。

message_delta 的 output_tokens 是累计值,继续覆盖起始值,不相加。

Fixes #7873
2026-11-27 19:05:47 +08:00
li a0522fae7f fix(apicompat): Chat→Responses 流在 length 截断时以 response.incomplete 收尾
FinalizeChatCompletionsResponsesStream 在 finish_reason=length 时已把
response.status 置为 incomplete 并带上 incomplete_details,但终止事件名
仍固定为 response.completed。按事件类型分派的 Responses 客户端(如 Codex)
会把被 max_tokens 截断的输出当作正常完成。

兄弟转换器 Anthropic→Responses 早已按 status 选择 response.incomplete,
本次对齐。计费用量取自上游原始 chunk 扫描,不读取这批事件,不受影响;
仓库内 Responses→Chat 转换器已把 response.incomplete 识别为终止事件。

既有两条用例把旧事件名编码进 switch 分支、且无"必须看到终止事件"的标志,
改名后断言会被静默跳过;改为匹配 response.incomplete、遇到 completed 直接
失败,并补 sawIncomplete 标志。

Refs #7876
2026-11-27 18:59:27 +08:00
Wesley Liddick 4233cc3d80 Merge pull request #9121 from Wei-Shaw/fix/moderation-anthropic-url-image
fix(moderation): moderate Anthropic URL image sources
2026-11-27 18:35:51 +08:00
shaw 959d365324 fix(moderation): moderate Anthropic URL image sources
Content moderation collected Anthropic image blocks only from source.data, never
from source.url. Since #8312 the /v1/messages -> OpenAI Responses bridge forwards
URL image sources upstream as input_image, so an image sent as
{"type":"url","url":...} (including a data: URI) reached the model without
being moderated, while the same image sent as base64 was. The native Anthropic
path forwarded such images unmoderated as well.

Collect source.url like the other image URL fields; addModerationImage still
accepts only http(s) and data: values.
2026-11-27 18:03:17 +08:00
Wesley Liddick 8aa4d39288 Merge pull request #9115 from NewtonCookie/fix/anthropic-chat-usage
fix: sample Claude usage on chat completions
2026-11-27 17:06:19 +08:00
Wesley Liddick aaec3887d0 Merge pull request #8843 from r266-tech/codex/oauth-deadline-clock-fixture
test(oauth): make late refresh deadline deterministic
2026-11-27 17:06:15 +08:00
Wesley Liddick a2df5a86e9 Merge pull request #8839 from r266-tech/codex/precontent-keepalive-clock-fixture
test(antigravity): stabilize repeated pre-content keepalives
2026-11-27 17:06:11 +08:00
Wesley Liddick d3ae7a17a6 Merge pull request #8756 from r266-tech/codex/synchronize-ws-ttft-fixture
test(openai): synchronize WebSocket TTFT fixtures
2026-11-27 17:06:07 +08:00
Wesley Liddick affdc20c02 Merge pull request #8705 from lzj960515/fix/request-memory-lifecycle
fix(gateway): 减少长会话请求的内存分配与持有
2026-11-27 17:06:02 +08:00
Wesley Liddick 7c6cbda974 Merge pull request #8596 from lkon2112/fix/grok-quota-test-races
test(grok): synchronize free-quota refresh tests
2026-11-27 17:05:57 +08:00
Wesley Liddick f7e0191ac2 Merge pull request #8355 from Yukinoshita-Yukino/codex/kimi-k31-minimal-support
fix(kimi): add K3.1 Pro routing, Codex reasoning and default pricing
2026-11-27 17:05:52 +08:00
Wesley Liddick 25a65452f2 Merge pull request #8312 from zyh-y/fix/anthropic-url-image-sources
fix(apicompat): preserve Anthropic URL image sources
2026-11-27 17:05:48 +08:00
Wesley Liddick 1d65de5cae Merge pull request #8295 from r266-tech/codex/fix-responses-tool-failover
fix(openai): fail over Sol/Terra tool requests on Chat-only accounts
2026-11-27 17:05:43 +08:00
Wesley Liddick 6e537028d4 Merge pull request #8254 from AndersonBY/codex/fix-quota-label-overlap
fix(frontend): keep long quota labels clear of progress bars
2026-11-27 17:05:39 +08:00
Wesley Liddick 6215b9fe5f Merge pull request #8246 from AndersonBY/codex/antigravity-parallel-tool-images
fix(antigravity): keep parallel tool results contiguous across notices
2026-11-27 17:05:35 +08:00
Wesley Liddick 18f8813da3 Merge pull request #8245 from AndersonBY/codex/antigravity-local-usage-stats
fix(accounts): show local Antigravity usage statistics
2026-11-27 17:05:31 +08:00
Wesley Liddick eaf4521e78 Merge pull request #8217 from r266-tech/codex/compact-failure-model
fix(responses): include model in compact failure events
2026-11-27 17:05:26 +08:00
Wesley Liddick 2b47d8a36c Merge pull request #7672 from william-drakemond/fix/updater-require-checksum
fix(update): 在线更新强制校验 checksum,缺失时拒绝安装
2026-11-27 17:05:22 +08:00
shaw fa375e60e1 fix(kimi): keep stripping the Codex none placeholder for K3.1
The previous Codex catalog advertised only "none" for k3.1-pro, so Codex
clients that still hold it send reasoning.effort=none. Preserving none for
K3.1 made those requests fail upstream with HTTP 400 (K3.1 cannot disable
thinking) instead of running at the default effort as they do today.

Keep the existing compatible-upstream rule on the Responses path: strip the
none placeholder for K3.1 exactly like every other Kimi model. The new
catalog no longer advertises none, so current clients are unaffected.
2026-11-27 16:29:02 +08:00
shaw 8950e12524 fix(gateway): keep OpenCode session hints valid JSON
openCodeSessionHintBody built the hint with strconv.Quote, which emits Go
escapes such as \U000f0001 that are not JSON. A session id containing such a
rune (private-use or tag characters, e.g. subdivision flag emoji) was read
back truncated, so different conversations could share one
x-opencode-session. Encode with json.Marshal instead.

Also measure the compaction allocation budget in a child test process, as
main already does for other process-wide allocation counters, so background
goroutines left by other service tests cannot fail it intermittently.
2026-11-27 16:27:11 +08:00
shaw cbe5bfd1cb fix(gateway): sample Claude usage on the Responses bridge too
The Anthropic /v1/responses bridge had the same gap as the Chat Completions
bridge: successful OAuth/setup-token responses never refreshed the 5h/7d
subscription windows. Sample the response headers on 2xx exactly like the
Chat Completions path, and cover both bridges in one regression test.
2026-11-27 16:25:22 +08:00
Yakun WuandClaude Opus 5.5 8cbd318de3 fix(frontend): keep info tooltips inside the viewport on mobile
HelpTooltip always centered its popup above the trigger, so on a ~375px
screen any info icon near the left or right edge (ops dashboard cards,
accounts table headers, modal fields) pushed the tooltip off screen.
Several forms also hand-rolled CSS-only hover popups that are absolutely
positioned from the icon and get cut off by the viewport and the dialog
body.

- Move the placement logic from UsageTable into a shared
  getTooltipPosition helper (utils/floatingPanel.ts): prefer one side,
  flip to the opposite side when it does not fit, otherwise pin to the
  viewport edge; clamp the cross axis.
- HelpTooltip measures its popup and uses the helper (above, flipping
  below near the top of the screen); the arrow keeps pointing at the icon.
- UsageTable token/cost tooltips use the same helper.
- Replace the hand-rolled info popups in GroupsView, Create/EditAccountModal
  and the usage stats cache breakdown with HelpTooltip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:31:58 +08:00
Yakun WuandClaude Opus 5.5 5d3ec1aa16 fix(usage): keep token/cost detail tooltips inside the viewport
The token and cost detail tooltips in the usage table were always placed
8px to the right of the info icon. On narrow (mobile) screens the cost
column sits near the right edge, so the non-wrapping tooltip was cut off.

After rendering, measure the tooltip: flip it to the left of the icon when
it does not fit on the right, pin it to the right edge when neither side
fits, and clamp it vertically to the viewport.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:22:26 +08:00
Wesley Liddick e38f8ad784 Merge pull request #9118 from Wei-Shaw/fix/proxy-selector-account-count
fix(accounts): 代理下拉框右侧显示账号数并在打开弹窗时刷新
2026-11-27 15:07:05 +08:00
Wesley Liddick 96148ee93b Merge pull request #9117 from Wei-Shaw/fix/issue-8992-image-safety-risk-control
fix(risk-control): 生图安全系统拒绝纳入风控中心(仅留证)
2026-11-27 15:06:28 +08:00
shaw 397f66aebf fix(risk-control): tighten image safety detection and display
Review follow-up:

- Stop treating parameter errors as safety rejections. The message
  matcher no longer uses a bare "moderation" keyword and rejects
  "unknown/unrecognized/unsupported parameter" style messages, so
  Azure-style "Unrecognized request argument supplied: moderation"
  (param null) and error-passthrough rewrites (which drop param/code)
  are not recorded with the user's prompt.
- Check explicit safety codes before the param exclusion, so Azure
  content filtering (code=content_filter, param=prompt), contentFilter
  and ResponsibleAIPolicyViolation are recorded; response_incomplete is
  only a 400 for content_filter/moderation reasons and counts as well.
- Show image_safety rows with the hit badge instead of the amber error
  badge, and exclude them from the "error" result filter.
2026-11-27 14:45:25 +08:00
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
r266-tech abe5903a17 Merge main and use the upstream allocation test isolation 2026-11-27 15:07:06 +09: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
shaw 75e6df8f4a fix(risk-control): record image safety-system rejections in the risk center
Image requests rejected by the upstream safety system (for example
"Your request was rejected by the safety system") were only visible in
the ops error log. They are now also written to the risk control center
as log-only evidence (action=image_safety, mode=risk_control_log_only):
no hash blacklist, no auto-ban count, no email, response unchanged.

Detection covers HTTP 400 from the native Images API, SSE/Responses
error events, model refusal text and content_filter incompletes. 400s
carrying error.param (e.g. an invalid `moderation` value) are excluded.
The record uses the gateway request ID from context so it joins with the
ops error log; the response header may carry the upstream x-request-id.

Refs #8992
2026-11-27 13:51:32 +08:00
NewtonCookie 650fab97d2 fix: sample Claude usage on chat completions 2026-11-27 11:40:40 +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
r266-tech 126d7743e2 fix(responses): include requested model in compact failure events 2026-11-27 05:24:43 +09: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
liaozijian 85cf114332 fix(gateway): reduce large request allocation and retention 2026-11-26 17:39:29 +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
一叶飘零 cc08bc0f17 fix(codex): use automatic identity for catalog downloads
Remove hardcoded DEFAULT_CODEX_CLIENT_VERSION. The download UI now
sends format=codex so the gateway uses its automatically maintained
Codex identity. Explicit client_version negotiation is preserved.

- Frontend: codex.ts drops default version; uses format param
- Backend: gateway.go accepts format=codex alongside client_version
- Tests: 44 vitest + Go route/service regressions

Upstream PR: https://github.com/Wei-Shaw/sub2api/pull/7557
2026-11-25 01:30:41 +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
feeeei 6a8fca6b4e fix(openai): 保留 Codex ExternalMessage namespace 并禁止 OAuth 误提升 id 为 call_id
- stripOpenAIResponsesInputNamespacesWithOptions 在非 compact、非摊平的 OpenAI OAuth/API Key 转发上保留 standalone ExternalMessage(无 call_id 且带 name+namespace 的 function_call_output)的 namespace,单次遍历防重复键走私(0 allocs/op)
- filterCodexInputWithOptions 不再将 standalone ExternalMessage 的 id 提升为 call_id,避免 OAuth HTTP 路径孤儿清理误删或 WSv2 路径伪造 call_id
- removeOpenAIResponsesRejectedNamespaceAtIndex 同步支持反应式剥离上游显式拒绝的 ExternalMessage input[N].namespace
2026-11-24 12:37:48 +08:00
feeeei d29660bfd7 fix(openai): 兼容长对话 Codex 定时 heartbeat 归一化与未转义 instructions
- normalizeCodexAutomationBootstrap 改为 allowHistoricalContext = true,允许与可明确配对的历史调用上下文及 previous_response_id 共存
- normalizeCodexCallOutputBootstrap 放行服务端托管 *_call、带 id/call_id 的 tool_search_call 以及同帧合法兄弟 delegation 与 agent ExternalMessage,避免互相死锁
- validCodexAutomationHeartbeat 改为按精确外层标签边界提取 <instructions> 原文,兼容未 XML 转义的 &、<tag> 与正文内字面量 </instructions>,同时拒绝重复标签与分裂信封
2026-11-24 12:37:48 +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
Yuan Liu 3313acad75 Merge upstream main and keep K3.1 Pro support
Conflict in backend/internal/service/openai_oauth_model_support_test.go:
upstream moved claude-sonnet-4-6 / claude-3-opus-20240229 into the
foreign-model list, while this branch added k3.1 / k3.1-pro-preview to the
servable list. Keep both sides: upstream's list plus the K3.1 aliases.
2026-11-23 14:44:02 +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
zyh-y 5dcf1801da Merge upstream main into fix/anthropic-url-image-sources
Validate the Anthropic image conversion fix against current main.
2026-11-22 21:31:53 +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
Anderson 14f949cbe2 test: use precise quota utilization type 2026-11-21 14:22:21 +08: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
Anderson 09c8e61277 Merge remote-tracking branch 'origin/main' into codex/fix-quota-label-overlap 2026-11-20 23:53:37 +08:00
Anderson 2ca3d72c04 Merge remote-tracking branch 'origin/main' into codex/antigravity-parallel-tool-images 2026-11-20 23:51:31 +08:00
Anderson e7354a91a1 Merge remote-tracking branch 'origin/main' into codex/antigravity-local-usage-stats
# Conflicts:
#	frontend/src/components/account/__tests__/AccountUsageCell.spec.ts
2026-11-20 23:51:14 +08:00
Anderson 1cd583d501 Merge remote-tracking branch 'origin/main' into codex/antigravity-quota-precision
# Conflicts:
#	frontend/src/components/account/__tests__/AccountUsageCell.spec.ts
2026-11-20 23:50:26 +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
William DrakeandClaude Opus 5.5 8ea6cd527f fix(update): require checksum verification before installing update
Abort the online update when the release has no checksums.txt, the
archive is not listed in it, or it cannot be fetched (fail closed).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-19 12:18:04 -07:00
lkon 27f044d45e test(grok): skip setup resets for private quota caches 2026-11-18 21:26:31 +08:00
Weicheng Yu 8185695197 Merge upstream main v0.2.23 2026-11-18 15:26:41 +08:00
r266-tech e281ae3e88 test(oauth): make late refresh deadline deterministic 2026-11-18 10:48:21 +08:00
Weicheng Yu 02dea61bdb Merge upstream main and retain upstream tool-schema allocation isolation
Keep upstream's subprocess isolation in the overlapping tool-schema test.
Preserve the capacity-shed retry-delay and WS passthrough fixes, together
with the remaining allocation-test isolation guards.

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

Validation on Go 1.27.4:
- GOMAXPROCS=4 go test -tags=unit -count=1 ./...:
  28,223 test cases including subtests passed; 40 skipped.
- golangci-lint 2.14.0: 0 issues.
- Independent review of the complete PR diff: no material findings.
2026-11-18 08:55:06 +08:00
Anderson cda1eadbd6 Merge remote-tracking branch 'origin/main' into codex/fix-quota-label-overlap 2026-11-17 23:10:27 +08:00
Anderson 0a67cc4507 Merge remote-tracking branch 'origin/main' into codex/antigravity-local-usage-stats 2026-11-17 23:10:24 +08:00
Anderson fa8c944053 Merge upstream main and preserve precise quota display 2026-11-17 23:10:13 +08:00
Anderson cd8fabd65a Merge remote-tracking branch 'origin/main' into codex/antigravity-parallel-tool-images 2026-11-17 23:08:35 +08:00
r266-tech fb9ba3f7dd test(openai): synchronize WebSocket TTFT fixtures 2026-11-17 21:59:07 +08:00
r266-tech eb4d34c5e1 test(antigravity): stabilize repeated pre-content keepalives 2026-11-17 21:53:24 +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
lkon 557954f1b6 Merge remote-tracking branch 'upstream/main' into fix/grok-quota-test-races 2026-11-14 05:25:54 +08:00
Anderson 5c69ca4c26 build: use Go 1.27.4 to address standard library security finding 2026-11-11 14:30:26 +08:00
Anderson e6698f1ee0 Merge upstream main and retain interleaved tool-result notice fix 2026-11-11 14:21:14 +08:00
Weicheng Yu a55ef06db7 Merge upstream main and retain its orphan allocation test isolation
Resolve the overlapping test change by keeping the upstream implementation from PR8603 unchanged. Preserve PR8560 capacity-shed handling and the other service allocation isolation fixes.

Validated the merged tree with focused service overload, WS lifecycle and allocation tests; handler failover/retry tests; golangci-lint2.14.0 (0 issues). The separately staged BWH0.2.20 release is unchanged.
2026-11-09 11:13:23 +08:00
lkon b74ed3cda4 test(grok): synchronize free-quota refresh tests 2026-11-08 15:14:18 +08:00
Weicheng Yu c85fd1c873 test: isolate service allocation assertions from background workers
The full CI suite exposed the same process-wide allocation counter interference in signed thinking-history filtering. Reuse one subprocess helper for all six service allocation tests while retaining the original thresholds and assertions. Verify the named child test actually executed and propagate its failures.

Validation: allocation tests passed twice; related precheck, model mapping, Gemini, compaction and tool schema tests passed; golangci-lint 2.14.0 reported 0 issues. A copying-parser negative control still fails the zero-allocation assertion.
2026-11-08 12:07:21 +08:00
Weicheng Yu 40fda7a702 test: isolate orphan allocation checks and format ws regression
Merge the current upstream base so CI exercises the same orphan precheck. Run the zero-allocation assertion in a fresh test process to exclude background workers from process-wide allocation counters. Keep the strict zero-allocation assertion and remove the trailing blank line from the WS regression test.

Validated: service precheck and passthrough lifecycle tests; handler capacity/failover tests; golangci-lint 2.14.0 (0 issues). Background-allocation pressure fails before isolation and passes after; a copying-parser negative control still fails.
2026-11-08 11:11:19 +08:00
r266-tech 217925ca0b test(gateway): isolate signed-history allocation measurement 2026-11-07 18:36:52 +08:00
r266-tech 38605c1fe8 test(openai): keep invalid Terra effort out of capability failover 2026-11-07 17:53:50 +08:00
r266-tech c62ccd5ee0 test(openai): cover Terra compatibility failover 2026-11-07 17:43:14 +08:00
r266-tech 71fa80873d test(openai): assert failover through selector calls and account state 2026-11-07 17:43:14 +08:00
r266-tech a4a9c3404b test(openai): use input-item additional tools fixture 2026-11-07 17:43:14 +08:00
r266-tech 95efb93c7a fix(openai): fail over Sol tool requests on Chat-only accounts 2026-11-07 17:43:13 +08:00
Weicheng Yu c8c1e7e649 fix(openai): strip retry-after from client-forwarded capacity shed errors and cover ws passthrough 2026-11-06 22:23:54 +08:00
Yuan Liu a0c827e97b Merge upstream main and retain Kimi and Terra pricing 2026-10-27 19:57:47 +08:00
Yuan Liu ccac47e187 fix(kimi): expose K3.1 options and preserve explicit disabled reasoning 2026-10-27 10:42:21 +08:00
Yuan Liu 8dc297ce94 fix(kimi): add bundled K3.1 Pro reference pricing 2026-10-26 19:04:30 +08:00
Yuan Liu 28eb088cd6 fix(kimi): recognize K3.1 Pro models and enable Codex reasoning 2026-10-26 17:16:17 +08:00
zyh-y 1dfd0224cd fix(apicompat): preserve Anthropic URL image sources
Preserve URL image sources in Anthropic user messages and tool results across both upstream request bridges. Add regression coverage with base64 controls.
2026-10-23 15:10:02 +08:00
Anderson 0cceee50e0 fix(frontend): keep long quota labels clear of progress bars 2026-10-21 02:28:53 +08:00
Anderson 3d23cc9958 fix(antigravity): keep parallel tool results before media 2026-10-20 20:40:12 +08:00
Anderson e8d71b932e fix(accounts): show local Antigravity usage statistics 2026-10-20 20:39:48 +08:00
Anderson 2e8b1ad7fa fix(antigravity): preserve fractional quota utilization 2026-10-20 20:39:25 +08:00
557 changed files with 37741 additions and 3493 deletions

No files matched your search

+3 -1
View File
@@ -6,6 +6,8 @@ Each build uses GoReleaser OSS in snapshot mode with the selected release versio
Go caches are isolated by target and refreshed on each source commit, with fallback to the preceding target cache. Save uses the original restore key, even if a build hook changes `go.sum`. Matrix jobs upload uniquely named artifacts. The publishing job extracts only the regular Linux binary from each verified archive and restores its executable permission before constructing Docker contexts. QEMU remains limited to runtime-image instructions. DockerHub images are omitted when its credentials are absent; GHCR is always retained. Simple mode still publishes only the amd64 GHCR image and the simple release description.
A tag push is rejected in `prepare`, before anything is built or published, unless `backend/cmd/server/VERSION` at the tagged commit already equals the tag version: commit the VERSION bump first, then tag that commit. Source builds of the tag (`go build`, GitHub source archives, Docker builds without `.git`) embed that file. To re-release an older tag created before this rule, run the workflow manually with `allow_version_mismatch=true`; it then emits a warning and builds with the tag version.
All build jobs use the commit resolved by `prepare`, including a manual release's selected tag. Helper scripts come from the workflow revision and are passed as a run-local artifact, so older application tags do not need to contain the new scripts. The workflow serializes release runs to prevent simultaneous updates to moving image tags.
## Validate without publication
@@ -17,7 +19,7 @@ gh workflow run release.yml --ref <branch> \
-f tag=<branch> -f dry_run=true -f simple_release=false
```
A dry run builds all selected archives and both runtime images, verifies artifact provenance and produces the final checksum file. It exports images locally as OCI archives instead of pushing them. It skips registry logins, GitHub Release publication, DockerHub description updates, Telegram notifications and VERSION synchronization. Test the simple path separately with `simple_release=true`.
A dry run builds all selected archives and both runtime images, verifies artifact provenance and produces the final checksum file. It exports images locally as OCI archives instead of pushing them. It skips registry logins, GitHub Release publication, DockerHub description updates, and Telegram notifications. Test the simple path separately with `simple_release=true`.
Dry-run artifacts are available in the Actions run, including `release-dry-run-report`. Compare job start/end times, GoReleaser's build duration and cache restore results. Do not present an initial cold-cache run as a warmed-cache benchmark; publishing network time is not measured by dry runs.
+10
View File
@@ -63,6 +63,15 @@ def plan(args):
tagged_sha = subprocess.check_output(['git', 'rev-parse', '--verify', f'refs/tags/{tag}^{{commit}}'], text=True).strip()
if sha != tagged_sha:
raise ValueError('checkout does not match the selected release tag')
committed = VERSION_FILE.read_text().strip()
if committed != version:
# Source builds of the tag (go build, archives, Docker builds without .git)
# embed this file, so the tagged commit itself must carry the new version.
message = (f'{VERSION_FILE} at {tag} is {committed!r}, expected {version!r}; '
'commit the VERSION bump first, then tag that commit')
if not args.allow_version_mismatch:
raise ValueError(message)
print(f'::warning::{message}')
if not VERSION_RE.fullmatch(version):
raise ValueError('invalid VERSION')
VERSION_FILE.write_text(version + '\n')
@@ -161,6 +170,7 @@ def main():
p.add_argument('--ref', required=True)
p.add_argument('--simple', action='store_true')
p.add_argument('--dry-run', action='store_true')
p.add_argument('--allow-version-mismatch', action='store_true')
p.set_defaults(run=plan)
p = commands.add_parser('config')
p.add_argument('mode', choices=['build', 'publish'])
+17 -1
View File
@@ -121,8 +121,24 @@ class ReleaseMatrixTest(unittest.TestCase):
self.assertEqual(binary.read_bytes(), b'fixture')
self.assertEqual(binary.stat().st_mode & 0o777, 0o755)
def test_tag_push_requires_committed_version_to_match_tag(self):
release.VERSION_FILE.write_text('9.8.6\n')
args = argparse.Namespace(ref='v9.8.7', dry_run=False, simple=False, allow_version_mismatch=False)
with patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'):
with self.assertRaisesRegex(ValueError, "is '9.8.6', expected '9.8.7'"):
release.plan(args)
def test_manual_release_of_older_tag_warns_and_uses_tag_version(self):
release.VERSION_FILE.write_text('9.8.6\n')
args = argparse.Namespace(ref='v9.8.7', dry_run=False, simple=False, allow_version_mismatch=True)
with patch.dict(os.environ, {'GITHUB_OUTPUT': 'outputs'}), patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'):
release.plan(args)
output = dict(line.split('=', 1) for line in Path('outputs').read_text().splitlines())
self.assertEqual(output['version'], '9.8.7')
self.assertEqual(release.VERSION_FILE.read_text(), '9.8.7\n')
def test_plan_requires_a_tag_for_publication(self):
args = argparse.Namespace(ref='main', dry_run=False, simple=False)
args = argparse.Namespace(ref='main', dry_run=False, simple=False, allow_version_mismatch=False)
with patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'):
with self.assertRaisesRegex(ValueError, 'version tag'):
release.plan(args)
+9 -32
View File
@@ -20,6 +20,11 @@ on:
required: false
type: boolean
default: false
allow_version_mismatch:
description: 'Re-release an older tag whose committed VERSION predates the tag (builds with the tag version)'
required: false
type: boolean
default: false
concurrency:
group: release-${{ github.repository }}
@@ -64,10 +69,14 @@ jobs:
id: plan
env:
REQUESTED_REF: ${{ inputs.tag || github.ref_name }}
ALLOW_VERSION_MISMATCH: ${{ github.event_name == 'workflow_dispatch' && inputs.allow_version_mismatch == true }}
run: |
args=(--ref "$REQUESTED_REF")
if [[ "$SIMPLE_RELEASE" == true ]]; then args+=(--simple); fi
if [[ "$DRY_RUN" == true ]]; then args+=(--dry-run); fi
# The tagged commit must already carry the release VERSION. Only an explicit
# manual re-release of an older tag may bypass this.
if [[ "$ALLOW_VERSION_MISMATCH" == true ]]; then args+=(--allow-version-mismatch); fi
python "$RUNNER_TEMP/release-tools/release_matrix.py" plan "${args[@]}"
- uses: actions/upload-artifact@v7
with:
@@ -374,35 +383,3 @@ jobs:
parse_mode: "Markdown",
disable_web_page_preview: true
}')"
sync-version-file:
needs: [prepare, release]
if: ${{ needs.release.result == 'success' && needs.prepare.outputs.dry_run != 'true' }}
runs-on: ubuntu-latest
permissions:
contents: write
env:
RELEASE_VERSION: ${{ needs.prepare.outputs.version }}
steps:
- name: Checkout default branch
uses: actions/checkout@v6
with:
ref: ${{ github.event.repository.default_branch }}
- name: Sync VERSION file to released tag
run: |
VERSION="$RELEASE_VERSION"
CURRENT_VERSION=$(tr -d '\r\n' < backend/cmd/server/VERSION || true)
if [ "$CURRENT_VERSION" = "$VERSION" ]; then
echo "VERSION file already matches $VERSION"
exit 0
fi
echo "$VERSION" > backend/cmd/server/VERSION
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add backend/cmd/server/VERSION
git commit -m "chore: sync VERSION to ${VERSION} [skip ci]"
git push origin HEAD:${{ github.event.repository.default_branch }}
+2 -7
View File
@@ -133,8 +133,8 @@ Please read the following carefully before using this project:
</tr>
<tr>
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>Thanks to AxisNow for sponsoring this project! <a href="https://www.axisnow.io/">AxisNow</a> protects and accelerates websites and APIs, delivering an optimal access experience across mainland China and globally, while extending acceleration and security capabilities to native/mobile apps through client SDKs — <strong>self-hosted private-deployment CDN</strong> | <strong>subscription-based DDoS-protected CDN</strong> | <strong>autonomous, flexibly composable CDN network</strong>.</td>
<td width="180"><a href="https://www.axisnow.io/zh/docs/guide/sub2api"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>Protect and accelerate your Sub2API with AxisNow<br>Optimized routes for users in mainland China, WAF and rate limiting to protect your API entry point, and support for self-hosted or subscription CDN edge nodes. <a href="https://www.axisnow.io/zh/docs/guide/sub2api">View the Sub2API integration guide →</a></td>
</tr>
<tr>
@@ -162,11 +162,6 @@ Please read the following carefully before using this project:
<td>🔑 Buying AI accounts at top prices | Gemini · Claude · GPT | Main and alt accounts all welcome, any channel wanted | Pay-per-usage supported | Seeking first-hand resources from major providers, I'll bring the KEY.<br>WeChat: Liuyou-zawd | Telegram: <a href="https://t.me/AACC8888888">AACC8888888</a></td>
</tr>
<tr>
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> provides affordable global proxy solutions for web scraping, AI agents, automation, and data collection. With residential proxies starting at $0.35/GB across 190+ countries and regions, NiuProxy offers flexible plans and HTTP(S)/SOCKS5 support.<br>🎁 Use code PAY2 for 10% OFF your recharge!</td>
</tr>
<tr>
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
<td>Thanks to <a href="https://soleapi.com/r/sub2api">SoleAPI</a> for supporting this project! SoleAPI is an AI model gateway for developers and enterprises: one API key gives you access to 30+ leading models including Claude, GPT and Gemini. It is natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex, Cursor and your existing SDKs work by simply changing the Base URL. Requests are routed in real time by latency and upstream health, with millisecond-level automatic failover to backup channels, 99.99% service availability and 24/7 technical support. Every call lands on a single bill with per-request token and cost breakdowns you can inspect at any time. Sign up through this project's <a href="https://soleapi.com/r/sub2api">referral link</a> to receive free trial credits, and earn ongoing cashback by inviting friends who top up!</td>
+2 -7
View File
@@ -136,8 +136,8 @@
</tr>
<tr>
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>感谢 AxisNow 赞助了本项目!<a href="https://www.axisnow.io/">AxisNow</a> 保护并加速网站与 API,兼顾中国大陆及全球的访问体验,并通过客户端 SDK,将加速与安全能力延伸至原生/移动 App — <strong>自建私有部署 CDN</strong>|<strong>订阅式高防 CDN</strong>|<strong>自主可控、灵活组合的 CDN 网络</strong>。</td>
<td width="180"><a href="https://www.axisnow.io/zh/docs/guide/sub2api"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>使用 AxisNow 保护并加速你的 Sub2API<br>为中国大陆用户提供优化线路,通过 WAF 和速率控制保护 API 入口,支持自建或订阅 CDN 边缘节点。<a href="https://www.axisnow.io/zh/docs/guide/sub2api">查看 Sub2API 接入教程 →</a></td>
</tr>
<tr>
@@ -165,11 +165,6 @@
<td>🔑 高价收 AI 账号|Gemini · Claude · GPT|大小号通收,各种渠道都要|支持按量跑付|寻一手大厂资源,我上 KEY 。<br>微信:Liuyou-zawd|TG:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
</tr>
<tr>
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> 为网页抓取、AI 智能体、自动化和数据采集提供高性价比的全球代理解决方案。住宅代理低至 $0.35/GB,覆盖 190+ 个国家和地区,套餐灵活,支持 HTTP(S)/SOCKS5 协议。<br>🎁 使用优惠码 PAY2 充值立享 9 折优惠!</td>
</tr>
<tr>
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
<td>感谢 <a href="https://soleapi.com/r/sub2api">SoleAPI</a> 对本项目的支持!SoleAPI 是面向开发者与企业的 AI 模型网关:一个 API Key 即可调用 Claude、GPT、Gemini 等 30+ 主流模型。原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex、Cursor 及现有 SDK 只需修改 Base URL 即可接入。请求按延迟与上游健康度实时路由,毫秒级自动切换至备用通道,服务可用性达 99.99%,并提供 7×24 小时技术支持。所有调用统一账单结算,每次请求的 token 与费用明细随时可查。通过本项目的<a href="https://soleapi.com/r/sub2api">推荐链接</a>注册即可获得免费试用额度,邀请好友充值还可持续获得返现!</td>
+2 -7
View File
@@ -135,8 +135,8 @@
</tr>
<tr>
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>AxisNow のご支援に感謝します!<a href="https://www.axisnow.io/">AxisNow</a> はウェブサイトと API を保護・高速化し、中国本土および世界中で快適なアクセス体験を実現します。クライアント SDK により、ネイティブ/モバイルアプリにも高速化・セキュリティ機能を拡張できます — <strong>自社構築・プライベートデプロイ CDN</strong>|<strong>サブスクリプション型高防御 CDN</strong>|<strong>自律制御で柔軟に組み合わせられる CDN ネットワーク</strong>。</td>
<td width="180"><a href="https://www.axisnow.io/zh/docs/guide/sub2api"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>AxisNow で Sub2API を保護・高速化<br>中国本土のユーザー向けに最適化された回線を提供し、WAF とレート制御で API の入口を保護します。自社構築またはサブスクリプションの CDN エッジノードに対応しています。<a href="https://www.axisnow.io/zh/docs/guide/sub2api">Sub2API 導入ガイドを見る →</a></td>
</tr>
<tr>
@@ -164,11 +164,6 @@
<td>🔑 AI アカウント高価買取|Gemini · Claude · GPT|メイン・サブアカウントすべて買取、チャネル問わず歓迎|従量制での支払いに対応|大手の一次リソースを求めています、KEY は私が用意します。<br>WeChat:Liuyou-zawd|Telegram:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
</tr>
<tr>
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> は、Web スクレイピング、AI エージェント、自動化、データ収集向けに、手頃な価格のグローバルプロキシソリューションを提供します。住宅プロキシは $0.35/GB から、190 以上の国と地域をカバーし、柔軟なプランと HTTP(S)/SOCKS5 に対応しています。<br>🎁 コード PAY2 でチャージが 10% オフ!</td>
</tr>
<tr>
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
<td><a href="https://soleapi.com/r/sub2api">SoleAPI</a> 様、本プロジェクトへのご支援ありがとうございます!SoleAPI は開発者と企業向けの AI モデルゲートウェイです。1 つの API キーで Claude、GPT、Gemini をはじめとする 30 以上の主要モデルを利用できます。OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex、Cursor や既存の SDK も Base URL を変更するだけで動作します。リクエストはレイテンシと上流の稼働状況に応じてリアルタイムにルーティングされ、ミリ秒単位でバックアップチャネルへ自動フェイルオーバーします。サービス可用性は 99.99%、24 時間 365 日の技術サポートも提供しています。すべての呼び出しは 1 つの請求書にまとめられ、リクエストごとの token 数と費用の内訳をいつでも確認できます。本プロジェクトの<a href="https://soleapi.com/r/sub2api">紹介リンク</a>から登録すると無料トライアルクレジットを受け取れ、友人を招待してチャージしてもらうと継続的にキャッシュバックを獲得できます!</td>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

+1 -1
View File
@@ -1 +1 @@
0.2.23
0.2.27
+2 -2
View File
@@ -175,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)
@@ -208,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)
+2 -2
View File
@@ -26,7 +26,7 @@ require (
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
@@ -55,7 +55,7 @@ require (
github.com/zeromicro/go-zero v1.9.4
go.uber.org/zap v1.24.0
golang.org/x/crypto v0.58.0
golang.org/x/image v0.41.0
golang.org/x/image v0.45.0
golang.org/x/mod v0.41.0
golang.org/x/net v0.62.0
golang.org/x/sync v0.24.0
+4
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=
@@ -589,6 +591,8 @@ golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
+29 -10
View File
@@ -115,9 +115,19 @@ type Config struct {
SimpleModeKeyRateLimitEnabled bool `mapstructure:"simple_mode_key_rate_limit_enabled" yaml:"simple_mode_key_rate_limit_enabled"`
}
// SimpleModeConfig controls startup behavior in simple mode.
// SimpleModeConfig controls optional behavior in simple mode.
type SimpleModeConfig struct {
AutoCreateDefaultGroups bool `mapstructure:"auto_create_default_groups" yaml:"auto_create_default_groups"`
GroupIsolation bool `mapstructure:"group_isolation" yaml:"group_isolation"`
}
// UsesSharedSimpleModePool reports whether scheduling may ignore account group bindings.
func (c *Config) UsesSharedSimpleModePool() bool {
return c != nil && c.RunMode == RunModeSimple && !c.SimpleMode.GroupIsolation
}
func (c *Config) SimpleModeGroupIsolationEnabled() bool {
return c != nil && c.RunMode == RunModeSimple && c.SimpleMode.GroupIsolation
}
// MCPConfig fixes the public resource URL used by OAuth discovery and tokens.
@@ -1179,6 +1189,9 @@ type GatewayConfig struct {
LogUpstreamErrorBody bool `mapstructure:"log_upstream_error_body"`
// 上游错误响应体记录最大字节数(超过会截断)
LogUpstreamErrorBodyMaxBytes int `mapstructure:"log_upstream_error_body_max_bytes"`
// RetryAfterMaxSeconds 限制下发给客户端的 Retry-After 秒数(默认 300):
// 上游或账号池给出的恢复时间可能长达数小时,客户端按原值冷却会长时间挂起。
RetryAfterMaxSeconds int `mapstructure:"retry_after_max_seconds"`
// API-key 账号在客户端未提供 anthropic-beta 时,是否按需自动补齐(默认关闭以保持兼容)
InjectBetaForAPIKey bool `mapstructure:"inject_beta_for_apikey"`
@@ -1193,6 +1206,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"`
@@ -1285,15 +1300,17 @@ type GatewayOpenAIHTTP2Config struct {
}
// GatewayOpenAIProxyStreamCircuitConfig controls the bounded, in-process
// proxy-ID circuit used for incomplete OpenAI Responses SSE streams.
// account+proxy circuit used for incomplete OpenAI Responses SSE streams.
// Entries are scoped to the account that owned the stream, so one account
// cannot quarantine other accounts that share the same egress proxy.
type GatewayOpenAIProxyStreamCircuitConfig struct {
// Disabled: 完全关闭代理断流熔断(默认开启)。
// Disabled: 完全关闭账号+代理断流熔断(默认开启)。
Disabled bool `mapstructure:"disabled"`
// FailureThreshold: 统计窗口内多少次断流后隔离代理。
// FailureThreshold: 统计窗口内多少次断流后隔离该账号在该代理上的熔断项。
FailureThreshold int `mapstructure:"failure_threshold"`
// WindowSeconds: 断流统计窗口(秒)。
WindowSeconds int `mapstructure:"window_seconds"`
// TTLSeconds: 代理隔离持续时间(秒)。
// TTLSeconds: 熔断项隔离持续时间(秒)。
TTLSeconds int `mapstructure:"ttl_seconds"`
}
@@ -1384,7 +1401,9 @@ type GatewayOpenAIWSConfig struct {
ClientReadLimitBytes int64 `mapstructure:"client_read_limit_bytes"`
// HTTPBridgeEnabled: 首包过大时,保持客户端 WS,改用 HTTP Responses 上游。
HTTPBridgeEnabled bool `mapstructure:"http_bridge_enabled"`
// HTTPBridgeThresholdBytes: 触发 HTTP bridge 的入站 WS payload 阈值。
// HTTPBridgeThresholdBytes caps the first-message size from which a WebSocket session is
// bridged to HTTP. Zero (the default) follows the limit announced by the upstream handshake
// (x-codex-websocket-max-message-bytes) and falls back to 15 MiB until one is known.
HTTPBridgeThresholdBytes int64 `mapstructure:"http_bridge_threshold_bytes"`
// Feature 开关:v2 优先于 v1
@@ -2132,6 +2151,7 @@ func setDefaults() {
viper.SetDefault("run_mode", RunModeStandard)
viper.SetDefault("gateway.min_output_tokens", 128)
viper.SetDefault("simple_mode.auto_create_default_groups", true)
viper.SetDefault("simple_mode.group_isolation", false)
viper.SetDefault("simple_mode_key_rate_limit_enabled", false)
// Server
@@ -2524,6 +2544,7 @@ func setDefaults() {
viper.SetDefault("gateway.openai_high_effort_first_output_timeout_seconds", 0)
viper.SetDefault("gateway.log_upstream_error_body", true)
viper.SetDefault("gateway.log_upstream_error_body_max_bytes", 2048)
viper.SetDefault("gateway.retry_after_max_seconds", 300)
viper.SetDefault("gateway.inject_beta_for_apikey", false)
viper.SetDefault("gateway.failover_on_400", false)
viper.SetDefault("gateway.max_account_switches", 10)
@@ -2553,7 +2574,7 @@ func setDefaults() {
viper.SetDefault("gateway.openai_ws.prewarm_generate_enabled", false)
viper.SetDefault("gateway.openai_ws.client_read_limit_bytes", 64*1024*1024)
viper.SetDefault("gateway.openai_ws.http_bridge_enabled", true)
viper.SetDefault("gateway.openai_ws.http_bridge_threshold_bytes", 15*1024*1024)
viper.SetDefault("gateway.openai_ws.http_bridge_threshold_bytes", 0)
viper.SetDefault("gateway.openai_ws.responses_websockets", false)
viper.SetDefault("gateway.openai_ws.responses_websockets_v2", true)
viper.SetDefault("gateway.openai_ws.max_conns_per_account", 128)
@@ -2621,6 +2642,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))
@@ -3649,9 +3671,6 @@ func (c *Config) Validate() error {
if c.Gateway.OpenAIWS.HTTPBridgeThresholdBytes < 0 {
return fmt.Errorf("gateway.openai_ws.http_bridge_threshold_bytes must be non-negative")
}
if c.Gateway.OpenAIWS.HTTPBridgeEnabled && c.Gateway.OpenAIWS.HTTPBridgeThresholdBytes == 0 {
return fmt.Errorf("gateway.openai_ws.http_bridge_threshold_bytes must be positive when http_bridge_enabled is true")
}
if c.Gateway.OpenAIWS.FallbackCooldownSeconds < 0 {
return fmt.Errorf("gateway.openai_ws.fallback_cooldown_seconds must be non-negative")
}
+36 -2
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()
@@ -211,6 +219,32 @@ func TestLoadSimpleModeKeyRateLimitEnabledFromEnvironment(t *testing.T) {
require.True(t, cfg.SimpleModeKeyRateLimitEnabled)
}
func TestLoadSimpleModeGroupIsolation(t *testing.T) {
for _, tt := range []struct {
name, mode, yaml, env string
shared, isolated bool
}{
{"default", RunModeSimple, "", "", true, false},
{"yaml with empty env", RunModeSimple, "simple_mode:\n group_isolation: true\n", "", false, true},
{"env opt-in", RunModeSimple, "", "true", false, true},
{"explicit opt-out", RunModeSimple, "simple_mode:\n group_isolation: true\n", "false", true, false},
{"standard", RunModeStandard, "", "true", false, false},
} {
t.Run(tt.name, func(t *testing.T) {
resetViperWithJWTSecret(t)
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(tt.yaml), 0o600))
t.Setenv("CONFIG_FILE", path)
t.Setenv("RUN_MODE", tt.mode)
t.Setenv("SIMPLE_MODE_GROUP_ISOLATION", tt.env)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, tt.shared, cfg.UsesSharedSimpleModePool())
require.Equal(t, tt.isolated, cfg.SimpleModeGroupIsolationEnabled())
})
}
}
func TestLoadRedisUsernameFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("REDIS_USERNAME", "app-user")
@@ -638,8 +672,8 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
if !cfg.Gateway.OpenAIWS.HTTPBridgeEnabled {
t.Fatalf("Gateway.OpenAIWS.HTTPBridgeEnabled = false, want true")
}
if cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes != 15*1024*1024 {
t.Fatalf("Gateway.OpenAIWS.HTTPBridgeThresholdBytes = %d, want %d", cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes, 15*1024*1024)
if cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes != 0 {
t.Fatalf("Gateway.OpenAIWS.HTTPBridgeThresholdBytes = %d, want 0 (follow upstream)", cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes)
}
if cfg.Gateway.OpenAIWS.RetryBackoffInitialMS != 120 {
t.Fatalf("Gateway.OpenAIWS.RetryBackoffInitialMS = %d, want 120", cfg.Gateway.OpenAIWS.RetryBackoffInitialMS)
@@ -12,4 +12,11 @@ type GroupCodexModelsManifestConfig struct {
// usable or all upstream fetches fail: fall back to the scheduler loop
// (true) or return the upstream error / 503 (false, default).
FallbackToScheduler bool `json:"fallback_to_scheduler,omitempty"`
// KeepHiddenAutoModes keeps Codex automatic modes (codex-auto-*) that the
// upstream manifest already hides from the picker, byte-for-byte, instead
// of removing them when the group model list does not select them. Codex
// then reviews approvals with its dedicated reviewer model, and an
// otherwise untouched upstream manifest keeps the upstream ETag. It applies
// to manifests fetched from upstream, with or without pinned accounts.
KeepHiddenAutoModes bool `json:"keep_hidden_auto_modes,omitempty"`
}
@@ -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()
@@ -588,6 +588,23 @@ func (s *stubAdminService) CheckMixedChannelRisk(ctx context.Context, currentAcc
return s.checkMixedErr
}
func matchesProxyFilters(proxy service.Proxy, protocol, status, search string) bool {
if protocol != "" && proxy.Protocol != protocol {
return false
}
if status != "" && proxy.Status != status {
return false
}
if search != "" {
name := strings.ToLower(proxy.Name)
host := strings.ToLower(proxy.Host)
if !strings.Contains(name, search) && !strings.Contains(host, search) {
return false
}
}
return true
}
func (s *stubAdminService) ListProxies(ctx context.Context, page, pageSize int, protocol, status, search string, sortBy, sortOrder string) ([]service.Proxy, int64, error) {
s.lastListProxies.protocol = protocol
s.lastListProxies.status = status
@@ -598,26 +615,24 @@ func (s *stubAdminService) ListProxies(ctx context.Context, page, pageSize int,
search = strings.TrimSpace(strings.ToLower(search))
filtered := make([]service.Proxy, 0, len(s.proxies))
for _, proxy := range s.proxies {
if protocol != "" && proxy.Protocol != protocol {
if !matchesProxyFilters(proxy, protocol, status, search) {
continue
}
if status != "" && proxy.Status != status {
continue
}
if search != "" {
name := strings.ToLower(proxy.Name)
host := strings.ToLower(proxy.Host)
if !strings.Contains(name, search) && !strings.Contains(host, search) {
continue
}
}
filtered = append(filtered, proxy)
}
return filtered, int64(len(filtered)), nil
}
func (s *stubAdminService) ListProxiesWithAccountCount(ctx context.Context, page, pageSize int, protocol, status, search string, sortBy, sortOrder string) ([]service.ProxyWithAccountCount, int64, error) {
return s.proxyCounts, int64(len(s.proxyCounts)), nil
search = strings.TrimSpace(strings.ToLower(search))
filtered := make([]service.ProxyWithAccountCount, 0, len(s.proxyCounts))
for _, item := range s.proxyCounts {
if !matchesProxyFilters(item.Proxy, protocol, status, search) {
continue
}
filtered = append(filtered, item)
}
return filtered, int64(len(filtered)), nil
}
func (s *stubAdminService) GetAllProxies(ctx context.Context) ([]service.Proxy, error) {
@@ -646,16 +646,6 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
})
}
// platformLiteLLMProvider maps a channel platform name to the corresponding
// LiteLLM provider string used as the key in the pricing catalog (platform list).
func platformLiteLLMProvider(platform string) (string, bool) {
spec, ok := domain.LookupPlatform(platform)
if !ok || spec.LiteLLMProvider == "" {
return "", false
}
return spec.LiteLLMProvider, true
}
// SyncPricingModels 返回 LiteLLM 定价目录中指定平台的最新模型列表
// GET /api/v1/admin/channels/pricing/sync-models?platform=anthropic
func (h *ChannelHandler) SyncPricingModels(c *gin.Context) {
@@ -666,14 +656,14 @@ func (h *ChannelHandler) SyncPricingModels(c *gin.Context) {
return
}
provider, ok := platformLiteLLMProvider(platform)
if !ok {
spec, ok := domain.LookupPlatform(platform)
if !ok || spec.LiteLLMProvider == "" {
response.ErrorFrom(c, infraerrors.BadRequest("UNSUPPORTED_PLATFORM",
fmt.Sprintf("unsupported platform: %s", platform)).
WithMetadata(map[string]string{"param": "platform"}))
return
}
models := h.pricingService.ListModelNamesByProvider(provider)
models := h.pricingService.ListModelNamesForPlatform(spec)
response.Success(c, gin.H{"models": models})
}
@@ -0,0 +1,141 @@
//go:build unit
package admin
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type moderationAccountsHandlerSettingRepo struct {
service.SettingRepository
mu sync.Mutex
values map[string]string
}
func (r *moderationAccountsHandlerSettingRepo) GetValue(_ context.Context, key string) (string, error) {
r.mu.Lock()
defer r.mu.Unlock()
v, ok := r.values[key]
if !ok {
return "", service.ErrSettingNotFound
}
return v, nil
}
func (r *moderationAccountsHandlerSettingRepo) GetMultiple(_ context.Context, keys []string) (map[string]string, error) {
r.mu.Lock()
defer r.mu.Unlock()
out := make(map[string]string, len(keys))
for _, k := range keys {
if v, ok := r.values[k]; ok {
out[k] = v
}
}
return out, nil
}
func (r *moderationAccountsHandlerSettingRepo) Set(_ context.Context, key, value string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.values[key] = value
return nil
}
type moderationAccountsHandlerStubRepo struct {
service.ContentModerationRepository
accounts []service.ContentModerationExcludedAccount
lastFilter service.ContentModerationAccountSearchFilter
}
func (r *moderationAccountsHandlerStubRepo) SearchModerationAccounts(
_ context.Context,
filter service.ContentModerationAccountSearchFilter,
) ([]service.ContentModerationExcludedAccount, error) {
r.lastFilter = filter
return r.accounts, nil
}
func (r *moderationAccountsHandlerStubRepo) ListModerationAccountsByIDs(
_ context.Context,
ids []int64,
) ([]service.ContentModerationExcludedAccount, error) {
byID := make(map[int64]service.ContentModerationExcludedAccount, len(r.accounts))
for _, item := range r.accounts {
byID[item.ID] = item
}
out := make([]service.ContentModerationExcludedAccount, 0, len(ids))
for _, id := range ids {
if item, ok := byID[id]; ok {
out = append(out, item)
}
}
return out, nil
}
func TestContentModerationHandler_ExcludedAccountsConfigAndSearch(t *testing.T) {
gin.SetMode(gin.TestMode)
settingRepo := &moderationAccountsHandlerSettingRepo{values: map[string]string{}}
modRepo := &moderationAccountsHandlerStubRepo{
accounts: []service.ContentModerationExcludedAccount{
{ID: 12, Name: "Claude-OAuth-A", Platform: "anthropic", Type: "oauth"},
{ID: 35, Name: "OpenAI-Key-B", Platform: "openai", Type: "apikey"},
},
}
svc := service.NewContentModerationService(settingRepo, modRepo, nil, nil, nil, nil, nil, nil)
h := NewContentModerationHandler(svc)
router := gin.New()
router.GET("/config", h.GetConfig)
router.PUT("/config", h.UpdateConfig)
router.GET("/accounts/search", h.SearchAccounts)
// 1. 按所选分组模糊搜索账户(OAuth + API Key)
recSearch := httptest.NewRecorder()
reqSearch := httptest.NewRequest(http.MethodGet, "/accounts/search?search=key&group_ids=3,8&limit=15", nil)
router.ServeHTTP(recSearch, reqSearch)
require.Equal(t, http.StatusOK, recSearch.Code)
require.Equal(t, "key", modRepo.lastFilter.Search)
require.False(t, modRepo.lastFilter.AllGroups)
require.Equal(t, []int64{3, 8}, modRepo.lastFilter.GroupIDs)
require.Equal(t, 15, modRepo.lastFilter.Limit)
// 非法 group_ids 返回 400
recBad := httptest.NewRecorder()
router.ServeHTTP(recBad, httptest.NewRequest(http.MethodGet, "/accounts/search?group_ids=abc", nil))
require.Equal(t, http.StatusBadRequest, recBad.Code)
// 2. 更新配置写入 excluded_account_ids 并验证 GET /config 正确回显详情
payload, err := json.Marshal(map[string]any{
"excluded_account_ids": []int64{12, 35},
})
require.NoError(t, err)
recUpdate := httptest.NewRecorder()
reqUpdate := httptest.NewRequest(http.MethodPut, "/config", bytes.NewReader(payload))
reqUpdate.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recUpdate, reqUpdate)
require.Equal(t, http.StatusOK, recUpdate.Code)
recGet := httptest.NewRecorder()
router.ServeHTTP(recGet, httptest.NewRequest(http.MethodGet, "/config", nil))
require.Equal(t, http.StatusOK, recGet.Code)
var resp struct {
Data service.ContentModerationConfigView `json:"data"`
}
require.NoError(t, json.Unmarshal(recGet.Body.Bytes(), &resp))
require.Equal(t, []int64{12, 35}, resp.Data.ExcludedAccountIDs)
require.Len(t, resp.Data.ExcludedAccounts, 2)
require.Equal(t, "Claude-OAuth-A", resp.Data.ExcludedAccounts[0].Name)
require.Equal(t, "OpenAI-Key-B", resp.Data.ExcludedAccounts[1].Name)
}
@@ -37,6 +37,7 @@ type contentModerationConfigRequest struct {
SampleRate *int `json:"sample_rate"`
AllGroups *bool `json:"all_groups"`
GroupIDs *[]int64 `json:"group_ids"`
ExcludedAccountIDs *[]int64 `json:"excluded_account_ids"`
RecordNonHits *bool `json:"record_non_hits"`
Thresholds *map[string]float64 `json:"thresholds"`
WorkerCount *int `json:"worker_count"`
@@ -106,6 +107,7 @@ func (h *ContentModerationHandler) UpdateConfig(c *gin.Context) {
SampleRate: req.SampleRate,
AllGroups: req.AllGroups,
GroupIDs: req.GroupIDs,
ExcludedAccountIDs: req.ExcludedAccountIDs,
RecordNonHits: req.RecordNonHits,
Thresholds: req.Thresholds,
WorkerCount: req.WorkerCount,
@@ -248,6 +250,45 @@ func (h *ContentModerationHandler) ClearFlaggedHashes(c *gin.Context) {
response.Success(c, result)
}
func (h *ContentModerationHandler) SearchAccounts(c *gin.Context) {
allGroups := strings.EqualFold(strings.TrimSpace(c.Query("all_groups")), "true") || strings.TrimSpace(c.Query("all_groups")) == "1"
var groupIDs []int64
for _, rawVal := range c.QueryArray("group_ids") {
for _, part := range strings.Split(rawVal, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
id, err := strconv.ParseInt(part, 10, 64)
if err != nil || id <= 0 {
response.BadRequest(c, "Invalid group_ids")
return
}
groupIDs = append(groupIDs, id)
}
}
limit := 20
if rawLimit := strings.TrimSpace(c.Query("limit")); rawLimit != "" {
parsedLimit, err := strconv.Atoi(rawLimit)
if err != nil || parsedLimit <= 0 {
response.BadRequest(c, "Invalid limit")
return
}
limit = parsedLimit
}
items, err := h.service.SearchAccounts(c.Request.Context(), service.ContentModerationAccountSearchFilter{
Search: strings.TrimSpace(c.Query("search")),
AllGroups: allGroups,
GroupIDs: groupIDs,
Limit: limit,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, items)
}
func parseContentModerationDate(raw string) (time.Time, bool, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
@@ -547,7 +547,8 @@ func (h *SettingHandler) TestWebSearchEmulation(c *gin.Context) {
result, err := service.TestWebSearch(c.Request.Context(), req.Query)
if err != nil {
response.ErrorFrom(c, err)
// Like the SMTP test, return the cause so the admin can fix the provider config.
response.BadRequest(c, "Web search test failed: "+err.Error())
return
}
response.Success(c, result)
@@ -0,0 +1,37 @@
//go:build unit
package admin
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestTestWebSearchEmulationReturnsFailureCause(t *testing.T) {
gin.SetMode(gin.TestMode)
service.SetWebSearchManager(nil)
t.Cleanup(func() { service.SetWebSearchManager(nil) })
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/settings/web-search-emulation/test", bytes.NewBufferString(`{"query":"golang"}`))
c.Request.Header.Set("Content-Type", "application/json")
(&SettingHandler{}).TestWebSearchEmulation(c)
require.Equal(t, http.StatusBadRequest, rec.Code)
var body struct {
Message string `json:"message"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
require.Contains(t, body.Message, "Web search test failed")
require.Contains(t, body.Message, "save config first", "the admin must see why the test failed, not a generic internal error")
}
@@ -47,6 +47,11 @@ func (h *BatchImageHandler) Submit(c *gin.Context) {
}
got, err := h.service.Submit(c.Request.Context(), owner, req, c.GetHeader("Idempotency-Key"))
if err != nil {
var modBlocked *accountModerationBlockedError
if errors.As(err, &modBlocked) && h.openAI != nil {
h.openAI.openAISecurityAuditError(c, modBlocked.decision)
return
}
batchImageError(c, err)
return
}
@@ -88,6 +93,12 @@ func (h *BatchImageHandler) checkSecurityAuditBeforeSubmit(c *gin.Context, req *
h.openAI.openAISecurityAuditError(c, decision)
return false
}
c.Request = c.Request.WithContext(service.WithAccountModerationHook(c.Request.Context(), func(accountID int64) error {
if dec := checkSelectedAccountModeration(c, accountID); dec != nil && !dec.AllowNextStage {
return &accountModerationBlockedError{decision: dec}
}
return nil
}))
return true
}
@@ -116,6 +116,17 @@ func bindRequestedReasoningEffort(c *gin.Context, body []byte, model string) {
c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort))
}
func bindRequestedReasoningEffortWithFields(c *gin.Context, body []byte, model, reasoningEffort, reasoningEffortTop, outputConfigEffort string) {
if c == nil || c.Request == nil {
return
}
effort := service.CanonicalRequestedReasoningEffortWithFields(body, reasoningEffort, reasoningEffortTop, outputConfigEffort, model)
if effort == nil {
return
}
c.Request = c.Request.WithContext(service.WithRequestedReasoningEffort(c.Request.Context(), *effort))
}
func stampOpenAIRequestedReasoningEffort(result *service.OpenAIForwardResult, c *gin.Context) {
if result == nil || result.RequestedReasoningEffort != nil {
return
@@ -142,6 +153,20 @@ func applyOpenAIReasoningEffortPolicyForRequest(c *gin.Context, apiKey *service.
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, overLimit)
}
func applyOpenAIReasoningEffortPolicyForRequestWithFields(
c *gin.Context,
apiKey *service.APIKey,
body []byte,
model, reasoningEffort, reasoningEffortTop, outputConfigEffort string,
) ([]byte, bool, error) {
bindRequestedReasoningEffortWithFields(c, body, strings.TrimSpace(model), reasoningEffort, reasoningEffortTop, outputConfigEffort)
maxEffort, mappings, overLimit, ok := openAIReasoningEffortPolicyForRequest(c, apiKey)
if !ok {
return body, false, nil
}
return service.ApplyOpenAIReasoningEffortPolicy(body, maxEffort, mappings, overLimit)
}
func respondOpenAIReasoningEffortPolicyError(c *gin.Context, err error, write func(*gin.Context, int, string, string)) {
if c == nil || err == nil || write == nil {
return
@@ -0,0 +1,225 @@
package handler
import (
"net/http"
"strings"
"sync"
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
const pendingAccountModerationContextKey = "sub2api.content_moderation.pending_account"
type pendingAccountModeration struct {
mu sync.Mutex
svc *service.ContentModerationService
reqLog *zap.Logger
input service.ContentModerationCheckInput
checkedNonExcl bool
cachedDecision *securityaudit.Decision
}
type accountModerationBlockedError struct {
decision *securityaudit.Decision
}
func (e *accountModerationBlockedError) Error() string {
if e == nil || e.decision == nil || e.decision.ClientMessage == "" {
return "Request blocked by content policy"
}
return e.decision.ClientMessage
}
func boundAccountIDFromGinContext(c *gin.Context) int64 {
if c == nil {
return 0
}
if v, ok := c.Get(opsAccountIDKey); ok {
if id, valid := v.(int64); valid && id > 0 {
return id
}
}
return 0
}
func deferAccountModerationIfNeeded(
c *gin.Context,
reqLog *zap.Logger,
svc *service.ContentModerationService,
input service.ContentModerationCheckInput,
) bool {
if c == nil || c.Request == nil || svc == nil || input.AccountID > 0 {
return false
}
if !svc.ShouldDeferForAccountExclusion(c.Request.Context(), input) {
return false
}
clonedInput := input
if input.GroupID != nil {
gid := *input.GroupID
clonedInput.GroupID = &gid
}
// 复制切片以防止调用方(如异步生图提交阶段)清空外层缓冲引用。
clonedInput.Body = append([]byte(nil), input.Body...)
c.Set(pendingAccountModerationContextKey, &pendingAccountModeration{
svc: svc,
reqLog: reqLog,
input: clonedInput,
})
return true
}
// resetWSRetryAccountModeration 在 WebSocket 后续轮次因故障切换以新 turn 1 重放时,
// 按当前重放载荷重建待审上下文并清空旧轮次缓存;若当前无排除账户则立即同步审计。
func resetWSRetryAccountModeration(
c *gin.Context,
reqLog *zap.Logger,
svc *service.ContentModerationService,
apiKey *service.APIKey,
subject middleware2.AuthSubject,
protocol string,
model string,
payload []byte,
) *securityaudit.Decision {
if c == nil || c.Request == nil {
return nil
}
if c.Keys != nil {
delete(c.Keys, pendingAccountModerationContextKey)
delete(c.Keys, securityAuditWSDedupeContextKey)
delete(c.Keys, opsAccountIDKey)
}
if svc == nil {
return nil
}
input := buildContentModerationInput(c, apiKey, subject, protocol, model, payload)
if trimmedModel := strings.TrimSpace(model); trimmedModel != "" {
input.Model = trimmedModel
}
input.AccountID = 0
if deferAccountModerationIfNeeded(c, reqLog, svc, input) {
return nil
}
legacyDecision := runContentModerationWithInput(c.Request.Context(), reqLog, svc, input)
if legacyDecision == nil || !legacyDecision.Blocked {
return nil
}
return &securityaudit.Decision{
Kind: securityaudit.DecisionBlock,
HTTPStatus: contentModerationStatus(legacyDecision),
ErrorCode: "content_policy_violation",
ClientMessage: legacyDecision.Message,
AllowNextStage: false,
Legacy: &securityaudit.LegacyDecision{
Allowed: legacyDecision.Allowed,
Blocked: legacyDecision.Blocked,
Flagged: legacyDecision.Flagged,
Message: legacyDecision.Message,
StatusCode: legacyDecision.StatusCode,
ErrorCode: "content_policy_violation",
Action: legacyDecision.Action,
},
}
}
func checkSelectedAccountModeration(c *gin.Context, accountID int64) *securityaudit.Decision {
if c == nil || c.Request == nil || accountID <= 0 {
return nil
}
raw, exists := c.Get(pendingAccountModerationContextKey)
if !exists || raw == nil {
return nil
}
pending, ok := raw.(*pendingAccountModeration)
if !ok || pending == nil || pending.svc == nil {
return nil
}
ctx := c.Request.Context()
// 选定账户命中内存排除集:全局最优先直接忽略(O(1) 内存查找,0 数据库/Redis 查询)。
if pending.svc.IsAccountExcluded(ctx, accountID) {
return nil
}
pending.mu.Lock()
defer pending.mu.Unlock()
if pending.checkedNonExcl {
return pending.cachedDecision
}
checkInput := pending.input
checkInput.AccountID = accountID
legacyDecision := runContentModerationWithInput(ctx, pending.reqLog, pending.svc, checkInput)
pending.checkedNonExcl = true
if legacyDecision == nil {
return nil
}
decision := securityaudit.Decision{
Kind: securityaudit.DecisionAllow,
HTTPStatus: http.StatusOK,
AllowNextStage: true,
Legacy: &securityaudit.LegacyDecision{
Allowed: legacyDecision.Allowed,
Blocked: legacyDecision.Blocked,
Flagged: legacyDecision.Flagged,
Message: legacyDecision.Message,
StatusCode: legacyDecision.StatusCode,
ErrorCode: "content_policy_violation",
Action: legacyDecision.Action,
},
}
if legacyDecision.Blocked {
decision.Kind = securityaudit.DecisionBlock
decision.HTTPStatus = contentModerationStatus(legacyDecision)
decision.ErrorCode = "content_policy_violation"
decision.ClientMessage = legacyDecision.Message
decision.AllowNextStage = false
}
pending.cachedDecision = &decision
if !decision.AllowNextStage {
return &decision
}
return nil
}
func selectionReleaseFunc(selection *service.AccountSelectionResult) func() {
if selection != nil && selection.Acquired {
return selection.ReleaseFunc
}
return nil
}
func webSearchSecurityAuditError(c *gin.Context, decision *securityaudit.Decision) {
if securityAuditStreamCommitted(c) {
writeGenericSecurityAuditSSEError(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
return
}
c.JSON(securityAuditStatus(decision), gin.H{"error": gin.H{
"type": securityAuditErrorCode(decision),
"message": securityAuditMessage(decision),
}})
}
func rejectSelectedAccountIfModerated(
c *gin.Context,
accountID int64,
releaseFunc func(),
writeErr func(*gin.Context, *securityaudit.Decision),
) bool {
decision := checkSelectedAccountModeration(c, accountID)
if decision == nil || decision.AllowNextStage {
return false
}
if releaseFunc != nil {
releaseFunc()
}
if writeErr != nil {
writeErr(c, decision)
}
return true
}
@@ -0,0 +1,251 @@
//go:build unit
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
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"
)
type stubBlockingPromptEngine struct{}
func (stubBlockingPromptEngine) EffectiveMode() securityaudit.Mode {
return securityaudit.ModeBlocking
}
func (stubBlockingPromptEngine) Enqueue(context.Context, securityaudit.Request) error {
return nil
}
func (stubBlockingPromptEngine) Evaluate(context.Context, securityaudit.Request) (*securityaudit.PromptDecision, error) {
return &securityaudit.PromptDecision{
Kind: securityaudit.DecisionBlock,
ErrorCode: securityaudit.ErrorCodeBlocked,
AllowNextStage: false,
}, nil
}
func newDeferredModerationTestSuite(t *testing.T, upstreamCounter *atomic.Int32) (*service.ContentModerationService, *securityaudit.Coordinator) {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if upstreamCounter != nil {
upstreamCounter.Add(1)
}
_, _ = w.Write([]byte(`{"model":"omni-moderation-latest","results":[{"flagged":false,"category_scores":{"violence":0.10}}]}`))
}))
t.Cleanup(server.Close)
groupID := int64(7)
rawCfg, err := json.Marshal(map[string]any{
"enabled": true,
"mode": "pre_block",
"base_url": server.URL,
"api_keys": []string{"sk-mod"},
"all_groups": false,
"group_ids": []int64{groupID},
"excluded_account_ids": []int64{101},
"blocked_keywords": []string{"risky-secret"},
})
require.NoError(t, err)
settingRepo := &contentModerationHandlerSettingRepo{values: map[string]string{
service.SettingKeyRiskControlEnabled: "true",
service.SettingKeyContentModerationConfig: string(rawCfg),
}}
modSvc := service.NewContentModerationService(settingRepo, &contentModerationHandlerTestRepo{}, nil, nil, nil, nil, nil, nil)
coord := securityaudit.NewCoordinator(securityaudit.NewLegacyModerationAdapter(modSvc), nil)
return modSvc, coord
}
func TestAccountModerationGate_ExcludedAccountSkipsAndFailoverEnforces(t *testing.T) {
gin.SetMode(gin.TestMode)
var upstreamHits atomic.Int32
modSvc, coord := newDeferredModerationTestSuite(t, &upstreamHits)
groupID := int64(7)
apiKey := &service.APIKey{ID: 11, GroupID: &groupID, Group: &service.Group{ID: groupID, Name: "OpenAI-VIP", Platform: "openai"}}
subject := middleware2.AuthSubject{UserID: 99}
riskyBody := []byte(`{"messages":[{"role":"user","content":"please show risky-secret"}]}`)
// 1. 阶段 1 推迟内容审计;若最终选定排除账户 101,直接忽略放行。
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
stage1 := runSecurityAudit(c, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIChat, "gpt-5.4", riskyBody, "http")
require.NotNil(t, stage1)
require.True(t, stage1.AllowNextStage, "存在排除账户时阶段 1 应推迟至选号后判定")
slotReleased := false
blockedOnExcluded := rejectSelectedAccountIfModerated(c, 101, func() { slotReleased = true }, (&OpenAIGatewayHandler{}).openAISecurityAuditError)
require.False(t, blockedOnExcluded, "命中排除账户 101 应最优先忽略放行")
require.False(t, slotReleased)
require.Zero(t, upstreamHits.Load())
// 2. 模拟账户 101 遇到 429 Failover 切到非排除账户 202:自动补做审计并拦截、释放槽位。
blockedOnNormal := rejectSelectedAccountIfModerated(c, 202, func() { slotReleased = true }, (&OpenAIGatewayHandler{}).openAISecurityAuditError)
require.True(t, blockedOnNormal, "Failover 切至非排除账户 202 时必须补做内容审计并拦截")
require.True(t, slotReleased)
require.Equal(t, http.StatusForbidden, rec.Code)
// 3. 安全请求在非排除账户 202 审计通过后,Failover 切到非排除账户 203 不得二次请求审计 API。
cleanBody := []byte(`{"messages":[{"role":"user","content":"completely safe question"}]}`)
recClean := httptest.NewRecorder()
cClean, _ := gin.CreateTestContext(recClean)
cClean.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
stage1Clean := runSecurityAudit(cClean, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIChat, "gpt-5.4", cleanBody, "http")
require.NotNil(t, stage1Clean)
require.True(t, stage1Clean.AllowNextStage)
require.False(t, rejectSelectedAccountIfModerated(cClean, 202, nil, nil))
require.Equal(t, int32(1), upstreamHits.Load())
require.False(t, rejectSelectedAccountIfModerated(cClean, 203, nil, nil))
require.Equal(t, int32(1), upstreamHits.Load(), "同一请求 Failover 至其他非排除账户应复用已通过审计结果")
}
func TestAccountModerationGate_WSSubsequentTurnAndPromptAuditOrder(t *testing.T) {
gin.SetMode(gin.TestMode)
modSvc, coord := newDeferredModerationTestSuite(t, nil)
groupID := int64(7)
apiKey := &service.APIKey{ID: 11, GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: "openai"}}
subject := middleware2.AuthSubject{UserID: 99}
riskyPayload := []byte(`{"model":"gpt-5.4","input":"risky-secret"}`)
// WebSocket 后续轮次:绑定排除账户 101 时直接放行;绑定普通账户 202 时拦截。
cWS, _ := gin.CreateTestContext(httptest.NewRecorder())
cWS.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
cWS.Set(securityAuditWSTurnContextKey, 2)
setOpsSelectedAccount(cWS, 101, "openai")
dExcluded := runSecurityAudit(cWS, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", riskyPayload, "subsequent_turn")
require.NotNil(t, dExcluded)
require.True(t, dExcluded.AllowNextStage)
cWSNormal, _ := gin.CreateTestContext(httptest.NewRecorder())
cWSNormal.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
cWSNormal.Set(securityAuditWSTurnContextKey, 2)
setOpsSelectedAccount(cWSNormal, 202, "openai")
dNormal := runSecurityAudit(cWSNormal, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", riskyPayload, "subsequent_turn")
require.NotNil(t, dNormal)
require.False(t, dNormal.AllowNextStage)
// PromptAudit 开启阻塞时,即使配置了排除账户,PromptAudit 仍在选号前立即拦截。
blockingCoord := securityaudit.NewCoordinator(securityaudit.NewLegacyModerationAdapter(modSvc), stubBlockingPromptEngine{})
cPrompt, _ := gin.CreateTestContext(httptest.NewRecorder())
cPrompt.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
dPrompt := runSecurityAudit(cPrompt, nil, blockingCoord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", []byte(`{"input":"safe"}`), "http")
require.NotNil(t, dPrompt)
require.False(t, dPrompt.AllowNextStage)
require.Equal(t, securityaudit.ErrorCodeBlocked, dPrompt.ErrorCode)
}
func TestAccountModerationGate_WSRetryRebuildsPendingForCurrentTurn(t *testing.T) {
gin.SetMode(gin.TestMode)
modSvc, coord := newDeferredModerationTestSuite(t, nil)
groupID := int64(7)
apiKey := &service.APIKey{ID: 11, GroupID: &groupID, Group: &service.Group{ID: groupID, Platform: "openai"}}
subject := middleware2.AuthSubject{UserID: 99}
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil)
// Turn 1: 安全输入进入并选中排除账户 101,pending 记录的是首轮安全输入。
turn1Safe := []byte(`{"type":"response.create","model":"gpt-5.4","input":"hello safe world"}`)
d1 := runSecurityAudit(c, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", turn1Safe, "first_turn")
require.NotNil(t, d1)
require.True(t, d1.AllowNextStage)
require.Nil(t, checkSelectedAccountModeration(c, 101))
setOpsSelectedAccount(c, 101, "openai")
// Turn 2: 违规输入在排除账户 101 的 BeforeRequest 中按排除账户放行。
c.Set(securityAuditWSTurnContextKey, 2)
turn2Risky := []byte(`{"type":"response.create","model":"gpt-5.4","input":"please expose risky-secret"}`)
d2 := runSecurityAudit(c, nil, coord, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", turn2Risky, "subsequent_turn")
require.NotNil(t, d2)
require.True(t, d2.AllowNextStage)
// Turn 2 在上游遇到 429 触发当前轮换号重放,切换到普通账户 202:必须审计第 2 轮违规输入并拦截。
retryImmediate := resetWSRetryAccountModeration(c, nil, modSvc, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, "gpt-5.4", turn2Risky)
require.Nil(t, retryImmediate, "存在排除账户时应重建待审上下文供新选号判定")
wsBlocked := checkSelectedAccountModeration(c, 202)
require.NotNil(t, wsBlocked, "换号至普通账户 202 时必须按第 2 轮载荷拦截,不能误用首轮安全载荷")
require.False(t, wsBlocked.AllowNextStage)
require.Equal(t, "content_policy_violation", wsBlocked.ErrorCode)
}
func TestSecurityAuditErrors_StreamingCommittedEmitsSSEEventsInsteadOfRawJSON(t *testing.T) {
gin.SetMode(gin.TestMode)
legacyBlock := &securityaudit.Decision{
Kind: securityaudit.DecisionBlock,
HTTPStatus: http.StatusForbidden,
ErrorCode: "content_policy_violation",
ClientMessage: "内容审计拦截测试",
AllowNextStage: false,
Legacy: &securityaudit.LegacyDecision{
Allowed: false,
Blocked: true,
StatusCode: http.StatusForbidden,
ErrorCode: "content_policy_violation",
Message: "内容审计拦截测试",
},
}
// 1. OpenAI /v1/responses 已发出 SSE 心跳后延迟拦截:输出合法的 response.failed 终止帧。
recResp := httptest.NewRecorder()
cResp, _ := gin.CreateTestContext(recResp)
cResp.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
cResp.Header("Content-Type", "text/event-stream")
cResp.Status(http.StatusOK)
_, _ = cResp.Writer.WriteString(": ping\n\n")
cResp.Writer.Flush()
(&OpenAIGatewayHandler{}).openAISecurityAuditError(cResp, legacyBlock)
respOut := recResp.Body.String()
require.Contains(t, respOut, ": ping\n\n")
require.Contains(t, respOut, "event: response.failed\n")
require.Contains(t, respOut, "内容审计拦截测试")
// 2. OpenAI /v1/chat/completions 已发出 SSE 心跳后延迟拦截:输出 event: error SSE 帧。
recCC := httptest.NewRecorder()
cCC, _ := gin.CreateTestContext(recCC)
cCC.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
cCC.Header("Content-Type", "text/event-stream")
cCC.Status(http.StatusOK)
_, _ = cCC.Writer.WriteString(": ping\n\n")
cCC.Writer.Flush()
(&OpenAIGatewayHandler{}).openAISecurityAuditError(cCC, legacyBlock)
ccOut := recCC.Body.String()
require.Contains(t, ccOut, ": ping\n\nevent: error\ndata: ")
require.Contains(t, ccOut, "content_policy_violation")
// 3. Anthropic /v1/messages 已发出 SSE 心跳后延迟拦截:输出 SSE data 帧而非裸 JSON。
recAnth := httptest.NewRecorder()
cAnth, _ := gin.CreateTestContext(recAnth)
cAnth.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
cAnth.Header("Content-Type", "text/event-stream")
cAnth.Status(http.StatusOK)
_, _ = cAnth.Writer.WriteString(": ping\n\n")
cAnth.Writer.Flush()
(&GatewayHandler{}).anthropicSecurityAuditError(cAnth, legacyBlock)
anthOut := recAnth.Body.String()
require.Contains(t, anthOut, ": ping\n\ndata: {\"type\":\"error\"")
require.Contains(t, anthOut, "内容审计拦截测试")
}
@@ -38,14 +38,14 @@ func clientRequestedUsageFields(c *gin.Context, mapping service.ChannelMappingRe
return mapping.ToUsageFields(clientRequestedModel(c, fallbackModel), upstreamModel)
}
func runContentModeration(c *gin.Context, reqLog *zap.Logger, svc *service.ContentModerationService, apiKey *service.APIKey, subject middleware2.AuthSubject, protocol string, model string, body []byte) *service.ContentModerationDecision {
if svc == nil || c == nil || c.Request == nil {
func runContentModerationWithInput(ctx context.Context, reqLog *zap.Logger, svc *service.ContentModerationService, input service.ContentModerationCheckInput) *service.ContentModerationDecision {
if svc == nil || ctx == nil {
return nil
}
input := buildContentModerationInput(c, apiKey, subject, protocol, model, body)
if reqLog != nil {
reqLog.Info("content_moderation.gateway_check_start",
reqLog.Debug("content_moderation.gateway_check_start",
zap.String("request_id", input.RequestID),
zap.Int64("account_id", input.AccountID),
zap.Int64("user_id", input.UserID),
zap.Int64("api_key_id", input.APIKeyID),
zap.String("api_key_name", input.APIKeyName),
@@ -55,10 +55,10 @@ func runContentModeration(c *gin.Context, reqLog *zap.Logger, svc *service.Conte
zap.String("provider", input.Provider),
zap.String("protocol", input.Protocol),
zap.String("model", input.Model),
zap.Int("body_bytes", len(body)),
zap.Int("body_bytes", len(input.Body)),
)
}
decision, err := svc.Check(c.Request.Context(), input)
decision, err := svc.Check(ctx, input)
if err != nil {
if reqLog != nil {
reqLog.Warn("content_moderation.check_failed", zap.Error(err))
@@ -66,8 +66,13 @@ func runContentModeration(c *gin.Context, reqLog *zap.Logger, svc *service.Conte
return nil
}
if reqLog != nil && decision != nil {
reqLog.Info("content_moderation.gateway_check_done",
logFn := reqLog.Debug
if decision.Blocked || decision.Flagged {
logFn = reqLog.Info
}
logFn("content_moderation.gateway_check_done",
zap.String("request_id", input.RequestID),
zap.Int64("account_id", input.AccountID),
zap.Bool("allowed", decision.Allowed),
zap.Bool("blocked", decision.Blocked),
zap.Bool("flagged", decision.Flagged),
@@ -17,6 +17,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
Enabled: true,
AccountIDs: []int64{101, 202},
FallbackToScheduler: true,
KeepHiddenAutoModes: true,
},
}
@@ -27,6 +28,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
Enabled bool `json:"enabled"`
AccountIDs []int64 `json:"account_ids"`
FallbackToScheduler bool `json:"fallback_to_scheduler"`
KeepHiddenAutoModes bool `json:"keep_hidden_auto_modes"`
} `json:"codex_models_manifest_config"`
}
require.NoError(t, json.Unmarshal(adminJSON, &adminEnvelope))
@@ -34,6 +36,7 @@ func TestGroupMapperRoundTripsCodexModelsManifestConfig(t *testing.T) {
require.True(t, adminEnvelope.CodexModelsManifestConfig.Enabled)
require.Equal(t, []int64{101, 202}, adminEnvelope.CodexModelsManifestConfig.AccountIDs)
require.True(t, adminEnvelope.CodexModelsManifestConfig.FallbackToScheduler)
require.True(t, adminEnvelope.CodexModelsManifestConfig.KeepHiddenAutoModes)
userJSON, err := json.Marshal(GroupFromService(group))
require.NoError(t, err)
+24
View File
@@ -562,6 +562,7 @@ func ProxyWithAccountCountFromService(p *service.ProxyWithAccountCount) *ProxyWi
QualityGrade: p.QualityGrade,
QualitySummary: p.QualitySummary,
QualityChecked: p.QualityChecked,
LatencyChecked: p.LatencyChecked,
}
}
@@ -607,6 +608,7 @@ func ProxyWithAccountCountFromServiceAdmin(p *service.ProxyWithAccountCount) *Ad
QualityGrade: p.QualityGrade,
QualitySummary: p.QualitySummary,
QualityChecked: p.QualityChecked,
LatencyChecked: p.LatencyChecked,
}
}
@@ -761,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")
})
}
}
+35 -28
View File
@@ -461,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(包含密码等敏感字段)。
@@ -487,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 {
@@ -602,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).
+26 -4
View File
@@ -55,6 +55,13 @@ const (
// 语义上等同于「无可用账号」:候选账号都不满足分组的利润约束。
const profitVetoExhaustedMessage = "No available accounts: all candidates rejected by group profit control"
func appendUpstreamRetryAfterField(fields []zap.Field, failoverErr *service.UpstreamFailoverError) []zap.Field {
if failoverErr != nil && failoverErr.UpstreamRetryAfter > 0 {
return append(fields, zap.Duration("upstream_retry_after", failoverErr.UpstreamRetryAfter))
}
return fields
}
func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryCount int) time.Duration {
if failoverErr == nil {
return sameAccountRetryDelay
@@ -76,6 +83,19 @@ func sameAccountRetryDelayFor(failoverErr *service.UpstreamFailoverError, retryC
return delay
}
// wsSameAccountRetryAllowed preserves the WebSocket retry contract: an OAuth
// 429 deadline or a request-scoped transient failure may use the existing
// retry budget. The caller checks that the current turn can be replayed.
func wsSameAccountRetryAllowed(account *service.Account, failoverErr *service.UpstreamFailoverError, retryCount int) bool {
if account == nil || failoverErr == nil {
return false
}
if (failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero()) && !failoverErr.RequestScopedTransient {
return false
}
return sameAccountRetryAllowed(failoverErr, retryCount, effectiveSameAccountRetryLimit(failoverErr, account))
}
func sameAccountRetryAllowed(failoverErr *service.UpstreamFailoverError, retryCount, retryLimit int) bool {
if failoverErr == nil || !failoverErr.RetryableOnSameAccount {
return false
@@ -220,13 +240,14 @@ func (s *FailoverState) HandleFailoverError(
if sameAccountRetry {
s.SameAccountRetryCount[accountID]++
retryDelay := sameAccountRetryDelayFor(failoverErr, s.SameAccountRetryCount[accountID])
logger.FromContext(ctx).Warn("gateway.failover_same_account_retry",
retryFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", accountID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("same_account_retry_count", s.SameAccountRetryCount[accountID]),
zap.Int("same_account_retry_max", retryLimit),
zap.Duration("retry_delay", retryDelay),
)
}, failoverErr)
logger.FromContext(ctx).Warn("gateway.failover_same_account_retry", retryFields...)
if !sleepWithContext(ctx, retryDelay) {
return FailoverCanceled
}
@@ -248,12 +269,13 @@ func (s *FailoverState) HandleFailoverError(
// 递增切换计数
s.SwitchCount++
logger.FromContext(ctx).Warn("gateway.failover_switch_account",
switchFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", accountID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", s.SwitchCount),
zap.Int("max_switches", s.MaxSwitches),
)
}, failoverErr)
logger.FromContext(ctx).Warn("gateway.failover_switch_account", switchFields...)
// Antigravity 平台换号线性递增延时
if platform == service.PlatformAntigravity {
@@ -1040,3 +1040,31 @@ func TestFailoverClientGone(t *testing.T) {
require.False(t, failoverClientGone(nil))
})
}
func TestWSSameAccountRetryRetainsBoundedRequestScopedCapacityRetry(t *testing.T) {
account := &service.Account{Type: service.AccountTypeAPIKey, Credentials: map[string]any{"pool_mode": true, "pool_mode_retry_count": float64(1)}}
failure := &service.UpstreamFailoverError{
StatusCode: http.StatusServiceUnavailable, RetryableOnSameAccount: true, RequestScopedTransient: true,
}
t.Run("first attempt may retry", func(t *testing.T) {
require.True(t, wsSameAccountRetryAllowed(account, failure, 0))
})
t.Run("configured limit still applies", func(t *testing.T) {
require.False(t, wsSameAccountRetryAllowed(account, failure, 1))
})
t.Run("non-transient 503 cannot retry", func(t *testing.T) {
other := *failure
other.RequestScopedTransient = false
require.False(t, wsSameAccountRetryAllowed(account, &other, 0))
})
t.Run("explicit zero disables capacity retry", func(t *testing.T) {
disabled := &service.Account{Type: service.AccountTypeAPIKey, Credentials: map[string]any{"pool_mode": true, "pool_mode_retry_count": float64(0)}}
require.False(t, wsSameAccountRetryAllowed(disabled, failure, 0))
})
t.Run("OAuth 429 with deadline still retries", func(t *testing.T) {
rateLimit := &service.UpstreamFailoverError{
StatusCode: http.StatusTooManyRequests, RetryableOnSameAccount: true, SameAccountRetryDeadline: time.Now().Add(time.Minute),
}
require.True(t, wsSameAccountRetryAllowed(account, rateLimit, 0))
})
}
+24 -2
View File
@@ -392,6 +392,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
}
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// 检查请求拦截(预热请求、SUGGESTION MODE等)
@@ -651,6 +654,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 {
@@ -725,6 +731,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
}
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// [DEBUG-STICKY] 打印账号选择结果
@@ -919,6 +928,11 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
// 选号按客户端模型,转发按渠道映射后的模型:模型级账号状态按选号模型记录。
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 {
@@ -1130,13 +1144,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) {
// Forward has completed; finish the bounded write even if the client disconnects.
bindCtx, cancelBind := context.WithTimeout(context.WithoutCancel(c.Request.Context()), 5*time.Second)
bindErr := h.gatewayService.BindStickySession(bindCtx, currentAPIKey.GroupID, sessionKey, account.ID)
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.Error(bindErr))
reqLog.Warn("gateway.bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Int("failed_over_account_count", len(failedOverAccountIDs)), zap.Error(bindErr))
}
}
@@ -238,6 +238,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
}
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// 4. Acquire account concurrency slot
@@ -427,7 +430,7 @@ func (h *GatewayHandler) handleCCFailoverExhausted(c *gin.Context, lastErr *serv
return
}
if lastErr != nil {
copyFailoverRetryAfter(c, lastErr.ResponseHeaders)
applyRateLimitRetryAfter(c, lastErr, h.cfg)
}
if lastErr != nil && lastErr.IsCredentialFailure() {
status, message := credentialFailoverClientResponse(lastErr)
@@ -238,6 +238,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
}
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.responsesSecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// 4. Acquire account concurrency slot
@@ -412,7 +415,7 @@ func (h *GatewayHandler) responsesErrorResponse(c *gin.Context, status int, code
// handleResponsesFailoverExhausted writes a failover-exhausted error in Responses format.
func (h *GatewayHandler) handleResponsesFailoverExhausted(c *gin.Context, lastErr *service.UpstreamFailoverError, streamStarted bool) {
if lastErr != nil {
copyFailoverRetryAfter(c, lastErr.ResponseHeaders)
applyRateLimitRetryAfter(c, lastErr, h.cfg)
}
statusCode := http.StatusBadGateway
if lastErr != nil && lastErr.StatusCode > 0 {
+69 -4
View File
@@ -234,12 +234,77 @@ func (h *ConcurrencyHelper) TryAcquireUserSlot(ctx context.Context, userID int64
return result.ReleaseFunc, true, nil
}
func (h *ConcurrencyHelper) TryAcquireUserSlotForAPIKey(ctx context.Context, userID int64, maxConcurrency int, apiKeyID int64) (func(), bool, error) {
// AcquireUserSlotForAPIKeyWithWait acquires a user concurrency slot for a
// connection that cannot carry SSE pings, such as a WebSocket turn. Like the
// HTTP path, it waits in the bounded per-user queue for up to timeout instead
// of failing as soon as the user is at the limit.
//
// It returns *WaitQueueFullError when the queue is full, *ConcurrencyError when
// the wait times out, and the context error when ctx ends first.
func (h *ConcurrencyHelper) AcquireUserSlotForAPIKeyWithWait(ctx context.Context, userID int64, maxConcurrency int, apiKeyID int64, timeout time.Duration) (func(), error) {
releaseFunc, acquired, err := h.TryAcquireUserSlot(ctx, userID, maxConcurrency)
if err != nil || !acquired {
return releaseFunc, acquired, err
if err != nil {
return nil, err
}
if acquired {
return h.withAPIKeySlot(ctx, apiKeyID, releaseFunc), nil
}
queueLimit := service.CalculateMaxWait(maxConcurrency) - maxConcurrency
if queueLimit < 1 {
queueLimit = 1
}
canWait, err := h.IncrementWaitCount(ctx, userID, queueLimit)
if err != nil {
return nil, err
}
if !canWait {
return nil, &WaitQueueFullError{SlotType: "user"}
}
defer h.DecrementWaitCount(ctx, userID)
releaseFunc, err = h.waitForUserSlot(ctx, userID, maxConcurrency, timeout)
if err != nil {
return nil, err
}
return h.withAPIKeySlot(ctx, apiKeyID, releaseFunc), nil
}
// waitForUserSlot polls for a user slot with the same backoff as
// waitForSlotWithPingTimeout, without writing anything to the client.
func (h *ConcurrencyHelper) waitForUserSlot(ctx context.Context, userID int64, maxConcurrency int, timeout time.Duration) (func(), error) {
waitCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
backoff := initialBackoff
timer := time.NewTimer(backoff)
defer timer.Stop()
for {
select {
case <-waitCtx.Done():
if parentErr := ctx.Err(); parentErr != nil {
return nil, parentErr
}
return nil, &ConcurrencyError{SlotType: "user", IsTimeout: true}
case <-timer.C:
result, err := h.concurrencyService.AcquireUserSlot(waitCtx, userID, maxConcurrency)
if err != nil {
if parentErr := ctx.Err(); parentErr != nil {
return nil, parentErr
}
if waitCtx.Err() != nil {
return nil, &ConcurrencyError{SlotType: "user", IsTimeout: true}
}
return nil, err
}
if result.Acquired {
return result.ReleaseFunc, nil
}
backoff = nextBackoff(backoff)
timer.Reset(backoff)
}
}
return h.withAPIKeySlot(ctx, apiKeyID, releaseFunc), true, nil
}
// AcquireOpenAIWSIngressLease bounds the whole client WebSocket lifecycle,
@@ -319,26 +319,6 @@ func TestAcquireUserSlotWithWait_TracksAPIKeySlot(t *testing.T) {
require.Equal(t, 1, cache.apiKeyReleaseCalls)
}
func TestTryAcquireUserSlotForAPIKey_TracksAPIKeySlot(t *testing.T) {
cache := &helperConcurrencyCacheStub{
userSeq: []bool{true},
}
concurrency := service.NewConcurrencyService(cache)
helper := NewConcurrencyHelper(concurrency, SSEPingFormatNone, 5*time.Millisecond)
release, acquired, err := helper.TryAcquireUserSlotForAPIKey(context.Background(), 202, 3, 77)
require.NoError(t, err)
require.True(t, acquired)
require.NotNil(t, release)
require.Equal(t, 1, cache.apiKeyTrackCalls)
require.Equal(t, []int64{77}, cache.apiKeyTrackIDs)
release()
require.Equal(t, 1, cache.userReleaseCalls)
require.Equal(t, 1, cache.apiKeyReleaseCalls)
}
func TestAcquireUserSlotWithWait_WaitSuccessDecrementsBeforeReturn(t *testing.T) {
cache := &helperConcurrencyCacheStub{
userSeq: []bool{false, true},
@@ -0,0 +1,99 @@
package handler
import (
"context"
"errors"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestAcquireUserSlotForAPIKeyWithWait_ImmediateAcquireSkipsWaitQueue(t *testing.T) {
cache := &helperConcurrencyCacheStub{userSeq: []bool{true}}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
release, err := helper.AcquireUserSlotForAPIKeyWithWait(context.Background(), 7, 3, 42, time.Second)
require.NoError(t, err)
require.NotNil(t, release)
release()
require.Equal(t, 1, cache.userAcquireCalls)
require.Zero(t, cache.waitIncrementCalls)
require.Zero(t, cache.waitDecrementCalls)
require.Equal(t, 1, cache.userReleaseCalls)
require.Equal(t, []int64{42}, cache.apiKeyTrackIDs)
require.Equal(t, 1, cache.apiKeyReleaseCalls)
}
func TestAcquireUserSlotForAPIKeyWithWait_WaitsForFreedSlot(t *testing.T) {
cache := &helperConcurrencyCacheStub{
userSeq: []bool{false, false, true},
waitAllowed: true,
}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
release, err := helper.AcquireUserSlotForAPIKeyWithWait(context.Background(), 7, 3, 42, 2*time.Second)
require.NoError(t, err)
require.NotNil(t, release)
require.Equal(t, 3, cache.userAcquireCalls)
require.Equal(t, 1, cache.waitIncrementCalls)
require.Equal(t, 1, cache.waitDecrementCalls, "the queue entry is released once the slot is acquired")
require.Equal(t, service.CalculateMaxWait(3)-3, cache.waitMaxWait)
release()
require.Equal(t, 1, cache.userReleaseCalls)
require.Equal(t, []int64{42}, cache.apiKeyTrackIDs)
require.Equal(t, 1, cache.apiKeyReleaseCalls)
}
func TestAcquireUserSlotForAPIKeyWithWait_TimesOut(t *testing.T) {
cache := &helperConcurrencyCacheStub{waitAllowed: true}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
start := time.Now()
release, err := helper.AcquireUserSlotForAPIKeyWithWait(context.Background(), 7, 3, 42, 250*time.Millisecond)
require.Nil(t, release)
var concurrencyErr *ConcurrencyError
require.ErrorAs(t, err, &concurrencyErr)
require.True(t, concurrencyErr.IsTimeout)
require.Equal(t, "user", concurrencyErr.SlotType)
require.Less(t, time.Since(start), 2*time.Second)
require.GreaterOrEqual(t, cache.userAcquireCalls, 2, "the slot is retried while waiting")
require.Equal(t, 1, cache.waitDecrementCalls)
require.Zero(t, cache.userReleaseCalls)
require.Empty(t, cache.apiKeyTrackIDs)
}
func TestAcquireUserSlotForAPIKeyWithWait_QueueFull(t *testing.T) {
cache := &helperConcurrencyCacheStub{waitAllowed: false}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
release, err := helper.AcquireUserSlotForAPIKeyWithWait(context.Background(), 7, 3, 42, time.Second)
require.Nil(t, release)
var queueFullErr *WaitQueueFullError
require.ErrorAs(t, err, &queueFullErr)
require.Equal(t, "user", queueFullErr.SlotType)
require.Equal(t, 1, cache.userAcquireCalls, "a full queue fails without polling")
require.Equal(t, 1, cache.waitIncrementCalls)
require.Zero(t, cache.waitDecrementCalls)
}
func TestAcquireUserSlotForAPIKeyWithWait_StopsWhenContextEnds(t *testing.T) {
cache := &helperConcurrencyCacheStub{waitAllowed: true}
helper := NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second)
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(150*time.Millisecond, cancel)
start := time.Now()
release, err := helper.AcquireUserSlotForAPIKeyWithWait(ctx, 7, 3, 42, 10*time.Second)
require.Nil(t, release)
require.True(t, errors.Is(err, context.Canceled), "got %v", err)
require.Less(t, time.Since(start), 2*time.Second)
require.Equal(t, 1, cache.waitDecrementCalls)
}
@@ -2,6 +2,7 @@ package handler
import (
"context"
"unsafe"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
@@ -13,11 +14,74 @@ type inflightReservationEstimator interface {
EstimateInflightReservation(ctx context.Context, apiKey *service.APIKey, req service.InflightEstimateRequest) (float64, bool)
}
// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini)。
// requestMaxOutputTokens 从请求体中提取输出 token 上限(兼容 Anthropic / OpenAI Chat / Responses / Gemini),
// 单遍零拷贝遍历顶层键,保持 max_tokens → max_completion_tokens → max_output_tokens → generationConfig.maxOutputTokens → generation_config.max_output_tokens 优先级。
func requestMaxOutputTokens(body []byte) int {
for _, path := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens", "generationConfig.maxOutputTokens", "generation_config.max_output_tokens"} {
if v := gjson.GetBytes(body, path); v.Exists() && v.Type == gjson.Number && v.Int() > 0 {
return int(v.Int())
if len(body) == 0 {
return 0
}
const (
maxTokensBit uint8 = 1 << iota
maxCompletionTokensBit
maxOutputTokensBit
genConfigCamelBit
genConfigSnakeBit
allMaxTokenBits = maxTokensBit | maxCompletionTokensBit | maxOutputTokensBit | genConfigCamelBit | genConfigSnakeBit
)
var seen uint8
var vals [5]int
root := gjson.Parse(unsafe.String(unsafe.SliceData(body), len(body)))
if !root.IsObject() {
return 0
}
root.ForEach(func(key, value gjson.Result) bool {
switch key.Str {
case "max_tokens":
if seen&maxTokensBit == 0 {
seen |= maxTokensBit
if value.Type == gjson.Number && value.Int() > 0 {
vals[0] = int(value.Int())
return false
}
}
case "max_completion_tokens":
if seen&maxCompletionTokensBit == 0 {
seen |= maxCompletionTokensBit
if value.Type == gjson.Number && value.Int() > 0 {
vals[1] = int(value.Int())
}
}
case "max_output_tokens":
if seen&maxOutputTokensBit == 0 {
seen |= maxOutputTokensBit
if value.Type == gjson.Number && value.Int() > 0 {
vals[2] = int(value.Int())
}
}
case "generationConfig":
if seen&genConfigCamelBit == 0 {
if v := value.Get("maxOutputTokens"); v.Exists() {
seen |= genConfigCamelBit
if v.Type == gjson.Number && v.Int() > 0 {
vals[3] = int(v.Int())
}
}
}
case "generation_config":
if seen&genConfigSnakeBit == 0 {
if v := value.Get("max_output_tokens"); v.Exists() {
seen |= genConfigSnakeBit
if v.Type == gjson.Number && v.Int() > 0 {
vals[4] = int(v.Int())
}
}
}
}
return seen != allMaxTokenBits
})
for _, v := range vals {
if v > 0 {
return v
}
}
return 0
@@ -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) {
@@ -527,7 +527,9 @@ func TestGatewayCodexModels_GeneratedManifestUsesFinalBodyETag(t *testing.T) {
second := httptest.NewRecorder()
secondContext, _ := gin.CreateTestContext(second)
secondContext.Request = httptest.NewRequest(http.MethodGet, "/models?client_version=0.147.0", nil)
secondContext.Request.Header.Set("If-None-Match", "W/"+etag)
// The generated ETag is weak; its strong form must still revalidate.
require.True(t, strings.HasPrefix(etag, "W/"))
secondContext.Request.Header.Set("If-None-Match", strings.TrimPrefix(etag, "W/"))
secondContext.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: group})
h.CodexModels(secondContext)
@@ -4,14 +4,17 @@ 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"
@@ -21,33 +24,49 @@ import (
type stickyWritebackContextKey struct{}
type stickyWritebackCall struct {
err error
groupID int64
account int64
session string
ttl time.Duration
value any
deadline time.Time
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
finished bool
calls []stickyWritebackCall
// 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 {
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,
})
s.record(ctx, groupID, session, account, ttl, nil)
}
if err := ctx.Err(); err != nil {
return err
@@ -56,6 +75,30 @@ func (s *stickyWritebackCache) SetSessionAccountID(ctx context.Context, groupID
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
}
@@ -75,6 +118,23 @@ func (b *stickyWritebackBody) Close() error {
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} {
@@ -83,11 +143,29 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
name = "streaming"
}
for _, tt := range []struct {
name string
bound int64
cancel bool
fail bool
wantWrites int
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},
@@ -95,18 +173,89 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
{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}
account := &service.Account{
ID: 9401, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
Credentials: map[string]any{"api_key": "test-key"},
Extra: map[string]any{"anthropic_passthrough": true},
AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}},
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)
@@ -121,23 +270,50 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
status = http.StatusBadRequest
responseBody = `{"type":"error","error":{"type":"invalid_request_error","message":"invalid input"}}`
}
upstream := &compatStreamUsageUpstream{response: &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": []string{contentType}},
Body: &stickyWritebackBody{Reader: strings.NewReader(responseBody), finish: func() {
// Forward closes its upstream body on return. Cancel precisely
// after that work, before the handler's terminal sticky write.
cache.finished = true
if tt.cancel {
cancel()
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}
other := *account
other.ID = 9499
other.Schedulable = false
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account, &other}}, nil, nil, nil, nil)
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,
@@ -163,7 +339,12 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
h.Messages(c)
require.Equal(t, 1, upstream.calls)
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 {
@@ -173,13 +354,30 @@ func TestGatewayMessagesStickyWritebackAfterForward(t *testing.T) {
for _, call := range cache.calls {
require.NoError(t, call.err, "a completed upstream request must retain its terminal sticky write")
require.Equal(t, groupID, call.groupID)
require.Equal(t, account.ID, call.account)
require.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")
}
})
}
}
@@ -161,6 +161,9 @@ func (h *GatewayHandler) SystemOne(c *gin.Context) {
}
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
return
}
accountRelease := selection.ReleaseFunc
if !selection.Acquired {
@@ -175,6 +175,10 @@ func (h *GatewayHandler) WebSearch(c *gin.Context) {
break
}
if rejectSelectedAccountIfModerated(c, selected.Account.ID, selectionReleaseFunc(selected), webSearchSecurityAuditError) {
return
}
release, acquireOK, acquireErr := h.acquireWebSearchAccountSlot(c, selected)
if !acquireOK {
// First hop: surface concurrency errors; later hops try another account.
@@ -194,6 +194,9 @@ func (h *GatewayHandler) GeminiCachedContentsCreate(c *gin.Context) {
ttlRejectedLimit = max(ttlRejectedLimit, account.GeminiExplicitCacheUpstreamMaxTTL())
continue
}
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), googleSecurityAuditError) {
return
}
accountReleaseFunc, ok := h.acquireGeminiCachedContentAccountSlot(c, reqLog, geminiConcurrency, selection)
if !ok {
return
@@ -87,11 +87,15 @@ func TestAppendUpstreamGeminiModelsPreservesMetadata(t *testing.T) {
// Exercise the real handler's native-upstream branch, including scope fallback.
type geminiMixedModelsUpstream struct {
service.HTTPUpstream
status int
body string
status int
body string
lastReq *http.Request
calls int
}
func (u *geminiMixedModelsUpstream) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
func (u *geminiMixedModelsUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
u.lastReq = req
u.calls++
return &http.Response{StatusCode: u.status, Header: http.Header{"Content-Type": {"application/json"}, "X-Request-Id": {"native-id"}}, Body: io.NopCloser(strings.NewReader(u.body))}, nil
}
func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) {
@@ -240,3 +244,122 @@ func TestGeminiNativeModelsUnmappedAccountKeepsUpstream(t *testing.T) {
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, 2, f.upstream.calls)
}
func TestGeminiV1BetaListModels_PaginationQueryForwarding(t *testing.T) {
newHandler := func(upstream *geminiMixedModelsUpstream, allowlist service.GroupModelAllowlist, includeMixedAG bool) (*GatewayHandler, *service.APIKey) {
id := int64(48)
accounts := []service.Account{
{ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Credentials: map[string]any{"api_key": "upstream-key"}},
}
if includeMixedAG {
accounts = append(accounts, service.Account{
ID: 2,
Platform: service.PlatformAntigravity,
Extra: map[string]any{"mixed_scheduling": true},
Credentials: map[string]any{"model_mapping": map[string]any{"gemini-synced-custom": "gemini-3.8-flash-high"}},
})
}
repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{id: accounts}}}
h := &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, nil, nil, upstream, nil, &config.Config{})}
key := &service.APIKey{GroupID: &id, Group: &service.Group{ID: id, Platform: service.PlatformGemini, ModelAllowlist: allowlist}}
return h, key
}
t.Run("allowlists pageSize and pageToken and drops key and unknown params", func(t *testing.T) {
upstream := &geminiMixedModelsUpstream{
status: http.StatusOK,
body: `{"models":[{"name":"models/gemini-page-2"}]}`,
}
h, key := newHandler(upstream, service.GroupModelAllowlist{}, true)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=1000&pageToken=abc%2B%2F%3D%3D&key=sk-client-secret&alt=json&foo=bar", nil)
c.Set(string(middleware.ContextKeyAPIKey), key)
h.GeminiV1BetaListModels(c)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.NotNil(t, upstream.lastReq)
gotQuery := upstream.lastReq.URL.Query()
require.Equal(t, "1000", gotQuery.Get("pageSize"))
require.Equal(t, "abc+/==", gotQuery.Get("pageToken"))
require.Empty(t, gotQuery.Get("key"))
require.Empty(t, gotQuery.Get("alt"))
require.Empty(t, gotQuery.Get("foo"))
require.Len(t, gotQuery, 2)
// 后续分页不重复附加混合分组的 Antigravity 模型。
require.Contains(t, rec.Body.String(), "models/gemini-page-2")
require.NotContains(t, rec.Body.String(), "models/gemini-synced-custom")
})
t.Run("pageSize zero succeeds and omits pageSize upstream", func(t *testing.T) {
upstream := &geminiMixedModelsUpstream{
status: http.StatusOK,
body: `{"models":[{"name":"models/gemini-page-1"}],"nextPageToken":"tok-2"}`,
}
h, key := newHandler(upstream, service.GroupModelAllowlist{}, true)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=0", nil)
c.Set(string(middleware.ContextKeyAPIKey), key)
h.GeminiV1BetaListModels(c)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.NotNil(t, upstream.lastReq)
require.Empty(t, upstream.lastReq.URL.RawQuery)
// 首页仍附加混合分组的 Antigravity 模型并保留 nextPageToken。
require.Contains(t, rec.Body.String(), "models/gemini-synced-custom")
require.Contains(t, rec.Body.String(), `"nextPageToken":"tok-2"`)
})
t.Run("invalid pagination params return 400 without hitting upstream", func(t *testing.T) {
for _, target := range []string{
"/v1beta/models?pageSize=-1",
"/v1beta/models?pageSize=abc",
"/v1beta/models?pageToken=bad%0Atoken",
"/v1beta/models?pageToken=" + strings.Repeat("x", 4097),
} {
upstream := &geminiMixedModelsUpstream{status: http.StatusOK, body: `{"models":[]}`}
h, key := newHandler(upstream, service.GroupModelAllowlist{}, false)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, target, nil)
c.Set(string(middleware.ContextKeyAPIKey), key)
h.GeminiV1BetaListModels(c)
require.Equal(t, http.StatusBadRequest, rec.Code, target)
require.Zero(t, upstream.calls, target)
}
})
t.Run("allowlist dropping all models on a page keeps empty array and nextPageToken", func(t *testing.T) {
upstream := &geminiMixedModelsUpstream{
status: http.StatusOK,
body: `{"models":[{"name":"models/gemini-blocked"}],"nextPageToken":"tok-2"}`,
}
h, key := newHandler(upstream, service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-allowed"}}, false)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageSize=1", nil)
c.Set(string(middleware.ContextKeyAPIKey), key)
h.GeminiV1BetaListModels(c)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.JSONEq(t, `{"models":[],"nextPageToken":"tok-2"}`, rec.Body.String())
})
t.Run("upstream error passes through untouched when allowlist is enabled", func(t *testing.T) {
upstream := &geminiMixedModelsUpstream{
status: http.StatusBadRequest,
body: `{"error":{"code":400,"message":"Invalid page token","status":"INVALID_ARGUMENT"}}`,
}
h, key := newHandler(upstream, service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-allowed"}}, false)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, "/v1beta/models?pageToken=expired", nil)
c.Set(string(middleware.ContextKeyAPIKey), key)
h.GeminiV1BetaListModels(c)
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
require.JSONEq(t, upstream.body, rec.Body.String())
})
}
@@ -48,6 +48,12 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
return
}
listQuery, err := service.ParseGeminiListModelsQuery(c.Query("pageSize"), c.Query("pageToken"))
if err != nil {
googleError(c, http.StatusBadRequest, err.Error())
return
}
// 分组级模型白名单开启时过滤 models[].name(名字形如 models/xxx)。
filterGeminiModels := func(models []gemini.Model) []gemini.Model {
if apiKey.Group == nil || !apiKey.Group.ModelAllowlistEnabled() {
@@ -106,7 +112,7 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
return
}
res, err := h.geminiCompatService.ForwardListModels(c.Request.Context(), account)
res, err := h.geminiCompatService.ForwardListModelsWithQuery(c.Request.Context(), account, listQuery)
if err != nil {
googleError(c, http.StatusBadGateway, err.Error())
return
@@ -115,13 +121,14 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: filterGeminiModels(mergeGeminiModelLists(gemini.DefaultModels(), agModels))})
return
}
if res.StatusCode == http.StatusOK && len(agModels) > 0 {
// 仅在首页附加混合分组内的 Antigravity 模型,避免后续分页重复追加。
if res.StatusCode == http.StatusOK && len(agModels) > 0 && listQuery.PageToken == "" {
if merged, ok := appendUpstreamGeminiModels(res.Body, agModels); ok {
res.Body = merged
}
}
if apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
if res.StatusCode == http.StatusOK && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
if filtered, dropped, ok := filterUpstreamGeminiModelsBody(res.Body, apiKey.Group.ModelAllowlist); ok && dropped {
// 只在确有条目被过滤时替换响应体;全命中或解析失败时保持原始响应,
// 统一经 writeUpstreamResponse 写出(保留全部上游响应头)。
@@ -637,6 +644,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
}
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), googleSecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
// 检测账号切换:如果粘性会话绑定的账号与当前选择的账号不同,清除 thoughtSignature
+3
View File
@@ -279,6 +279,9 @@ func (h *OpenAIGatewayHandler) GrokVoice(c *gin.Context, endpoint string) {
return
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
var started bool
release, status := h.acquireResponsesAccountSlot(c, apiKey.GroupID, "", selection, false, &started, reqLog)
if status == openAISlotAcquireProfitVetoed {
+3
View File
@@ -357,6 +357,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
if failoverClientGone(c) {
return
}
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
setOpsSelectedAccount(c, account.ID, account.Platform)
+23 -3
View File
@@ -32,6 +32,10 @@ type noAccountErrorClassification struct {
ErrType string
Message string
ModelNotFound bool // true when this is a 404 model_not_found classification
// RetryAfterSeconds carries the earliest recovery time the gateway could
// determine for a temporary availability failure. Zero means unknown; no
// Retry-After header is emitted in that case.
RetryAfterSeconds int
}
var selectionModelRateLimitedPattern = regexp.MustCompile(`(?:model_rate_limited|rate_limited)=(\d+)`)
@@ -68,9 +72,10 @@ func classifySelectionFailureError(err error, fallback noAccountErrorClassificat
return fallback
}
return noAccountErrorClassification{
Status: http.StatusTooManyRequests,
ErrType: "rate_limit_error",
Message: "All available accounts are currently rate-limited. Please retry later.",
Status: http.StatusTooManyRequests,
ErrType: "rate_limit_error",
Message: "All available accounts are currently rate-limited. Please retry later.",
RetryAfterSeconds: fallback.RetryAfterSeconds,
}
}
@@ -134,6 +139,7 @@ func classifyNoAccountError(
ModelNotFound: true,
}
}
fallback.RetryAfterSeconds = result.RetryAfterSeconds
return fallback
}
@@ -153,12 +159,26 @@ func classifyNoAccountErrorFromGin(
ctx = c.Request.Context()
}
classification := classifyNoAccountError(ctx, diag, apiKey, routingModel, displayModel, platform)
classification.applyRetryAfter(c)
if classification.ModelNotFound {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
}
return classification
}
// applyRetryAfter publishes the scheduler-derived recovery hint for temporary
// availability failures. It never adds the header to a 404 model_not_found or
// when the recovery time is unknown.
func (classification noAccountErrorClassification) applyRetryAfter(c *gin.Context) {
if c == nil || classification.RetryAfterSeconds <= 0 {
return
}
switch classification.Status {
case http.StatusTooManyRequests, http.StatusServiceUnavailable, 529:
c.Header("Retry-After", strconv.Itoa(classification.RetryAfterSeconds))
}
}
func classifyOpenAICompatibleNoAccountErrorFromGin(
c *gin.Context,
diag service.ModelAvailabilityDiagnoser,
@@ -322,3 +322,84 @@ func TestGPT55RetirementEmptyListingDoesNotUseDefaults(t *testing.T) {
require.Empty(t, modelListingSource(service.PlatformOpenAI, []string{}, []string{"gpt-5.5"}))
require.Equal(t, []string{"gpt-5.5"}, modelListingSource(service.PlatformOpenAI, nil, []string{"gpt-5.5"}))
}
// The scheduler publishes the earliest cooldown among model-capable accounts;
// the classifier must turn it into Retry-After on both the 503 fallback and the
// 429 rate-limit verdict.
func TestClassifyNoAccountError_RateLimitedPoolCarriesRetryAfter(t *testing.T) {
c := newTestGinContextWithRequest()
fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{
HasAccountsInPool: true,
HasModelSupport: true,
RetryAfterSeconds: 59,
}}
apiKey := &service.APIKey{GroupID: ptrInt64(7)}
cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5.6-sol", "gpt-5.6-sol", service.PlatformOpenAI)
require.Equal(t, http.StatusServiceUnavailable, cls.Status)
require.Equal(t, 59, cls.RetryAfterSeconds)
require.Equal(t, "59", c.Writer.Header().Get("Retry-After"))
cls = classifySelectionFailureError(
fmt.Errorf("no available OpenAI accounts supporting model: gpt-5.6-sol (pool=3, filtered: model_rate_limited=3)"),
cls,
)
require.Equal(t, http.StatusTooManyRequests, cls.Status)
require.Equal(t, "rate_limit_error", cls.ErrType)
require.Equal(t, 59, cls.RetryAfterSeconds, "the 429 upgrade must keep the recovery hint")
require.Equal(t, "59", c.Writer.Header().Get("Retry-After"))
}
func TestClassifyNoAccountError_UnknownRecoveryOmitsRetryAfter(t *testing.T) {
c := newTestGinContextWithRequest()
fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{HasAccountsInPool: true, HasModelSupport: true}}
apiKey := &service.APIKey{GroupID: ptrInt64(7)}
cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5", "gpt-5", service.PlatformOpenAI)
require.Equal(t, http.StatusServiceUnavailable, cls.Status)
require.Zero(t, cls.RetryAfterSeconds)
require.Empty(t, c.Writer.Header().Get("Retry-After"),
"an unknown recovery time must not be invented")
}
func TestClassifyNoAccountError_ModelNotFoundOmitsRetryAfter(t *testing.T) {
c := newTestGinContextWithRequest()
fd := &fakeDiagnoser{resp: service.ModelAvailabilityDiagnosis{
HasAccountsInPool: true,
HasModelSupport: false,
RetryAfterSeconds: 59,
}}
apiKey := &service.APIKey{GroupID: ptrInt64(7)}
cls := classifyNoAccountErrorFromGin(c, fd, apiKey, "gpt-5.9-unknown", "gpt-5.9-unknown", service.PlatformOpenAI)
require.Equal(t, http.StatusNotFound, cls.Status)
require.True(t, cls.ModelNotFound)
require.Zero(t, cls.RetryAfterSeconds)
require.Empty(t, c.Writer.Header().Get("Retry-After"),
"a permanent model configuration error has no recovery time")
}
// The scheduler now appends a model-cooldown reason breakdown to the legacy
// summary. The 429 upgrade must keep parsing the aggregate model_rate_limited
// count, and the breakdown keys must not be mistaken for it.
func TestClassifySelectionFailureError_NewReasonBreakdownStillUpgrades(t *testing.T) {
fallback := noAccountErrorClassification{
Status: http.StatusServiceUnavailable,
ErrType: "api_error",
Message: "Service temporarily unavailable",
}
got := classifySelectionFailureError(
fmt.Errorf("no available accounts supporting model: gpt-5.6-sol "+
"(total=37 eligible=0 excluded=0 unschedulable=0 platform_filtered=0 model_unsupported=0 "+
"model_rate_limited=36 model_rate_limited_reasons=other:2,upstream_404_model_not_found:34 profit_threshold=0 "+
"profit_invalid_account_rate=0)"),
fallback,
)
require.Equal(t, http.StatusTooManyRequests, got.Status)
require.Equal(t, "rate_limit_error", got.ErrType)
require.False(t, got.ModelNotFound)
}
@@ -173,6 +173,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
accountRelease, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, sessionHash, selection, false, &streamStarted, reqLog)
if slotResult == openAISlotAcquireProfitVetoed {
@@ -220,7 +223,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
return
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err)
if failoverErr.Reason != service.OpenAIAlphaSearchRejectedReason {
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestedModel, false, result), false, nil, err)
}
if c.Writer.Size() != writerSizeBeforeForward {
h.handleFailoverExhausted(c, failoverErr, true)
return
@@ -237,13 +242,14 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
sameAccountRetryCount[account.ID]++
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
reqLog.Warn("openai_alpha_search.same_account_retry",
retryFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("retry_limit", retryLimit),
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
zap.Duration("retry_delay", retryDelay),
)
}, failoverErr)
reqLog.Warn("openai_alpha_search.same_account_retry", retryFields...)
select {
case <-c.Request.Context().Done():
return
@@ -264,11 +270,12 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
h.handleFailoverExhausted(c, failoverErr, false)
return
}
reqLog.Warn("openai_alpha_search.upstream_failover_switching",
switchFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
)
}, failoverErr)
reqLog.Warn("openai_alpha_search.upstream_failover_switching", switchFields...)
}
}
@@ -0,0 +1,107 @@
package handler
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type alphaSearchUpstream struct {
service.HTTPUpstream
successAccount int64
calls []int64
}
const alphaSearchSuccess = `{"output":"search result"}`
func alphaSearchRejection(accountID int64) string {
return fmt.Sprintf(`{ "error": {"message": "rejected by %d"} }`+"\n", accountID)
}
func (u *alphaSearchUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
u.calls = append(u.calls, accountID)
status, contentType, body := http.StatusBadRequest, "application/problem+json", alphaSearchRejection(accountID)
if accountID == u.successAccount {
status, contentType, body = http.StatusOK, "application/json", alphaSearchSuccess
}
return &http.Response{
StatusCode: status,
Header: http.Header{"Content-Type": {contentType}},
Body: io.NopCloser(strings.NewReader(body)),
}, nil
}
func TestAlphaSearchBadRequestFailover(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name string
accountCount int
successAccount int64
maxSwitches int
firstType string
wantCalls []int64
wantStatus int
wantBody string
}{
{"next account succeeds", 2, 2, 2, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusOK, alphaSearchSuccess},
{"single account", 1, 0, 2, service.AccountTypeAPIKey, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)},
{"all accounts reject", 2, 0, 3, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)},
{"switch limit", 3, 3, 1, service.AccountTypeAPIKey, []int64{1, 2}, http.StatusBadRequest, alphaSearchRejection(2)},
{"oauth passes through", 2, 2, 2, service.AccountTypeOAuth, []int64{1}, http.StatusBadRequest, alphaSearchRejection(1)},
} {
t.Run(tc.name, func(t *testing.T) {
repo := &openAIWSFailoverHandlerAccountRepoStub{}
for i := 1; i <= tc.accountCount; i++ {
account := newPinnedCodexAccount(int64(i), service.StatusActive, true, false)
account.Concurrency = 0
account.Credentials["pool_mode"] = true
account.Credentials["pool_mode_retry_status_codes"] = []any{400}
repo.accounts = append(repo.accounts, account)
}
if tc.firstType == service.AccountTypeOAuth {
repo.accounts[0].Type = tc.firstType
repo.accounts[0].Credentials = map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-account"}
}
cfg := &config.Config{RunMode: config.RunModeSimple}
upstream := &alphaSearchUpstream{successAccount: tc.successAccount}
usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 4)}
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
gateway := service.NewOpenAIGatewayService(repo, usage, nil, nil, nil, nil, nil, cfg,
nil, nil, service.NewBillingService(cfg, nil), service.NewRateLimitService(repo, nil, cfg, nil, nil), billing, upstream,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil)
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, &service.APIKeyService{}, nil, nil, nil, nil, cfg)
h.maxAccountSwitches = tc.maxSwitches
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/alpha/search", strings.NewReader(`{"model":"gpt-5.6-sol","commands":{"search_query":[{"q":"news"}]}}`))
group := &service.Group{ID: 42, Platform: service.PlatformOpenAI}
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, GroupID: &group.ID, Group: group, User: &service.User{ID: 2}})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 2})
h.AlphaSearch(c)
require.Equal(t, tc.wantCalls, upstream.calls)
require.Equal(t, tc.wantStatus, rec.Code)
require.Equal(t, tc.wantBody, rec.Body.String())
require.Empty(t, repo.rateLimitedIDs)
if tc.wantStatus == http.StatusOK {
require.Len(t, usage.created, 1)
require.Equal(t, tc.successAccount, (<-usage.created).AccountID)
require.Equal(t, "application/json", rec.Header().Get("Content-Type"))
} else {
require.Empty(t, usage.created)
require.Equal(t, "application/problem+json", rec.Header().Get("Content-Type"))
}
})
}
}
@@ -1,11 +1,14 @@
package handler
import (
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"go.uber.org/zap"
)
const automationBootstrapPrompt = "Review the project and report any important changes."
@@ -82,12 +85,20 @@ func TestNormalizeCodexAutomationBootstrapRejectsUnsafeShapes(t *testing.T) {
body: codexAutomationBootstrapBody(t, validOutput, `,"call_id":"call-1"`),
},
{
name: "previous response",
body: []byte(`{"model":"gpt-5","previous_response_id":"resp-1","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `}]}`),
name: "ambiguous call context",
body: []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `},{"type":"function_call"}]}`),
},
{
name: "real call context",
body: []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `},{"type":"function_call","call_id":"call-1"}]}`),
name: "ambiguous built-in call context",
body: []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `},{"type":"computer_call"}]}`),
},
{
name: "ambiguous tool search call without call id or id",
body: []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `},{"type":"tool_search_call"}]}`),
},
{
name: "non-string previous response id",
body: []byte(`{"model":"gpt-5","previous_response_id":null,"input":[{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, validOutput) + `}]}`),
},
{
name: "mismatched memory id",
@@ -190,16 +201,19 @@ Read the reference index and report changes. Preserve A &amp; B and &lt;tags&gt;
}
for _, invalid := range []string{
strings.Replace(output, "2026-09-09T00:33:34.775Z", "yesterday", 1),
strings.Replace(output, "2026-09-09T00:33:34.775Z", " 2026-09-09T00:33:34.775Z ", 1),
strings.Replace(output, "2026-09-09T00:33:34.775Z", "<v>2026-09-09T00:33:34.775Z</v>", 1),
strings.Replace(output, "<current_time_iso>2026-09-09T00:33:34.775Z</current_time_iso>", "", 1),
strings.Replace(output, "Read the reference index and report changes. Preserve A &amp; B and &lt;tags&gt;.", " ", 1),
strings.Replace(output, "<instructions>", `<instructions source="other">`, 1),
strings.Replace(output, "<instructions>", "<instructions><nested/>", 1),
strings.Replace(output, "</instructions>", "", 1),
output + "<heartbeat><automation_id>dup</automation_id></heartbeat>",
`<heartbeat><automation_id>wiki</automation_id><current_time_iso>2026-09-09T00:33:34.775Z</current_time_iso><instructions>a</heartbeat>OUTSIDE<heartbeat><fake>b</fake></instructions></heartbeat>`,
} {
require.False(t, validCodexAutomationHeartbeat(invalid))
require.False(t, validCodexAutomationHeartbeat(invalid), invalid)
}
for _, guarded := range [][]byte{
codexAutomationBootstrapBody(t, output, `,"call_id":"call-1"`),
[]byte(strings.Replace(string(body), `"model":"gpt-5"`, `"model":"gpt-5","previous_response_id":"resp-1"`, 1)),
[]byte(strings.Replace(string(body), `"namespace":"codex_app"`, `"namespace":"other"`, 1)),
} {
unchanged, normalized := normalizeCodexAutomationBootstrap(guarded)
@@ -208,6 +222,134 @@ Read the reference index and report changes. Preserve A &amp; B and &lt;tags&gt;
}
}
func TestNormalizeCodexAutomationBootstrapHeartbeatLiteralClosingTagAndHistoryVariants(t *testing.T) {
// 正文内包含字面量 </instructions> 时仍应按外层边界正确识别。
promptWithClosingTag := "<heartbeat>\n" +
" <automation_id>prompt-audit</automation_id>\n" +
" <current_time_iso>2026-11-22T14:55:28.776Z</current_time_iso>\n" +
" <instructions>\n" +
"Verify all <instructions>...</instructions> blocks in prompts/ are properly closed.\n" +
" </instructions>\n" +
"</heartbeat>"
got, changed := normalizeCodexAutomationBootstrap(codexAutomationBootstrapBody(t, promptWithClosingTag, ""))
require.True(t, changed)
require.Equal(t, promptWithClosingTag, gjson.GetBytes(got, "input.0.content.0.text").String())
// Bootstrap(Automation: ...)格式与历史上下文、托管工具(含无 id 的 web_search_call / x_search_call /
// 带 id 的 tool_search_call)共存时也能正常归一化。
bootstrapText := codexAutomationBootstrap("wiki", "never", automationBootstrapPrompt)
withHistory := []byte(`{"model":"gpt-6.1-sol","previous_response_id":"resp_1","input":[` +
`{"type":"function_call","call_id":"call_1","name":"exec","arguments":"{}"},` +
`{"type":"function_call_output","call_id":"call_1","output":"ok"},` +
`{"type":"web_search_call","status":"completed"},` +
`{"type":"x_search_call","id":"xs_1","status":"completed"},` +
`{"type":"tool_search_call","id":"ts_1","arguments":{"query":"repo"}},` +
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, bootstrapText) + `}` +
`]}`)
got, changed = normalizeCodexAutomationBootstrap(withHistory)
require.True(t, changed)
require.Equal(t, "message", gjson.GetBytes(got, "input.5.type").String())
require.Equal(t, "user", gjson.GetBytes(got, "input.5.role").String())
require.Equal(t, bootstrapText, gjson.GetBytes(got, "input.5.content.0.text").String())
// automation_update 与 delegation(create_thread)同帧共存时不得互相死锁。
mixedDelegation := []byte(`{"model":"gpt-6.1-sol","input":[` +
`{"type":"function_call_output","namespace":"codex_app","name":"create_thread","output":` + mustJSON(t, delegationEnvelope) + `},` +
`{"type":"function_call_output","namespace":"codex_app","name":"automation_update","output":"<heartbeat><automation_id>wiki</automation_id></heartbeat>"}` +
`]}`)
got, changed = normalizeCodexAutomationBootstrap(mixedDelegation)
require.True(t, changed)
require.Equal(t, "message", gjson.GetBytes(got, "input.1.type").String())
got, changed = normalizeCodexDelegationBootstrap(got)
require.True(t, changed)
require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String())
// 未在 untrusted 白名单里的 standalone agent ExternalMessage(如 browser_tabs)
// 不得阻断同请求中 automation_update 的归一化。
mixedAgent := []byte(`{"model":"gpt-6.1-sol","input":[` +
`{"type":"function_call_output","id":"fco_1","namespace":"agent","name":"browser_tabs","output":"<tabs/>"},` +
`{"type":"function_call_output","id":"fco_2","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, promptWithClosingTag) + `}` +
`]}`)
got, changed = normalizeCodexAutomationBootstrap(mixedAgent)
require.True(t, changed)
require.Equal(t, "function_call_output", gjson.GetBytes(got, "input.0.type").String())
require.Equal(t, "agent", gjson.GetBytes(got, "input.0.namespace").String())
require.Equal(t, "message", gjson.GetBytes(got, "input.1.type").String())
require.Equal(t, "user", gjson.GetBytes(got, "input.1.role").String())
}
func TestNormalizeCodexAutomationBootstrapHeartbeatWithUnescapedInstructionsAndHistory(t *testing.T) {
// 复现 Codex Desktop Windows 定时任务真实载荷:
// 1. <instructions> 含未 XML 转义的 PowerShell `&`、`<OrderNo>`、`<单号>` 与 CRLF;
// 2. 长对话复用同一线程,包含历史配对的 function_call / function_call_output、
// item_reference、web_search_call(无 call_id 仅有 id)与多轮历史 heartbeat。
heartbeat1 := "<heartbeat>\r\n" +
" <automation_id>automation</automation_id>\r\n" +
" <current_time_iso>2026-11-22T14:55:28.776Z</current_time_iso>\r\n" +
" <instructions>\r\n" +
"每轮仅运行一次:\n" +
"& 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' -File 'Run-Monitor.ps1'\n" +
"再定位slt<OrderNo>所在行,证据 runs/verified_<单号>.png,支持 <nested/> 标签。\r\n" +
" </instructions>\r\n" +
"</heartbeat>\r\n"
heartbeat2 := "<heartbeat>\r\n" +
" <automation_id>automation</automation_id>\r\n" +
" <current_time_iso>2026-11-23T04:58:10.100Z</current_time_iso>\r\n" +
" <instructions>\r\n" +
"第二轮定时检查:a < b && c > d\r\n" +
" </instructions>\r\n" +
"</heartbeat>\r\n"
body := []byte(`{` +
`"model":"gpt-6.1-sol",` +
`"previous_response_id":"resp_hist_1",` +
`"metadata":{"large":9007199254740993},` +
`"input":[` +
`{"type":"message","role":"user","content":"initial"},` +
`{"type":"function_call","call_id":"call_1","name":"exec","arguments":"{}"},` +
`{"type":"function_call_output","call_id":"call_1","output":"ok"},` +
`{"type":"web_search_call","id":"ws_1","status":"completed"},` +
`{"type":"item_reference","id":"item_1"},` +
`{"type":"function_call_output","id":"fco_1","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, heartbeat1) + `},` +
`{"type":"function_call_output","id":"fco_2","namespace":"codex_app","name":"automation_update","output":` + mustJSON(t, heartbeat2) + `},` +
`{"type":"message","role":"user","content":"??"}` +
`]}`)
got, changed := normalizeCodexAutomationBootstrap(body)
require.True(t, changed)
require.Equal(t, "resp_hist_1", gjson.GetBytes(got, "previous_response_id").String())
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
// 历史调用上下文保持原样
require.Equal(t, "call_1", gjson.GetBytes(got, "input.1.call_id").String())
require.Equal(t, "call_1", gjson.GetBytes(got, "input.2.call_id").String())
require.Equal(t, "ws_1", gjson.GetBytes(got, "input.3.id").String())
require.Equal(t, "item_1", gjson.GetBytes(got, "input.4.id").String())
// 两轮 heartbeat 均被转为标准 user message,内容原样保留
require.Equal(t, "message", gjson.GetBytes(got, "input.5.type").String())
require.Equal(t, "user", gjson.GetBytes(got, "input.5.role").String())
require.Equal(t, heartbeat1, gjson.GetBytes(got, "input.5.content.0.text").String())
require.False(t, gjson.GetBytes(got, "input.5.namespace").Exists())
require.Equal(t, "message", gjson.GetBytes(got, "input.6.type").String())
require.Equal(t, "user", gjson.GetBytes(got, "input.6.role").String())
require.Equal(t, heartbeat2, gjson.GetBytes(got, "input.6.content.0.text").String())
require.Equal(t, "??", gjson.GetBytes(got, "input.7.content").String())
// 幂等
again, changedAgain := normalizeCodexAutomationBootstrap(got)
require.False(t, changedAgain)
require.Equal(t, got, again)
// 首轮无历史上下文时也能通过 HTTP call_id 校验
firstTurn := codexAutomationBootstrapBody(t, heartbeat1, "")
firstTurnNormalized, firstChanged := normalizeCodexAutomationBootstrap(firstTurn)
require.True(t, firstChanged)
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.True(t, h.validateFunctionCallOutputRequest(c, firstTurnNormalized, zap.NewNop()))
require.False(t, c.Writer.Written())
}
// The byte precheck must stay a necessary condition: an escaped type or tool
// name is still a candidate, and a body without either is returned untouched
// without the token scan and decode.
@@ -0,0 +1,91 @@
//go:build unit
package handler
import (
"bytes"
"fmt"
"io"
"net/http"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func capacityShedSSEOverloadResponse(retryAfterSec string) *http.Response {
stream := fmt.Sprintf(
"event: response.created\n"+
"data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_shed\"}}\n\n"+
"event: error\n"+
"data: {\"type\":\"error\",\"error\":{\"type\":\"service_unavailable_error\",\"code\":\"server_is_overloaded\",\"message\":\"Our servers are currently overloaded. Please try again later.\",\"headers\":{\"retry-after\":%q}}}\n\n",
retryAfterSec,
)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(bytes.NewBufferString(stream)),
}
}
func capacityShedHTTPOverloadResponse(retryAfterMs string) *http.Response {
h := http.Header{"Content-Type": []string{"application/json"}}
if retryAfterMs != "" {
h.Set("Retry-After-Ms", retryAfterMs)
}
return &http.Response{
StatusCode: http.StatusServiceUnavailable,
Header: h,
Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"service_unavailable_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}`,
)),
}
}
func TestOpenAIGatewayHandlerResponses_LongOverloadRetryAfterSwitchesImmediately(t *testing.T) {
gin.SetMode(gin.TestMode)
upstream := newAstraProCapturedUpstream(capacityShedSSEOverloadResponse("315"), astra200())
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
handler.Responses(c)
_, accountIDs, _ := upstream.snapshot()
require.Equal(t, []int64{1, 2}, accountIDs)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "completed", gjson.GetBytes(rec.Body.Bytes(), "status").String())
}
func TestOpenAIGatewayHandlerResponses_ShortOverloadRetryAfterRetriesSameAccount(t *testing.T) {
gin.SetMode(gin.TestMode)
upstream := newAstraProCapturedUpstream(capacityShedHTTPOverloadResponse("10"), astra200())
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
handler.Responses(c)
_, accountIDs, _ := upstream.snapshot()
require.Equal(t, []int64{1, 1}, accountIDs)
require.Equal(t, http.StatusOK, rec.Code)
}
func TestOpenAIGatewayHandlerResponses_AllAccountsLongOverloadFailsFast503(t *testing.T) {
gin.SetMode(gin.TestMode)
upstream := newAstraProCapturedUpstream(
capacityShedSSEOverloadResponse("315"),
capacityShedSSEOverloadResponse("335"),
)
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
c, rec := newAstraProFailoverContext(t, astraProRequestBody)
handler.Responses(c)
_, accountIDs, _ := upstream.snapshot()
require.Equal(t, []int64{1, 2}, accountIDs)
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "servers are currently overloaded")
}
@@ -227,6 +227,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
return
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
reqLog.Debug("openai_chat_completions.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
_ = scheduleDecision
@@ -356,13 +359,14 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
sameAccountRetryCount[account.ID]++
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry",
retryFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("retry_limit", retryLimit),
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
zap.Duration("retry_delay", retryDelay),
)
}, failoverErr)
reqLog.Warn("openai_chat_completions.pool_mode_same_account_retry", retryFields...)
select {
case <-c.Request.Context().Done():
return
@@ -383,12 +387,13 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
reqLog.Warn("openai_chat_completions.upstream_failover_switching",
switchFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
zap.Int("max_switches", maxAccountSwitches),
)
}, failoverErr)
reqLog.Warn("openai_chat_completions.upstream_failover_switching", switchFields...)
continue
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, nil), false, nil, err)
@@ -53,7 +53,7 @@ func TestCodexCallOutputGateAdmitsEveryRewrite(t *testing.T) {
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)
_, rewritten := normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, true)
if rewritten {
rewrites++
require.True(t, mayContainCodexCallOutputCandidate(body, "automation_update"), "%s", body)
@@ -0,0 +1,119 @@
package handler
import (
"net/http"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestCodexModelsFallsBackToLocalManifestWhenUpstreamCannotServeModels(t *testing.T) {
cases := []struct {
name string
firstStatus int
firstBody string
}{
{name: "upstream 5xx", firstStatus: http.StatusServiceUnavailable},
{name: "empty manifest", firstStatus: http.StatusOK, firstBody: `{"models":[]}`},
{name: "non JSON body", firstStatus: http.StatusOK, firstBody: `not-json`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(tc.firstStatus, 1, 3)
upstream.firstBody = tc.firstBody
recorder := performCodexModelsRequest(t, handler, groupID)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.NotEmpty(t, recorder.Header().Get("ETag"))
slugs := codexHandlerManifestSlugs(t, recorder)
require.Contains(t, slugs, "gpt-5.6-sol")
require.NotContains(t, slugs, "gpt-image-2")
})
}
}
func TestCodexModelsFallsBackToLocalManifestAfterAllCandidatesFail(t *testing.T) {
handler, upstream, groupID := newCodexModelsFailoverTestHandler(http.StatusServiceUnavailable)
upstream.statuses = map[int64]int{
1: http.StatusServiceUnavailable,
2: http.StatusServiceUnavailable,
}
recorder := performCodexModelsRequest(t, handler, groupID)
require.Equal(t, []int64{1, 2}, upstream.calls())
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Contains(t, codexHandlerManifestSlugs(t, recorder), "gpt-5.6-sol")
}
func TestCodexModelsFallbackPrefersGroupModelsListConfig(t *testing.T) {
handler, upstream, groupID := newCodexModelsFailoverTestHandler(http.StatusServiceUnavailable)
upstream.statuses = map[int64]int{
1: http.StatusServiceUnavailable,
2: http.StatusServiceUnavailable,
}
group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI}
group.ModelAllowlist = service.GroupModelAllowlist{
Enabled: true,
Models: []string{"gpt-5.6-luna", "gpt-6.2-sol"},
}
recorder := performCodexModelsRequestForGroup(t, handler, group, "")
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.ElementsMatch(t, []string{"gpt-5.6-luna", "gpt-6.2-sol"}, codexHandlerManifestSlugs(t, recorder))
}
func TestCodexModelsUpstreamManifestWinsOverLocalFallback(t *testing.T) {
handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusOK, 1, 3)
upstream.firstBody = `{"models":[{"slug":"upstream-only-model"}]}`
recorder := performCodexModelsRequest(t, handler, groupID)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Equal(t, []string{"upstream-only-model"}, codexHandlerManifestSlugs(t, recorder))
}
func TestCodexModelsFallbackSupportsETagRevalidation(t *testing.T) {
handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusServiceUnavailable, 1, 3)
group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI}
first := performCodexModelsRequestForGroup(t, handler, group, "")
require.Equal(t, http.StatusOK, first.Code, first.Body.String())
etag := first.Header().Get("ETag")
require.NotEmpty(t, etag)
require.NotEmpty(t, upstream.calls())
second := performCodexModelsRequestForGroup(t, handler, group, etag)
require.Equal(t, http.StatusNotModified, second.Code, second.Body.String())
require.Empty(t, second.Body.Bytes())
}
func TestCodexModelsKeepsUpstreamErrorWhenLocalFallbackIsEmpty(t *testing.T) {
handler, upstream, groupID := newCodexModelsFailoverTestHandlerWithAccountCount(http.StatusServiceUnavailable, 1, 3)
group := &service.Group{ID: groupID, Platform: service.PlatformOpenAI}
// Dedicated image models are dropped from Codex manifests, so the local
// list is empty and the original upstream error must be preserved.
group.ModelAllowlist = service.GroupModelAllowlist{Enabled: true, Models: []string{"gpt-image-2"}}
recorder := performCodexModelsRequestForGroup(t, handler, group, "")
require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String())
require.NotEmpty(t, upstream.calls())
}
// codexModelsGroupWithoutLocalFallback configures a model list that Codex
// cannot advertise (image-generation only). The #5252 local fallback therefore
// stays empty and tests can still observe the original upstream error.
func codexModelsGroupWithoutLocalFallback(groupID int64) *service.Group {
return &service.Group{
ID: groupID,
Platform: service.PlatformOpenAI,
ModelAllowlist: service.GroupModelAllowlist{
Enabled: true,
Models: []string{"gpt-image-2"},
},
}
}
@@ -5,6 +5,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
@@ -20,6 +21,9 @@ import (
// when disabled, groups with explicit mappings are generated locally;
// otherwise ChatGPT manifests are proxied verbatim and custom API key manifests
// receive provider-compatibility normalization plus short-lived caching.
// When no upstream can serve /models (missing endpoint, 5xx, or an empty
// manifest), a local fallback manifest is generated instead of failing the
// request while the group still has a usable local model list (#5252).
func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
if c.Request.Context().Err() != nil {
return
@@ -67,7 +71,7 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
if c.Request.Context().Err() != nil {
return
}
writeOpenAIModelsResponse(c, pinnedManifest)
h.writeCodexModelsResponse(c, apiKey.Group, pinnedManifest)
return
}
}
@@ -86,7 +90,7 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
return
}
if configured {
writeOpenAIModelsResponse(c, configuredManifest)
h.writeCodexModelsResponse(c, apiKey.Group, configuredManifest)
return
}
}
@@ -106,6 +110,9 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
return
}
if lastUpstreamErr != nil {
if h.writeLocalCodexModelsFallback(c, apiKey.Group, lastUpstreamErr) {
return
}
h.errorResponse(c, infraerrors.Code(lastUpstreamErr), "upstream_error", infraerrors.Message(lastUpstreamErr))
return
}
@@ -122,15 +129,29 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
if c.Request.Context().Err() != nil {
return
}
if service.IsRetryableCodexModelsManifestError(err) && switchCount < maxAccountSwitches {
failedAccountIDs[account.ID] = struct{}{}
switchCount++
lastUpstreamErr = err
continue
if service.IsRetryableCodexModelsManifestError(err) {
if switchCount < maxAccountSwitches {
failedAccountIDs[account.ID] = struct{}{}
switchCount++
lastUpstreamErr = err
continue
}
// All candidates failed (or the switch budget is exhausted): an
// upstream without a usable /models endpoint must not break the
// client model picker while the group can describe its models
// locally (#5252).
if h.writeLocalCodexModelsFallback(c, apiKey.Group, err) {
return
}
}
h.errorResponse(c, infraerrors.Code(err), "upstream_error", infraerrors.Message(err))
return
}
// A 2xx manifest with no models is as unusable as a failed request for
// Codex clients. Prefer the local catalog when one exists.
if service.CodexModelsManifestIsEmpty(manifest.Body) && h.writeLocalCodexModelsFallback(c, apiKey.Group, errors.New("upstream returned an empty models manifest")) {
return
}
if err := h.gatewayService.CompleteAPIKeyCodexModelsManifestForClient(manifest, account); err != nil {
h.errorResponse(c, http.StatusInternalServerError, "api_error", "Failed to complete Codex models manifest")
return
@@ -147,7 +168,48 @@ func (h *OpenAIGatewayHandler) CodexModels(c *gin.Context) {
return
}
writeOpenAIModelsResponse(c, manifest)
h.writeCodexModelsResponse(c, apiKey.Group, manifest)
return
}
}
// writeLocalCodexModelsFallback writes a locally generated Codex manifest when
// the selected upstreams cannot serve /models. It reports false when the local
// model list is empty so the caller can preserve the original upstream error.
func (h *OpenAIGatewayHandler) writeLocalCodexModelsFallback(c *gin.Context, group *service.Group, upstreamErr error) bool {
if h == nil || h.gatewayService == nil {
return false
}
var groupID int64
if group != nil {
groupID = group.ID
}
reqLog := requestLogger(c, "handler.openai_gateway.codex_models", zap.Int64("group_id", groupID))
manifest, configured, err := h.gatewayService.BuildLocalCodexModelsFallbackManifest(
c.Request.Context(),
group,
c.GetHeader("If-None-Match"),
)
if err != nil {
reqLog.Warn("openai.codex_models_local_fallback_failed", zap.Error(err), zap.NamedError("upstream_error", upstreamErr))
return false
}
if !configured || manifest == nil {
return false
}
// The client gets a 200, so this is the only signal that the upstream
// /models endpoint is unusable for the group.
reqLog.Warn("openai.codex_models_local_fallback_served", zap.NamedError("upstream_error", upstreamErr))
h.writeCodexModelsResponse(c, group, manifest)
return true
}
// writeCodexModelsResponse records the ETag the group's manifest is served with,
// so codex.response.metadata events can be translated to it, and writes the
// manifest response.
func (h *OpenAIGatewayHandler) writeCodexModelsResponse(c *gin.Context, group *service.Group, manifest *service.OpenAIModelsResponse) {
if group != nil && h.gatewayService != nil {
h.gatewayService.RecordCodexModelsManifestETag(group.ID, manifest)
}
writeOpenAIModelsResponse(c, manifest)
}
@@ -534,7 +534,7 @@ func TestCodexModelsReturnsLastUpstreamErrorWhenAccountsAreExhausted(t *testing.
1: http.StatusServiceUnavailable,
2: http.StatusGatewayTimeout,
}
recorder := performCodexModelsRequest(t, handler, groupID)
recorder := performCodexModelsRequestForGroup(t, handler, codexModelsGroupWithoutLocalFallback(groupID), "")
if got, want := upstream.calls(), []int64{1, 2}; !equalInt64Slices(got, want) {
t.Fatalf("upstream account calls: got %v, want %v", got, want)
@@ -555,7 +555,7 @@ func TestCodexModelsHonorsAccountSwitchLimit(t *testing.T) {
3: http.StatusGatewayTimeout,
4: http.StatusInternalServerError,
}
recorder := performCodexModelsRequest(t, handler, groupID)
recorder := performCodexModelsRequestForGroup(t, handler, codexModelsGroupWithoutLocalFallback(groupID), "")
if got, want := upstream.calls(), []int64{1, 2, 3}; !equalInt64Slices(got, want) {
t.Fatalf("upstream account calls: got %v, want %v", got, want)
@@ -181,6 +181,9 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
return
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
accountReleaseFunc, slotResult := h.acquireResponsesAccountSlot(c, apiKey.GroupID, "", selection, false, &streamStarted, reqLog)
@@ -244,12 +247,13 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
return
}
switchCount++
reqLog.Warn("openai_embeddings.upstream_failover_switching",
switchFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
zap.Int("max_switches", maxAccountSwitches),
)
}, failoverErr)
reqLog.Warn("openai_embeddings.upstream_failover_switching", switchFields...)
continue
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, reqModel, false, result), false, nil, err)
@@ -123,6 +123,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
return
}
if rejectSelectedAccountIfModerated(c, account.ID, nil, h.openAISecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
if err := h.gatewayService.ForwardResponsesInputTokens(c.Request.Context(), c, account, forwardBody); err != nil {
reqLog.Error("openai_input_tokens.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err))
@@ -297,6 +300,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
return
}
if rejectSelectedAccountIfModerated(c, account.ID, nil, h.anthropicSecurityAuditError) {
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
forwardBody := mappedBodyForMessages(channelMapping.Mapped, channelMapping.MappedModel)
defaultMappedModel := preferredMappedModel
@@ -277,7 +277,7 @@ func TestFailoverExhaustionRejectsSecretBearingRetryAfter(t *testing.T) {
require.NotContains(t, recorder.Body.String(), "must-not-leak")
}
func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) {
func TestFailoverExhaustionCapsFarFutureRetryAfterDate(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
@@ -291,10 +291,11 @@ func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) {
}, false)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
require.Empty(t, recorder.Header().Get("Retry-After"))
require.Equal(t, "300", recorder.Header().Get("Retry-After"),
"absurd upstream windows must be capped instead of forwarded verbatim")
}
func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) {
func TestFailoverExhaustionConvertsRetryAfterDateToSeconds(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
@@ -307,7 +308,8 @@ func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) {
}, false)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
require.Equal(t, retryAfter, recorder.Header().Get("Retry-After"))
require.Equal(t, "300", recorder.Header().Get("Retry-After"),
"dates are converted to integer seconds and capped")
}
func TestOpsClassificationTreatsCredentialFailureAsAuthNotInference(t *testing.T) {
@@ -438,3 +440,38 @@ func TestOpsWebSocketCredentialFailoverExhaustedIsRecorded(t *testing.T) {
require.Equal(t, http.StatusServiceUnavailable, job.entry.StatusCode)
require.Equal(t, service.GrokCredentialUnavailableClientMessage, job.entry.ErrorMessage)
}
func TestFailoverExhaustionUsesBodyRetryAfterMs(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := &OpenAIGatewayHandler{}
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
StatusCode: http.StatusTooManyRequests,
ResponseBody: []byte(`{"error":{"headers":{"retry-after-ms":"1500"}}}`),
}, false)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
require.Equal(t, "2", recorder.Header().Get("Retry-After"),
"body-provided millisecond hints are converted to whole seconds")
}
func TestFailoverExhaustionCapacityShedOmitsRetryAfter(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := &OpenAIGatewayHandler{}
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
StatusCode: http.StatusTooManyRequests,
RequestScopedTransient: true,
ResponseHeaders: http.Header{"Retry-After": []string{"480"}},
ResponseBody: []byte(`{"error":{"type":"server_error","code":"server_is_overloaded",` +
`"message":"Our servers are currently overloaded. Please try again later."}}`),
}, false)
require.NotEmpty(t, recorder.Body.String())
require.Empty(t, recorder.Header().Get("Retry-After"),
"capacity-shed windows must not be forwarded; clients would sleep through a transient blip")
}
+451 -144
View File
@@ -16,6 +16,7 @@ import (
"sync/atomic"
"time"
"unicode/utf8"
"unsafe"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/domain"
@@ -81,7 +82,8 @@ func newOpenAIWSUnsupportedModelSwitchError(model string) error {
}
func shouldReportOpenAIWSProxyAccountFailure(err error) bool {
return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) && !service.IsOpenAIWSSessionPreemptedError(err)
return err != nil && !errors.Is(err, errOpenAIWSUnsupportedModelSwitch) &&
!errors.Is(err, service.ErrResponsesWSBridgeHistoryLimit) && !service.IsOpenAIWSSessionPreemptedError(err)
}
// openAIWSIngressEndedByClient reports whether a finished ingress WebSocket turn
@@ -470,55 +472,67 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body")
return
}
service.MarkOpenAIRequestBodyJSONValidated(c)
// 使用 gjson 只读提取字段做校验,避免完整 Unmarshal
modelResult := gjson.GetBytes(body, "model")
if !modelResult.Exists() || modelResult.Type != gjson.String || modelResult.String() == "" {
// 单次只读扫描顶层校验与路由字段,避免对大请求体重复调用 gjson.GetBytes。
ingressFields := parseOpenAIResponsesIngressFields(body)
if !ingressFields.ModelValid {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required")
return
}
reqModel := modelResult.String()
reqModel := ingressFields.Model
ensureCompositeTargetPlatform(c, apiKey, reqModel)
if !openAICompatibleTextTargetAllowed(c, apiKey, reqModel) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups")
return
}
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequest(c, apiKey, body); err != nil {
ingressBodyChanged := false
if cappedBody, changed, err := applyOpenAIReasoningEffortPolicyForRequestWithFields(
c, apiKey, body, reqModel,
ingressFields.ReasoningEffort, ingressFields.ReasoningEffortTop, ingressFields.OutputConfigEffort,
); err != nil {
respondOpenAIReasoningEffortPolicyError(c, err, h.errorResponse)
return
} else if changed {
body = cappedBody
ingressBodyChanged = true
}
if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed {
body = normalizedBody
ingressBodyChanged = true
reqLog.Info("openai.codex_untrusted_context_normalized",
zap.String("normalization", "call_output_to_user_message"),
)
}
if normalizedBody, changed := normalizeCodexAutomationBootstrap(body); changed {
body = normalizedBody
ingressBodyChanged = true
reqLog.Info("openai.codex_automation_bootstrap_normalized",
zap.String("normalization", "call_output_to_user_message"),
)
}
if normalizedBody, changed := normalizeCodexDelegationBootstrap(body); changed {
body = normalizedBody
ingressBodyChanged = true
reqLog.Info("openai.codex_delegation_bootstrap_normalized",
zap.String("normalization", "call_output_to_user_message"),
)
}
if ingressBodyChanged {
ingressFields = parseOpenAIResponsesIngressFields(body)
}
reqStream, ok := parseOpenAICompatibleStream(body)
if !ok {
if !ingressFields.StreamValid {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", invalidStreamFieldTypeMessage)
return
}
if _, err := service.ValidateOpenAIServiceTierField(body); err != nil {
reqStream := ingressFields.Stream
if _, err := service.ValidateOpenAIServiceTierResult(ingressFields.ServiceTier); err != nil {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream))
previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String())
previousResponseID := ingressFields.PreviousResponseID
if previousResponseID != "" {
previousResponseIDKind := service.ClassifyOpenAIPreviousResponseIDKind(previousResponseID)
reqLog = reqLog.With(
@@ -563,10 +577,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
return
}
// 使用 IsExplicitImageGenerationIntent 排除被动 image_gen namespace 声明。
// 使用 IsExplicitImageGenerationIntentValidated 排除被动 image_gen namespace 声明。
// Codex 在所有请求中被动声明 image_gen namespace,宽泛检测会导致禁了生图的
// 分组中所有 Codex 请求被 403(#4447),并误占生图并发槽位。
imageIntent := service.IsExplicitImageGenerationIntent("/v1/responses", reqModel, body)
imageIntent := service.IsExplicitImageGenerationIntentValidated("/v1/responses", reqModel, body)
if imageIntent && !service.GroupAllowsImageGeneration(apiKey.Group) {
h.errorResponse(c, http.StatusForbidden, "permission_error", service.ImageGenerationPermissionMessage())
return
@@ -632,7 +646,11 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
}
// 余额模式在途预留:防止并发请求在预检时看到同一份余额而集体透支。
inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, tokenInflightEstimate(reqModel, body))
var inflightEstimate service.InflightEstimateRequest
if h.billingCacheService != nil && h.billingCacheService.InflightReservationEnabled() {
inflightEstimate = tokenInflightEstimate(reqModel, body)
}
inflightRelease, err := reserveInflightBalance(c, h.billingCacheService, h.gatewayService, apiKey, subscription, inflightEstimate)
if err != nil {
reqLog.Info("openai.inflight_reservation_rejected", zap.Error(err))
status, code, message, retryAfter := billingErrorDetails(err)
@@ -685,6 +703,18 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID)
c.Request = c.Request.WithContext(pricingCtx)
var (
requestPayloadHashComputed bool
requestPayloadHashValue string
)
getRequestPayloadHash := func() string {
if !requestPayloadHashComputed {
requestPayloadHashValue = service.HashUsageRequestPayload(body)
requestPayloadHashComputed = true
}
return requestPayloadHashValue
}
for {
// Streaming Forward intentionally detaches the upstream request so usage can
// be drained after a disconnect. Re-check the client context before every
@@ -789,6 +819,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
)
continue
}
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
reqLog.Debug("openai.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
setOpsSelectedAccount(c, account.ID, account.Platform)
@@ -828,11 +861,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
if h.handleForwardRequestBodyMemoryOverload(c, err, streamStarted) {
return
}
var cyberBlockBodyHTTP []byte
if service.GetOpsCyberPolicy(c) != nil {
cyberBlockBodyHTTP = sessionHashBody
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, sessionHashBody, clientRequestedUsageFields(c, channelMapping, reqModel, ""), getRequestPayloadHash())
}
h.recordCyberPolicyIfMarked(c, apiKey, account, subscription, reqModel, err != nil, cyberBlockBodyHTTP, clientRequestedUsageFields(c, channelMapping, reqModel, ""), service.HashUsageRequestPayload(body))
forwardDurationMs := time.Since(forwardStart).Milliseconds()
upstreamLatencyMs, _ := getContextInt64(c, service.OpsUpstreamLatencyMsKey)
responseLatencyMs := forwardDurationMs
@@ -852,7 +883,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
stampOpenAIRequestedReasoningEffort(res, c)
userAgent := c.GetHeader("User-Agent")
clientIP := ip.GetClientIP(c)
requestPayloadHash := service.HashUsageRequestPayload(body)
requestPayloadHash := getRequestPayloadHash()
inboundEndpoint := GetInboundEndpoint(c)
upstreamEndpoint := resolveOpenAIUpstreamEndpoint(c, account, res)
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
@@ -950,13 +981,14 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
sameAccountRetryCount[account.ID]++
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
reqLog.Warn("openai.pool_mode_same_account_retry",
retryFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("retry_limit", retryLimit),
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
zap.Duration("retry_delay", retryDelay),
)
}, failoverErr)
reqLog.Warn("openai.pool_mode_same_account_retry", retryFields...)
select {
case <-c.Request.Context().Done():
return
@@ -993,6 +1025,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
} else if account.ProxyID != nil {
failoverSwitchFields = append(failoverSwitchFields, zap.Int64p("proxy_id", account.ProxyID))
}
failoverSwitchFields = appendUpstreamRetryAfterField(failoverSwitchFields, failoverErr)
reqLog.Warn("openai.upstream_failover_switching", failoverSwitchFields...)
continue
}
@@ -1391,6 +1424,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
return
}
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.anthropicSecurityAuditError) {
return
}
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
reqLog.Debug("openai_messages.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
_ = scheduleDecision
@@ -1527,13 +1563,14 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
sameAccountRetryCount[account.ID]++
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
reqLog.Warn("openai_messages.pool_mode_same_account_retry",
retryFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("retry_limit", retryLimit),
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
zap.Duration("retry_delay", retryDelay),
)
}, failoverErr)
reqLog.Warn("openai_messages.pool_mode_same_account_retry", retryFields...)
select {
case <-c.Request.Context().Done():
return
@@ -1554,12 +1591,13 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted)
return
}
reqLog.Warn("openai_messages.upstream_failover_switching",
switchFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
zap.Int("max_switches", maxAccountSwitches),
)
}, failoverErr)
reqLog.Warn("openai_messages.upstream_failover_switching", switchFields...)
continue
}
if result != nil && result.ClientDisconnect {
@@ -1656,7 +1694,7 @@ func (h *OpenAIGatewayHandler) anthropicStreamingAwareError(c *gin.Context, stat
// handleAnthropicFailoverExhausted maps upstream failover errors to Anthropic format.
func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) {
if failoverErr != nil {
copyFailoverRetryAfter(c, failoverErr.ResponseHeaders)
applyRateLimitRetryAfter(c, failoverErr, h.cfg)
}
if failoverErr != nil && failoverErr.IsCredentialFailure() {
status, message := credentialFailoverClientResponse(failoverErr)
@@ -1692,7 +1730,99 @@ func (h *OpenAIGatewayHandler) ensureAnthropicErrorResponse(c *gin.Context, stre
return true
}
type openAIResponsesIngressFields struct {
Model string
ModelValid bool
Stream bool
StreamValid bool
ServiceTier gjson.Result
PreviousResponseID string
ReasoningEffort string
ReasoningEffortTop string
OutputConfigEffort string
}
// parseOpenAIResponsesIngressFields 单次只读扫描 /v1/responses 顶层入口字段,
// 提取出的字符串全部 clone 断开对原始请求体的引用;ServiceTier 仅在本次同步校验期间使用。
func parseOpenAIResponsesIngressFields(body []byte) openAIResponsesIngressFields {
fields := openAIResponsesIngressFields{StreamValid: true}
if len(body) == 0 {
return fields
}
root := gjson.Parse(unsafe.String(unsafe.SliceData(body), len(body)))
if !root.IsObject() {
return fields
}
const (
seenModel uint8 = 1 << iota
seenStream
seenServiceTier
seenPrevRespID
seenReasoning
seenReasoningTop
seenOutputConfig
seenAll = seenModel | seenStream | seenServiceTier | seenPrevRespID |
seenReasoning | seenReasoningTop | seenOutputConfig
)
var seen uint8
root.ForEach(func(key, value gjson.Result) bool {
switch key.Str {
case "model":
if seen&seenModel == 0 {
seen |= seenModel
if value.Type == gjson.String && value.String() != "" {
fields.ModelValid = true
fields.Model = strings.Clone(value.String())
}
}
case "stream":
if seen&seenStream == 0 {
seen |= seenStream
if value.Type != gjson.True && value.Type != gjson.False {
fields.StreamValid = false
} else {
fields.Stream = value.Bool()
}
}
case "service_tier":
if seen&seenServiceTier == 0 {
seen |= seenServiceTier
fields.ServiceTier = value
}
case "previous_response_id":
if seen&seenPrevRespID == 0 {
seen |= seenPrevRespID
fields.PreviousResponseID = strings.Clone(strings.TrimSpace(value.String()))
}
case "reasoning":
if seen&seenReasoning == 0 {
if effort := value.Get("effort"); effort.Exists() {
seen |= seenReasoning
fields.ReasoningEffort = strings.Clone(strings.TrimSpace(effort.String()))
}
}
case "reasoning_effort":
if seen&seenReasoningTop == 0 {
seen |= seenReasoningTop
fields.ReasoningEffortTop = strings.Clone(strings.TrimSpace(value.String()))
}
case "output_config":
if seen&seenOutputConfig == 0 {
if effort := value.Get("effort"); effort.Exists() {
seen |= seenOutputConfig
fields.OutputConfigEffort = strings.Clone(strings.TrimSpace(effort.String()))
}
}
}
return seen != seenAll
})
return fields
}
func (h *OpenAIGatewayHandler) validateFunctionCallOutputRequest(c *gin.Context, body []byte, reqLog *zap.Logger) bool {
if !bytes.Contains(body, []byte("function_call_output")) && !service.JSONMayEscapePlainASCII(body) {
return true
}
if !gjson.GetBytes(body, `input.#(type=="function_call_output")`).Exists() {
return true
}
@@ -1739,7 +1869,10 @@ func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) {
if !mayContainCodexCallOutputCandidate(body, "automation_update") {
return body, false
}
return normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false)
// 定时任务复用已有长对话时,会在历史调用上下文之后追加 automation_update heartbeat,
// 也可能携带 previous_response_id;它仍是客户端注入的触发消息而非历史工具调用的结果,
// 因此允许它与可明确配对的历史上下文共存。
return normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, true)
}
// mayContainCodexCallOutputCandidate is a necessary condition for a bootstrap
@@ -1796,8 +1929,8 @@ func normalizeCodexCallOutputBootstrap(body []byte, isCandidate func(map[string]
// Responses built-ins follow the *_call / *_call_output naming convention,
// so classify by the wire type shape instead of maintaining an incomplete
// allowlist. Delegation may coexist with historical anchors only when their
// IDs make them unambiguous; automation retains the bootstrap-only boundary.
// allowlist. Delegation and automation may coexist with historical anchors
// only when their IDs make them unambiguous.
for _, raw := range input {
item, ok := raw.(map[string]any)
if !ok {
@@ -1805,19 +1938,32 @@ func normalizeCodexCallOutputBootstrap(body []byte, isCandidate func(map[string]
}
typ := stringField(item, "type")
if isCandidate(item) {
callIDValue, exists := item["call_id"]
callID, isString := callIDValue.(string)
if exists && (!isString || strings.TrimSpace(callID) != "") {
if !hasMissingOrBlankCallID(item) {
return body, false
}
continue
}
if allowHistoricalContext && isCodexCoexistingStandaloneOutput(item) {
continue
}
if typ == "item_reference" {
if allowHistoricalContext && strings.TrimSpace(stringField(item, "id")) != "" {
continue
}
return body, false
}
if isResponsesServerSideCallType(typ) {
if allowHistoricalContext {
continue
}
return body, false
}
if typ == "tool_search_call" {
if allowHistoricalContext && (strings.TrimSpace(stringField(item, "call_id")) != "" || strings.TrimSpace(stringField(item, "id")) != "") {
continue
}
return body, false
}
if strings.HasSuffix(typ, "_call") || isResponsesCallOutputType(typ) {
if allowHistoricalContext && strings.TrimSpace(stringField(item, "call_id")) != "" {
continue
@@ -1914,6 +2060,48 @@ func isResponsesCallOutputType(typ string) bool {
return strings.HasSuffix(typ, "_call_output") || typ == "tool_search_output"
}
// isResponsesServerSideCallType 识别服务端托管的 Responses *_call 历史项。
// 这类项不与客户端 *_call_output 配对,协议上不带 call_id(且 store=false 回放可能无 id)。
func isResponsesServerSideCallType(typ string) bool {
switch typ {
case "web_search_call", "x_search_call", "file_search_call", "code_interpreter_call", "image_generation_call", "mcp_call":
return true
default:
return false
}
}
func hasMissingOrBlankCallID(item map[string]any) bool {
callIDValue, exists := item["call_id"]
if !exists {
return true
}
callID, isString := callIDValue.(string)
return isString && strings.TrimSpace(callID) == ""
}
// isCodexCoexistingStandaloneOutput 允许同一请求中的合法兄弟 Codex ExternalMessage 共存:
// 1. automation_update 与 delegation(create_thread/send_message_to_thread)可共存,避免两步归一化互相死锁;
// 2. namespace=="agent" 的 standalone 环境上下文(如 browser_tabs/terminal_info)与 codex_app 任务触发独立,
// 不应阻断 automation/delegation 归一化。
//
// 注意:不放行 codex_app/codex_tui 下畸形的非候选输出,保留原有拒绝语义。
func isCodexCoexistingStandaloneOutput(item map[string]any) bool {
if !hasMissingOrBlankCallID(item) {
return false
}
if isCodexAutomationCandidate(item) || isCodexDelegationCandidate(item) {
return true
}
if stringField(item, "type") != "function_call_output" ||
stringField(item, "namespace") != "agent" ||
strings.TrimSpace(stringField(item, "name")) == "" {
return false
}
_, ok := item["output"].(string)
return ok
}
func isCodexDelegationCandidate(item map[string]any) bool {
if stringField(item, "type") != "function_call_output" ||
!isCodexDelegationTool(stringField(item, "namespace"), stringField(item, "name")) {
@@ -2008,77 +2196,107 @@ func validCodexAutomationLastRun(value string) bool {
return err == nil && runAt.UnixMilli() == epochMillis
}
// validCodexAutomationHeartbeat 校验 Codex Desktop 生成的 <heartbeat> 触发信封。
// Codex Desktop 通过字符串拼接写入 <instructions> 正文,不会对用户 prompt 中的
// `&`、`<OrderNo>` 等字符做 XML 转义,因此外层标签仍按精确字面量严格校验,
// 而 <instructions>...</instructions> 内部作为原始文本提取。
func validCodexAutomationHeartbeat(value string) bool {
decoder := xml.NewDecoder(strings.NewReader(value))
var rootSeen, automationIDSeen bool
var childName string
var childText bytes.Buffer
fields := make(map[string]string)
depth := 0
rest := strings.TrimSpace(value)
if !strings.HasPrefix(rest, "<heartbeat>") || !strings.HasSuffix(rest, "</heartbeat>") {
return false
}
inner := rest[len("<heartbeat>") : len(rest)-len("</heartbeat>")]
fields := make(map[string]string, 3)
for {
token, err := decoder.Token()
if err == io.EOF {
id := fields["automation_id"]
timestamp, hasTime := fields["current_time_iso"]
instructions, hasInstructions := fields["instructions"]
if hasTime != hasInstructions {
return false
}
if hasTime {
if _, err := time.Parse(time.RFC3339Nano, timestamp); err != nil || strings.TrimSpace(instructions) == "" {
return false
}
}
return rootSeen && automationIDSeen && depth == 0 &&
strings.TrimSpace(id) == id && validCodexAutomationID(id)
inner = strings.TrimSpace(inner)
if inner == "" {
break
}
if err != nil {
var tagName, closeTag string
switch {
case strings.HasPrefix(inner, "<automation_id>"):
tagName, closeTag = "automation_id", "</automation_id>"
case strings.HasPrefix(inner, "<current_time_iso>"):
tagName, closeTag = "current_time_iso", "</current_time_iso>"
case strings.HasPrefix(inner, "<instructions>"):
tagName, closeTag = "instructions", "</instructions>"
default:
return false
}
switch current := token.(type) {
case xml.StartElement:
depth++
if current.Name.Space != "" || len(current.Attr) != 0 || depth > 2 {
return false
}
if depth == 1 {
if rootSeen || current.Name.Local != "heartbeat" {
return false
}
rootSeen = true
} else {
childName = current.Name.Local
switch childName {
case "automation_id", "current_time_iso", "instructions":
default:
return false
}
if _, duplicate := fields[childName]; duplicate {
return false
}
childText.Reset()
}
case xml.EndElement:
if current.Name.Space != "" {
return false
}
if depth == 2 {
fields[childName] = childText.String()
automationIDSeen = automationIDSeen || childName == "automation_id"
}
depth--
if depth < 0 {
return false
}
case xml.CharData:
if depth == 2 {
_, _ = childText.Write(current)
} else if len(bytes.TrimSpace(current)) != 0 {
return false
}
case xml.Comment, xml.ProcInst, xml.Directive:
if _, duplicate := fields[tagName]; duplicate {
return false
}
inner = inner[len("<")+len(tagName)+len(">"):]
var end int
if tagName == "instructions" {
end = findHeartbeatInstructionsEnd(inner, fields)
} else {
end = strings.Index(inner, closeTag)
}
if end < 0 {
return false
}
fields[tagName] = inner[:end]
inner = inner[end+len(closeTag):]
}
id, hasID := fields["automation_id"]
if !hasID || strings.TrimSpace(id) != id || !validCodexAutomationID(id) {
return false
}
timestamp, hasTime := fields["current_time_iso"]
instructions, hasInstructions := fields["instructions"]
if hasTime != hasInstructions {
return false
}
if hasTime {
if strings.TrimSpace(timestamp) != timestamp {
return false
}
if _, err := time.Parse(time.RFC3339Nano, timestamp); err != nil {
return false
}
if strings.TrimSpace(instructions) == "" || strings.Contains(instructions, "</heartbeat>") {
return false
}
}
return true
}
// findHeartbeatInstructionsEnd 寻找与当前 <instructions> 配对的结束标签偏移。
// 允许正文内包含字面量 `</instructions>`,仅当其后(跳过空白)紧跟信封结尾或尚未出现的
// 合法兄弟标签(`<automation_id>` / `<current_time_iso>`)时才视为结束边界;
// 若其后紧跟重复标签,直接返回 -1 拒绝。
func findHeartbeatInstructionsEnd(inner string, fields map[string]string) int {
const closeTag = "</instructions>"
offset := 0
for {
rel := strings.Index(inner[offset:], closeTag)
if rel < 0 {
return -1
}
end := offset + rel
after := strings.TrimSpace(inner[end+len(closeTag):])
if after == "" {
return end
}
if strings.HasPrefix(after, "<instructions>") {
return -1
}
if strings.HasPrefix(after, "<automation_id>") {
if _, seen := fields["automation_id"]; !seen {
return end
}
return -1
}
if strings.HasPrefix(after, "<current_time_iso>") {
if _, seen := fields["current_time_iso"]; !seen {
return end
}
return -1
}
offset = end + len(closeTag)
}
}
@@ -2547,6 +2765,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
c.Request = c.Request.WithContext(ctx)
}
clientReadLimit := service.ResolveOpenAIWSClientReadLimitBytes(h.cfg)
service.SetOpenAIWSClientMaxMessageBytesHeader(c.Writer.Header(), clientReadLimit)
wsConn, err := coderws.Accept(c.Writer, c.Request, &coderws.AcceptOptions{
CompressionMode: coderws.CompressionContextTakeover,
})
@@ -2565,7 +2785,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
defer func() {
_ = wsConn.CloseNow()
}()
wsConn.SetReadLimit(service.ResolveOpenAIWSClientReadLimitBytes(h.cfg))
wsConn.SetReadLimit(clientReadLimit)
firstMessageTimeout := service.ResolveOpenAIWSClientFirstMessageTimeout(h.cfg)
msgType, firstMessage, err := service.ReadOpenAIWSClientMessage(
@@ -2731,7 +2951,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 必须尽早注册,确保任何 early return 都能释放已获取的并发槽位。
defer releaseTurnSlots()
userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID)
userReleaseFunc, userAcquired, err := h.acquireOpenAIWSUserSlot(ctx, subject, apiKey.ID)
if err != nil {
reqLog.Warn("openai.websocket_user_slot_acquire_failed", zap.Error(err))
closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to acquire user concurrency slot")
@@ -2746,7 +2966,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
if currentUserRelease != nil {
return true
}
userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID)
userReleaseFunc, userAcquired, err := h.acquireOpenAIWSUserSlot(ctx, subject, apiKey.ID)
if err != nil {
reqLog.Warn("openai.websocket_user_slot_reacquire_failed", zap.Error(err))
closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to acquire user concurrency slot")
@@ -2812,11 +3032,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
var oauth429FailoverState service.OpenAIOAuth429FailoverState
wsAttemptMessage := append([]byte(nil), firstMessage...)
waitForWSSameAccountRetry := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool {
if account == nil || failoverErr == nil || failoverErr.StatusCode != http.StatusTooManyRequests || failoverErr.SameAccountRetryDeadline.IsZero() {
return false
}
retryLimit := effectiveSameAccountRetryLimit(failoverErr, account)
if !sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
if account == nil || !wsSameAccountRetryAllowed(account, failoverErr, sameAccountRetryCount[account.ID]) {
return false
}
sameAccountRetryCount[account.ID]++
@@ -2861,12 +3077,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr)
return false
}
reqLog.Warn("openai.websocket_upstream_failover_switching",
wsSwitchFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
zap.Int("max_switches", maxAccountSwitches),
)
}, failoverErr)
reqLog.Warn("openai.websocket_upstream_failover_switching", wsSwitchFields...)
if ctx.Err() != nil {
return false
}
@@ -2893,6 +3110,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
if ctx.Err() != nil {
return
}
// Re-evaluated on every selection: a current-turn failover replay clears
// previousResponseID because the retry payload already carries the full
// input, so it must not be held to the original continuation chain.
strictPreviousResponseAffinity := previousResponseID != "" && requestPlatform == service.PlatformOpenAI
schedulePreviousResponseCanMove := previousResponseCanMove && !strictPreviousResponseAffinity
reqLog.Debug("openai.websocket_account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
ctx,
@@ -2904,7 +3126,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
requiredTransport,
requiredCapability,
false,
previousResponseCanMove,
schedulePreviousResponseCanMove,
!imageIntent,
requestPlatform,
)
@@ -2930,6 +3152,19 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
account := selection.Account
if strictPreviousResponseAffinity && !scheduleDecision.StickyPreviousHit {
if selection.ReleaseFunc != nil {
selection.ReleaseFunc()
selection.ReleaseFunc = nil
}
reqLog.Warn("openai.websocket_previous_response_not_found",
zap.Int64("account_id", account.ID),
zap.String("schedule_layer", scheduleDecision.Layer),
)
writePreviousResponseNotFoundWSError(ctx, wsConn)
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "previous_response_not_found")
return
}
accountMaxConcurrency := account.Concurrency
if selection.WaitPlan != nil && selection.WaitPlan.MaxConcurrency > 0 {
accountMaxConcurrency = selection.WaitPlan.MaxConcurrency
@@ -2996,6 +3231,14 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
// 准入完成:门并入连接 ctx,turn 级复核与 failover 重选共用。
ctx = admissionCtx
if wsDecision := checkSelectedAccountModeration(c, account.ID); wsDecision != nil && !wsDecision.AllowNextStage {
if accountReleaseFunc != nil {
accountReleaseFunc()
}
writeSecurityAuditWSError(ctx, wsConn, wsDecision)
closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(wsDecision), securityAuditWSCloseReason(wsDecision))
return
}
// Account selection starts a fresh upstream attempt. Clear any model
// captured by the previous failover account before credential lookup.
setOpsSelectedAccount(c, account.ID, account.Platform)
@@ -3167,7 +3410,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 防御式清理:避免异常路径下旧槽位覆盖导致泄漏。
releaseTurnSlots()
// 非首轮 turn 需要重新抢占并发槽位,避免长连接空闲占槽。
userReleaseFunc, userAcquired, err := h.concurrencyHelper.TryAcquireUserSlotForAPIKey(ctx, subject.UserID, subject.Concurrency, apiKey.ID)
userReleaseFunc, userAcquired, err := h.acquireOpenAIWSUserSlot(ctx, subject, apiKey.ID)
if err != nil {
return service.NewOpenAIWSClientCloseError(coderws.StatusInternalError, "failed to acquire user concurrency slot", err)
}
@@ -3300,17 +3543,6 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
wsFirstMessage := wsAttemptMessage
// 切组/会话失配防护:previous_response_id 未在当前分组命中粘连账号(StickyPreviousHit=false),
// 说明该会话链不属于本次调度到的账号,原样转发会触发上游会话链鉴权失败(“鉴权失败,请检查 API Key”)。
// 故剥离首包里的 previous_response_id,改用首包内 input 重建上下文;带 function_call_output 的
// 工具续链无法重建,保持原样。仅作用于首轮首包,后续 turn 的续链由 WS 转发层既有逻辑处理。
if previousResponseID != "" && !scheduleDecision.StickyPreviousHit && previousResponseCanMove {
wsFirstMessage = service.RemovePreviousResponseIDFromBody(wsFirstMessage)
reqLog.Debug("openai.websocket_previous_response_id_stripped_cross_group",
zap.Int64("account_id", account.ID),
zap.String("schedule_layer", scheduleDecision.Layer),
)
}
// WebSocket 首包可能很大,hash 必须在 hooks 外算成字符串,避免 AfterTurn 闭包保活请求体。
requestPayloadHash = service.HashUsageRequestPayload(wsFirstMessage)
@@ -3341,6 +3573,28 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
wsAttemptMessage = nextAttemptMessage
if retryCurrentTurn {
previousResponseID = ""
retryModPayload := retryPayload
if len(retryModPayload) == 0 {
retryModPayload = wsAttemptMessage
}
retryModModel := strings.TrimSpace(gjson.GetBytes(retryModPayload, "model").String())
if retryModModel == "" {
retryModModel = reqModel
}
if retryDecision := resetWSRetryAccountModeration(
c,
reqLog,
h.contentModerationService,
apiKey,
subject,
service.ContentModerationProtocolOpenAIResponses,
retryModModel,
retryModPayload,
); retryDecision != nil && !retryDecision.AllowNextStage {
writeSecurityAuditWSError(ctx, wsConn, retryDecision)
closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(retryDecision), securityAuditWSCloseReason(retryDecision))
return
}
reqLog.Warn("openai.websocket_current_turn_failover_retry",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
@@ -3366,6 +3620,12 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
currentAccountRelease = wrapReleaseOnDone(ctx, accountRelease)
}
if sameAccDecision := checkSelectedAccountModeration(c, account.ID); sameAccDecision != nil && !sameAccDecision.AllowNextStage {
writeSecurityAuditWSError(ctx, wsConn, sameAccDecision)
closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(sameAccDecision), securityAuditWSCloseReason(sameAccDecision))
return
}
setOpsSelectedAccount(c, account.ID, account.Platform)
wsFirstMessage = wsAttemptMessage
continue
}
@@ -3640,7 +3900,17 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE
h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted)
return
}
copyFailoverRetryAfter(c, failoverErr.ResponseHeaders)
if failoverErr.Reason == service.OpenAIAlphaSearchRejectedReason && !streamStarted {
h.gatewayService.WriteAlphaSearchResponse(c, failoverErr.StatusCode, failoverErr.ResponseHeaders, failoverErr.ResponseBody)
return
}
if failoverErr.Reason == service.OpenAIResponsesToolsUnsupportedReason {
// No upstream request was sent for this local capability mismatch. Keep
// the original client error without attributing it to upstream health.
h.handleStreamingAwareError(c, failoverErr.ClientStatusCode, "invalid_request_error", failoverErr.ClientMessage, streamStarted)
return
}
applyRateLimitRetryAfter(c, failoverErr, h.cfg)
if failoverErr.IsOpenAIRequestBodyTooLarge() {
// An operator-configured passthrough rule wins over the built-in body
// limit mapping below. Failover on 413 exists because different
@@ -3778,34 +4048,15 @@ func credentialFailoverClientResponse(failoverErr *service.UpstreamFailoverError
return http.StatusServiceUnavailable, service.GrokCredentialUnavailableClientMessage
}
func copyFailoverRetryAfter(c *gin.Context, headers http.Header) {
if c == nil || headers == nil {
// applyRateLimitRetryAfter forwards an upstream rate-limit cooldown hint to the
// downstream error response. Only explicit upstream 429s qualify: capacity-shed
// and generic 5xx responses advertise long windows that clients would honor by
// sleeping through a transient blip (#8560, #8938).
func applyRateLimitRetryAfter(c *gin.Context, failoverErr *service.UpstreamFailoverError, cfg *config.Config) {
if c == nil || failoverErr == nil || failoverErr.IsOpenAICapacityShed() {
return
}
retryAfter := strings.TrimSpace(headers.Get("Retry-After"))
if retryAfter == "" || len(retryAfter) > 128 || strings.ContainsAny(retryAfter, "\r\n") || !isSafeRetryAfter(retryAfter) {
return
}
c.Header("Retry-After", retryAfter)
}
func isSafeRetryAfter(value string) bool {
digitsOnly := true
for _, char := range value {
if char < '0' || char > '9' {
digitsOnly = false
break
}
}
if digitsOnly {
seconds, err := strconv.ParseUint(value, 10, 32)
return err == nil && seconds <= uint64((7*24*time.Hour)/time.Second)
}
retryAt, err := http.ParseTime(value)
if err != nil {
return false
}
return !retryAt.After(time.Now().Add(7 * 24 * time.Hour))
service.SetUpstreamRateLimitRetryAfter(c, failoverErr.StatusCode, failoverErr.ResponseHeaders, failoverErr.ResponseBody, cfg)
}
// handleFailoverExhaustedSimple 简化版本,用于没有响应体的情况
@@ -4123,6 +4374,35 @@ func blockedModelAllowlistCandidate(group *service.Group, candidates []string) s
return ""
}
// openAIWSUserSlotWait bounds how long a WebSocket turn waits for a user
// concurrency slot. It is longer than the HTTP wait because a rejected
// WebSocket turn costs more: the client has already uploaded the full request,
// and repeated rejections move the whole session to HTTP. It stays well below
// the default Codex stream idle timeout of five minutes.
var openAIWSUserSlotWait = 60 * time.Second
// acquireOpenAIWSUserSlot waits for a user concurrency slot for a WebSocket
// turn instead of rejecting it at once. By the time a turn needs a slot, the
// client has already uploaded the full request, and clients such as Codex
// switch the session to HTTP after repeated rejections, which then resends the
// whole context on every turn.
//
// acquired is false without an error when the wait timed out, the wait queue
// is full or the connection context ended; callers close the connection with
// StatusTryAgainLater as before.
func (h *OpenAIGatewayHandler) acquireOpenAIWSUserSlot(ctx context.Context, subject middleware2.AuthSubject, apiKeyID int64) (func(), bool, error) {
releaseFunc, err := h.concurrencyHelper.AcquireUserSlotForAPIKeyWithWait(ctx, subject.UserID, subject.Concurrency, apiKeyID, openAIWSUserSlotWait)
if err == nil {
return releaseFunc, true, nil
}
var concurrencyErr *ConcurrencyError
var queueFullErr *WaitQueueFullError
if errors.As(err, &concurrencyErr) || errors.As(err, &queueFullErr) || ctx.Err() != nil {
return nil, false, nil
}
return nil, false, err
}
func closeOpenAIClientWS(conn *coderws.Conn, status coderws.StatusCode, reason string) {
if conn == nil {
return
@@ -4213,6 +4493,33 @@ func writeContentModerationWSError(ctx context.Context, conn *coderws.Conn, deci
_ = conn.Write(writeCtx, coderws.MessageText, payload)
}
// writePreviousResponseNotFoundWSError sends an error frame telling the client
// that previous_response_id could not be resolved to its owning upstream chain.
func writePreviousResponseNotFoundWSError(ctx context.Context, conn *coderws.Conn) {
if conn == nil {
return
}
if ctx == nil {
ctx = context.Background()
}
payload, err := json.Marshal(gin.H{
"event_id": "evt_previous_response_not_found",
"type": "error",
"status": http.StatusBadRequest,
"error": gin.H{
"type": "invalid_request_error",
"code": "previous_response_not_found",
"message": "Previous response not found; reconnect with full input history.",
},
})
if err != nil {
payload = []byte(`{"event_id":"evt_previous_response_not_found","type":"error","status":400,"error":{"type":"invalid_request_error","code":"previous_response_not_found","message":"Previous response not found; reconnect with full input history."}}`)
}
writeCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
_ = conn.Write(writeCtx, coderws.MessageText, payload)
}
// writeCyberSessionBlockedWSError sends an error frame telling the client this
// session is blocked by the cyber session block (F5a) before closing.
func writeCyberSessionBlockedWSError(ctx context.Context, conn *coderws.Conn) {
@@ -1132,6 +1132,26 @@ func TestOpenAIResponsesWebSocket_FirstMessageTimeoutUsesConfig(t *testing.T) {
}, time.Second, 10*time.Millisecond)
}
func TestOpenAIResponsesWebSocket_AnnouncesClientReadLimit(t *testing.T) {
gin.SetMode(gin.TestMode)
h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil)
h.cfg = &config.Config{}
h.cfg.Gateway.OpenAIWS.ClientReadLimitBytes = 96 * 1024 * 1024
h.cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 1
wsServer := newOpenAIWSHandlerTestServer(t, h, middleware.AuthSubject{UserID: 1, Concurrency: 1})
defer wsServer.Close()
dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
clientConn, resp, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http")+"/openai/v1/responses", nil)
cancelDial()
require.NoError(t, err)
defer func() { _ = clientConn.CloseNow() }()
require.NotNil(t, resp)
require.Equal(t, "100663296", resp.Header.Get("x-codex-websocket-max-message-bytes"))
}
func TestOpenAIResponsesWebSocket_IngressLeaseReleasedOnEarlyReturn(t *testing.T) {
gin.SetMode(gin.TestMode)
cache := &concurrencyCacheMock{
@@ -1364,6 +1384,14 @@ func (r *contentModerationHandlerTestRepo) UpdateLogEmailSent(ctx context.Contex
return nil
}
func (r *contentModerationHandlerTestRepo) SearchModerationAccounts(context.Context, service.ContentModerationAccountSearchFilter) ([]service.ContentModerationExcludedAccount, error) {
return []service.ContentModerationExcludedAccount{}, nil
}
func (r *contentModerationHandlerTestRepo) ListModerationAccountsByIDs(context.Context, []int64) ([]service.ContentModerationExcludedAccount, error) {
return []service.ContentModerationExcludedAccount{}, nil
}
func TestOpenAIResponsesWebSocket_ContentModerationBlocksFirstFrame(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -0,0 +1,190 @@
package handler
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
coderws "github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// newOpenAIWSUserSlotTestServer starts a WebSocket gateway in front of one
// upstream account. userSlotFree decides every user slot acquisition attempt;
// the account slot is always free. The returned counter reports how many
// messages reached the upstream.
func newOpenAIWSUserSlotTestServer(t *testing.T, userSlotFree func(attempt int32) bool) (string, *atomic.Int32) {
t.Helper()
gin.SetMode(gin.TestMode)
var upstreamMessages atomic.Int32
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
if err != nil {
return
}
defer func() { _ = conn.CloseNow() }()
for {
_, _, err := conn.Read(r.Context())
if err != nil {
return
}
turn := upstreamMessages.Add(1)
completed := fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_slot_wait_%d","model":"gpt-5.1","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`, turn)
if err := conn.Write(r.Context(), coderws.MessageText, []byte(completed)); err != nil {
return
}
}
}))
t.Cleanup(upstream.Close)
groupID := int64(4301)
accounts := []service.Account{{
ID: 9951,
Name: "openai-ws-slot-wait",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 5,
Priority: 1,
Credentials: map[string]any{
"api_key": "sk-slot-wait",
"base_url": upstream.URL,
},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
},
}}
cfg := &config.Config{}
cfg.RunMode = config.RunModeSimple
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.Enabled = false
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
service.NewBillingService(cfg, nil), rateLimitSvc, billingCacheSvc, nil,
&service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil,
)
var userAttempts atomic.Int32
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
return userSlotFree(userAttempts.Add(1)), nil
},
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
}
h := &OpenAIGatewayHandler{
gatewayService: gatewaySvc,
billingCacheService: billingCacheSvc,
apiKeyService: &service.APIKeyService{},
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
maxAccountSwitches: 1,
}
apiKey := &service.APIKey{
ID: 1951,
GroupID: &groupID,
User: &service.User{ID: 1851, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
}
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})
c.Next()
})
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
server := httptest.NewServer(router)
t.Cleanup(server.Close)
return "ws" + strings.TrimPrefix(server.URL, "http") + "/openai/v1/responses", &upstreamMessages
}
func dialOpenAIWSUserSlotTestClient(t *testing.T, url string) *coderws.Conn {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
conn, _, err := coderws.Dial(ctx, url, &coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover})
require.NoError(t, err)
t.Cleanup(func() { _ = conn.CloseNow() })
return conn
}
func writeOpenAIWSUserSlotTestMessage(t *testing.T, conn *coderws.Conn, message string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(message)))
}
func readOpenAIWSUserSlotTestEvent(conn *coderws.Conn) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, event, err := conn.Read(ctx)
return event, err
}
func TestOpenAIResponsesWebSocket_WaitsForUserSlotOnEveryTurn(t *testing.T) {
// Attempts 1-2 find the user at the limit, attempt 3 admits the first turn.
// The second turn re-acquires its slot: attempt 4 is busy, attempt 5 admits it.
url, upstreamMessages := newOpenAIWSUserSlotTestServer(t, func(attempt int32) bool {
return attempt == 3 || attempt >= 5
})
conn := dialOpenAIWSUserSlotTestClient(t, url)
writeOpenAIWSUserSlotTestMessage(t, conn, `{"type":"response.create","model":"gpt-5.1","input":[{"role":"user","content":"first"}]}`)
event, err := readOpenAIWSUserSlotTestEvent(conn)
require.NoError(t, err, "a busy user slot must queue the turn instead of closing the connection")
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
require.Equal(t, "resp_slot_wait_1", gjson.GetBytes(event, "response.id").String())
writeOpenAIWSUserSlotTestMessage(t, conn, `{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_slot_wait_1","input":[{"role":"user","content":"second"}]}`)
event, err = readOpenAIWSUserSlotTestEvent(conn)
require.NoError(t, err, "a later turn must also queue for its slot on the same connection")
require.Equal(t, "response.completed", gjson.GetBytes(event, "type").String())
require.Equal(t, "resp_slot_wait_2", gjson.GetBytes(event, "response.id").String())
require.Equal(t, int32(2), upstreamMessages.Load())
}
func TestOpenAIResponsesWebSocket_ClosesWhenUserSlotWaitTimesOut(t *testing.T) {
previousWait := openAIWSUserSlotWait
openAIWSUserSlotWait = 300 * time.Millisecond
t.Cleanup(func() { openAIWSUserSlotWait = previousWait })
url, upstreamMessages := newOpenAIWSUserSlotTestServer(t, func(int32) bool { return false })
conn := dialOpenAIWSUserSlotTestClient(t, url)
writeOpenAIWSUserSlotTestMessage(t, conn, `{"type":"response.create","model":"gpt-5.1","input":[{"role":"user","content":"first"}]}`)
_, err := readOpenAIWSUserSlotTestEvent(conn)
require.Equal(t, coderws.StatusTryAgainLater, coderws.CloseStatus(err), "got %v", err)
require.ErrorContains(t, err, "too many concurrent requests")
require.Zero(t, upstreamMessages.Load(), "a turn without a user slot must not reach the upstream")
}
+10 -4
View File
@@ -235,6 +235,9 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
)
account := selection.Account
if rejectSelectedAccountIfModerated(c, account.ID, selectionReleaseFunc(selection), h.openAISecurityAuditError) {
return
}
sessionHash = ensureOpenAIPoolModeSessionHash(sessionHash, account)
reqLog.Debug("openai.images.account_selected", zap.Int64("account_id", account.ID), zap.String("account_name", account.Name))
setOpsSelectedAccount(c, account.ID, account.Platform)
@@ -292,6 +295,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), false, nil, err)
} else {
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), true, nil)
h.recordOpenAIImagesSafetyRefusal(c, apiKey, account, clientRequestModel, parsed.Prompt, imageUpstreamErr)
}
logEvent := "openai.images.upstream_user_error"
if retryableServerError {
@@ -329,13 +333,14 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
if sameAccountRetryAllowed(failoverErr, sameAccountRetryCount[account.ID], retryLimit) {
sameAccountRetryCount[account.ID]++
retryDelay := sameAccountRetryDelayFor(failoverErr, sameAccountRetryCount[account.ID])
reqLog.Warn("openai.images.pool_mode_same_account_retry",
retryFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("retry_limit", retryLimit),
zap.Int("retry_count", sameAccountRetryCount[account.ID]),
zap.Duration("retry_delay", retryDelay),
)
}, failoverErr)
reqLog.Warn("openai.images.pool_mode_same_account_retry", retryFields...)
select {
case <-requestCtx.Done():
return
@@ -356,12 +361,13 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
reqLog.Warn("openai.images.upstream_failover_switching",
switchFields := appendUpstreamRetryAfterField([]zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
zap.Int("max_switches", maxAccountSwitches),
)
}, failoverErr)
reqLog.Warn("openai.images.upstream_failover_switching", switchFields...)
continue
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, requestModel, false, result), false, nil, err)
@@ -26,7 +26,10 @@ func TestOpenAIImagesBalanceExhaustionPreservesMachineReadableCause(t *testing.T
ClientMessage: service.OpenAIImagesInsufficientBalanceMessage,
ResponseHeaders: http.Header{"Retry-After": []string{"23"}, "X-Request-Id": []string{"req-images-balance"}},
}, streamStarted)
require.Equal(t, "23", recorder.Header().Get("Retry-After"))
// A Retry-After on a non-rate-limit upstream failure (502 mapped to 402
// here) is intentionally not forwarded: only explicit upstream 429 rate
// limits carry a usable cooldown (#8560, #8938).
require.Empty(t, recorder.Header().Get("Retry-After"))
if streamStarted {
require.Contains(t, recorder.Body.String(), `"code":"insufficient_balance"`)
@@ -0,0 +1,61 @@
package handler
import (
"context"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
const imageSafetyRecordTimeout = 30 * time.Second
// recordOpenAIImagesSafetyRefusal 在图像上游以安全系统拒绝终结请求时,异步把事件
// 写入风控中心。拒绝已经返回给用户,这里只做留证,不影响响应。
func (h *OpenAIGatewayHandler) recordOpenAIImagesSafetyRefusal(c *gin.Context, apiKey *service.APIKey, account *service.Account, model string, prompt string, upErr *service.OpenAIImagesUpstreamError) {
cmSvc := h.contentModerationService
if cmSvc == nil || c == nil || !service.IsOpenAIImagesSafetyRefusal(upErr) {
return
}
// 在 gin.Context 回收前把需要的值拍成标量。
// request_id 取 context 中网关自己的 ID(与运维错误日志、转发前审核日志同源):
// 响应头里的 X-Request-Id 属于可透传头,可能已被上游的 x-request-id 覆盖。
requestID := ""
if c.Request != nil {
requestID = contentModerationRequestID(c.Request.Context())
}
if requestID == "" {
requestID = c.Writer.Header().Get("X-Request-Id")
}
in := service.ImageSafetyRecordInput{
RequestID: requestID,
Endpoint: GetInboundEndpoint(c),
Model: model,
Prompt: prompt,
UpstreamStatus: upErr.StatusCode,
UpstreamType: upErr.ErrorType,
UpstreamCode: upErr.Code,
UpstreamMessage: upErr.Message,
UpstreamRequestID: upErr.UpstreamRequestID,
}
if apiKey != nil {
in.APIKeyID = apiKey.ID
in.APIKeyName = apiKey.Name
in.GroupID = apiKey.GroupID
if apiKey.User != nil {
in.UserID = apiKey.User.ID
in.UserEmail = apiKey.User.Email
}
if apiKey.Group != nil {
in.GroupName = apiKey.Group.Name
}
}
if account != nil {
in.Provider = account.Platform
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), imageSafetyRecordTimeout)
defer cancel()
cmSvc.RecordImageSafetyEvent(ctx, in)
}()
}
@@ -0,0 +1,131 @@
//go:build unit
package handler
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
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"
"github.com/tidwall/gjson"
)
type openAIImagesStaticHTTPUpstream struct {
service.HTTPUpstream
status int
body string
}
func (u *openAIImagesStaticHTTPUpstream) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
return &http.Response{
StatusCode: u.status,
Header: http.Header{
"Content-Type": []string{"application/json"},
"X-Request-Id": []string{"upstream-req-1"},
},
Body: io.NopCloser(bytes.NewBufferString(u.body)),
}, nil
}
func runOpenAIImagesWithUpstream(t *testing.T, status int, upstreamBody string) (*httptest.ResponseRecorder, *contentModerationHandlerTestRepo) {
t.Helper()
gin.SetMode(gin.TestMode)
groupID := int64(8992)
accountRepo := openAIImagesFailoverAccountRepo{accounts: []service.Account{{
ID: 1,
Name: "image-apikey",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Credentials: map[string]any{"api_key": "sk-test"},
}}}
cfg := &config.Config{RunMode: config.RunModeSimple}
gatewayService := service.NewOpenAIGatewayService(
accountRepo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil,
&openAIImagesStaticHTTPUpstream{status: status, body: upstreamBody},
nil, nil, nil, nil, nil, nil, nil, nil,
)
billingService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingService.Stop)
h := NewOpenAIGatewayHandler(
gatewayService,
service.NewConcurrencyService(nil),
billingService,
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg),
nil, nil, nil, nil,
cfg,
)
repo := &contentModerationHandlerTestRepo{}
h.contentModerationService = service.NewContentModerationService(
&contentModerationHandlerSettingRepo{values: map[string]string{
service.SettingKeyRiskControlEnabled: "true",
service.SettingKeyContentModerationConfig: `{"enabled":false,"mode":"off","all_groups":true}`,
}},
repo, nil, nil, nil, nil, nil, nil,
)
body := []byte(`{"model":"gpt-image-1","prompt":"draw a forbidden thing","size":"1024x1024"}`)
ctx := context.WithValue(context.Background(), ctxkey.RequestID, "gateway-req-8992")
req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = req
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
ID: 99,
Name: "issue-key",
GroupID: &groupID,
Group: &service.Group{ID: groupID, Name: "img-group", AllowImageGeneration: true},
User: &service.User{ID: 100, Email: "user@example.com"},
})
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 100})
h.Images(c)
return rec, repo
}
func TestOpenAIGatewayHandlerImages_SafetySystemRejectionRecordedInRiskControl(t *testing.T) {
const msg = "Your request was rejected by the safety system. If you believe this is an error, contact us at help.openai.com and include the request ID b553d2f5-3906-4f26-aa3a-e3bb7e24396c."
rec, repo := runOpenAIImagesWithUpstream(t, http.StatusBadRequest, `{"error":{"message":"`+msg+`"}}`)
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "safety system")
require.Eventually(t, func() bool { return len(repo.logSnapshot()) == 1 }, 2*time.Second, 10*time.Millisecond)
log := repo.logSnapshot()[0]
require.Equal(t, service.ContentModerationActionImageSafety, log.Action)
require.Equal(t, service.ContentModerationModeRiskControlLogOnly, log.Mode)
require.True(t, log.Flagged)
require.Equal(t, "gateway-req-8992", log.RequestID, "must join with the ops error log, not the upstream request id")
require.Contains(t, log.Error, "upstream_request_id=upstream-req-1")
require.NotNil(t, log.UserID)
require.Equal(t, int64(100), *log.UserID)
require.Equal(t, "user@example.com", log.UserEmail)
require.Equal(t, "issue-key", log.APIKeyName)
require.Equal(t, "img-group", log.GroupName)
require.Equal(t, "gpt-image-1", log.Model)
require.Equal(t, service.PlatformOpenAI, log.Provider)
require.Equal(t, "draw a forbidden thing", log.InputExcerpt)
require.Contains(t, log.Error, "safety system")
require.Contains(t, log.Error, "upstream_status=400")
require.False(t, log.AutoBanned)
require.False(t, log.EmailSent)
}
func TestOpenAIGatewayHandlerImages_NonSafety400NotRecorded(t *testing.T) {
rec, repo := runOpenAIImagesWithUpstream(t, http.StatusBadRequest, `{"error":{"message":"Invalid size","type":"invalid_request_error","param":"size"}}`)
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
require.Never(t, func() bool { return len(repo.logSnapshot()) > 0 }, 200*time.Millisecond, 10*time.Millisecond)
}
+12 -1
View File
@@ -113,8 +113,19 @@ func (h *OpenAIGatewayHandler) Live(c *gin.Context) {
defer userRelease()
identity := liveCallIdentity(c, apiKey, subject.UserID, subscription)
created, err := h.gatewayService.CreateLiveCall(c.Request.Context(), request, identity, subject.Concurrency)
liveCtx := service.WithAccountModerationHook(c.Request.Context(), func(accountID int64) error {
if d := checkSelectedAccountModeration(c, accountID); d != nil && !d.AllowNextStage {
return &accountModerationBlockedError{decision: d}
}
return nil
})
created, err := h.gatewayService.CreateLiveCall(liveCtx, request, identity, subject.Concurrency)
if err != nil {
var modBlocked *accountModerationBlockedError
if errors.As(err, &modBlocked) && modBlocked.decision != nil {
h.openAISecurityAuditError(c, modBlocked.decision)
return
}
h.writeLiveCreateError(c, err)
return
}
@@ -7,17 +7,33 @@ import (
"regexp"
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/service"
)
var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`)
// codexContextTagName is the shape of the context names Codex derives from
// its context keys; only such names are safe to embed in a tag.
var codexContextTagName = regexp.MustCompile(`^[A-Za-z0-9_]{1,128}$`)
// mayContainCodexAgentContext is the cheap gate for agent context outputs.
// Names are not enumerated: Codex keeps adding context tools, and any agent
// namespace output without a call_id is injected context, not a tool result.
// The type and namespace are JSON strings, which appear literally unless a
// \u escape spells their letters; without either the body cannot match.
func mayContainCodexAgentContext(body []byte) bool {
if !service.JSONMayEscapePlainASCII(body) &&
(!bytes.Contains(body, []byte("function_call_output")) || !bytes.Contains(body, []byte("agent"))) {
return false
}
return service.ResponsesInputHasAgentFunctionCallOutput(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", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan",
) || !hasUniqueJSONMembers(body) {
if !mayContainCodexAgentContext(body) || !hasUniqueJSONMembers(body) {
return body, false
}
var request map[string]json.RawMessage
@@ -50,12 +66,12 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
}
name := readString("name")
var output *string
if json.Unmarshal(item["output"], &output) != nil || output == nil || !validCodexUntrustedContext(name, *output) {
if json.Unmarshal(item["output"], &output) != nil || output == nil {
continue
}
text := "<external_" + name + ">" + *output + "</external_" + name + ">"
if validCodexPageContext(name, *output) {
text = "<external_" + name + ">\n" + *output + "\n</external_" + name + ">"
text, ok := codexUntrustedContextText(name, *output)
if !ok {
continue
}
message := map[string]any{
"type": "message",
@@ -87,9 +103,42 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
return encoded, true
}
// codexUntrustedContextText renders an agent context output as user text.
// Known context names keep their existing tags and format checks. Any other
// name is still context when it comes from the agent namespace, so it is
// rendered the way Codex renders context when it does not send it as a tool
// output: <external_{name}>. The name is client supplied, so it is only used
// as a tag when it has the shape Codex derives names in; anything else falls
// back to a generic tag.
func codexUntrustedContextText(name, output string) (string, bool) {
if !knownCodexUntrustedContextName(name) {
tag := "agent_context"
if codexContextTagName.MatchString(name) {
tag = name
}
return "<external_" + tag + ">" + output + "</external_" + tag + ">", true
}
if !validCodexUntrustedContext(name, output) {
return "", false
}
text := "<external_" + name + ">" + output + "</external_" + name + ">"
if validCodexPageContext(name, output) {
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
}
return text, true
}
func knownCodexUntrustedContextName(name string) bool {
switch name {
case "codex_apps_open_page", "browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan":
return true
}
return codexSelectedPageName.MatchString(name)
}
func validCodexUntrustedContext(name, output string) bool {
switch name {
case "browser_info", "goal_objective", "untrusted_context", "ide_context":
case "browser_info", "browser_tabs", "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.
@@ -3,6 +3,7 @@ package handler
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -54,7 +55,186 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
require.Equal(t, got, again)
}
var codexTextContextNamesForTest = []string{"browser_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"}
var codexTextContextNamesForTest = []string{"browser_info", "browser_tabs", "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"}},
{"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"},
map[string]any{"type": "function_call_output", "name": "read_file", "output": "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 TestNormalizeCodexAgentContextUnknownNames(t *testing.T) {
const browserTabs = `{"tabs":[{"title":"Example","url":"https://example.com"}]}`
longName := strings.Repeat("a", 129)
body := pageContextRequest(t,
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": browserTabs},
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "some_new_context", "output": "new context"},
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info_extra", "output": "suffix name"},
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "Terminal_info", "output": "case name"},
map[string]any{"type": "function_call_output", "namespace": "agent", "name": "bad>name</x", "output": "unsafe name"},
map[string]any{"type": "function_call_output", "namespace": "agent", "output": "missing name"},
map[string]any{"type": "function_call_output", "namespace": "agent", "name": longName, "output": ""},
map[string]any{"role": "user", "content": "hello"},
)
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
require.Equal(t, 400, w.Code)
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.False(t, c.Writer.Written())
for i, want := range []struct{ tag, output string }{
{"browser_tabs", browserTabs},
{"some_new_context", "new context"},
{"terminal_info_extra", "suffix name"},
{"Terminal_info", "case name"},
{"agent_context", "unsafe name"},
{"agent_context", "missing name"},
{"agent_context", ""},
} {
item := gjson.GetBytes(got, "input").Array()[i]
require.Equal(t, "message", item.Get("type").String())
require.Equal(t, "user", item.Get("role").String())
require.Equal(t, "<external_"+want.tag+">"+want.output+"</external_"+want.tag+">", item.Get("content.0.text").String())
require.False(t, item.Get("call_id").Exists())
require.False(t, item.Get("id").Exists())
}
require.Equal(t, "hello", gjson.GetBytes(got, "input.7.content").String())
again, changed := normalizeCodexUntrustedContext(got)
require.False(t, changed)
require.Equal(t, got, again)
}
func TestNormalizeCodexAgentContextEscapedAndBlankCallID(t *testing.T) {
for _, body := range []string{
`{"input":[{"type":"function_call_output","namespace":"\u0061gent","name":"browser_tabs","output":"tabs"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":" ","output":"tabs"}]}`,
} {
got, changed := normalizeCodexUntrustedContext([]byte(body))
require.True(t, changed)
require.Equal(t, "<external_browser_tabs>tabs</external_browser_tabs>", gjson.GetBytes(got, "input.0.content.0.text").String())
}
}
func TestNormalizeCodexAgentContextKeepsToolOutputsRejected(t *testing.T) {
for _, testCase := range []struct {
name string
item map[string]any
}{
{"no namespace", map[string]any{"type": "function_call_output", "name": "read_file", "output": "file body"}},
{"other namespace", map[string]any{"type": "function_call_output", "namespace": "codex_app", "name": "read_file", "output": "file body"}},
{"non-string output", map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": []any{map[string]any{"url": "https://example.com"}}}},
} {
t.Run(testCase.name, func(t *testing.T) {
body := pageContextRequest(t, testCase.item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
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")
})
}
}
func TestNormalizeCodexAgentContextLeavesCallIDItems(t *testing.T) {
body := []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":"call_real","output":"tabs"}]}`)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
// Items with a call_id keep the original validation path.
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(), "item_reference")
}
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
for _, name := range codexTextContextNamesForTest {
@@ -124,7 +304,7 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput
}
// Recognized external context cannot make an unrelated tool result valid.
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
pageContextItem("read_file", "result"))
map[string]any{"type": "function_call_output", "name": "read_file", "output": "result"})
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
h := &OpenAIGatewayHandler{}
@@ -219,7 +399,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
}
badTool := pageContextItem("read_file", "result")
badTool := map[string]any{"type": "function_call_output", "name": "read_file", "output": "result"}
body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool)
got, changed = normalizeCodexUntrustedContext(body)
require.True(t, changed)
@@ -261,7 +441,6 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
{"null call id", "call_id", nil},
{"other namespace", "namespace", "codex_app"},
{"missing namespace", "namespace", ""},
{"other tool", "name", "read_file"},
{"other type", "type", "custom_tool_call_output"},
{"not JSON", "output", "some text"},
{"not snapshot", "output", `{"other":null}`},
@@ -288,3 +467,62 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
require.Equal(t, body, string(got))
}
}
func TestNormalizeCodexBrowserTabs(t *testing.T) {
// Shape sent by the Codex desktop in-app browser: an agent-namespace output
// with an item id but no call_id, followed by the user's question.
tabs := "<in-app-browser-context source=\"ambient-ui-state\">\nTab 1 (active): https://example.com/\nTab 2: https://example.org/\n</in-app-browser-context>"
body := pageContextRequest(t,
map[string]any{"type": "function_call_output", "id": "fco_123", "namespace": "agent", "name": "browser_tabs", "output": tabs},
map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "How many tabs are open?"}}})
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
require.Equal(t, 400, w.Code)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String())
require.Equal(t, "user", gjson.GetBytes(got, "input.0.role").String())
require.Equal(t, "<external_browser_tabs>"+tabs+"</external_browser_tabs>", gjson.GetBytes(got, "input.0.content.0.text").String())
require.JSONEq(t, gjson.GetBytes(body, "input.1").Raw, gjson.GetBytes(got, "input.1").Raw)
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.False(t, c.Writer.Written())
}
func TestNormalizeCodexBrowserTabsBoundaries(t *testing.T) {
for _, testCase := range []struct {
name string
key string
value any
}{
{"real call id", "call_id", "call_real"},
{"other namespace", "namespace", "browser"},
{"empty output", "output", ""},
{"blank output", "output", " \n\t"},
{"object output", "output", map[string]any{"tabs": 2}},
} {
t.Run(testCase.name, func(t *testing.T) {
item := pageContextItem("browser_tabs", "Tab 1: https://example.com/")
item[testCase.key] = testCase.value
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
})
}
}
func TestNormalizeCodexBrowserTabsNameVariantsUseOwnTag(t *testing.T) {
for _, name := range []string{"browser_tabs_extra", "Browser_tabs"} {
t.Run(name, func(t *testing.T) {
body := pageContextRequest(t, pageContextItem(name, "Tab 1: https://example.com/"))
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "<external_"+name+">Tab 1: https://example.com/</external_"+name+">", gjson.GetBytes(got, "input.0.content.0.text").String())
})
}
}
@@ -0,0 +1,118 @@
package handler
import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestParseOpenAIResponsesIngressFields(t *testing.T) {
body := []byte(`{
"model": "gpt-6.2-astra",
"stream": true,
"service_tier": "fast",
"previous_response_id": " resp_abc ",
"reasoning": {"effort": " medium "},
"reasoning_effort": " high ",
"output_config": {"effort": " low "}
}`)
fields := parseOpenAIResponsesIngressFields(body)
require.True(t, fields.ModelValid)
require.Equal(t, "gpt-6.2-astra", fields.Model)
require.True(t, fields.StreamValid)
require.True(t, fields.Stream)
require.Equal(t, "resp_abc", fields.PreviousResponseID)
require.Equal(t, "medium", fields.ReasoningEffort)
require.Equal(t, "high", fields.ReasoningEffortTop)
require.Equal(t, "low", fields.OutputConfigEffort)
tier, err := service.ValidateOpenAIServiceTierResult(fields.ServiceTier)
require.NoError(t, err)
require.Equal(t, "priority", tier)
// Invalid stream type.
badStream := parseOpenAIResponsesIngressFields([]byte(`{"model":"gpt-6.2-astra","stream":"true"}`))
require.True(t, badStream.ModelValid)
require.False(t, badStream.StreamValid)
// Missing/non-string model.
missingModel := parseOpenAIResponsesIngressFields([]byte(`{"stream":false}`))
require.False(t, missingModel.ModelValid)
require.True(t, missingModel.StreamValid)
require.False(t, missingModel.Stream)
// Escaped keys.
escaped := parseOpenAIResponsesIngressFields([]byte(`{"\u006dodel":"gpt-6.2-astra","\u0073tream":true,"service_tier":"invalid"}`))
require.True(t, escaped.ModelValid)
require.Equal(t, "gpt-6.2-astra", escaped.Model)
require.True(t, escaped.StreamValid)
require.True(t, escaped.Stream)
_, err = service.ValidateOpenAIServiceTierResult(escaped.ServiceTier)
require.Error(t, err)
// Non-object root.
arr := parseOpenAIResponsesIngressFields([]byte(`[{"model":"x"}]`))
require.False(t, arr.ModelValid)
require.True(t, arr.StreamValid)
// Duplicate parent keys keep scanning until nested effort exists.
dupParent := parseOpenAIResponsesIngressFields([]byte(`{"model":"gpt-6.2-astra","reasoning":{},"reasoning":{"effort":"xhigh"},"output_config":null,"output_config":{"effort":"low"}}`))
require.Equal(t, "xhigh", dupParent.ReasoningEffort)
require.Equal(t, "low", dupParent.OutputConfigEffort)
}
func TestRequestMaxOutputTokensSinglePassPriority(t *testing.T) {
tests := []struct {
name string
body string
want int
}{
{
name: "max_tokens wins even when last",
body: `{"generation_config":{"max_output_tokens":50},"generationConfig":{"maxOutputTokens":40},"max_output_tokens":30,"max_completion_tokens":20,"max_tokens":10}`,
want: 10,
},
{
name: "max_completion_tokens wins when max_tokens absent or non-positive",
body: `{"max_tokens":0,"max_output_tokens":30,"max_completion_tokens":20}`,
want: 20,
},
{
name: "max_output_tokens wins over generationConfig",
body: `{"generationConfig":{"maxOutputTokens":40},"max_output_tokens":30}`,
want: 30,
},
{
name: "generationConfig camelCase wins over snake_case",
body: `{"generation_config":{"max_output_tokens":50},"generationConfig":{"maxOutputTokens":40}}`,
want: 40,
},
{
name: "generation_config snake_case fallback",
body: `{"generation_config":{"max_output_tokens":50}}`,
want: 50,
},
{
name: "absent or non-object returns zero",
body: `[{"max_tokens":10}]`,
want: 0,
},
{
name: "duplicate parent keys keep scanning for nested maxOutputTokens",
body: `{"generationConfig":null,"generationConfig":{"maxOutputTokens":40},"generation_config":{"max_output_tokens":50}}`,
want: 40,
},
{
name: "duplicate snake_case parent keys keep scanning for nested max_output_tokens",
body: `{"generation_config":{},"generation_config":{"max_output_tokens":55}}`,
want: 55,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.want, requestMaxOutputTokens([]byte(tc.body)))
})
}
}
@@ -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", "可换号的首输出前错误不得写给客户端")
}
@@ -0,0 +1,176 @@
//go:build unit
package handler
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
const solToolsTestResponse = `{"id":"resp_tools","object":"response","model":"gpt-6.1-sol","status":"completed","output":[{"id":"fc_lookup","type":"function_call","call_id":"call_lookup","name":"lookup","arguments":"{}","status":"completed"}],"usage":{"input_tokens":1,"output_tokens":1}}`
func TestResponsesSolToolsSwitchAccount(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, stream := range []bool{false, true} {
t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) {
accounts := solToolsTestAccounts(false, true)
before, err := json.Marshal(accounts)
require.NoError(t, err)
response := solToolsTestResponse
contentType := "application/json"
if stream {
contentType = "text/event-stream"
response = "event: response.created\ndata: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_tools\",\"status\":\"in_progress\"}}\n\n" +
"event: response.function_call_arguments.delta\ndata: {\"type\":\"response.function_call_arguments.delta\",\"item_id\":\"fc_lookup\",\"output_index\":0,\"delta\":\"{}\"}\n\n" +
"event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":" + solToolsTestResponse + "}\n\n"
}
upstream := newAstraProCapturedUpstream(&http.Response{
StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}},
Body: io.NopCloser(strings.NewReader(response)),
})
h, repo := newSolToolsFailoverHandler(t, accounts, upstream)
body := solToolsTestRequest(stream)
c, rec := newAstraProFailoverContext(t, body)
h.Responses(c)
urls, accountIDs, bodies := upstream.snapshot()
require.Equal(t, []int64{2}, accountIDs, "the first account is incompatible, not an upstream attempt")
require.Equal(t, []string{"https://upstream.example/v1/responses"}, urls)
require.Len(t, bodies, 1)
require.Equal(t, "gpt-6.1-sol", gjson.GetBytes(bodies[0], "model").String())
require.JSONEq(t, gjson.Get(body, "tools").Raw, gjson.GetBytes(bodies[0], "tools").Raw)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), "function_call")
require.NotContains(t, rec.Body.String(), "response.failed")
require.NotContains(t, rec.Body.String(), "only supports Chat Completions")
require.Equal(t, 2, repo.selectorCalls())
require.Empty(t, repo.errorIDs())
require.Empty(t, repo.rateLimitedAccountIDs())
after, err := json.Marshal(accounts)
require.NoError(t, err)
require.JSONEq(t, string(before), string(after), "routing must not change capability flags, models or scheduling")
})
}
}
func TestResponsesSolToolsFailoverExhausted(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name string
stream bool
started bool
maxSwitches int
wantSelections int
}{
{"json", false, false, 10, 3},
{"stream_not_started", true, false, 10, 3},
{"stream_keepalive", true, true, 10, 3},
{"bounded", false, false, 0, 1},
} {
t.Run(tc.name, func(t *testing.T) {
upstream := newAstraProCapturedUpstream()
accounts := solToolsTestAccounts(false, false)
before, err := json.Marshal(accounts)
require.NoError(t, err)
h, repo := newSolToolsFailoverHandler(t, accounts, upstream)
h.maxAccountSwitches = tc.maxSwitches
c, rec := newAstraProFailoverContext(t, solToolsTestRequest(tc.stream))
if tc.started {
_, err := c.Writer.WriteString(": keepalive\n\n")
require.NoError(t, err)
c.Writer.Flush()
}
h.Responses(c)
_, accountIDs, _ := upstream.snapshot()
require.Empty(t, accountIDs)
if tc.started {
require.Equal(t, 1, strings.Count(rec.Body.String(), "event: response.failed\n"))
require.True(t, strings.HasPrefix(rec.Body.String(), ": keepalive\n\nevent: response.failed\n"))
} else {
require.Equal(t, http.StatusBadRequest, rec.Code)
require.True(t, json.Valid(rec.Body.Bytes()), "must not append SSE to a JSON error")
require.Equal(t, "invalid_request_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String())
}
require.Contains(t, rec.Body.String(), "gpt-6.1-sol")
_, hasUpstreamError := c.Get(service.OpsUpstreamStatusCodeKey)
require.False(t, hasUpstreamError, "local incompatibility must not be recorded as an upstream HTTP failure")
require.Equal(t, tc.wantSelections, repo.selectorCalls())
require.Empty(t, repo.errorIDs())
require.Empty(t, repo.rateLimitedAccountIDs())
after, err := json.Marshal(accounts)
require.NoError(t, err)
require.JSONEq(t, string(before), string(after), "exhaustion must not change account state")
})
}
}
func TestResponsesSolPlainTextStillUsesChatAccount(t *testing.T) {
upstream := newAstraProCapturedUpstream(&http.Response{
StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"id":"chat_sol","model":"gpt-6.1-sol","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)),
})
h, repo := newSolToolsFailoverHandler(t, solToolsTestAccounts(false, true), upstream)
c, rec := newAstraProFailoverContext(t, `{"model":"public-alias","input":"hello","stream":false}`)
h.Responses(c)
urls, accountIDs, _ := upstream.snapshot()
require.Equal(t, []int64{1}, accountIDs)
require.Equal(t, []string{"https://upstream.example/v1/chat/completions"}, urls)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "ok", gjson.GetBytes(rec.Body.Bytes(), "output.0.content.0.text").String())
require.Equal(t, 1, repo.selectorCalls())
}
func solToolsTestRequest(stream bool) string {
return fmt.Sprintf(`{"model":"public-alias","input":"hello","stream":%t,"tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]}`, stream)
}
func solToolsTestAccounts(supported ...bool) []service.Account {
accounts := make([]service.Account, 0, len(supported))
for i, value := range supported {
accounts = append(accounts, service.Account{
ID: int64(i + 1), Name: fmt.Sprintf("responses-account-%d", i+1),
Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Priority: i,
Credentials: map[string]any{
"api_key": "test-key", "base_url": "https://upstream.example",
"model_mapping": map[string]any{"public-alias": "gpt-6.1-sol"},
},
Extra: map[string]any{"openai_responses_supported": value},
})
}
return accounts
}
func newSolToolsFailoverHandler(t *testing.T, accounts []service.Account, upstream service.HTTPUpstream) (*OpenAIGatewayHandler, *grokCredentialHandlerRepo) {
t.Helper()
cfg := &config.Config{RunMode: config.RunModeSimple}
repo := &grokCredentialHandlerRepo{accounts: accounts}
gateway := service.NewOpenAIGatewayService(
repo, 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(
gateway, service.NewConcurrencyService(nil), billing,
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg),
nil, nil, nil, nil, cfg,
)
h.maxAccountSwitches = 10
return h, repo
}
@@ -0,0 +1,202 @@
package handler
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
coderws "github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
type wsReplayFailoverUpstream struct {
mu sync.Mutex
calls map[int64]int
bodies map[int64][][]byte
}
func (u *wsReplayFailoverUpstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) {
u.mu.Lock()
defer u.mu.Unlock()
body, _ := io.ReadAll(req.Body)
u.calls[accountID]++
u.bodies[accountID] = append(u.bodies[accountID], body)
n := u.calls[accountID]
sse := func(id string) *http.Response {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"" + id + "\",\"output\":[{\"id\":\"msg_" + id + "\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"ok-" + id + "\"}]}],\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n",
)),
}
}
if accountID == 9921 {
switch n {
case 1:
return sse("resp_f1_seed"), nil
case 2:
return sse("resp_f1_turn1"), nil
default:
return &http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"Content-Type": []string{"application/json"}, "Retry-After": []string{"600"}},
Body: io.NopCloser(strings.NewReader(`{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached"}}`)),
}, nil
}
}
return sse("resp_f1_replayed"), nil
}
func (u *wsReplayFailoverUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, profile *tlsfingerprint.Profile) (*http.Response, error) {
return u.Do(req, proxyURL, accountID, accountConcurrency)
}
func TestOpenAIResponsesWebSocket_CurrentTurnReplayAfterContinuationIsNotRejected(t *testing.T) {
gin.SetMode(gin.TestMode)
upstream := &wsReplayFailoverUpstream{calls: map[int64]int{}, bodies: map[int64][][]byte{}}
groupID := int64(4291)
accounts := []service.Account{
{
ID: 9921, Name: "f1-apikey", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 0,
Credentials: map[string]any{"api_key": "sk-a", "base_url": "http://127.0.0.1:1"},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeHTTPBridge,
},
},
{
ID: 9922, Name: "f1-oauth", Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth,
Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 5,
Credentials: map[string]any{"access_token": "tok", "chatgpt_account_id": "acct"},
Extra: map[string]any{
"openai_oauth_responses_websockets_v2_enabled": true,
"openai_oauth_responses_websockets_v2_mode": service.OpenAIWSIngressModeHTTPBridge,
},
},
}
cfg := &config.Config{}
cfg.RunMode = config.RunModeSimple
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.Enabled = false
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.OAuthEnabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
cfg.Gateway.MaxAccountSwitches = 2
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
service.NewBillingService(cfg, nil), rateLimitSvc, billingCacheSvc,
upstream, &service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
}
h := &OpenAIGatewayHandler{
gatewayService: gatewaySvc,
billingCacheService: billingCacheSvc,
apiKeyService: &service.APIKeyService{},
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
maxAccountSwitches: 2,
}
apiKey := &service.APIKey{
ID: 1891, GroupID: &groupID,
User: &service.User{ID: 1791, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
}
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})
c.Next()
})
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
srv := httptest.NewServer(router)
defer srv.Close()
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http") + "/openai/v1/responses"
dial := func() *coderws.Conn {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
c, _, err := coderws.Dial(ctx, wsURL, nil)
require.NoError(t, err)
return c
}
write := func(c *coderws.Conn, s string) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
require.NoError(t, c.Write(ctx, coderws.MessageText, []byte(s)))
}
readUntilTerminal := func(c *coderws.Conn) ([]byte, error) {
for {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_, msg, err := c.Read(ctx)
cancel()
if err != nil {
return nil, err
}
switch gjson.GetBytes(msg, "type").String() {
case "response.completed", "error", "response.failed":
return msg, nil
}
}
}
// Seed connection binds resp_f1_seed to the API-key account 9921.
c1 := dial()
write(c1, `{"type":"response.create","model":"gpt-5.1","input":[{"type":"message","role":"user","content":"seed"}]}`)
msg, err := readUntilTerminal(c1)
require.NoError(t, err)
require.Equal(t, "resp_f1_seed", gjson.GetBytes(msg, "response.id").String(), string(msg))
require.NoError(t, c1.Close(coderws.StatusNormalClosure, "done"))
// Continuation connection: first frame continues resp_f1_seed (sticky hit 9921).
c2 := dial()
defer func() { _ = c2.CloseNow() }()
write(c2, `{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_f1_seed","input":[{"type":"message","role":"user","content":"turn1"}]}`)
msg, err = readUntilTerminal(c2)
require.NoError(t, err)
require.Equal(t, "resp_f1_turn1", gjson.GetBytes(msg, "response.id").String(), string(msg))
// Turn 2 fails on 9921 with 429 -> current-turn failover replay on 9922.
write(c2, `{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_f1_turn1","input":[{"type":"message","role":"user","content":"turn2"}]}`)
msg, err = readUntilTerminal(c2)
require.NoError(t, err, "connection closed instead of replaying on replacement account")
require.Equal(t, "response.completed", gjson.GetBytes(msg, "type").String(), string(msg))
require.Equal(t, "resp_f1_replayed", gjson.GetBytes(msg, "response.id").String())
upstream.mu.Lock()
defer upstream.mu.Unlock()
require.Len(t, upstream.bodies[9922], 1)
require.False(t, gjson.GetBytes(upstream.bodies[9922][0], "previous_response_id").Exists())
}
@@ -0,0 +1,336 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
coderws "github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestOpenAIResponsesWebSocket_FirstFrameStickyMissFailsLoudlyWithPreviousResponseNotFound(t *testing.T) {
gin.SetMode(gin.TestMode)
var upstreamHits atomic.Int32
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upstreamHits.Add(1)
w.WriteHeader(http.StatusInternalServerError)
}))
defer upstream.Close()
groupID := int64(4211)
accounts := []service.Account{
{
ID: 9911,
Name: "openai-ws-sticky-miss-acct",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 1,
Credentials: map[string]any{
"api_key": "sk-first",
"base_url": upstream.URL,
},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
},
},
}
cfg := &config.Config{}
cfg.RunMode = config.RunModeSimple
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.Enabled = false
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
cfg.Gateway.MaxAccountSwitches = 2
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo,
nil, nil, nil, nil, nil, nil,
cfg,
nil, nil,
service.NewBillingService(cfg, nil),
rateLimitSvc,
billingCacheSvc,
nil,
&service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
}
h := &OpenAIGatewayHandler{
gatewayService: gatewaySvc,
billingCacheService: billingCacheSvc,
apiKeyService: &service.APIKeyService{},
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
maxAccountSwitches: 2,
}
apiKey := &service.APIKey{
ID: 1811,
GroupID: &groupID,
User: &service.User{ID: 1711, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
}
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})
c.Next()
})
handlerDone := make(chan struct{})
router.GET("/openai/v1/responses", func(c *gin.Context) {
h.ResponsesWebSocket(c)
close(handlerDone)
})
handlerServer := httptest.NewServer(router)
defer handlerServer.Close()
dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
clientConn, _, err := coderws.Dial(
dialCtx,
"ws"+strings.TrimPrefix(handlerServer.URL, "http")+"/openai/v1/responses",
&coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover},
)
cancelDial()
require.NoError(t, err)
defer func() { _ = clientConn.CloseNow() }()
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
err = clientConn.Write(writeCtx, coderws.MessageText, []byte(
`{"type":"response.create","model":"gpt-5.1","previous_response_id":"resp_expired_or_unknown_1","input":[{"type":"message","role":"user","content":"What was the marker?"}]}`,
))
cancelWrite()
require.NoError(t, err)
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
msgType, rawEvent, err := clientConn.Read(readCtx)
cancelRead()
require.NoError(t, err)
require.Equal(t, coderws.MessageText, msgType)
require.Equal(t, "error", gjson.GetBytes(rawEvent, "type").String())
require.Equal(t, "invalid_request_error", gjson.GetBytes(rawEvent, "error.type").String())
require.Equal(t, "previous_response_not_found", gjson.GetBytes(rawEvent, "error.code").String())
readCloseCtx, cancelReadClose := context.WithTimeout(context.Background(), 3*time.Second)
_, _, closeReadErr := clientConn.Read(readCloseCtx)
cancelReadClose()
require.Error(t, closeReadErr)
var closeErr coderws.CloseError
require.ErrorAs(t, closeReadErr, &closeErr)
require.Equal(t, coderws.StatusPolicyViolation, closeErr.Code)
require.Equal(t, "previous_response_not_found", closeErr.Reason)
select {
case <-handlerDone:
case <-time.After(3 * time.Second):
t.Fatal("handler did not finish after sticky-miss previous_response_not_found")
}
require.Equal(t, int32(0), upstreamHits.Load(), "sticky-miss delta must never strip previous_response_id and hit upstream")
}
func TestOpenAIResponsesWebSocket_FirstFrameStickyHitContinuesWithPreviousResponseID(t *testing.T) {
gin.SetMode(gin.TestMode)
receivedCh := make(chan []byte, 4)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
if err != nil {
return
}
defer func() { _ = conn.CloseNow() }()
for i := 0; i < 2; i++ {
readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second)
_, payload, readErr := conn.Read(readCtx)
cancelRead()
if readErr != nil {
return
}
receivedCh <- append([]byte(nil), payload...)
respID := "resp_ws_sticky_turn_1"
if i == 1 {
respID = "resp_ws_sticky_turn_2"
}
writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second)
_ = conn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.completed","response":{"id":"`+respID+`","model":"gpt-5.1","usage":{"input_tokens":5,"output_tokens":2}}}`))
cancelWrite()
}
}))
defer upstream.Close()
groupID := int64(4212)
accounts := []service.Account{
{
ID: 9912,
Name: "openai-ws-sticky-hit-acct",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 1,
Credentials: map[string]any{
"api_key": "sk-first",
"base_url": upstream.URL,
},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
},
},
}
cfg := &config.Config{}
cfg.RunMode = config.RunModeSimple
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.Enabled = false
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
cfg.Gateway.MaxAccountSwitches = 2
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo,
nil, nil, nil, nil, nil, nil,
cfg,
nil, nil,
service.NewBillingService(cfg, nil),
rateLimitSvc,
billingCacheSvc,
nil,
&service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
}
h := &OpenAIGatewayHandler{
gatewayService: gatewaySvc,
billingCacheService: billingCacheSvc,
apiKeyService: &service.APIKeyService{},
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
maxAccountSwitches: 2,
}
apiKey := &service.APIKey{
ID: 1812,
GroupID: &groupID,
User: &service.User{ID: 1712, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
}
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})
c.Next()
})
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
handlerServer := httptest.NewServer(router)
defer handlerServer.Close()
dial := func() *coderws.Conn {
dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
conn, _, err := coderws.Dial(
dialCtx,
"ws"+strings.TrimPrefix(handlerServer.URL, "http")+"/openai/v1/responses",
&coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover},
)
require.NoError(t, err)
return conn
}
// Socket A: seed turn 1 so sticky response -> account + conn is bound.
connA := dial()
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
require.NoError(t, connA.Write(writeCtx, coderws.MessageText, []byte(
`{"type":"response.create","model":"gpt-5.1","store":false,"input":[{"type":"message","role":"user","content":"Remember PLUM"}]}`,
)))
cancelWrite()
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
_, msgA, err := connA.Read(readCtx)
cancelRead()
require.NoError(t, err)
require.Equal(t, "resp_ws_sticky_turn_1", gjson.GetBytes(msgA, "response.id").String())
require.NoError(t, connA.Close(coderws.StatusNormalClosure, "done"))
// Socket B: reconnect with valid bound previous_response_id.
connB := dial()
defer func() { _ = connB.CloseNow() }()
writeCtx2, cancelWrite2 := context.WithTimeout(context.Background(), 3*time.Second)
require.NoError(t, connB.Write(writeCtx2, coderws.MessageText, []byte(
`{"type":"response.create","model":"gpt-5.1","store":false,"previous_response_id":"resp_ws_sticky_turn_1","input":[{"type":"message","role":"user","content":"Which word?"}]}`,
)))
cancelWrite2()
readCtx2, cancelRead2 := context.WithTimeout(context.Background(), 3*time.Second)
_, msgB, err := connB.Read(readCtx2)
cancelRead2()
require.NoError(t, err)
require.Equal(t, "response.completed", gjson.GetBytes(msgB, "type").String())
require.Equal(t, "resp_ws_sticky_turn_2", gjson.GetBytes(msgB, "response.id").String())
<-receivedCh
secondUpstreamPayload := <-receivedCh
require.Equal(t, "resp_ws_sticky_turn_1", gjson.GetBytes(secondUpstreamPayload, "previous_response_id").String())
}
func TestOpenAIResponsesWebSocket_GrokFirstFramePreviousResponseIDNotRejectedByOpenAIStickyCheck(t *testing.T) {
got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"public-alias","previous_response_id":"resp_grok_prev_1","input":[{"type":"message","role":"user","content":"full history"}]}`,
group: compositeWSGroup("public-alias"),
accountPlatform: service.PlatformGrok,
ingressMode: service.OpenAIWSIngressModeCtxPool,
compositeResolver: compositeWSResolver(service.PlatformGrok, service.CompositeRouteEndpointResponses, "grok-4.3"),
})
require.Len(t, got.upstreamPayloads, 1)
require.Equal(t, "grok-4.3", gjson.GetBytes(got.upstreamPayloads[0], "model").String())
require.Equal(t, "response.completed", gjson.GetBytes(got.clientEvents[0], "type").String())
}
@@ -0,0 +1,214 @@
//go:build unit
package handler
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
coderws "github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestOpenAIResponsesWebSocket_FirstFrameContinuationPinsBoundAccountInStickyWeightedMode(t *testing.T) {
gin.SetMode(gin.TestMode)
service.EnableOpenAIAdvancedSchedulerStickyWeightedForTest(t)
var preferredHits atomic.Int32
boundReceivedCh := make(chan []byte, 4)
preferredUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
preferredHits.Add(1)
w.WriteHeader(http.StatusInternalServerError)
}))
defer preferredUpstream.Close()
boundUpstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := coderws.Accept(w, r, &coderws.AcceptOptions{CompressionMode: coderws.CompressionContextTakeover})
if err != nil {
return
}
defer func() { _ = conn.CloseNow() }()
for i := 0; i < 2; i++ {
readCtx, cancelRead := context.WithTimeout(r.Context(), 3*time.Second)
_, payload, readErr := conn.Read(readCtx)
cancelRead()
if readErr != nil {
return
}
boundReceivedCh <- append([]byte(nil), payload...)
respID := "resp_ws_weighted_turn_1"
if i == 1 {
respID = "resp_ws_weighted_turn_2"
}
writeCtx, cancelWrite := context.WithTimeout(r.Context(), 3*time.Second)
_ = conn.Write(writeCtx, coderws.MessageText, []byte(`{"type":"response.completed","response":{"id":"`+respID+`","model":"gpt-5.1","usage":{"input_tokens":5,"output_tokens":2}}}`))
cancelWrite()
}
}))
defer boundUpstream.Close()
groupID := int64(4213)
// Account 9913 starts schedulable=false during turn 1 so turn 1 binds to 9914 (Priority 100).
// Before turn 2 reconnects, 9913 (higher priority 0) becomes schedulable. With sticky-weighted
// mode and LBTopK=1, a movable continuation would pick 9913 (StickyPreviousHit=false) and fail;
// pinning continuation scheduling (previousResponseCanMove=false) keeps turn 2 on 9914.
accounts := []service.Account{
{
ID: 9913,
Name: "openai-ws-higher-priority",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
Concurrency: 2,
Priority: 0,
Credentials: map[string]any{
"api_key": "sk-preferred",
"base_url": preferredUpstream.URL,
},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
},
},
{
ID: 9914,
Name: "openai-ws-bound-owner",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 2,
Priority: 100,
Credentials: map[string]any{
"api_key": "sk-bound",
"base_url": boundUpstream.URL,
},
Extra: map[string]any{
"openai_apikey_responses_websockets_v2_enabled": true,
"openai_apikey_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool,
},
},
}
cfg := &config.Config{}
cfg.RunMode = config.RunModeSimple
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.Enabled = false
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true
cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true
cfg.Gateway.OpenAIWS.LBTopK = 1
cfg.Gateway.OpenAIWS.SchedulerScoreWeights.Priority = 1
cfg.Gateway.OpenAIWS.DialTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3
cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3
cfg.Gateway.MaxAccountSwitches = 2
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
rateLimitSvc := service.NewRateLimitService(accountRepo, nil, cfg, nil, nil)
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo,
nil, nil, nil, nil, nil, nil,
cfg,
nil, nil,
service.NewBillingService(cfg, nil),
rateLimitSvc,
billingCacheSvc,
nil,
&service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(ctx context.Context, userID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
acquireAccountSlotFn: func(ctx context.Context, accountID int64, maxConcurrency int, requestID string) (bool, error) {
return true, nil
},
}
h := &OpenAIGatewayHandler{
gatewayService: gatewaySvc,
billingCacheService: billingCacheSvc,
apiKeyService: &service.APIKeyService{},
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(cache), SSEPingFormatNone, time.Second),
maxAccountSwitches: 2,
}
apiKey := &service.APIKey{
ID: 1813,
GroupID: &groupID,
User: &service.User{ID: 1713, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
}
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})
c.Next()
})
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
handlerServer := httptest.NewServer(router)
defer handlerServer.Close()
dial := func() *coderws.Conn {
dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
conn, _, err := coderws.Dial(
dialCtx,
"ws"+strings.TrimPrefix(handlerServer.URL, "http")+"/openai/v1/responses",
&coderws.DialOptions{CompressionMode: coderws.CompressionContextTakeover},
)
require.NoError(t, err)
return conn
}
// Socket A binds resp_ws_weighted_turn_1 to account 9914.
connA := dial()
writeCtx, cancelWrite := context.WithTimeout(context.Background(), 3*time.Second)
require.NoError(t, connA.Write(writeCtx, coderws.MessageText, []byte(
`{"type":"response.create","model":"gpt-5.1","store":false,"input":[{"type":"message","role":"user","content":"Remember PLUM"}]}`,
)))
cancelWrite()
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
_, msgA, err := connA.Read(readCtx)
cancelRead()
require.NoError(t, err)
require.Equal(t, "resp_ws_weighted_turn_1", gjson.GetBytes(msgA, "response.id").String())
require.NoError(t, connA.Close(coderws.StatusNormalClosure, "done"))
// Make higher-priority account 9913 schedulable before reconnecting on Socket B.
accountRepo.accounts[0].Schedulable = true
connB := dial()
defer func() { _ = connB.CloseNow() }()
writeCtx2, cancelWrite2 := context.WithTimeout(context.Background(), 3*time.Second)
require.NoError(t, connB.Write(writeCtx2, coderws.MessageText, []byte(
`{"type":"response.create","model":"gpt-5.1","store":false,"previous_response_id":"resp_ws_weighted_turn_1","input":[{"type":"message","role":"user","content":"Which word?"}]}`,
)))
cancelWrite2()
readCtx2, cancelRead2 := context.WithTimeout(context.Background(), 3*time.Second)
_, msgB, err := connB.Read(readCtx2)
cancelRead2()
require.NoError(t, err)
require.Equal(t, "response.completed", gjson.GetBytes(msgB, "type").String())
require.Equal(t, "resp_ws_weighted_turn_2", gjson.GetBytes(msgB, "response.id").String())
require.Equal(t, int32(0), preferredHits.Load(), "bound continuation must pin to owning account rather than drifting to higher-priority account")
}
+159 -22
View File
@@ -3,6 +3,7 @@ package handler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
@@ -14,20 +15,71 @@ import (
"github.com/gin-gonic/gin"
)
func securityAuditStreamCommitted(c *gin.Context) bool {
if service.StopOpenAICompactSSEKeepaliveCommitted(c) {
return true
}
return c != nil && c.Writer != nil && c.Writer.Written()
}
func writeGenericSecurityAuditSSEError(c *gin.Context, status int, errType, code, message string) {
if c == nil || c.Writer == nil {
return
}
service.MarkOpsStreamError(c, errType, message, status)
if inboundIsResponses(c) {
if writeResponsesFailedSSE(c, errType, code, message) {
return
}
}
flusher, ok := c.Writer.(http.Flusher)
if !ok {
return
}
errObj := gin.H{"type": errType, "message": message}
if code != "" {
errObj["code"] = code
}
payload, err := json.Marshal(gin.H{"error": errObj})
if err != nil {
payload = []byte(`{"error":{"type":"content_policy_violation","message":"Request blocked by content policy"}}`)
}
_, _ = fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", payload)
flusher.Flush()
}
func (h *OpenAIGatewayHandler) openAISecurityAuditError(c *gin.Context, decision *securityaudit.Decision) {
if decision == nil {
return
}
status := securityAuditStatus(decision)
code := securityAuditErrorCode(decision)
msg := securityAuditMessage(decision)
if securityAuditStreamCommitted(c) {
errType := code
if decision.Legacy == nil || !decision.Legacy.Blocked {
errType = "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
}
if h != nil {
h.handleStreamingAwareErrorWithCode(c, status, errType, code, msg, true, false)
return
}
writeGenericSecurityAuditSSEError(c, status, errType, code, msg)
return
}
if decision.Legacy != nil && decision.Legacy.Blocked {
h.errorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
h.errorResponse(c, status, code, msg)
return
}
errType := "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
c.JSON(securityAuditStatus(decision), gin.H{"error": gin.H{
"type": errType, "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
c.JSON(status, gin.H{"error": gin.H{
"type": errType, "code": code, "message": msg,
}})
}
@@ -35,16 +87,34 @@ func (h *GatewayHandler) openAISecurityAuditError(c *gin.Context, decision *secu
if decision == nil {
return
}
status := securityAuditStatus(decision)
code := securityAuditErrorCode(decision)
msg := securityAuditMessage(decision)
if securityAuditStreamCommitted(c) {
errType := code
if decision.Legacy == nil || !decision.Legacy.Blocked {
errType = "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
}
if h != nil {
h.handleStreamingAwareErrorWithCode(c, status, errType, code, msg, true)
return
}
writeGenericSecurityAuditSSEError(c, status, errType, code, msg)
return
}
if decision.Legacy != nil && decision.Legacy.Blocked {
h.chatCompletionsErrorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
h.chatCompletionsErrorResponse(c, status, code, msg)
return
}
errType := "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
c.JSON(securityAuditStatus(decision), gin.H{"error": gin.H{
"type": errType, "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
c.JSON(status, gin.H{"error": gin.H{
"type": errType, "code": code, "message": msg,
}})
}
@@ -52,12 +122,26 @@ func (h *GatewayHandler) responsesSecurityAuditError(c *gin.Context, decision *s
if decision == nil {
return
}
if decision.Legacy != nil && decision.Legacy.Blocked {
h.responsesErrorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
status := securityAuditStatus(decision)
code := securityAuditErrorCode(decision)
msg := securityAuditMessage(decision)
if securityAuditStreamCommitted(c) {
errType := code
if decision.Legacy == nil || !decision.Legacy.Blocked {
errType = "api_error"
}
service.MarkOpsStreamError(c, errType, msg, status)
if !writeResponsesFailedSSE(c, errType, code, msg) {
writeGenericSecurityAuditSSEError(c, status, errType, code, msg)
}
return
}
c.JSON(securityAuditStatus(decision), gin.H{"error": gin.H{
"type": "api_error", "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
if decision.Legacy != nil && decision.Legacy.Blocked {
h.responsesErrorResponse(c, status, code, msg)
return
}
c.JSON(status, gin.H{"error": gin.H{
"type": "api_error", "code": code, "message": msg,
}})
}
@@ -65,16 +149,34 @@ func (h *GatewayHandler) anthropicSecurityAuditError(c *gin.Context, decision *s
if decision == nil {
return
}
status := securityAuditStatus(decision)
code := securityAuditErrorCode(decision)
msg := securityAuditMessage(decision)
if securityAuditStreamCommitted(c) {
errType := code
if decision.Legacy == nil || !decision.Legacy.Blocked {
errType = "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
}
if h != nil {
h.handleStreamingAwareErrorWithCode(c, status, errType, code, msg, true)
return
}
writeGenericSecurityAuditSSEError(c, status, errType, code, msg)
return
}
if decision.Legacy != nil && decision.Legacy.Blocked {
h.errorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
h.errorResponse(c, status, code, msg)
return
}
errType := "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
c.JSON(securityAuditStatus(decision), gin.H{"type": "error", "error": gin.H{
"type": errType, "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
c.JSON(status, gin.H{"type": "error", "error": gin.H{
"type": errType, "code": code, "message": msg,
}})
}
@@ -82,16 +184,30 @@ func (h *OpenAIGatewayHandler) anthropicSecurityAuditError(c *gin.Context, decis
if decision == nil {
return
}
status := securityAuditStatus(decision)
code := securityAuditErrorCode(decision)
msg := securityAuditMessage(decision)
if securityAuditStreamCommitted(c) {
errType := code
if decision.Legacy == nil || !decision.Legacy.Blocked {
errType = "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
}
h.anthropicStreamingAwareError(c, status, errType, msg, true)
return
}
if decision.Legacy != nil && decision.Legacy.Blocked {
h.anthropicErrorResponse(c, securityAuditStatus(decision), securityAuditErrorCode(decision), securityAuditMessage(decision))
h.anthropicErrorResponse(c, status, code, msg)
return
}
errType := "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
c.JSON(securityAuditStatus(decision), gin.H{"type": "error", "error": gin.H{
"type": errType, "code": securityAuditErrorCode(decision), "message": securityAuditMessage(decision),
c.JSON(status, gin.H{"type": "error", "error": gin.H{
"type": errType, "code": code, "message": msg,
}})
}
@@ -99,16 +215,36 @@ func googleSecurityAuditError(c *gin.Context, decision *securityaudit.Decision)
if decision == nil {
return
}
status := securityAuditStatus(decision)
code := securityAuditErrorCode(decision)
msg := securityAuditMessage(decision)
if securityAuditStreamCommitted(c) {
service.MarkOpsStreamError(c, code, msg, status)
if flusher, ok := c.Writer.(http.Flusher); ok {
googleStatus := googleapi.HTTPStatusToGoogleStatus(status)
payload, err := json.Marshal(gin.H{
"error": gin.H{
"code": status,
"message": msg,
"status": googleStatus,
},
})
if err == nil {
_, _ = fmt.Fprintf(c.Writer, "data: %s\n\n", payload)
flusher.Flush()
}
}
return
}
if decision.Legacy != nil && decision.Legacy.Blocked {
googleErrorWithType(c, securityAuditStatus(decision), securityAuditErrorCode(decision), "", securityAuditMessage(decision))
googleErrorWithType(c, status, code, "", msg)
return
}
errType := "api_error"
if decision.Kind == securityaudit.DecisionBlock {
errType = "permission_error"
}
service.SetOpsLocalErrorType(c, errType, securityAuditErrorCode(decision))
status := securityAuditStatus(decision)
service.SetOpsLocalErrorType(c, errType, code)
googleStatus := googleapi.HTTPStatusToGoogleStatus(status)
if status == http.StatusServiceUnavailable {
googleStatus = "UNAVAILABLE"
@@ -118,10 +254,11 @@ func googleSecurityAuditError(c *gin.Context, decision *securityaudit.Decision)
requestID = contentModerationRequestID(c.Request.Context())
}
c.JSON(status, gin.H{"error": gin.H{
"code": status, "message": securityAuditMessage(decision), "status": googleStatus,
"code": status, "message": msg, "status": googleStatus,
"details": []gin.H{{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": securityAuditErrorCode(decision), "domain": "sub2api.securityaudit",
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": code,
"domain": "sub2api.securityaudit",
"metadata": gin.H{"request_id": requestID},
}},
}})
@@ -75,8 +75,19 @@ func runSecurityAudit(c *gin.Context, reqLog *zap.Logger, coordinator *securitya
return nil
}
}
legacyInput := buildContentModerationInput(c, apiKey, subject, protocol, model, body)
if strings.TrimSpace(stage) == "subsequent_turn" {
legacyInput.AccountID = boundAccountIDFromGinContext(c)
}
deferredLegacy := deferAccountModerationIfNeeded(c, reqLog, legacy, legacyInput)
if coordinator == nil {
legacyDecision := runContentModeration(c, reqLog, legacy, apiKey, subject, protocol, model, body)
if deferredLegacy {
if cacheCompletion {
c.Set(securityAuditCompletedContextKey, true)
}
return &securityaudit.Decision{Kind: securityaudit.DecisionAllow, HTTPStatus: http.StatusOK, AllowNextStage: true}
}
legacyDecision := runContentModerationWithInput(c.Request.Context(), reqLog, legacy, legacyInput)
if legacyDecision == nil {
return nil
}
@@ -94,7 +105,9 @@ func runSecurityAudit(c *gin.Context, reqLog *zap.Logger, coordinator *securitya
}
return &decision
}
request := buildSecurityAuditRequest(c, apiKey, subject, protocol, model, body, stage)
request := buildSecurityAuditRequestFromLegacy(apiKey, legacyInput, body, stage)
request.AccountID = legacyInput.AccountID
request.SkipLegacy = deferredLegacy
if isSecurityAuditWebSocketStage(request.Stage) {
if turnNo, ok := securityAuditWSTurn(c); ok {
bodyHash := sha256.Sum256(body)
@@ -157,10 +170,9 @@ func securityAuditWSTurn(c *gin.Context) (int, bool) {
return turnNo, ok
}
func buildSecurityAuditRequest(c *gin.Context, apiKey *service.APIKey, subject middleware2.AuthSubject, protocol, model string, body []byte, stage string) securityaudit.Request {
legacy := buildContentModerationInput(c, apiKey, subject, protocol, model, body)
func buildSecurityAuditRequestFromLegacy(apiKey *service.APIKey, legacy service.ContentModerationCheckInput, body []byte, stage string) securityaudit.Request {
request := securityaudit.Request{
RequestID: legacy.RequestID, UserID: legacy.UserID, UserEmail: legacy.UserEmail,
RequestID: legacy.RequestID, AccountID: legacy.AccountID, UserID: legacy.UserID, UserEmail: legacy.UserEmail,
APIKeyID: legacy.APIKeyID, APIKeyName: legacy.APIKeyName, GroupID: cloneSecurityAuditGroupID(legacy.GroupID),
GroupName: legacy.GroupName, Provider: legacy.Provider, Endpoint: legacy.Endpoint,
Protocol: legacy.Protocol, Model: legacy.Model, Body: body, Stage: strings.TrimSpace(stage),
+39 -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
@@ -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})
@@ -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,152 @@
//go:build unit
package antigravity
import (
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
type finishTestEvent struct {
name string
data map[string]any
}
func runFinishTestStream(t *testing.T, chunks ...string) ([]finishTestEvent, *ClaudeUsage) {
t.Helper()
processor := NewStreamingProcessor("gemini-4-neon")
var out strings.Builder
for _, chunk := range chunks {
out.Write(processor.ProcessLine("data: " + chunk))
}
final, usage := processor.Finish()
out.Write(final)
var events []finishTestEvent
var name string
for _, line := range strings.Split(out.String(), "\n") {
if v, ok := strings.CutPrefix(line, "event: "); ok {
name = v
continue
}
if v, ok := strings.CutPrefix(line, "data: "); ok {
var data map[string]any
require.NoError(t, json.Unmarshal([]byte(v), &data))
events = append(events, finishTestEvent{name: name, data: data})
}
}
return events, usage
}
func finishTestStopReason(events []finishTestEvent) string {
for _, event := range events {
if event.name == "message_delta" {
reason, _ := event.data["delta"].(map[string]any)["stop_reason"].(string)
return reason
}
}
return ""
}
func TestFinishReasonMapping(t *testing.T) {
const usage = `"usageMetadata":{"promptTokenCount":12,"candidatesTokenCount":3}`
text := func(reason string) string {
return `{"candidates":[{"content":{"role":"model","parts":[{"text":"partial"}]},"finishReason":"` + reason + `"}],` + usage + `}`
}
call := func(reason string) string {
return `{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"Read","args":{}},"thoughtSignature":"SIG"}]},"finishReason":"` + reason + `"}],` + usage + `}`
}
empty := func(reason string) string {
return `{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"SIG"}]},"finishReason":"` + reason + `"}],` + usage + `}`
}
thoughtOnly := func(reason string) string {
return `{"candidates":[{"content":{"role":"model","parts":[{"text":"Plan the call.","thought":true}]},"finishReason":"` + reason + `"}],` + usage + `}`
}
const promptBlocked = `{"promptFeedback":{"blockReason":"PROHIBITED_CONTENT"},` + usage + `}`
tests := []struct {
name string
chunk string
wantStop string
wantError bool
}{
{name: "STOP", chunk: text("STOP"), wantStop: "end_turn"},
{name: "MAX_TOKENS", chunk: text("MAX_TOKENS"), wantStop: "max_tokens"},
{name: "OTHER keeps end_turn", chunk: text("OTHER"), wantStop: "end_turn"},
{name: "tool call with STOP", chunk: call("STOP"), wantStop: "tool_use"},
{name: "SAFETY", chunk: text("SAFETY"), wantStop: "refusal"},
{name: "PROHIBITED_CONTENT", chunk: text("PROHIBITED_CONTENT"), wantStop: "refusal"},
{name: "SPII", chunk: text("SPII"), wantStop: "refusal"},
{name: "BLOCKLIST", chunk: text("BLOCKLIST"), wantStop: "refusal"},
{name: "IMAGE_SAFETY", chunk: text("IMAGE_SAFETY"), wantStop: "refusal"},
{name: "RECITATION", chunk: text("RECITATION"), wantStop: "refusal"},
{name: "SAFETY after a tool call", chunk: call("SAFETY"), wantStop: "refusal"},
{name: "prompt blocked without candidates", chunk: promptBlocked, wantStop: "refusal"},
{name: "UNEXPECTED_TOOL_CALL without content", chunk: empty("UNEXPECTED_TOOL_CALL"), wantError: true},
{name: "TOO_MANY_TOOL_CALLS without content", chunk: empty("TOO_MANY_TOOL_CALLS"), wantError: true},
{name: "MALFORMED_RESPONSE without content", chunk: empty("MALFORMED_RESPONSE"), wantError: true},
{name: "MALFORMED_FUNCTION_CALL after thinking only", chunk: thoughtOnly("MALFORMED_FUNCTION_CALL"), wantError: true},
{name: "UNEXPECTED_TOOL_CALL after thinking only", chunk: thoughtOnly("UNEXPECTED_TOOL_CALL"), wantError: true},
{name: "UNEXPECTED_TOOL_CALL after text", chunk: text("UNEXPECTED_TOOL_CALL"), wantStop: "end_turn"},
{name: "MALFORMED_FUNCTION_CALL after text", chunk: text("MALFORMED_FUNCTION_CALL"), wantStop: "end_turn"},
{name: "TOO_MANY_TOOL_CALLS after a call", chunk: call("TOO_MANY_TOOL_CALLS"), wantStop: "tool_use"},
}
for _, tt := range tests {
t.Run("stream/"+tt.name, func(t *testing.T) {
events, gotUsage := runFinishTestStream(t, tt.chunk)
require.Equal(t, 12, gotUsage.InputTokens, "usage is still collected for billing")
if tt.wantError {
last := events[len(events)-1]
require.Equal(t, "error", last.name)
require.Equal(t, "api_error", last.data["error"].(map[string]any)["type"])
require.Empty(t, finishTestStopReason(events))
for _, event := range events {
require.NotEqual(t, "message_stop", event.name)
}
return
}
require.Equal(t, tt.wantStop, finishTestStopReason(events))
})
t.Run("non-stream/"+tt.name, func(t *testing.T) {
body, _, err := TransformGeminiToClaude([]byte(tt.chunk), "gemini-4-neon")
if tt.wantError {
require.True(t, errors.Is(err, ErrInvalidOutputWithoutContent) || errors.Is(err, ErrMalformedFunctionCall), "got %v", err)
require.Nil(t, body)
return
}
require.NoError(t, err)
var resp map[string]any
require.NoError(t, json.Unmarshal(body, &resp))
require.Equal(t, tt.wantStop, resp["stop_reason"])
})
}
}
func TestFinishReasonMapping_MalformedFunctionCallWithoutContent(t *testing.T) {
const chunk = `{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`
events, _ := runFinishTestStream(t, chunk)
require.Equal(t, "message_start", events[0].name)
require.Equal(t, "error", events[len(events)-1].name)
_, _, err := TransformGeminiToClaude([]byte(chunk), "gemini-4-neon")
require.ErrorIs(t, err, ErrMalformedFunctionCall)
}
func TestFinishReasonMapping_NothingFollowsTheErrorEvent(t *testing.T) {
events, usage := runFinishTestStream(t,
`{"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MALFORMED_FUNCTION_CALL"}]}`,
`{"candidates":[{"content":{"role":"model","parts":[{"text":"late"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":40,"candidatesTokenCount":2}}`,
)
require.Equal(t, "error", events[len(events)-1].name)
for _, event := range events {
require.NotEqual(t, "content_block_start", event.name)
require.NotEqual(t, "message_delta", event.name)
}
require.Equal(t, 40, usage.InputTokens)
}
@@ -147,10 +147,21 @@ type V1InternalResponse struct {
// GeminiResponse Gemini 响应
type GeminiResponse struct {
Candidates []GeminiCandidate `json:"candidates,omitempty"`
UsageMetadata *GeminiUsageMetadata `json:"usageMetadata,omitempty"`
ResponseID string `json:"responseId,omitempty"`
ModelVersion string `json:"modelVersion,omitempty"`
Candidates []GeminiCandidate `json:"candidates,omitempty"`
PromptFeedback *GeminiPromptFeedback `json:"promptFeedback,omitempty"`
UsageMetadata *GeminiUsageMetadata `json:"usageMetadata,omitempty"`
ResponseID string `json:"responseId,omitempty"`
ModelVersion string `json:"modelVersion,omitempty"`
}
// GeminiPromptFeedback 是 prompt 被拦截时上游返回的原因,此时没有 candidates。
type GeminiPromptFeedback struct {
BlockReason string `json:"blockReason,omitempty"`
}
// promptBlocked 判断 prompt 是否被拦截:没有 candidates 且带 blockReason。
func (r *GeminiResponse) promptBlocked() bool {
return len(r.Candidates) == 0 && r.PromptFeedback != nil && r.PromptFeedback.BlockReason != ""
}
// GeminiCandidate 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\.?`),
}
@@ -420,9 +421,21 @@ func buildSystemInstruction(system json.RawMessage, modelName string, opts Trans
}
// buildContents 构建 contents
//
// {role: "system"} messages before the first model turn are the conversation's
// standing context and go to systemInstruction. Later ones are notices an agent
// client adds as the conversation goes on (Claude Code adds one after each tool
// result); they stay at their place as user text. systemInstruction precedes
// the contents in the prompt, and Gemini's implicit cache only matches a prompt
// prefix, so a notice appended there would change every request's prefix and
// leave the whole conversation uncached.
func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isThinkingEnabled, allowDummyThought, multimodalToolResults bool) ([]GeminiContent, []GeminiPart, bool, error) {
var contents []GeminiContent
var systemParts []GeminiPart
// Notices that follow a model turn wait for the next user turn: a
// functionCall must be followed directly by its functionResponse.
var pendingNotices []GeminiPart
seenModel := false
strippedThinking := false
for i, msg := range messages {
@@ -440,10 +453,31 @@ func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isT
}
if role == "system" {
systemParts = append(systemParts, parts...)
parts = trimSystemTextParts(parts)
if !seenModel {
systemParts = append(systemParts, parts...)
continue
}
notice := systemReminderParts(parts)
if n := len(contents); n > 0 && contents[n-1].Role == "user" && len(pendingNotices) == 0 {
contents[n-1].Parts = append(contents[n-1].Parts, notice...)
} else {
pendingNotices = append(pendingNotices, notice...)
}
continue
}
if role == "model" {
seenModel = true
if len(pendingNotices) > 0 {
contents = append(contents, GeminiContent{Role: "user", Parts: pendingNotices})
pendingNotices = nil
}
} else if len(pendingNotices) > 0 {
parts = append(parts, pendingNotices...)
pendingNotices = nil
}
// 只有 Gemini 模型支持 dummy thinking block workaround
// 只对最后一条 assistant 消息添加(Pre-fill 场景)
// 历史 assistant 消息不能添加没有 signature 的 dummy thinking block
@@ -474,10 +508,48 @@ func buildContents(messages []ClaudeMessage, toolIDToName map[string]string, isT
Parts: parts,
})
}
if len(pendingNotices) > 0 {
contents = append(contents, GeminiContent{Role: "user", Parts: pendingNotices})
}
return contents, systemParts, strippedThinking, nil
}
// trimSystemTextParts renders a system message's text the same way whether
// the client sent it as a string (which buildParts trims) or as text blocks:
// Claude Code sends its newest system message as blocks with cache_control and
// the same message as a string once it is history.
func trimSystemTextParts(parts []GeminiPart) []GeminiPart {
out := parts[:0]
for _, p := range parts {
if isPlainTextPart(p) {
p.Text = strings.TrimSpace(p.Text)
if p.Text == "" {
continue
}
}
out = append(out, p)
}
return out
}
// systemReminderParts marks a system notice placed in a user turn the way
// agent clients mark harness text in user turns.
func systemReminderParts(parts []GeminiPart) []GeminiPart {
out := make([]GeminiPart, 0, len(parts))
for _, p := range parts {
if isPlainTextPart(p) {
p.Text = "<system-reminder>\n" + p.Text + "\n</system-reminder>"
}
out = append(out, p)
}
return out
}
func isPlainTextPart(p GeminiPart) bool {
return !p.Thought && p.InlineData == nil && p.FunctionCall == nil && p.FunctionResponse == nil
}
// DummyThoughtSignature 用于跳过 Gemini 3 thought_signature 验证
// 参考: https://ai.google.dev/gemini-api/docs/thought-signatures
// 导出供跨包使用(如 gemini_native_signature_cleaner 跨账号修复)
@@ -505,6 +577,7 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu
}
var toolMediaParts []GeminiPart
var toolResults []GeminiPart
for _, block := range blocks {
switch block.Type {
case "text":
@@ -595,13 +668,14 @@ func buildParts(content json.RawMessage, toolIDToName map[string]string, allowDu
} else {
toolMediaParts = append(toolMediaParts, media...)
}
parts = append(parts, GeminiPart{FunctionResponse: response})
toolResults = append(toolResults, GeminiPart{FunctionResponse: response})
}
}
parts = append(parts, toolMediaParts...)
return parts, strippedThinking, nil
// Interleaved notices must not split a parallel tool-result batch.
return append(toolResults, parts...), strippedThinking, nil
}
// parseToolResultContent 解析 tool_result 的 content
@@ -2,6 +2,7 @@ package antigravity
import (
"encoding/json"
"fmt"
"strings"
"testing"
@@ -755,3 +756,33 @@ func TestTransformClaudeToGemini_ToolResultImagesReachUpstream(t *testing.T) {
require.Equal(t, "image/jpeg", userParts[3].InlineData.MimeType)
require.Equal(t, "d29ybGQ=", userParts[3].InlineData.Data)
}
func TestBuildParts_ParallelResultsWithInterleavedNotice(t *testing.T) {
for _, multimodal := range []bool{false, true} {
t.Run(fmt.Sprintf("multimodal=%t", multimodal), func(t *testing.T) {
content := json.RawMessage(`[
{"type":"tool_result","tool_use_id":"image-1","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"aGVsbG8="}}]},
{"type":"text","text":"Keep this notice."},
{"type":"tool_result","tool_use_id":"image-2","content":[{"type":"document","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0="}}]}
]`)
parts, stripped, err := buildParts(content, map[string]string{"image-1": "Read", "image-2": "Read"}, true, multimodal)
require.NoError(t, err)
require.False(t, stripped)
for i, id := range []string{"image-1", "image-2"} {
require.NotNil(t, parts[i].FunctionResponse)
require.Equal(t, id, parts[i].FunctionResponse.ID)
}
require.Equal(t, "Keep this notice.", parts[2].Text)
if multimodal {
require.Len(t, parts, 3)
require.Equal(t, "aGVsbG8=", parts[0].FunctionResponse.Parts[0].InlineData.Data)
require.Equal(t, "JVBERi0=", parts[1].FunctionResponse.Parts[0].InlineData.Data)
} else {
require.Len(t, parts, 5)
require.Equal(t, "aGVsbG8=", parts[3].InlineData.Data)
require.Equal(t, "application/pdf", parts[4].InlineData.MimeType)
require.Equal(t, "JVBERi0=", parts[4].InlineData.Data)
}
})
}
}
@@ -13,8 +13,68 @@ import (
var ErrMalformedFunctionCall = errors.New("upstream returned MALFORMED_FUNCTION_CALL")
// ErrInvalidOutputWithoutContent 表示上游以模型产出无效的结束原因结束,且没有 text 或 tool_use 内容,客户端应重试。
var ErrInvalidOutputWithoutContent = errors.New("upstream finished with an invalid-output reason and no content")
// refusalFinishReasons 是内容被过滤的结束原因,对应 Claude 的 refusal。
var refusalFinishReasons = map[string]bool{
"SAFETY": true,
"PROHIBITED_CONTENT": true,
"SPII": true,
"BLOCKLIST": true,
"IMAGE_SAFETY": true,
"RECITATION": true,
}
// invalidOutputFinishReasons 是模型产出的调用或响应无效的结束原因。
var invalidOutputFinishReasons = map[string]bool{
"MALFORMED_FUNCTION_CALL": true,
"UNEXPECTED_TOOL_CALL": true,
"TOO_MANY_TOOL_CALLS": true,
"MALFORMED_RESPONSE": true,
}
// hasVisibleContent 判断响应里是否有 text 或 tool_use 块(思考块不算)。
func hasVisibleContent(blocks []ClaudeContentItem) bool {
for _, block := range blocks {
if block.Type == "text" || block.Type == "tool_use" {
return true
}
}
return false
}
// claudeStopReason 把 Gemini finishReason 映射为 Claude stop_reason。
func claudeStopReason(finishReason string, usedTool bool) string {
switch {
case refusalFinishReasons[finishReason]:
return "refusal"
case usedTool:
return "tool_use"
case finishReason == "MAX_TOKENS":
return "max_tokens"
default:
return "end_turn"
}
}
// ResponseTransformOptions 调整 Gemini→Claude 非流式转换的输出;零值不改变输出。
type ResponseTransformOptions struct {
// ThinkingSignaturePrefix 加在 thinking 块签名前;tool_use 的签名不加。
ThinkingSignaturePrefix string
// DropTextSignatures 丢弃 text part 上的签名,不再输出只为承载它的空 thinking 块。
// Vertex 只强制校验 functionCall part 的签名,见
// https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thought-signatures
DropTextSignatures bool
}
// TransformGeminiToClaude 将 Gemini 响应转换为 Claude 格式(非流式)
func TransformGeminiToClaude(geminiResp []byte, originalModel string) ([]byte, *ClaudeUsage, error) {
return TransformGeminiToClaudeWithOptions(geminiResp, originalModel, ResponseTransformOptions{})
}
// TransformGeminiToClaudeWithOptions 同 TransformGeminiToClaude,按 opts 调整输出。
func TransformGeminiToClaudeWithOptions(geminiResp []byte, originalModel string, opts ResponseTransformOptions) ([]byte, *ClaudeUsage, error) {
// 解包 v1internal 响应
var v1Resp V1InternalResponse
if err := json.Unmarshal(geminiResp, &v1Resp); err != nil {
@@ -37,13 +97,25 @@ func TransformGeminiToClaude(geminiResp []byte, originalModel string) ([]byte, *
v1Resp.ModelVersion = directResp.ModelVersion
}
if len(v1Resp.Response.Candidates) > 0 && v1Resp.Response.Candidates[0].FinishReason == "MALFORMED_FUNCTION_CALL" {
return nil, nil, ErrMalformedFunctionCall
}
// 使用处理器转换
processor := NewNonStreamingProcessor()
processor.dropTextSignatures = opts.DropTextSignatures
claudeResp := processor.Process(&v1Resp.Response, v1Resp.ResponseID, originalModel)
if len(v1Resp.Response.Candidates) > 0 && !hasVisibleContent(claudeResp.Content) {
switch finishReason := v1Resp.Response.Candidates[0].FinishReason; {
case finishReason == "MALFORMED_FUNCTION_CALL":
return nil, nil, ErrMalformedFunctionCall
case invalidOutputFinishReasons[finishReason]:
return nil, nil, fmt.Errorf("%w: %s", ErrInvalidOutputWithoutContent, finishReason)
}
}
if opts.ThinkingSignaturePrefix != "" {
for i := range claudeResp.Content {
if block := &claudeResp.Content[i]; block.Type == "thinking" && block.Signature != "" {
block.Signature = opts.ThinkingSignaturePrefix + block.Signature
}
}
}
// 序列化
respBytes, err := json.Marshal(claudeResp)
@@ -62,6 +134,8 @@ type NonStreamingProcessor struct {
thinkingSignature string
trailingSignature string
hasToolCall bool
// dropTextSignatures 见 ResponseTransformOptions.DropTextSignatures。
dropTextSignatures bool
}
// NewNonStreamingProcessor 创建非流式响应处理器
@@ -134,11 +208,16 @@ func (p *NonStreamingProcessor) processPart(part *GeminiPart) {
toolID = fmt.Sprintf("%s-%s", part.FunctionCall.Name, generateRandomID())
}
// 无参调用也要带 input 字段:Anthropic 的 tool_use 块要求 input 是对象。
input := part.FunctionCall.Args
if input == nil {
input = map[string]any{}
}
item := ClaudeContentItem{
Type: "tool_use",
ID: toolID,
Name: part.FunctionCall.Name,
Input: part.FunctionCall.Args,
Input: input,
}
if signature != "" {
@@ -171,6 +250,9 @@ func (p *NonStreamingProcessor) processPart(part *GeminiPart) {
p.thinkingSignature = signature
}
} else {
if p.dropTextSignatures {
signature = ""
}
// 普通 Text
if part.Text == "" {
// 空 text 带签名 - 暂存
@@ -276,11 +358,9 @@ func (p *NonStreamingProcessor) buildResponse(geminiResp *GeminiResponse, respon
}
}
stopReason := "end_turn"
if p.hasToolCall {
stopReason = "tool_use"
} else if finishReason == "MAX_TOKENS" {
stopReason = "max_tokens"
stopReason := claudeStopReason(finishReason, p.hasToolCall)
if geminiResp.promptBlocked() {
stopReason = "refusal"
}
// 注意:Gemini 的 promptTokenCount 包含 cachedContentTokenCount,
@@ -0,0 +1,110 @@
//go:build unit
package antigravity
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestProcessorsKeepEmptyToolInputAndImageSignature(t *testing.T) {
tests := []struct {
name string
parts string
wantSignatures []string
wantNoArgsCall bool
}{
{
name: "call without args keeps an empty input object",
parts: `[{"functionCall":{"name":"TodoRead"},"thoughtSignature":"SIG_CALL"}]`,
wantNoArgsCall: true,
},
{
name: "signature on an image part stays out of the thinking blocks",
parts: `[{"inlineData":{"mimeType":"image/png","data":"aGVsbG8="},"thoughtSignature":"SIG_IMAGE"}]`,
},
}
for _, tt := range tests {
chunk := `{"candidates":[{"content":{"role":"model","parts":` + tt.parts + `},"finishReason":"STOP"}]}`
t.Run("stream/"+tt.name, func(t *testing.T) {
processor := NewStreamingProcessor("gemini-4-neon")
out := string(processor.ProcessLine("data: " + chunk))
final, _ := processor.Finish()
out += string(final)
var got []string
for _, line := range strings.Split(out, "\n") {
data, ok := strings.CutPrefix(line, "data: ")
if !ok {
continue
}
var event map[string]any
require.NoError(t, json.Unmarshal([]byte(data), &event))
if delta, _ := event["delta"].(map[string]any); delta["type"] == "signature_delta" {
got = append(got, delta["signature"].(string))
}
}
require.Equal(t, tt.wantSignatures, got)
})
t.Run("non-stream/"+tt.name, func(t *testing.T) {
body, _, err := TransformGeminiToClaude([]byte(chunk), "gemini-4-neon")
require.NoError(t, err)
var resp struct {
Content []map[string]any `json:"content"`
}
require.NoError(t, json.Unmarshal(body, &resp))
var got []string
for _, block := range resp.Content {
if block["type"] == "thinking" {
got = append(got, block["signature"].(string))
}
if block["type"] == "tool_use" && tt.wantNoArgsCall {
require.Contains(t, block, "input")
require.Equal(t, map[string]any{}, block["input"])
}
}
require.Equal(t, tt.wantSignatures, got)
})
}
}
// 只带签名的 text part(空 text 或没有 text 字段)不产生内容块:回合以文本结束,与不设选项时一致。
func TestSignatureOnlyTextPartAddsNoBlock(t *testing.T) {
tails := map[string]string{
"empty text part": `{"text":"","thoughtSignature":"SIG_TAIL"}`,
"part without text": `{"thoughtSignature":"SIG_TAIL"}`,
}
options := map[string]ResponseTransformOptions{
"zero options": {},
"vertex options": {ThinkingSignaturePrefix: "vertex-thought-v1:", DropTextSignatures: true},
}
want := []testBlock{{Type: "text", Text: "Hello world"}}
for tailName, tail := range tails {
for optionsName, opts := range options {
t.Run("stream/"+optionsName+"/"+tailName, func(t *testing.T) {
processor := NewStreamingProcessor("gemini-4-neon")
processor.SetThinkingSignaturePrefix(opts.ThinkingSignaturePrefix)
processor.SetDropTextSignatures(opts.DropTextSignatures)
out := string(processor.ProcessLine(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Hello world"}]}}]}`))
out += string(processor.ProcessLine(`data: {"candidates":[{"content":{"role":"model","parts":[` + tail + `]},"finishReason":"STOP"}]}`))
final, _ := processor.Finish()
require.Equal(t, want, streamTestBlocks(t, out+string(final)))
})
t.Run("non-stream/"+optionsName+"/"+tailName, func(t *testing.T) {
body := `{"candidates":[{"content":{"role":"model","parts":[{"text":"Hello world"},` + tail + `]},"finishReason":"STOP"}]}`
claudeResp, _, err := TransformGeminiToClaudeWithOptions([]byte(body), "gemini-4-neon", opts)
require.NoError(t, err)
require.Equal(t, want, nonStreamTestBlocks(t, claudeResp))
})
}
}
}
@@ -34,6 +34,10 @@ type StreamingProcessor struct {
webSearchQueries []string
groundingChunks []GeminiGroundingChunk
usageMapHook UsageMapHook
// thinkingSignaturePrefix 加在 thinking 块签名前;tool_use 的签名不加。
thinkingSignaturePrefix string
// dropTextSignatures 见 ResponseTransformOptions.DropTextSignatures。
dropTextSignatures bool
// 累计 usage
inputTokens int
@@ -41,6 +45,12 @@ type StreamingProcessor struct {
cacheReadTokens int
imageOutputTokens int
hasContent bool
promptBlocked bool
// visibleContent 表示已开始过 text 或 tool_use 块(思考块不算)。
visibleContent bool
// streamFailed 表示已发出 error 事件,之后不再输出任何事件。
streamFailed bool
}
// NewStreamingProcessor 创建流式响应处理器
@@ -51,6 +61,18 @@ func NewStreamingProcessor(originalModel string) *StreamingProcessor {
}
}
// SetThinkingSignaturePrefix sets a prefix for the signatures of thinking blocks.
// tool_use signatures are not changed. An empty prefix keeps the output unchanged.
func (p *StreamingProcessor) SetThinkingSignaturePrefix(prefix string) {
p.thinkingSignaturePrefix = prefix
}
// SetDropTextSignatures drops the signatures of text parts, so no empty thinking
// block is emitted to carry them. Thinking and tool_use signatures are kept.
func (p *StreamingProcessor) SetDropTextSignatures(drop bool) {
p.dropTextSignatures = drop
}
// SetUsageMapHook sets an optional hook that modifies usage maps before they are emitted.
func (p *StreamingProcessor) SetUsageMapHook(fn UsageMapHook) {
p.usageMapHook = fn
@@ -128,6 +150,10 @@ func (p *StreamingProcessor) ProcessLine(line string) []byte {
p.imageOutputTokens = geminiResp.UsageMetadata.ImageOutputTokens()
}
if p.streamFailed {
return result.Bytes()
}
// 处理 parts
if len(geminiResp.Candidates) > 0 && geminiResp.Candidates[0].Content != nil {
for _, part := range geminiResp.Candidates[0].Content.Parts {
@@ -154,6 +180,10 @@ func (p *StreamingProcessor) ProcessLine(line string) []byte {
_, _ = result.Write(p.emitFinish(finishReason))
}
}
if geminiResp.promptBlocked() {
p.promptBlocked = true
_, _ = result.Write(p.emitFinish(geminiResp.PromptFeedback.BlockReason))
}
return result.Bytes()
}
@@ -264,6 +294,9 @@ func (p *StreamingProcessor) processPart(part *GeminiPart) []byte {
if part.Thought {
_, _ = result.Write(p.processThinking(part.Text, signature))
} else {
if p.dropTextSignatures {
signature = ""
}
_, _ = result.Write(p.processText(part.Text, signature))
}
}
@@ -430,6 +463,9 @@ func (p *StreamingProcessor) startBlock(blockType BlockType, contentBlock map[st
_, _ = result.Write(p.formatSSE("content_block_start", event))
p.blockType = blockType
if blockType == BlockTypeText || blockType == BlockTypeFunction {
p.visibleContent = true
}
return result.Bytes()
}
@@ -445,7 +481,7 @@ func (p *StreamingProcessor) endBlock() []byte {
// Thinking 块结束时发送暂存的签名
if p.blockType == BlockTypeThinking && p.pendingSignature != "" {
_, _ = result.Write(p.emitDelta("signature_delta", map[string]any{
"signature": p.pendingSignature,
"signature": p.thinkingSignaturePrefix + p.pendingSignature,
}))
p.pendingSignature = ""
}
@@ -494,7 +530,7 @@ func (p *StreamingProcessor) emitEmptyThinkingWithSignature(signature string) []
"thinking": "",
}))
_, _ = result.Write(p.emitDelta("signature_delta", map[string]any{
"signature": signature,
"signature": p.thinkingSignaturePrefix + signature,
}))
_, _ = result.Write(p.endBlock())
@@ -503,6 +539,23 @@ func (p *StreamingProcessor) emitEmptyThinkingWithSignature(signature string) []
// emitFinish 发送结束事件
func (p *StreamingProcessor) emitFinish(finishReason string) []byte {
if p.streamFailed {
return nil
}
// 模型产出无效且没有输出 text 或 tool_use:发可重试的 error 事件,Claude 客户端会重发请求。
// 思考块不算:开启思考时,无效调用之前几乎总有思考摘要。
if invalidOutputFinishReasons[finishReason] && !p.visibleContent {
p.streamFailed = true
p.messageStopSent = true
return p.formatSSE("error", map[string]any{
"type": "error",
"error": map[string]any{
"type": "api_error",
"message": "upstream finished with " + finishReason + " and no content",
},
})
}
var result bytes.Buffer
// 关闭最后一个块
@@ -532,11 +585,9 @@ func (p *StreamingProcessor) emitFinish(finishReason string) []byte {
}
// 确定 stop_reason
stopReason := "end_turn"
if p.usedTool {
stopReason = "tool_use"
} else if finishReason == "MAX_TOKENS" {
stopReason = "max_tokens"
stopReason := claudeStopReason(finishReason, p.usedTool)
if p.promptBlocked {
stopReason = "refusal"
}
usage := ClaudeUsage{
@@ -0,0 +1,210 @@
package antigravity
import (
"encoding/json"
"fmt"
"math/rand"
"strings"
"testing"
"testing/quick"
"github.com/stretchr/testify/require"
)
// Messages shaped like Claude Code's: a {role: "system"} message with the
// environment after the first user message, and another {role: "system"}
// notice after every tool result. The newest system message carries
// cache_control as a block list; once it is history the client sends it as a
// plain string.
const (
ccAsk = `{"role":"user","content":[{"type":"text","text":"read f.txt"}]}`
ccEnvLatest = `{"role":"system","content":[{"type":"text","text":"# Environment\nPrimary working directory: /repo","cache_control":{"type":"ephemeral"}}]}`
ccEnv = `{"role":"system","content":"# Environment\nPrimary working directory: /repo"}`
ccCall1 = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{"file_path":"/repo/f.txt"}}]}`
ccResult1 = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"hello"}]}`
ccCall2 = `{"role":"assistant","content":[{"type":"tool_use","id":"toolu_2","name":"Read","input":{"file_path":"/repo/g.txt"}}]}`
ccResult2 = `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_2","content":"world"}]}`
ccNotice = `{"role":"system","content":"Plain output style is active."}`
ccNoticeLast = `{"role":"system","content":[{"type":"text","text":"Plain output style is active.","cache_control":{"type":"ephemeral"}}]}`
)
func transformClaudeCodeMessages(t *testing.T, msgs ...string) V1InternalRequest {
t.Helper()
var messages []ClaudeMessage
require.NoError(t, json.Unmarshal([]byte("["+strings.Join(msgs, ",")+"]"), &messages))
body, err := TransformClaudeToGeminiWithOptions(&ClaudeRequest{
Model: "gemini-4-neon",
System: json.RawMessage(`"You are Claude Code."`),
Messages: messages,
Tools: []ClaudeTool{{Name: "Read", Description: "Read a file", InputSchema: map[string]any{"type": "object"}}},
}, "project-1", "gemini-4-neon-high", DefaultTransformOptions())
require.NoError(t, err)
var req V1InternalRequest
require.NoError(t, json.Unmarshal(body, &req))
return req
}
func mustJSON(t *testing.T, v any) string {
t.Helper()
b, err := json.Marshal(v)
require.NoError(t, err)
return string(b)
}
// Gemini's implicit cache matches the prompt from its first byte, and the
// systemInstruction comes before the conversation. Each request of a tool loop
// must therefore keep the previous request's systemInstruction, tools and
// contents byte for byte and only add to the end.
func TestClaudeCodeToolLoopKeepsThePromptPrefix(t *testing.T) {
requests := []V1InternalRequest{
transformClaudeCodeMessages(t, ccAsk, ccEnvLatest),
transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNoticeLast),
transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNotice, ccCall2, ccResult2, ccNoticeLast),
}
for n := 1; n < len(requests); n++ {
before, now := requests[n-1].Request, requests[n].Request
require.Equal(t, mustJSON(t, before.SystemInstruction), mustJSON(t, now.SystemInstruction), "request %d changed the systemInstruction", n+1)
require.Equal(t, mustJSON(t, before.Tools), mustJSON(t, now.Tools), "request %d changed the tools", n+1)
require.Greater(t, len(now.Contents), len(before.Contents))
for i := range before.Contents {
require.Equal(t, mustJSON(t, before.Contents[i]), mustJSON(t, now.Contents[i]), "request %d changed content %d of the request before", n+1, i)
}
}
}
// The same holds for any conversation that grows the way Claude Code grows
// it: tool calls, tool results with notices after some of them or between a
// call and its result, finished replies and new questions.
func TestGrowingConversationOnlyAddsToThePrompt(t *testing.T) {
notices := []string{"Plain output style is active.", " The user hasn't heard from you in a while.\n", "Today's date is 2026-12-01."}
// system renders a system message; the newest one comes as blocks with
// cache_control, older ones as strings.
system := func(text string, newest bool) string {
if newest {
return mustJSON(t, map[string]any{"role": "system", "content": []map[string]any{{"type": "text", "text": text, "cache_control": map[string]string{"type": "ephemeral"}}}})
}
return mustJSON(t, map[string]any{"role": "system", "content": text})
}
type message struct {
json string
notice string // the text of a system message, rendered by position
}
render := func(msgs []message) []string {
out := make([]string, len(msgs))
for i, m := range msgs {
if m.notice != "" {
out[i] = system(m.notice, i == len(msgs)-1)
} else {
out[i] = m.json
}
}
return out
}
property := func(seed int64) bool {
rng := rand.New(rand.NewSource(seed))
msgs := []message{{json: ccAsk}, {notice: "# Environment\nPrimary working directory: /repo"}}
var requests [][]string
requests = append(requests, render(msgs))
for step := 0; step < 2+rng.Intn(8); step++ {
id := fmt.Sprintf("toolu_%d", step)
if rng.Intn(4) == 0 {
msgs = append(msgs,
message{json: mustJSON(t, map[string]any{"role": "assistant", "content": fmt.Sprintf("answer %d", step)})},
message{json: mustJSON(t, map[string]any{"role": "user", "content": fmt.Sprintf("question %d", step)})})
} else {
msgs = append(msgs, message{json: mustJSON(t, map[string]any{"role": "assistant", "content": []map[string]any{
{"type": "tool_use", "id": id, "name": "Read", "input": map[string]string{"file_path": id}}}})})
if rng.Intn(5) == 0 {
msgs = append(msgs, message{notice: notices[rng.Intn(len(notices))]})
}
msgs = append(msgs, message{json: mustJSON(t, map[string]any{"role": "user", "content": []map[string]any{
{"type": "tool_result", "tool_use_id": id, "content": fmt.Sprintf("result %d", step)}}})})
}
for n := rng.Intn(3); n > 0; n-- {
msgs = append(msgs, message{notice: notices[rng.Intn(len(notices))]})
}
requests = append(requests, render(msgs))
}
var before V1InternalRequest
for n, r := range requests {
now := transformClaudeCodeMessages(t, r...)
for i, c := range now.Request.Contents {
if c.Role == "system" || (i > 0 && now.Request.Contents[i-1].Role == c.Role) {
t.Logf("seed %d request %d: content %d has role %q after %q", seed, n, i, c.Role, now.Request.Contents[max(i-1, 0)].Role)
return false
}
}
if n > 0 {
if mustJSON(t, before.Request.SystemInstruction) != mustJSON(t, now.Request.SystemInstruction) {
t.Logf("seed %d request %d changed the systemInstruction", seed, n)
return false
}
for i := range before.Request.Contents {
if mustJSON(t, before.Request.Contents[i]) != mustJSON(t, now.Request.Contents[i]) {
t.Logf("seed %d request %d changed content %d", seed, n, i)
return false
}
}
}
before = now
}
return true
}
require.NoError(t, quick.Check(property, &quick.Config{MaxCount: 300}))
}
func TestSystemMessagesBeforeTheFirstModelTurnStayInSystemInstruction(t *testing.T) {
req := transformClaudeCodeMessages(t, ccAsk, ccEnvLatest, ccCall1, ccResult1, ccNoticeLast).Request
var system []string
for _, p := range req.SystemInstruction.Parts {
system = append(system, p.Text)
}
joined := strings.Join(system, "\n")
require.Contains(t, joined, "# Environment")
require.NotContains(t, joined, "Plain output style is active.")
}
func TestSystemNoticeFollowsTheToolResultsOfItsUserTurn(t *testing.T) {
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccResult1, ccNotice, ccCall2, ccResult2, ccNoticeLast).Request
require.Len(t, req.Contents, 5)
for i, c := range req.Contents {
require.NotEqual(t, "system", c.Role)
if i > 0 {
require.NotEqual(t, req.Contents[i-1].Role, c.Role, "contents %d and %d share a role", i-1, i)
}
}
for _, i := range []int{2, 4} {
parts := req.Contents[i].Parts
require.Equal(t, "user", req.Contents[i].Role)
require.Len(t, parts, 2)
require.NotNil(t, parts[0].FunctionResponse, "the tool result must come first")
require.Equal(t, "<system-reminder>\nPlain output style is active.\n</system-reminder>", parts[1].Text)
}
}
// A notice between a model turn and the user turn holding its tool results
// joins that user turn after the results: a functionCall must be followed
// directly by its functionResponse.
func TestSystemNoticeAfterAModelTurnWaitsForTheNextUserTurn(t *testing.T) {
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, ccCall1, ccNotice, ccResult1).Request
require.Len(t, req.Contents, 3)
require.Equal(t, "model", req.Contents[1].Role)
last := req.Contents[2]
require.Equal(t, "user", last.Role)
require.Len(t, last.Parts, 2)
require.NotNil(t, last.Parts[0].FunctionResponse)
require.Contains(t, last.Parts[1].Text, "Plain output style is active.")
}
func TestSystemNoticeEndingTheRequestAfterAModelTurnBecomesAUserTurn(t *testing.T) {
req := transformClaudeCodeMessages(t, ccAsk, ccEnv, `{"role":"assistant","content":"partial answer"}`, ccNotice).Request
require.Len(t, req.Contents, 3)
require.Equal(t, "model", req.Contents[1].Role)
require.Equal(t, "user", req.Contents[2].Role)
require.Contains(t, req.Contents[2].Parts[0].Text, "Plain output style is active.")
}
@@ -0,0 +1,137 @@
//go:build unit
package antigravity
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
// testBlock 是客户端看到的一个内容块:类型、文本(text 或 thinking)与签名。
type testBlock struct {
Type string
Text string
Signature string
}
// streamTestBlocks 按 SSE 事件重建客户端的内容块。
func streamTestBlocks(t *testing.T, sse string) []testBlock {
t.Helper()
var blocks []testBlock
for _, line := range strings.Split(sse, "\n") {
data, ok := strings.CutPrefix(line, "data: ")
if !ok {
continue
}
var event struct {
Type string `json:"type"`
ContentBlock map[string]any `json:"content_block"`
Delta map[string]any `json:"delta"`
}
require.NoError(t, json.Unmarshal([]byte(data), &event))
switch event.Type {
case "content_block_start":
block := testBlock{Type: event.ContentBlock["type"].(string)}
block.Signature, _ = event.ContentBlock["signature"].(string)
blocks = append(blocks, block)
case "content_block_delta":
last := &blocks[len(blocks)-1]
switch event.Delta["type"] {
case "text_delta":
last.Text += event.Delta["text"].(string)
case "thinking_delta":
last.Text += event.Delta["thinking"].(string)
case "signature_delta":
last.Signature = event.Delta["signature"].(string)
}
}
}
return blocks
}
func nonStreamTestBlocks(t *testing.T, body []byte) []testBlock {
t.Helper()
var resp struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
Thinking string `json:"thinking"`
Signature string `json:"signature"`
} `json:"content"`
}
require.NoError(t, json.Unmarshal(body, &resp))
blocks := make([]testBlock, 0, len(resp.Content))
for _, item := range resp.Content {
blocks = append(blocks, testBlock{Type: item.Type, Text: item.Text + item.Thinking, Signature: item.Signature})
}
return blocks
}
func TestDropTextSignatures(t *testing.T) {
tests := []struct {
name string
parts string
drop []testBlock
keep []testBlock
}{
{
name: "a signature on the final text part",
parts: `{"text":"Answer.","thoughtSignature":"SIG_TEXT"}`,
drop: []testBlock{{Type: "text", Text: "Answer."}},
keep: []testBlock{{Type: "text", Text: "Answer."}, {Type: "thinking", Signature: "SIG_TEXT"}},
},
{
name: "a signature in a trailing empty text part",
parts: `{"text":"Answer."},{"text":"","thoughtSignature":"SIG_TAIL"}`,
drop: []testBlock{{Type: "text", Text: "Answer."}},
keep: []testBlock{{Type: "text", Text: "Answer."}},
},
{
name: "a real thinking block keeps its signature",
parts: `{"text":"plan","thought":true,"thoughtSignature":"SIG_THOUGHT"},{"text":"Answer.","thoughtSignature":"SIG_TEXT"}`,
drop: []testBlock{{Type: "thinking", Text: "plan", Signature: "SIG_THOUGHT"}, {Type: "text", Text: "Answer."}},
keep: []testBlock{{Type: "thinking", Text: "plan", Signature: "SIG_THOUGHT"}, {Type: "text", Text: "Answer."},
{Type: "thinking", Signature: "SIG_TEXT"}},
},
{
name: "a function call keeps tool_use.signature",
parts: `{"text":"Reading.","thoughtSignature":"SIG_TEXT"},{"functionCall":{"name":"Read","args":{}},"thoughtSignature":"SIG_CALL"}`,
drop: []testBlock{{Type: "text", Text: "Reading."}, {Type: "tool_use", Signature: "SIG_CALL"}},
keep: []testBlock{{Type: "text", Text: "Reading."}, {Type: "thinking", Signature: "SIG_TEXT"},
{Type: "tool_use", Signature: "SIG_CALL"}},
},
{
name: "text split around a signed part stays in order",
parts: `{"text":"One "},{"text":"two ","thoughtSignature":"SIG_TEXT"},{"text":"three."}`,
drop: []testBlock{{Type: "text", Text: "One two three."}},
},
}
for _, tt := range tests {
chunk := `{"candidates":[{"content":{"role":"model","parts":[` + tt.parts + `]},"finishReason":"STOP"}]}`
for _, drop := range []bool{true, false} {
want := tt.keep
mode := "keep"
if drop {
want, mode = tt.drop, "drop"
}
if want == nil {
continue
}
t.Run("stream/"+mode+"/"+tt.name, func(t *testing.T) {
processor := NewStreamingProcessor("gemini-4-neon")
processor.SetDropTextSignatures(drop)
out := string(processor.ProcessLine("data: " + chunk))
final, _ := processor.Finish()
require.Equal(t, want, streamTestBlocks(t, out+string(final)))
})
t.Run("non-stream/"+mode+"/"+tt.name, func(t *testing.T) {
body, _, err := TransformGeminiToClaudeWithOptions([]byte(chunk), "gemini-4-neon", ResponseTransformOptions{DropTextSignatures: drop})
require.NoError(t, err)
require.Equal(t, want, nonStreamTestBlocks(t, body))
})
}
}
}
@@ -0,0 +1,66 @@
//go:build unit
package antigravity
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestThinkingSignaturePrefixMarksOnlyThinkingBlocks(t *testing.T) {
const chunk = `{"candidates":[{"content":{"role":"model","parts":[` +
`{"text":"plan","thought":true,"thoughtSignature":"SIG_THOUGHT"},` +
`{"functionCall":{"name":"Read","args":{}},"thoughtSignature":"SIG_CALL"},` +
`{"text":"Done.","thoughtSignature":"SIG_TAIL"}]},"finishReason":"STOP"}]}`
for _, prefix := range []string{"", "p:"} {
t.Run("stream/prefix="+prefix, func(t *testing.T) {
processor := NewStreamingProcessor("gemini-4-neon")
processor.SetThinkingSignaturePrefix(prefix)
out := string(processor.ProcessLine("data: " + chunk))
final, _ := processor.Finish()
out += string(final)
var thinking, toolUse []string
for _, line := range strings.Split(out, "\n") {
data, ok := strings.CutPrefix(line, "data: ")
if !ok {
continue
}
var event map[string]any
require.NoError(t, json.Unmarshal([]byte(data), &event))
if delta, _ := event["delta"].(map[string]any); delta["type"] == "signature_delta" {
thinking = append(thinking, delta["signature"].(string))
}
if block, _ := event["content_block"].(map[string]any); block["type"] == "tool_use" {
toolUse = append(toolUse, block["signature"].(string))
}
}
require.Equal(t, []string{prefix + "SIG_THOUGHT", prefix + "SIG_TAIL"}, thinking)
require.Equal(t, []string{"SIG_CALL"}, toolUse)
})
t.Run("non-stream/prefix="+prefix, func(t *testing.T) {
body, _, err := TransformGeminiToClaudeWithOptions([]byte(chunk), "gemini-4-neon", ResponseTransformOptions{ThinkingSignaturePrefix: prefix})
require.NoError(t, err)
var resp struct {
Content []map[string]any `json:"content"`
}
require.NoError(t, json.Unmarshal(body, &resp))
var thinking, toolUse []string
for _, block := range resp.Content {
switch block["type"] {
case "thinking":
thinking = append(thinking, block["signature"].(string))
case "tool_use":
toolUse = append(toolUse, block["signature"].(string))
}
}
require.Equal(t, []string{prefix + "SIG_THOUGHT", prefix + "SIG_TAIL"}, thinking)
require.Equal(t, []string{"SIG_CALL"}, toolUse)
})
}
}
@@ -0,0 +1,39 @@
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestAnthropicRequest_TopLevelCacheControlJSON(t *testing.T) {
t.Run("omitted when nil", func(t *testing.T) {
req := AnthropicRequest{
Model: "claude-opus-5-5",
MaxTokens: 1024,
Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
}
raw, err := json.Marshal(req)
require.NoError(t, err)
require.NotContains(t, string(raw), `"cache_control"`)
})
t.Run("round-trips top-level cache_control", func(t *testing.T) {
req := AnthropicRequest{
Model: "claude-opus-5-5",
MaxTokens: 1024,
Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}},
CacheControl: &AnthropicCacheControl{Type: "ephemeral", TTL: "1h"},
}
raw, err := json.Marshal(req)
require.NoError(t, err)
require.Contains(t, string(raw), `"cache_control":{"type":"ephemeral","ttl":"1h"}`)
var decoded AnthropicRequest
require.NoError(t, json.Unmarshal(raw, &decoded))
require.NotNil(t, decoded.CacheControl)
require.Equal(t, "ephemeral", decoded.CacheControl.Type)
require.Equal(t, "1h", decoded.CacheControl.TTL)
})
}
@@ -0,0 +1,86 @@
package apicompat
import (
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestAnthropicRequestBridges_ImageSources(t *testing.T) {
const imageURL = "https://example.com/screenshot.png?version=1&format=png"
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jkXcAAAAASUVORK5CYII="
for _, source := range []struct {
name string
raw string
want string
}{
{"url", `{"type":"url","url":"` + imageURL + `"}`, imageURL},
{"base64_control", `{"type":"base64","media_type":"image/png","data":"` + png + `"}`, "data:image/png;base64," + png},
} {
image := `{"type":"image","source":` + source.raw + `}`
for _, context := range []struct {
name string
messages string
}{
{"user_image", `[{"role":"user","content":[` + image + `,{"type":"text","text":"Describe this image."}]}]`},
{"tool_result_image", `[
{"role":"user","content":"Inspect the screenshot."},
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_image","name":"inspect","input":{}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_image","content":[` + image + `,{"type":"text","text":"The screenshot is attached."}]}]}
]`},
} {
raw := fmt.Sprintf(`{"model":"gpt-4o","max_tokens":1024,"tools":[{"name":"inspect","input_schema":{"type":"object","properties":{}}}],"messages":%s}`, context.messages)
t.Run(source.name+"/"+context.name+"/chat_completions", func(t *testing.T) {
var req AnthropicRequest
require.NoError(t, json.Unmarshal([]byte(raw), &req))
out, err := AnthropicToChatCompletionsRequest(&req)
require.NoError(t, err)
wire, err := json.Marshal(out)
require.NoError(t, err)
var upstream ChatCompletionsRequest
require.NoError(t, json.Unmarshal(wire, &upstream))
var got []string
for _, msg := range upstream.Messages {
var parts []ChatContentPart
if json.Unmarshal(msg.Content, &parts) != nil {
continue
}
for _, part := range parts {
if part.Type == "image_url" && part.ImageURL != nil {
got = append(got, part.ImageURL.URL)
}
}
}
require.Equal(t, []string{source.want}, got, "the image must reach the upstream as image_url")
})
t.Run(source.name+"/"+context.name+"/responses", func(t *testing.T) {
var req AnthropicRequest
require.NoError(t, json.Unmarshal([]byte(raw), &req))
out, err := AnthropicToResponses(&req)
require.NoError(t, err)
wire, err := json.Marshal(out)
require.NoError(t, err)
var upstream ResponsesRequest
require.NoError(t, json.Unmarshal(wire, &upstream))
var items []ResponsesInputItem
require.NoError(t, json.Unmarshal(upstream.Input, &items))
var got []string
for _, item := range items {
if len(item.Content) == 0 {
continue
}
var parts []ResponsesContentPart
require.NoError(t, json.Unmarshal(item.Content, &parts))
for _, part := range parts {
if part.Type == "input_image" {
got = append(got, part.ImageURL)
}
}
}
require.Equal(t, []string{source.want}, got, "the image must reach the upstream as input_image")
})
}
}
}
Loaded 100 of 557 files, more files were not shown because too many files have changed in this diff. Show more