Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs: GHSA-p3r4-jcm3-2hph

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Changes:

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

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

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

Existing benchmarks:

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

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

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

Three avoidable copies showed up in that path:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

All three are required:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

同步升级 8 处版本点:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

修复:

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

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

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

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

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

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

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

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

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

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

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

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

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

同步升级 8 处版本点:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Same order and amount now map to the same Alipay refund request; the
existing QueryRefund prefix contract is unchanged.
2026-11-10 23:56:34 +08:00
xy3 6a2c744af3 Merge main and reconcile overlapping Claude 5.2 pricing 2026-11-10 22:24:20 +08:00
Wesley Liddick e2c9812190 Merge pull request #8357 from ychy7001/fix/audit-worker-wake
fix(securityaudit): 审计任务入队后立即唤醒本进程 worker
2026-11-10 21:30:34 +08:00
Wesley Liddick 2cc43fdeff Merge pull request #8575 from WGeorgezzzz/fix/openai-responses-reject-invalid-utf8
fix(openai): reject invalid UTF-8 Responses bodies
2026-11-10 21:30:26 +08:00
Wesley Liddick e6981f0ffd Merge pull request #8379 from danvilig/codex/fix-native-image-error-status
fix(openai): preserve native Codex image error statuses
2026-11-10 21:30:19 +08:00
Wesley Liddick b045db4a40 Merge pull request #8622 from Hato626/fix/codex-page-context
fix(openai): normalize Codex Desktop page context before tool validation
2026-11-10 21:30:14 +08:00
Wesley Liddick 41e4a6b108 Merge pull request #8367 from SmallNew2003/feat/settings-save-dock
feat(settings): 系统设置保存按钮改为底部吸附浮标
2026-11-10 21:30:08 +08:00
Wesley Liddick 48b11bf743 Merge pull request #8642 from baowl2022/fix/balance-recharge-multiplier-6-decimals
fix(payment): support up to 6 decimals for balance recharge multiplier
2026-11-10 21:30:02 +08:00
Wesley Liddick 51a0e89b8b Merge pull request #8581 from Ming-Sir-69/fix/accounts-refresh-stability
fix(accounts): retain rows and quota values while refreshing
2026-11-10 21:29:56 +08:00
Wesley Liddick a870836599 Merge pull request #8346 from hezhaoqian1/perf/upstream-keys-usage-index
perf(keys): API 密钥列表不再等待 30 天用量统计,并为其加覆盖索引
2026-11-10 21:29:51 +08:00
Wesley Liddick 5fe13c3c48 Merge pull request #8161 from wucm667/fix/issue-8156-synthesized-reasoning-mapping
fix(openai): apply mappings to synthesized reasoning effort
2026-11-10 21:29:45 +08:00
Wesley Liddick efdc399ecf Merge pull request #8637 from lishuangqiang/fix/atomic-refresh-token-rotation
fix(auth): consume refresh tokens atomically during rotation
2026-11-10 21:29:40 +08:00
Wesley Liddick b455228b46 Merge pull request #8631 from lishuangqiang/fix/slot-leak-on-hydrate-error
fix(scheduling): release acquired slot when account hydration fails
2026-11-10 21:29:34 +08:00
Wesley Liddick d18e1dff60 Merge pull request #8566 from r266-tech/codex/easypay-refund-success-code
fix(payment): configure EasyPay refund success codes per instance
2026-11-10 21:29:29 +08:00
Wesley Liddick 968c1022e6 Merge pull request #8568 from r266-tech/codex/pro-argon-cooldown
fix(antigravity): isolate Pro Argon quota cooldowns
2026-11-10 21:29:24 +08:00
Wesley Liddick 6f6b54d316 Merge pull request #8621 from baryon/contrib/antigravity-parallel-tool-result-images
fix(antigravity): keep parallel tool functionResponses contiguous before media
2026-11-10 21:29:18 +08:00
Wesley Liddick 350c800449 Merge pull request #8584 from feeeei/fix/gemini-nonstream-thought-parts
fix(gemini): 兼容入口非流式响应不再把思考摘要混入正文
2026-11-10 21:29:13 +08:00
Wesley Liddick 9de6dd766b Merge pull request #8385 from r266-tech/codex/compat-account-error-policy
fix(gateway): honor account error policies in compatibility paths
2026-11-10 21:29:07 +08:00
Wesley Liddick f7ddfb8236 Merge pull request #8589 from r266-tech/codex/stable-responses-session-prefix
fix(openai): stabilize Responses session seeds across tool loops
2026-11-10 21:29:02 +08:00
Wesley Liddick 73e75a18d1 Merge pull request #8386 from r266-tech/codex/skip-foreign-reasoning-envelope
fix(apicompat): skip foreign CC Switch reasoning envelopes
2026-11-10 21:28:56 +08:00
Wesley Liddick aa56a4606d Merge pull request #8585 from r266-tech/codex/preserve-sealed-response-calls
fix(apicompat): preserve sealed function call metadata
2026-11-10 21:28:50 +08:00
Wesley Liddick 6e128ba405 Merge pull request #8579 from r266-tech/codex/honor-overload-model-cooldown
fix(openai): honor explicit model cooldowns for capacity errors
2026-11-10 21:28:45 +08:00
Wesley Liddick fc9d811385 Merge pull request #8576 from WGeorgezzzz/fix/openai-codex-metadata-events
fix(openai): keep Codex metadata events retry-safe
2026-11-10 21:28:39 +08:00
Wesley Liddick 32d0576edc Merge pull request #8565 from qsy4/fix/openai-ws-ttft-mode
fix(openai-ws): follow the TTFT mode for WebSocket first token
2026-11-10 21:28:32 +08:00
Wesley Liddick 9725718e12 Merge pull request #8358 from AndersonBY/codex/fix-oauth-ws-search-activation
fix(openai-ws): reconnect pooled OAuth sockets before search activation
2026-11-10 21:28:26 +08:00
Wesley Liddick 2fd34acc1f Merge pull request #8564 from r266-tech/codex/native-ws-later-turn-fail-closed
fix(openai): stop native WS later-turn first-frame replay
2026-11-10 21:28:20 +08:00
Wesley Liddick d216e42156 Merge pull request #8634 from r266-tech/codex/claude52-pricing
fix(pricing): add Claude Fable and Mythos 5.2 fallback rates
2026-11-10 21:28:14 +08:00
Wesley Liddick 1cae79565a Merge pull request #8384 from r266-tech/codex/pricing-sync-body-hash
fix(pricing): retry sync after catalog hash mismatch
2026-11-10 21:28:08 +08:00
Wesley Liddick 722bbf6dbe Merge pull request #8381 from r266-tech/codex/sonnet55-cache-read-pricing
fix: correct Sonnet 5.5 cache read fallback pricing
2026-11-10 21:28:02 +08:00
xy3 ea6b3de808 test: keep Claude Code version fixtures above the built-in floor 2026-11-10 20:05:28 +08:00
r266-tech c115dc27ab fix(usage): read Fable weekly quotas from scoped limits 2026-11-10 19:37:32 +08:00
baowl2022 edd7db77fe fix(payment): support up to 6 decimals for balance recharge multiplier
Persist BALANCE_RECHARGE_MULTIPLIER with up to 6 decimal places so operators
can track a live FX rate (e.g. 1 USD = 7.100000 CNY -> 0.140845). Values with
more than 6 decimals are rejected instead of being silently truncated.
Credited balance still rounds to settlement-currency precision, so order and
ledger semantics are unchanged.

Adds backend unit tests and a frontend formatter test; updates the admin input
step/preview and the checkout rate display.
2026-11-10 18:47:03 +08:00
lishuangqiang 7122efee94 fix(auth): consume refresh tokens atomically during rotation
RefreshTokenPair read the token and deleted it in two Redis calls. Two
concurrent requests with the same refresh token both passed the read and
validation, so both could mint a new token pair, keeping a stolen token
alive across rotations.

Add an atomic ConsumeRefreshToken (Lua GET+DEL) and require rotation to
win that consume. Losers get ErrRefreshTokenInvalid; Redis errors now
fail closed instead of issuing a new pair without invalidating the old
token.
2026-11-10 15:03:59 +08:00
r266-tech 3e8c2ee3f7 fix(pricing): add Claude Fable and Mythos 5.2 fallback rates 2026-11-10 13:58:08 +08:00
xy3 eb2da34484 feat(gateway): support Claude Fable and Mythos 5.2 2026-11-10 12:01:31 +08:00
lishuangqiang 4ac713c4d4 fix(scheduling): release acquired slot when account hydration fails
newSelectionResult is the only exit for acquired Anthropic/Gemini
selections. When hydrateSelectedAccount failed, the already acquired
Redis concurrency slot was dropped with the error because callers only
receive ReleaseFunc through a successful result.

Release it on the error path, matching the OpenAI path that already does
this via newAcquiredSelectionResult. Without the fix the slot stays
occupied until its TTL expires, so the account can look idle while
requests queue or fail.
2026-11-10 10:55:01 +08:00
wucm667 661770bf34 fix(usage): reconcile Anthropic and OpenAI cache TTL accounting 2026-11-10 10:01:06 +08:00
wucm667 f6ea845c58 fix(openai): preserve configured GLM downgrade semantics 2026-11-10 10:00:55 +08:00
Hato b2a695d617 fix(openai): normalize Codex Desktop page context 2026-11-09 18:41:16 +09:00
Long Li e2ce0b43dc fix(TASK-144): keep Antigravity tool functionResponses contiguous before media 2026-11-09 17:29:00 +09: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
Wesley Liddick ee58c0013c Merge pull request #8606 from r266-tech/codex/preserve-openai-cache-write-ttl
fix(openai): preserve cache-write TTLs in usage and billing
2026-11-09 11:07:27 +08:00
Wesley Liddick 8ca1a613e9 Merge pull request #8590 from william-drakemond/pr/antigravity-usage-query
feat(antigravity): 用量格子加查询按钮,强制查询跳过缓存 / Query button for antigravity usage; force skips the cache
2026-11-09 11:07:16 +08:00
Wesley Liddick 27ef2a7137 Merge pull request #8603 from lkon2112/fix/openai-orphan-allocation-test
test(openai): isolate orphan precheck allocation test
2026-11-09 11:07:01 +08:00
Wesley Liddick 8e649dd654 Merge pull request #8607 from r266-tech/codex/document-image-format-mismatches
docs(images): explain upstream output format mismatches
2026-11-09 10:47:52 +08:00
Wesley Liddick d7c0505387 Merge pull request #8610 from Wei-Shaw/fix/adaptive-request-body-budget
fix(gateway): auto-size request body memory budget from the memory limit
2026-11-09 10:44:06 +08:00
shaw 03bd718abe fix(sysutil): confine cgroup limit reads to the mount with os.Root
gosec G703 flagged the cgroup path taken from /proc/self/cgroup flowing
into os.ReadFile. Read the limit files through os.Root instead, so the
path can never resolve outside the cgroup mount (including via symlinks),
and cover the escape cases in tests.
2026-11-09 10:27:08 +08:00
shaw c004c962a7 fix(gateway): auto-size request body memory budget from the memory limit
The 1 GiB default introduced in v0.2.20 is shared by every group on an
instance and stays charged for the whole streaming response, so large
hosts under high concurrency returned 503 "Request body buffering capacity
is exhausted" long before memory was actually short.

When gateway.request_body_memory_budget_bytes is set in neither the config
file nor a non-empty env var, size it to 1/4 of the process memory limit
(min of physical RAM, cgroup v1/v2 limit along the cgroup path, and
GOMEMLIMIT), never below the previous 1 GiB. Explicit values, including 0,
are used as-is. The example config no longer pins 1 GiB.
2026-11-09 10:13:11 +08:00
r266-tech 9935268573 docs(images): align model scope across translations 2026-11-08 23:47:19 +08:00
r266-tech 5184ff55f6 docs(images): explain upstream output format mismatches 2026-11-08 23:31:10 +08:00
r266-tech 7156213cce fix(openai): retain Fast multiplier with free input prices 2026-11-08 22:12:23 +08:00
r266-tech fe093d76bd fix(openai): preserve cache-write TTLs in usage and billing 2026-11-08 22:00:15 +08:00
lkon 2273a5d63f test(openai): isolate orphan precheck allocation test 2026-11-08 19:33:33 +08:00
lkon 8a1315e8cc test(billing): reuse rate resolver and isolate heap checks 2026-11-08 16:43:43 +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
William DrakeandClaude Opus 5.5 4ac1675b56 feat(antigravity): query button that refreshes usage past the cache
Antigravity accounts had no manual query button in the usage cell, unlike Claude
and OpenAI, and the server ignored force=true for them: getAntigravityUsage
always answered from its in-memory cache while fresh. After an upgrade or an
upstream reset the cell kept old figures (an account upgraded to Ultra still
showed its Claude week at 100%).

- getAntigravityUsage takes force; cachedAntigravityUsage skips the cache when
  forced. singleflight still merges concurrent fetches.
- The antigravity cell shows the same 查询/Query button (active, force=true) in
  every state, including errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 14:33:29 -07:00
r266-tech 85f43b640a fix(openai): stabilize Responses session seeds across tool loops 2026-11-08 04:52:04 +08:00
r266-tech f2b0a32b1f fix(apicompat): preserve sealed function call metadata 2026-11-08 02:48:04 +08:00
feeeei 36484727c7 fix(gemini): 兼容入口非流式响应不再把思考摘要混入正文
部分上游在未请求 includeThoughts 时仍返回 thought=true 的 part,非流式转换把它当正文输出,导致 chat/messages 的 content 混入思考文字。转换时跳过思考 part 的文字,与流式路径的分流口径一致;用量仍取自 usageMetadata,计费不变。
2026-11-08 02:01:08 +08:00
Ming-Sir-69 4a22a75b3d fix(accounts): retain rows and quota values while refreshing 2026-11-07 23:32:29 +08:00
r266-tech a1395eeaf2 fix(openai): preserve other platforms' capacity handling 2026-11-07 21:35:48 +08:00
r266-tech 88b7090a35 fix(openai): match cooldown rules against actual error fields 2026-11-07 21:28:51 +08:00
r266-tech ebf0168085 fix(openai): honor explicit model cooldown rules for overloads 2026-11-07 21:07:52 +08:00
WGeorgezzzz 189b336f47 fix(openai): enforce stream idle deadlines and pre-output failover 2026-11-07 19:45:33 +08:00
WGeorgezzzz e401c58053 fix(openai): keep Codex metadata events retry-safe 2026-11-07 19:36:05 +08:00
WGeorgezzzz 63f1172292 fix(openai): reject invalid UTF-8 Responses bodies 2026-11-07 19:23:53 +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
r266-tech 7796a2d57a fix(antigravity): isolate Pro Argon quota cooldowns 2026-11-07 14:35:15 +08:00
github-actions[bot] 6b4b37db43 chore: sync VERSION to 0.2.20 [skip ci] 2026-11-07 06:31:41 +00:00
Wesley Liddick dab829a4e9 Merge pull request #8365 from lyy0709/codex/gpt61-terra-followup
fix(openai): complete GPT-6.1 Terra Codex metadata, validation and billing
2026-11-07 14:06:18 +08:00
r266-tech 137316a14c fix(payment): configure EasyPay refund success codes per instance 2026-11-07 11:29:13 +08:00
Wesley Liddick d22e0724d6 Merge pull request #8380 from danvilig/codex/improve-codex-native-tools-export
fix(frontend): improve Codex image and live-search exports
2026-11-07 11:27:14 +08:00
qsy4 fab3ec2516 fix(openai-ws): follow the TTFT mode for WebSocket first token
Problem: SSE streams decide first-token time with the admin
openai_ttft_mode setting (semantic: first non-lifecycle event; visible:
first visible output), but WebSocket passthrough turns always wait for
the first ".delta" event and ignore the setting. On reasoning models the
reasoning item is announced when reasoning starts while the first delta
only arrives after it ends, so in semantic mode a WS turn reports the
reasoning time as first-token latency and an HTTP request does not. The
same user's WS turns look seconds slower than their HTTP requests, and
the gap grows with reasoning tokens while the HTTP numbers stay flat.

Fix: let RelayOptions take the first-token rule and have the passthrough
adapter pass the configured TTFT mode through the same check the SSE
path uses (openAIStreamDataStartsTTFT). codex.* frames are WebSocket-only
out-of-band events and never count; terminal events still never count,
as before. Without a rule the relay keeps the delta-based behaviour.

Test: TestOpenAIWSPassthroughFirstTokenFollowsTTFTMode replays two
reasoning turns on one passthrough connection in both modes and expects
each turn's first token at the event the SSE rule picks.
TestRelay_IsFirstTokenEventDecidesEveryTurnFirstToken checks the relay
applies the injected rule per turn and still skips terminal events.
2026-11-06 19:10:49 -08:00
Wesley Liddick 2c93aea9f7 Merge pull request #8420 from wozhenbang2004/fix/cloudflare-rest-messages-beta
fix(anthropic): omit beta query for Cloudflare REST messages
2026-11-07 11:03:42 +08:00
Wesley Liddick 2fcd47aa13 Merge pull request #8409 from unique01082/fix/antigravity-response-json-schema
fix(antigravity): Gemini 原生请求的 responseJsonSchema 改写为 responseSchema
2026-11-07 11:01:19 +08:00
Wesley Liddick c0a3ce60b6 Merge pull request #8471 from qsy4/fix/auth-client-gone-malformed-key
fix(auth): stop reporting client disconnects and malformed keys as 500
2026-11-07 10:58:24 +08:00
Wesley Liddick a2f7c12cdd Merge pull request #8464 from kiuber/fix/ws-http-bridge-codex-fingerprint
fix(openai): apply Codex fingerprint convergence in the WebSocket HTTP bridge so multi-turn requests hit the prompt cache
2026-11-07 10:58:12 +08:00
Wesley Liddick ec5ee14ca5 Merge pull request #8520 from qsy4/fix/openai-ws-per-turn-first-token
fix(openai-ws): record first token time for every passthrough turn
2026-11-07 10:57:49 +08:00
Wesley Liddick e479d5d249 Merge pull request #8445 from folltoshe/fix/openai-responses-probe-forced-mode
fix(openai): skip responses probe when routing mode is forced
2026-11-07 10:57:36 +08:00
Wesley Liddick 38029f3d21 Merge pull request #8432 from 111pointer111/fix/gpt-image-account-test-response-format
fix(openai): omit response_format from GPT Image account tests
2026-11-07 10:57:22 +08:00
Wesley Liddick 52c83021e3 Merge pull request #8441 from mordekasiser/codex/fix-antigravity-direct-response
fix(antigravity): preserve direct Gemini streaming responses
2026-11-07 10:56:42 +08:00
Wesley Liddick 66ea4d311f Merge pull request #8553 from Yajun312890225/codex/fix-claude-setup-token-weekly-usage
fix(anthropic): preserve setup-token weekly usage without 5h limits
2026-11-07 10:55:20 +08:00
Wesley Liddick 3c46c12833 Merge pull request #8522 from william-drakemond/pr/antigravity-quota-summary
feat(antigravity): 按配额分组显示真实的 5 小时与每周窗口 / Show each quota group's real 5-hour and weekly window
2026-11-07 10:55:02 +08:00
Wesley Liddick 72c2acdcb9 Merge pull request #8457 from cyhhao/fix/request-body-read-timeout
fix(gateway): report request body read timeouts as 408 and log read failures
2026-11-07 10:54:39 +08:00
Wesley Liddick 0ff31d7a99 Merge pull request #8557 from hansnow/codex/gpt-image-26
fix(openai): 打通 GPT Image 2.6 原生图片链路
2026-11-07 10:54:20 +08:00
Wesley Liddick 9aaa72cabd Merge pull request #8430 from lkon2112/fix/gemini-tool-response-media
fix(gemini): preserve tool media in native function responses
2026-11-07 10:53:56 +08:00
Wesley Liddick 1209e71e6d Merge pull request #8437 from m11y/fix/error-passthrough-before-body-limit-failover
fix(openai): let error passthrough rules override the built-in body-limit 413
2026-11-07 10:53:41 +08:00
Wesley Liddick c86645c3b6 Merge pull request #8521 from william-drakemond/pr/antigravity-internal500-scope
fix(antigravity): INTERNAL 500 只冷却出错的图像模型,账号惩罚档位可配置 / Scope INTERNAL 500 penalties to image models; configurable account tiers
2026-11-07 10:53:16 +08:00
Wesley Liddick c70ef412e3 Merge pull request #8531 from william-drakemond/pr/antigravity-test-prompt
fix(antigravity): 账号测试发送管理员输入的提示词并允许模型作答 / Account test sends the admin's prompt and lets the model answer
2026-11-07 10:52:57 +08:00
Wesley Liddick 2ee66a660f Merge pull request #8429 from lkon2112/fix/responses-message-content
fix(responses): preserve message content fields in completed responses
2026-11-07 10:52:25 +08:00
Wesley Liddick b628339986 Merge pull request #8563 from r266-tech/codex/buffered-reasoning-content
fix(apicompat): preserve buffered reasoning content
2026-11-07 10:52:10 +08:00
shaw e6c19082f2 chore: update sponsors 2026-11-07 09:49:12 +08:00
r266-tech 0578fb160e fix(openai): stop native WS later-turn first-frame replay 2026-11-07 09:40:59 +08:00
r266-tech 30ec2ecc98 fix(apicompat): preserve buffered reasoning content 2026-11-07 04:47:20 +08:00
cyh 22693fb4fe fix(grok): classify Grok Voice body read failures
Stalled uploads to /v1/tts, /v1/stt and /v1/custom-voices reach GrokVoice
directly. Its read errors fell through to a 400 carrying err.Error(): with
the read timeout now preserved, that reported a timeout as a malformed
request and returned the raw socket error. Keep the validation message for
a missing body and send every read error through the shared classifier.
2026-11-07 02:07:37 +08:00
cyh fdfadb2442 Merge upstream main; classify WithBodyReadTimeout failures
Upstream added WithBodyReadTimeout (gateway.request_body_read_timeout_seconds)
and client-gone handling for body reads. Drop this branch's own server-level
idle-timeout wrapper and server.request_body_idle_timeout setting in favor of
it, and keep the classification and diagnostics on top:

- readRequestBodyChunksWithBudget reports the read error before ctx.Err():
  on HTTP/1 a read deadline also cancels the request context, which turned
  every timeout into context.Canceled. Read errors carry bytes read and
  elapsed time in RequestBodyReadError.
- handleRequestBodyReadError and RejectRequestBodyReadError skip the
  client-gone (empty 499) path for read timeouts, so they are reported as
  408 instead of a client cancellation (HTTP/1) or a generic 400 (HTTP/2).
- Every gateway body read site and both body-reading middlewares log
  payload-free diagnostics, including the client-gone path.
2026-11-07 01:52:36 +08:00
lkon f9d1b10c2c Merge remote-tracking branch 'upstream/main' into fix/gemini-tool-response-media 2026-11-07 00:47:34 +08:00
lkon b7c0e9c90b Merge remote-tracking branch 'upstream/main' into fix/responses-message-content 2026-11-07 00:47:33 +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
Wesley Liddick 0eee80ba87 Merge pull request #8518 from StarryKira/codex/json-hotpath-performance
perf(gateway): reduce JSON copies and repeated request parsing
2026-11-06 18:49:10 +08:00
harukaandClaude Opus 5.5 1c83bb825a test(repository): assert the auth projection carries require_privacy_set
OpenAI scheduling now reads the privacy gate from the auth snapshot; cover
the GetByKeyForAuth projection so a dropped column fails here instead of
admitting accounts without privacy set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 f654c23eb7 perf(gateway): decide thinking-block filtering without decoding the body
FilterThinkingBlocks runs on every Anthropic forward. Its substring fast path
matches any request with top-level thinking config or signed thinking
history, which is nearly all Claude Code traffic, so it decoded the whole body
into a map even when nothing would be filtered.

Mirror the filter decision on borrowed gjson views, applying encoding/json's
last-wins rule for duplicate keys, and return the body untouched when no block
would be dropped. Bodies that need filtering still take the original decode
and marshal path, so output bytes are unchanged; a differential test and fuzz
target compare both paths.

On a 450 KB signed history: 1.29 ms, 904 KB, 10,629 allocs -> 0.67 ms, 0 B.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 4ca1a2097c perf(openai): skip full-body decodes for Codex bootstrap and compaction
Every /v1/responses request ran the automation and delegation bootstrap
normalizers, each a json.Decoder token scan plus a full map decode, and
NormalizeCompactionTriggerInputOrder decoded the whole body on each HTTP
request and WebSocket turn, although almost none of them can change it.

- Bootstrap normalizers return early unless the raw body contains
  function_call_output and one of their tool names, or any \u escape that
  could spell them.
- The compaction normalizer returns early when the body has neither
  compaction_trigger nor a \u escape and is a valid JSON object, so invalid
  or non-object bodies still report the original decode error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 00660a227a perf(gemini): stop copying the emitted prefix on every stream delta
computeGeminiTextDelta returned seen+incoming for each incremental chunk, so
a long thinking, text or tool-argument block copied its whole prefix per
chunk and grew quadratically.

Keep the emitted text in a strings.Builder per block. Only storage changes:
the cumulative, duplicate/rewind and delta decisions and the returned deltas
are identical, verified against the previous implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 d446c4a6bb fix(gemini): bound upstream SSE lines and antigravity non-stream reads
The Gemini native, Claude-compat, Chat Completions-compat and stream collector
paths read upstream SSE with bufio.Reader.ReadString, so a custom base_url
upstream that never sends a newline could grow one line without limit.

- Read these streams through boundedSSELineReader, which keeps line endings
  and EOF semantics and enforces the configured line and event limits. An
  overflow is a stream read error; no truncated prefix is forwarded.
- Thread cfg into collectGeminiSSE/collectGeminiSSEObserved.
- Antigravity ForwardUpstream reads non-stream responses with
  ReadUpstreamResponseBody instead of an unlimited io.ReadAll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 9bb073d0d1 perf(openai): read the group privacy gate from the auth snapshot
Each OpenAI account selection read the group row twice: once to resolve
require_privacy_set into the request, and again in selectByLoadBalance,
which ignored that result.

- Project require_privacy_set into the auth snapshot (v27) and resolve it
  from the ctx group when it is the scheduled group; composite members and
  other mismatches still read the repository.
- selectByLoadBalance filters on the already-resolved req.RequirePrivacySet,
  so a failed group read is handled once, fail-closed, as in Select.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 76221c9cb0 perf(billing): stop querying the RPM override on every request
The auth snapshot stored "no override" and "lookup failed" both as nil, so
checkRPM fell back to SELECT rpm_override on nearly every gateway request.

Record the group whose override lookup succeeded (snapshot v26). checkRPM
trusts a nil override only for that group; lookup failures and other groups,
such as composite members, still query the database. Admin override writes
already invalidate the auth cache by group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 a0b058a9e9 fix(bedrock): validate EventStream frame lengths before allocating
The decoder allocated total_length bytes straight from the upstream prelude
(up to ~4 GiB) and sliced headers by an unchecked headers_length, which could
panic in the decode goroutine outside gin's recovery and crash the process.

Reject frames whose headers exceed 128 KiB or the frame, or whose payload
exceeds 16 MiB (the AWS EventStream protocol limits), before allocating.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 0853d16036 fix(images): give async image tasks their own body memory reservation
Async tasks inherited the ingress reservation through context.WithoutCancel,
but RequestBodyLimit releases and closes it when Submit returns. The task's
request body was a plain reader, so the gateway's read reserved against the
closed reservation and every task failed with a 503 budget error.

- Add httputil.DetachRequestBodyMemory: a reservation on the same budget that
  the handler's release does not close. It takes over the retained body's
  existing charge from the request and reserves only the remainder, so the
  body is never counted twice; the caller releases it when the work ends.
- Submit reserves the retained body before creating the task, returning 503
  with Retry-After on exhaustion instead of accepting a task that cannot run;
  the task releases it when execution finishes.
- Back the task request with PrereadBody so the body is not buffered again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
harukaandClaude Opus 5.5 957a83f32e fix(gateway): settle patch budget per attempt and keep map fallback reachable
- ApplyPatches reserves the input size before editing on every strategy
  (batched Doc, single edit, sequential sjson), settles to the exact output
  length, and refunds on failure, so batching no longer adds a rejection
  that the unoptimized paths bypass.
- Forward holds patched outputs in a WithRequestBodyMemoryScope: a newer
  output releases the superseded one and the last is returned when the
  attempt ends, instead of accumulating across failovers until the handler
  returns.
- A Doc edit error retries with sequential sjson; when raw edits cannot
  express the patch set, Forward replays it onto the decoded map rather than
  re-running ApplyPatches and failing the request.
- Snapshot reuse in CloneForBody/ReplaceBody also checks a maphash content
  fingerprint, so in-place edits of shared storage reparse.
- Reuse openAIWSPayloadStringView for borrowed views and split batch path
  eligibility into isOpenAIBatchPatchPath with an O(P^2) ancestor check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 03:00:03 -05:00
haruka 6c140b8976 perf(gateway): reduce JSON copies and repeated request parsing 2026-11-06 03:00:02 -05:00
hansnow 7f2876defa fix(openai): 打通 GPT Image 2.6 原生图片链路
让 2.6 走 Codex Images,保留 complexity 和原生编辑选项。兼容编辑端点返回的完整 JSON,并补齐模型目录、格式处理和计费兜底。

Fixes #8526
Closes #8534
2026-11-06 15:30:49 +08:00
wucm667 3bf2a375db chore: reconcile upstream transcript and security fixes 2026-11-06 12:41:14 +08:00
wucm667 4656364337 test(usage): assert incomplete cache streams and isolate allocation guard 2026-11-06 12:13:35 +08:00
wucm667 b25dbe3e4b chore: sync upstream main for cache usage validation 2026-11-06 12:13:35 +08:00
Yajun a8d90a72ea fix(anthropic): preserve setup-token weekly usage without 5h limits
Capture weekly usage headers independently of 5h status and before 429 window handlers return. Reuse passive snapshots for Anthropic setup-token usage queries, with regression coverage for weekly/Fable windows and existing cooldowns.
2026-11-06 11:44:33 +08:00
Wesley Liddick c5ca149a3d Merge pull request #8543 from wucm667/feat/issue-8541-openai-transport-cooldown
feat(openai): allow disabling transport error cooldown
2026-11-06 10:45:17 +08:00
Wesley Liddick 9432aa05fc Merge pull request #8549 from Wei-Shaw/fix/issue-8519-cyber-transcript-overflow
fix(openai): 按已屏蔽前缀长度精确匹配 cyber transcript,修复长会话误拦 (#8519)
2026-11-06 10:29:20 +08:00
wucm667 aa245176ae fix(openai): enforce synthesized effort ceilings and final validation 2026-11-06 10:15:12 +08:00
wucm667 fba4c193ae chore: sync upstream main for reasoning policy fix 2026-11-06 10:15:12 +08:00
shaw b6c0ca4256 chore(deps): 升级 brotli v1.2.7 与 klauspost/compress v1.20.2 修复 govulncheck 告警
GO-2026-6888 (brotli 解压过量内存分配) 与 GO-2026-6865 (zstd 双块帧 panic)
均有可达调用路径,backend-security 扫描因此失败。
2026-11-06 09:33:04 +08:00
danvilig 7f07bca99b Merge main and resolve Codex export model default 2026-11-05 16:19:22 +00:00
wucm667 489cfd5f4f feat(openai): allow disabling transport error cooldown 2026-11-05 21:55:07 +08:00
shaw 7e3b6c72fa fix(openai): 按已屏蔽前缀长度精确匹配 cyber transcript,修复长会话误拦 (#8519)
同一来源触发 cyber 屏蔽后,scope 激活期间任何历史超过 256 个 item 的
会话都会因 lookup 截断被 fail-closed 判为 transcript_lookup_limit_exceeded,
即使与被屏蔽会话毫无关系、且带有不同的显式 session_id。

改为在命中时记录 transcript 屏蔽 key 覆盖的历史长度(按 API Key 建 Redis
SET 索引,随 scope 同 TTL),查询时仅在这些长度处重算前缀哈希:
- 无关长会话不再被误拦,历史长度本身不再决定屏蔽
- 追加任意数量 item 仍能命中被屏蔽前缀,防逃逸能力不降
- 查询 MGET 由最多 256 key 降为记录长度数,遍历在最长记录长度处提前终止
- scope 门控、API Key 命名空间与 cyber-transcript:v3 哈希格式均不变
2026-11-05 21:51:26 +08:00
shaw 25608d216b chore: update sponsors 2026-11-05 17:55:19 +08:00
William DrakeandClaude Opus 5.5 0ee6b6c5d1 fix(antigravity): connection test sends the admin's prompt and lets the model answer
Every other platform's account test sends the admin's prompt (default "hi") and returns the
model's reply. The Antigravity text and Claude tests sent "." with a 1-token output cap and
ignored the prompt, so the UI showed "sent: hi" with an empty response, and thinking models
(gemini-4-argon, gemini-3.8-flash) spent the one token thinking. They now send the prompt (or
"hi") with 256 output tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:46:03 -07:00
Wesley Liddick 8e92c892b4 Merge pull request #8495 from FeeiCN/patch-1
fix: GPT-5.5已不提供服务,默认导出模型改为GPT5.6-SOL
2026-11-05 09:34:43 +08:00
wucm667 71532bf91c fix(usage): preserve compatible cache snapshot semantics 2026-11-05 09:24:56 +08:00
Wesley Liddick 503617a82f Merge pull request #8484 from StarryKira/codex/backend-resource-safety
fix(backend): bound gateway resources and background work
2026-11-05 09:15:13 +08:00
William DrakeandClaude Opus 5.5 455751402f fix(antigravity): label Pro plans' separate Argon quota as its own row
Pro accounts report a third quota group, gemini-argon-wtu ("For paid Pro plans, Argon
quota is separate", weekly only). It was labelled like the Claude/GPT group, so the cell
showed C·weekly twice. It now shows as A·weekly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:35:14 -07:00
William DrakeandClaude Opus 5.5 2ce1849bdf fix(antigravity): scope INTERNAL 500 penalties to image models; make account tiers configurable
An INTERNAL 500 that survives every retry put the whole antigravity account
in the progressive penalty (30 min, 2 h, then disabled), whatever model failed.
The image endpoint (gemini-3.1-flash-image) returns this 500 far more often
than text models, so one failing image request took the account's text models
(gemini-4-argon, gemini-3.8-flash) offline for 30 minutes, and repeats could
disable the account.

- An INTERNAL 500 on an image model now cools only that model (model-level
  rate limit, default 2 min, GATEWAY_ANTIGRAVITY_INTERNAL500_IMAGE_COOLDOWN_SECONDS)
  and does not count toward the account penalty.
- The account penalty tiers can be set per deployment:
  GATEWAY_ANTIGRAVITY_INTERNAL500_TIER1_SECONDS, ..._TIER2_SECONDS and
  GATEWAY_ANTIGRAVITY_INTERNAL500_DISABLE_ACCOUNT (false repeats tier 2 instead
  of disabling). Unset, every value is the previous default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:35:14 -07:00
William DrakeandClaude Opus 5.5 bf4e16b90e feat(antigravity): show each quota group's real 5-hour and weekly window
fetchAvailableModels reports one remainingFraction per model, whichever window is
tighter at the moment, so the 5-hour and the weekly limit could not be told apart:
a used-up weekly limit showed as "5h 99%" with a reset days away. The quota fetcher
now also calls v1internal:retrieveUserQuotaSummary, which reports every window of
every group (Gemini models; Claude and GPT models), and returns it as
antigravity_quota_groups. The account usage cell shows G·5h / G·weekly and
C·5h / C·weekly from it, and keeps the per-model bars when the summary is missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:35:14 -07:00
haruka 457602c8fc fix(backend): bound gateway resources and background work 2026-11-04 23:54:03 +08:00
qsy4 e16e69a7c4 fix(openai-ws): record first token time for every passthrough turn
Problem: on a WS v2 passthrough connection only the first turn gets a
first_token_ms. The per-turn value was stamped in two places: together
with the connection-level first token (which only happens once per
connection), or when the token event itself carries response.id. Token
events (*.delta, response.output_text.done,
response.function_call_arguments.done) never carry response.id, so from
the second turn on every usage log and every scheduler TTFT sample of a
long-lived Codex connection is nil.

Fix: resolve the turn first (by response.id, otherwise the active turn)
and stamp that turn's first token from its own start time. The
connection-level first token is unchanged.

Test: TestRelay_OnTurnComplete_FirstTokenMsRecordedForEveryTurn replays
two real-shaped turns on one connection (deltas without response.id) and
expects each turn's first token to be measured from its own start. It
fails on the second turn without the fix.
2026-11-04 07:16:09 -08:00
shaw 876b96d204 chore: update sponsors 2026-11-04 22:31:07 +08:00
shaw 2510944363 chore: update sponsors 2026-11-04 21:06:20 +08:00
shaw e353c83226 chore: update sponsors 2026-11-04 21:04:17 +08:00
Wesley Liddick b9d6ff5ca2 Merge pull request #8504 from feeeei/feat/registration-email-blacklist
feat(auth): 注册邮箱精确黑名单,保存时可批量禁用命中的已注册用户
2026-11-04 21:01:00 +08:00
feeeei 721dfb282e feat(auth): 注册邮箱精确黑名单,保存时可批量禁用命中的已注册用户
- 系统设置 → 注册设置新增「邮箱黑名单(精确匹配)」,弹窗编辑、批量粘贴,上限 20000 条,
  名单存于 settings 键 registration_email_blacklist,由专用接口整体读写;运行时读 60s TTL
  进程内缓存,保存后本实例立即生效
- 按收件箱身份匹配(复用 NormalizeEmailForAliasDedup):Gmail 点号、googlemail.com 与 +后缀
  变体视为同一邮箱
- 邮箱注册、发验证码、第三方登录补建账号、绑定/换绑邮箱命中时返回 EMAIL_BLOCKED;
  已验证邮箱的 OAuth 登录只在新建账号时拦截,已有账号是否可用由账号状态决定
- 保存后对新增项查找仍启用的普通用户并弹窗确认批量禁用(跳过管理员、已禁用与已删除用户),
  与单个禁用一样在同一事务内吊销 MCP 授权,禁用后清理认证缓存;也可随时对整份名单手动检查
2026-11-04 17:52:05 +08:00
Wesley Liddick 6f92090d7f Merge pull request #8462 from feeeei/feat/openai-image-size-tier-routing
feat(openai): 生图账号按 1K/2K/4K 尺寸档位分流
2026-11-04 17:11:58 +08:00
Wesley Liddick ee74473e03 Merge pull request #8499 from feeeei/fix/openai-passthrough-instructions-echo
fix(openai): 透传放行空 instructions,响应回显按客户端原值还原
2026-11-04 17:11:47 +08:00
Wesley Liddick e320a1500b Merge pull request #8318 from wucm667/fix/issue-8313-antigravity-system-identity
fix(antigravity): neutralize stale system identities on forwarding
2026-11-04 17:11:35 +08:00
Wesley Liddick 393167ea9a Merge pull request #8436 from feeeei/fix/usage-export-rate-limit
fix(usage): 用户导出 CSV 每页取 1000 条,遇面板限流 429 按 Retry-After 等待后重试
2026-11-04 17:11:23 +08:00
Wesley Liddick ccc2c161b5 Merge pull request #8503 from wucm667/fix/issue-8502-kimi-concurrency-cooldown
fix(kimi): use short cooldown for concurrency-limit 403
2026-11-04 17:11:12 +08:00
Wesley Liddick 45b51a8ac4 Merge pull request #8465 from wucm667/fix/issue-8461-grok-message-input
fix(grok): normalize delegated message input for Responses
2026-11-04 17:11:00 +08:00
wucm667 9e4c03d2fe fix(usage): reconcile prompt totals across cache-only updates 2026-11-04 09:08:54 +08:00
wucm667 17772947bd fix(kimi): use short cooldown for concurrency-limit 403 2026-11-04 00:43:51 +08:00
feeeei 6b565e45a6 fix(openai): 生图尺寸溢出选号后按首轮前的绑定处理会话粘性
未指定尺寸的生图请求逐层选号时:

- 较早轮次只拿到排队结果后,后续轮次选号不写会话粘性绑定;
- 溢出轮次抢到槽位时,会话仍绑定在首轮选号前的账号上则保留该绑定,
  否则(首轮前没有绑定,或绑定在选号中被清除、改写)绑定实际服务的账号;
- 各轮都只能排队时,绑定保持首轮选号后的状态。

旧调度器顺序模式在抢槽前写绑定,此前会让首轮前没有可用绑定的会话在溢出后仍绑定在排队账号上。
2026-11-03 23:56:39 +08:00
feeeei a699c2baed fix(openai): 透传放行空 instructions,响应回显按客户端原值还原
- OAuth 透传不再对 codex 模型的空串、空白或非字符串 instructions 本地返回 403,原样转发给上游(官方 Codex 接口已不要求 instructions 必传)。
- 网关补写、追加或搬运 instructions 后,response.instructions 回显按客户端请求里的原始取值还原,客户端未传时还原为 null;覆盖原生与透传两条 HTTP 路径的流式、非流式与 SSE 转 JSON 出口。还原值压缩成单行,写回 SSE data 行不会拆帧。
2026-11-03 23:01:12 +08:00
Feei e97a48d84b fix: GPT-5.5已不提供服务,默认导出模型改为GPT5.6-SOL 2026-11-03 15:35:48 +08:00
feeeei e452e41e40 feat(openai): 生图账号按 1K/2K/4K 尺寸档位分流
账号 extra 新增 openai_image_size_tiers,限定账号承接的生图尺寸档位;档位口径与
计费 ClassifyImageBillingTier 一致(最长边 ≤1024=1K、≤2048=2K、更大=4K)。
缺省、空列表或三档齐全表示不限,存量账号行为不变。

- 请求尺寸可识别:只调度到允许该档位的账号,切号也只在这些账号之间进行。
- 未传 size / auto / 无法识别:不过滤,按偏好层级逐层选号——不限档位 → 允许 4K →
  允许 2K → 仅 1K;跳过没有账号的层级;较早层级只能排队时继续尝试后续层级,都抢不到
  槽位时返回最早的排队结果,且溢出选中的账号不改写会话已有的粘性绑定;会话粘性与
  previous_response_id 绑定的账号不受偏好约束。
- 档位轮次包在代理隔离 fail-open 之内:先不绕过隔离跑完全部档位,再整体绕过重跑。
- 覆盖 /v1/images/generations、/v1/images/edits(含异步图片任务)与 /v1/responses
  显式 image_generation 工具(tools[].size);判定挂在高级调度与旧调度/DB 复检的共用
  兼容检查上;调度快照 extra 白名单加入该键。
- 分组内持久可调度、支持该模型且具备所需能力的账号都不允许该档位时返回 400
  invalid_request_error,临时不可用仍为 503。
- 测试连接:受限账号按最低允许档位发送代表尺寸(1024x1024 / 1536x1024 / 3840x2160)。
- 前端:创建/编辑账号弹窗(OpenAI 全部类型)与批量编辑加入档位多选,至少保留一档;
  批量编辑全选时提交空列表表示不限。
2026-11-03 13:18:50 +08:00
Wesley Liddick 4a4a83ee5e Merge pull request #8476 from lyen1688/fix/admin-key-permissions-8473
完善管理员 API Key 权限并新增需确认的全权兼容模式
2026-11-02 11:17:44 +08:00
wucm667 bcb0512132 fix(billing): account for unclassified cache creation tokens and TTL overrides 2026-11-02 09:16:06 +08:00
wucm667 7b879c56a6 chore(deps): update follow-redirects security patch 2026-11-02 09:16:06 +08:00
lyen1688 b0db521ceb 修复权限国际化编码的 ES2020 类型兼容错误 2026-11-02 00:19:57 +08:00
lyen1688 ff04296510 补齐管理员密钥中英文权限展示并修复依赖安全扫描 2026-11-02 00:11:17 +08:00
lyen1688 194d69e636 完善管理员密钥权限并新增需确认的全权兼容模式 2026-11-01 23:52:35 +08:00
qsy4 f10a45c030 fix(auth): stop reporting client disconnects and malformed keys as 500
Problem: when GetByKey fails with anything other than not-found or
overloaded, the API key middlewares answer 500 "Failed to validate API
key" without logging the cause. Two client-side conditions end up there:

- The client goes away while the key is being looked up (connection
  closed after the body was sent, or an HTTP/2 stream reset). net/http
  cancels the request context, the cache/DB lookup returns
  context.Canceled, and a pure client disconnect is recorded as an
  internal server error. A key that is not in the 15 s L1 cache always
  reaches Redis/Postgres, so infrequent clients hit this regularly.
- A key that is not valid UTF-8. Postgres rejects the parameter
  (invalid byte sequence, SQLSTATE 22021), which surfaces as 500 instead
  of 401. Generated and custom keys are always ASCII, so such a key can
  never match.

Fix: GetByKey treats non-UTF-8 keys as not found before any cache or DB
access. Both middlewares (OpenAI/Anthropic and Google) end the request
with 499 when the request context is already done, which the ops error
logger already skips as a client-closed request; any other lookup error
is now logged before the 500.

Test: api_key_auth_test.go drives both middlewares with a lookup that is
cancelled mid-flight (499) and with a plain repository error (500), and
sends a non-UTF-8 x-api-key (401). api_key_service_cache_test.go checks
that a non-UTF-8 key never reaches the repository. All three fail
without the fix.
2026-11-01 00:26:34 -07:00
wucm667 9e8913876f Merge remote-tracking branch 'upstream/main' into HEAD 2026-11-01 09:44:39 +08:00
wucm667 522f1fb999 fix(grok): normalize delegated message input for Responses 2026-10-31 23:49:02 +08:00
40d9c0964b fix(openai): apply Codex fingerprint convergence in the WebSocket HTTP bridge
proxyOpenAIWSHTTPBridgeTurn built its upstream request without staging the
converged Codex fingerprint IDs, unlike Forward and forwardOpenAIPassthrough.
The bridge therefore sent different device-fingerprint headers than the HTTP
paths for the same account, and when the client sent no prompt_cache_key the
request carried no session_id at all, so upstream prompt-cache routing was
effectively random and multi-turn requests rarely hit the cache.

Stage the IDs (and rewrite client_metadata) the same way
forwardOpenAIPassthrough does, clearing any stale IDs first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-10-31 06:38:40 -07:00
cyh 3425ba3663 fix(gateway): bound stalled request body reads and classify read failures
Gateway handlers such as Anthropic /v1/messages read the whole request body
before they know the model or account. The HTTP server sets no ReadTimeout
(large bodies may legitimately take long), so a stalled upload held the
handler until the client gave up, and every read failure then surfaced as a
generic 400 "Failed to read request body" with no diagnostics.

- Add server.request_body_idle_timeout (default 60s, 0 disables). A body
  read that receives no bytes for that long fails with 408. Each Read re-arms
  the deadline, so total upload time is not limited and handler pauses are
  not counted. HTTP/2 deadlines are armed only during a Read; HTTP/1 keeps
  one armed while the body is unfinished so net/http's own drain of an
  unread body cannot hang an early error response.
- Classify body read failures in the shared reader: read timeout (408),
  client disconnect (499), truncated body, decode errors and size limit.
  Other failures keep the stable 400 message. Map 408 to DEADLINE_EXCEEDED
  in Google-format errors.
- Log payload-free diagnostics for every gateway and middleware body read
  failure: kind, protocol, declared length, encoding, bytes received and
  read duration.
2026-10-31 11:45:55 +08:00
folltoshe c476edbf40 fix(openai): skip responses probe when routing mode is forced 2026-10-30 22:45:35 +08:00
mordekasiser c35418032b fix(antigravity): preserve direct Gemini streaming responses 2026-10-30 03:43:16 -07:00
wangjunwei fa6f06510b fix(openai): let error passthrough rules override the built-in body-limit 413
handleFailoverExhausted returned a fixed 413 for
IsOpenAIRequestBodyTooLarge() before reaching the generic error-passthrough
rule lookup further down, so a rule configured with error_codes [413] could
never match on this path. The service layer already returns the same
failover sentinel ahead of applyErrorPassthroughRule, so both layers
short-circuit and the rule vocabulary silently excludes 413.

Extract the existing rule application into
applyOpenAIFailoverPassthroughRule and call it first inside the body-limit
branch (and reuse it for the generic branch). Failover on 413 is left
intact: different accounts can front proxies with different body limits, so
switching may still succeed. The rule only decides the client-facing
response once failover is exhausted.

This matters for clients that treat 413 as retryable. Codex CLI maps a
non-2xx HTTP status to CodexErr::UnexpectedStatus, whose is_retryable()
returns true, and retries the sampling request up to stream_max_retries
(default 5) times. When the payload can never fit, every retry is wasted
work, and an operator has no supported way to signal "do not retry". Mapping
the same upstream 413 to 400 makes Codex map it to InvalidRequest, which is
not retryable, so it fails fast.

Tests cover the override on both unary and started-stream paths, the
unchanged built-in 413 when no rule matches, and skip_monitoring.
2026-10-30 15:19:54 +08:00
feeeei e47abd8f9b fix(usage): 用户导出 CSV 每页取 1000 条,遇面板限流 429 按 Retry-After 等待后重试
用户使用记录导出按 100 条/页连续请求 GET /api/v1/usage,该路由计入按用户的
重查询限流(默认 heavy_rpm=60,固定 60 秒窗口)。数据量超过约 5,000 行时,
导出在第 50~60 页收到 429,任一页失败即整体报「导出失败」。

- 导出页大小改为 1000(后端分页上限),请求数降为原来的 1/10。
- API 客户端结构化错误携带 retry_after_seconds(解析整数秒的 Retry-After)。
- 导出遇 429 时提示并按 Retry-After 等待(读不到时按 60 秒,夹在 1~60 秒)
  后重试同一页,每页最多重试 3 次。
2026-10-30 13:53:18 +08:00
111pointer111 890120120d fix(openai): 修复 GPT Image 账号生图测试参数 2026-10-30 12:54:52 +08:00
shaw d851a38477 fix(frontend): upgrade vue-i18n to v11 and patch decode-uri-component
Fixes frontend-security on main for two new high advisories:
- GHSA-83rm-6c8r-g728 (vue-i18n / @intlify/* srcdoc XSS): v9 and v10
  are end of life and will not be patched, so move vue-i18n and
  @intlify/message-compiler to 11.4.16.
- GHSA-qr28-fpjm-wq7f (decode-uri-component quadratic DoS): add a
  pnpm override to >=0.5.1; its API and types are unchanged.

vue-i18n 11 requires Node >= 22, so CI and release workflows move from
Node 20 to Node 24, matching the Docker build image.

JIT message compilation is always on since v10, so the obsolete
__INTLIFY_JIT_COMPILATION__ define is removed; the build still has no
new Function. SubscriptionPlanCard spec asserted raw keys that v9's
runtime build returned; it now asserts the rendered test messages.
2026-10-30 10:44:47 +08:00
Wesley Liddick 7386bc6ae0 Merge pull request #8389 from StarryKira/codex/management-mcp
feat: add OAuth-authenticated management MCP
2026-10-30 09:49:16 +08:00
shaw fb22c92126 fix(backend): bump MCP go-sdk to v1.4.1 for GO-2026-4770/4773
go-sdk v1.4.1 fixes GO-2026-4773 (cross-site tool execution) and
GO-2026-4770 (null Unicode JSON parsing), which fail govulncheck.

v1.4.1 also adds transport-level cross-origin and Content-Type checks
that would reject requests Authenticate already accepts:
- trust the same allowed origins in the SDK's CrossOriginProtection so
  CORS-allowlisted browser clients are not refused with 403;
- accept application/json with parameters (e.g. charset) by normalizing
  the header, while still refusing non-JSON bodies with 415.
2026-10-30 09:36:53 +08:00
shaw f532737de2 Merge branch 'main' into codex/management-mcp
# Conflicts:
#	backend/go.mod
#	backend/go.sum
2026-10-30 09:21:24 +08:00
lkon aae31c7438 fix(gemini): preserve tool media in native function responses 2026-10-30 09:06:51 +08:00
lkon 2d6b64a18e fix(responses): preserve message content fields in completed responses 2026-10-30 09:06:51 +08:00
harukaandClaude Opus 5.5 b3eb7194c2 fix(frontend): truncate long MCP client IDs
Signed client IDs are now about 200 characters. Show them on one line on
the consent page and in the connection list, with the full value in the
title. The random part leads, so truncated IDs still differ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 14:46:08 -04:00
harukaandClaude Opus 5.5 575dd9bc2b fix(backend): make MCP client registration stateless
Registration was capped at 1000 pending clients site-wide while the limit
per IP was 10 per minute, so one address could exhaust the cap and block
every new MCP client.

- Issue client IDs as HMAC-signed tokens carrying the client name,
  redirect URI digests and grant types. Registration writes nothing;
  rows are created only when a user approves a client, so there is no
  shared capacity to exhaust.
- Persist the signing key in security_secrets via the existing
  get-or-create helper, cached lock-free, so instances share it.
- Drop mcp_oauth_clients from migration 249 and keep the client name on
  each grant. Prune expired grants on authorization, before the owner
  row is locked.
- Fix an unchecked type assertion in managementmcp tests flagged by
  golangci-lint v2.14.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 14:46:08 -04:00
Kayokoi 2106081510 fix(anthropic): omit beta query for Cloudflare REST messages 2026-10-29 07:06:40 -07:00
Bao Le 0b535b5c07 fix(antigravity): Gemini 原生请求的 responseJsonSchema 改写为 responseSchema
Antigravity 上游 (v1internal) 接受 generationConfig.responseJsonSchema 字段但静默忽略,
返回普通文本而非 JSON;只有 responseSchema 能触发结构化输出。@ai-sdk/google >= 4.0.70
等客户端只发送 responseJsonSchema,导致经网关的结构化输出全部失效。

cleanGeminiRequest 现在把 responseJsonSchema / response_json_schema 改写为 responseSchema,
并复用 CleanJSONSchema 清理(去掉 $schema、additionalProperties,约束迁移到 description)。
已有 responseSchema 时以其为准;没有 schema 的请求保持原样。
2026-10-29 12:41:57 +07:00
Wesley Liddick a3298b46eb Merge pull request #7979 from ShuminFu/fix/oauth-passthrough-non-stream-7978
fix(openai): return JSON for non-stream OAuth passthrough /v1/responses
2026-10-28 21:41:00 +08:00
harukaandClaude Opus 5.5 8a34f1ecf3 fix(frontend): use the MCP logo and hide MCP when disabled
- Replace the cube icon with the official MCP logo in the sidebar and on
  the MCP connection and consent pages.
- Show the MCP entry only when the deployment enables MCP (mcp_enabled).
- Explain that administrator write grants always need TOTP verification,
  and add MCP OAuth to the audit log auth-method filter.
- Remove the unreferenced screenshots and their .gitignore exceptions (L6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:30:23 -04:00
harukaandClaude Opus 5.5 ee71c7f379 fix(backend): harden management MCP per review
- Reject JSON-RPC batches and non-object bodies before the SDK; return each
  tool result once as text and bound the encoded payload (H1).
- Enable MCP only when MCP_PUBLIC_URL is set; drop the frontend URL fallback
  and expose a read-only mcp_enabled public setting (M1).
- Expire never-authorized clients after 24h, cap pending registrations
  globally, aggregate MCP IP limits by IPv6 /64, and limit registration
  bodies to 4 KiB (M2).
- Revoke MCP grants with revoke-all-sessions and always require step-up for
  administrator write grants (M3).
- Rate limit /api/v1/mcp per IP before authentication and write last_used_at
  at most once per minute (M4).
- Persistently revoke grants when an account is disabled or demoted, derive
  result redaction from SensitiveCredentialKeys, allowlist browser sessions
  for step-up, audit every MCP read, reject invisible characters in
  client_name, and document site-root-only deployment (L1-L5, L7).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:30:23 -04:00
ShuminFuandSipengXie2024 4db8402b50 fix(openai): detect SSE body without Content-Type in OAuth passthrough non-stream
The ChatGPT OAuth upstream may answer with SSE but omit the Content-Type
header. Fall back to bodyHasSSEFraming for OAuth accounts in
handleNonStreamingResponsePassthrough, matching handleNonStreamingResponse,
and add a regression test covering both passthrough and non-passthrough.

Co-authored-by: SipengXie2024 <184713193+SipengXie2024@users.noreply.github.com>
2026-10-28 09:06:04 -04:00
github-actions[bot] a9240d5016 chore: sync VERSION to 0.2.19 [skip ci] 2026-10-28 10:16:21 +00:00
Wesley Liddick dece261536 Merge pull request #8373 from feeeei/fix/openai-models-cache-singleflight-recheck
fix(models): 模型列表刷新进入 singleflight 后复查缓存,避免并发冷启动重复请求上游
2026-10-28 18:03:26 +08:00
Wesley Liddick 184193f01e Merge pull request #8369 from feeeei/fix/gemini-bound-cache-pool-retry
fix(gemini): 绑定显式缓存的请求在池模式上游网关账号上按配置同账号重试
2026-10-28 18:03:11 +08:00
Wesley Liddick 7311b865f3 Merge pull request #8287 from feeeei/feat/gemini-same-account-retries-config
feat(gemini): 同账号重试次数改为可配置 gateway.max_same_account_retries_gemini
2026-10-28 18:02:29 +08:00
Wesley Liddick bf02c1a6e0 Merge pull request #8395 from feeeei/fix/gemini-model-lists
fix(gemini): /v1beta/models 按分组声明的模型应答,并刷新 Gemini 默认模型列表
2026-10-28 17:42:12 +08:00
Wesley Liddick 8b3f33f28a Merge pull request #8390 from wc4440222/pr/fix-websearch-emulation-dimensions
fix(channels): 渠道保存不再覆盖 web_search_emulation 的平台维度
2026-10-28 17:41:29 +08:00
feeeei 31564b2e86 fix(gemini): 刷新 Gemini 默认模型列表,移除已停用的 2.x 模型
- 账号白名单"同步最新支持模型"、/v1/models 与 /v1beta/models 的兜底列表共用的三处 Gemini 默认列表
  (前端 geminiModels、geminicli.DefaultModels、gemini.DefaultModels)统一为同一份 17 个现役模型:
  3.x 生图、3-flash、3.1-pro-preview(-customtools)、3.1/3.5 flash(-lite)、3.6/3.7/3.8-flash、4-argon;
  移除 2.0/2.5 系列与 3-pro-preview
- 连接测试默认模型由 gemini-2.0-flash 改为 gemini-3.5-flash;Google One 账号仍用其保守模型集
- 前端下拉候选总表补入 antigravity 模型并去重,antigravity 账号白名单下拉不再只显示与其他平台重叠的条目
- 生图模型识别补上 gemini-3.1-flash-lite-image
2026-10-28 16:00:21 +08:00
feeeei de44e3a0bf fix(gemini): 分组账号都声明模型映射时,/v1beta/models 列表与详情按声明的模型应答
- 原先 /v1beta/models 与 /v1beta/models/{model} 从分组中按优先级挑一个账号透传其上游列表;
  分组由多个第三方中转 Key 组成且各配 model_mapping 时,结果只反映选中账号的上游,
  与 /v1/models(合并各账号映射)不一致,下游"同步上游支持的模型"会拿到残缺或不可路由的模型
- 分组内每个可调度 Gemini 账号都有生效映射时,列表返回映射键并集(并上混合调度
  antigravity 账号的 Gemini 模型),分组白名单按 FilterForListing 与 /v1/models 同口径过滤,不再请求上游
- 详情按同一来源判断:键末尾 * 按前缀匹配,customtools 别名按请求路径的规则归一,未覆盖返回 404
- 有账号未配置映射(接受任意模型)或查询出错时,保持原选号透传逻辑
2026-10-28 16:00:21 +08:00
shaw 0a2a29b32e chore(deps): bump golang.org/x/net to v0.62.0 (GO-2026-6860)
govulncheck flags html.Parse quadratic text-node coalescing reached via
parseOllamaCloudUsageHTML. Bump x/net (and its x/* siblings pulled by go get).
2026-10-28 15:01:09 +08:00
wc4440222 1352e899ec test(channels): use checked type assertions in web search merge tests
golangci-lint (errcheck, check-type-assertions) flags single-value type
assertions; switch to the two-value form so the assertions stay explicit.
2026-10-28 14:07:46 +08:00
Wesley Liddick b2e7c60943 Merge pull request #8352 from ychy7001/fix/admin-guard-400
fix(admin): 管理员保护校验返回 400 而不是 500
2026-10-28 13:54:31 +08:00
wc4440222 9eba617367 fix(channels): preserve web_search_emulation platform dimensions on update
The admin channel editor rendered and submitted only the anthropic dimension of
features_config.web_search_emulation, while UpdateChannel replaces features_config
as a whole block. Saving a channel from the UI therefore erased the openai /
command_code / ... dimensions written via the API, silently disabling web search
emulation for those platforms until they were written again.

Backend: merge the key per platform dimension on update (request dimensions win,
missing dimensions are inherited; a missing key inherits the whole value so
clients unaware of the feature cannot wipe it; an explicit empty object still
clears). Other features_config keys keep the historical whole-block replacement.

Frontend: render and submit every platform in a whitelist that mirrors the
backend account-level whitelist, including explicit false for disabled sections,
so the stored value cannot go stale.

Tests: merge unit tests + applyUpdateInput wiring tests (backend), and a
source-contract spec for the channel editor (frontend). Reverting either side
makes the new tests fail.
2026-10-28 13:32:13 +08:00
haruka cf33006336 feat(frontend): add MCP OAuth consent and connections 2026-10-28 05:55:02 +08:00
haruka f17918ea17 feat(backend): add OAuth-authenticated management MCP 2026-10-28 05:54:56 +08:00
r266-tech 552d1ab4bb fix(apicompat): skip foreign CC Switch reasoning envelopes 2026-10-28 03:54:26 +08:00
r266-tech 090c58f663 fix(gateway): honor account error policies in compatibility paths 2026-10-28 03:45:29 +08:00
r266-tech 92d35a6947 fix(pricing): retry sync after catalog hash mismatch 2026-10-28 03:30:52 +08:00
danvilig ffd26af507 test(openai): cover native image routes and proxy deadlines 2026-10-27 16:26:45 +00:00
danvilig 1e0f56d76f fix(frontend): default Codex exports to GPT-6.1 Sol 2026-10-27 16:18:03 +00:00
danvilig 1afe5ffe35 fix(frontend): enable live web search in Codex exports 2026-10-27 15:18:34 +00:00
r266-tech 508bb9560f fix: correct Sonnet 5.5 cache read fallback pricing 2026-10-27 22:24:47 +08:00
danvilig 0d2459d986 fix(frontend): preserve Codex image configuration in key exports 2026-10-27 13:40:01 +00:00
Wesley Liddick f178e5ae32 Merge pull request #8362 from lkon2112/fix/nonstream-malformed-function-call
fix(antigravity): 非流式畸形工具调用返回错误而非空成功响应
2026-10-27 20:43:08 +08:00
Wesley Liddick 449b65a2ed Merge pull request #8348 from SipengXie2024/fix/images-upload-part-limit
fix(images): reject oversized multipart uploads instead of truncating them
2026-10-27 20:43:01 +08:00
Wesley Liddick 2c9d9760d8 Merge pull request #8303 from SipengXie2024/fix/pagination-offset-overflow
fix(pagination): keep page offsets from overflowing int
2026-10-27 20:42:55 +08:00
Wesley Liddick af4462ebae Merge pull request #8376 from fxjs/fix/opencode-deepseek-developer-role
fix(gateway): 修复 OpenCode 转发 DeepSeek 时的 developer 角色 422
2026-10-27 20:42:48 +08:00
Wesley Liddick 8e231ff5d6 Merge pull request #8354 from ychy7001/fix/deepseek-cache-hit-tokens
fix(usage): DeepSeek prompt_cache_hit_tokens 计为缓存读取
2026-10-27 20:42:41 +08:00
Wesley Liddick 98bcee7a89 Merge pull request #8366 from wx-11/fix/model-plaza-group-pricing
fix(model-plaza): 修复模型广场定价被覆盖的问题
2026-10-27 20:42:35 +08:00
Wesley Liddick 3f1ae7ee76 Merge pull request #8003 from Yukinoshita-Yukino/codex/fix-deepseek-pro-pricing
fix(billing): retain DeepSeek V4 Pro pricing after September 14
2026-10-27 20:42:28 +08:00
Wesley Liddick bb021d330e Merge pull request #8326 from r266-tech/codex/gemini-file-images
fix(gemini): count fileData image outputs for billing
2026-10-27 20:42:22 +08:00
Wesley Liddick 3bd166babc Merge pull request #8377 from StarryKira/codex/fix-cc-version-utf16
fix(claude): align cc_version suffix with JavaScript UTF-16 indexing
2026-10-27 20:42:15 +08:00
Wesley Liddick 0232cb7137 Merge pull request #8286 from coder-zhw/fix/cn-frequency-429-short-cooldown
fix(ratelimit): 国产 Coding Plan 的频率型 429 改用秒级冷却,不再冷却到 5h 窗口结束
2026-10-27 20:42:08 +08:00
danvilig cf1ba819b9 fix(openai): preserve native Codex image error statuses 2026-10-27 12:08:54 +00:00
Yuan Liu a0c827e97b Merge upstream main and retain Kimi and Terra pricing 2026-10-27 19:57:47 +08:00
Wesley Liddick 15701ba187 Merge pull request #8339 from aomsir/fix/grok-model-catalog-audit
fix(grok): 完善模型目录来源诊断与原始响应模型审计
2026-10-27 19:00:01 +08:00
Wesley Liddick b332f169f9 Merge pull request #8364 from wucm667/feat/issue-8363-gpt61-terra
feat(openai): support GPT-6.1 Terra
2026-10-27 18:51:29 +08:00
haruka 7bce2cfb45 fix(claude): match JavaScript UTF-16 billing fingerprint semantics 2026-10-27 18:33:06 +08:00
zhangyiyi ba5b218794 fix(gateway): 修复 OpenCode 转发 DeepSeek 的角色兼容
- 按映射后的 DeepSeek 模型和选中的 OpenCode 上游转换 developer 角色,避免 422
- 覆盖原生平台及 OpenAI 兼容接法,保留其他模型和原始重试请求
- 补充流式、非流式、模型别名及域名判定回归测试
2026-10-27 17:57:48 +08:00
feeeei b2b1bcf260 fix(models): 模型列表刷新进入 singleflight 后复查缓存,避免并发冷启动重复请求上游
- 调用方读缓存未命中后才进入 singleflight;上一轮刷新若在两者之间完成并写入缓存,
  后到的调用会再发起一次上游请求
- 刷新函数先复查缓存,已是新鲜结果则直接复用,只有缺失或过期时才请求上游
- 修复 TestPinnedOpenAIModelsListMixedAccountsShareColdCacheAcrossGroups 偶发上游调用 2 次
  (-race -count=3000 -cpu 1,2,4:修复前 34/9000 失败,修复后 0)
2026-10-27 14:30:38 +08:00
feeeei a207412375 fix(gemini): 绑定显式缓存的请求在池模式上游网关账号上按配置同账号重试
- 绑定缓存的请求收到上游网关账号的 429 / 5xx 时,原先直接按耗尽处理原样回写,pool_mode_retry_count 不生效;
  现按 pool_mode_retry_status_codes 判定可重试,在持有缓存的账号上同账号重试,用尽后仍原样回写
- 可重试的错误标为请求级瞬时故障:故障在上游网关持有缓存的账号上,重试用尽不临时封禁本账号
- 可重试时每次尝试登记 retry 类 ops 上游事件,重试成功记为恢复,不计入换号次数
- 非池模式账号或状态码不在重试列表内时行为不变
2026-10-27 12:11:54 +08:00
Yuan Liu ccac47e187 fix(kimi): expose K3.1 options and preserve explicit disabled reasoning 2026-10-27 10:42:21 +08:00
Jelvin 5965ac4e93 feat(settings): 系统设置保存按钮改为底部吸附浮标
各 tab 表单很长,保存按钮只在滚到最底部时可见。改为 sticky 浮标贴在视口右下角,
样式沿用已有 tab 导航条的毛玻璃胶囊语言,深色模式覆盖放在非 scoped 块内。
2026-10-27 10:35:40 +08:00
wx-11 d0afece15f fix(model-plaza): prefer group model pricing over image fallback tiers 2026-10-27 08:57:35 +08:00
lyy0709 64e6c260cc fix(billing): exempt GPT-6.1 Terra subscriptions from long-context surcharge
Codex opens GPT-6.1 Terra with a 500k default window, so subscription
requests routinely pass the 272k API long-context threshold. Apply the
existing GPT-6.1 Sol rule: OAuth and setup-token requests whose final
upstream model is Terra skip the model surcharge, while API keys keep
the published 2x input/cache and 1.5x output rates. Also label Terra's
fallback prices with their own release date.
2026-10-27 08:01:28 +08:00
lyy0709 e73f4c5e52 fix(openai): validate GPT-6.1 Terra effort and compat cache keys
GPT-6.1 Terra publishes none through max; minimal is not on its scale.
Recognize the -minimal spelling so the alias still resolves to Terra,
and reject minimal on the Chat, Messages and Responses compatibility
paths with the same 400 Sol uses for its unsupported levels. none stays
valid for Terra, and Sol keeps its stricter low-through-max checks.

Compatibility requests mapped to Terra also did not receive the derived
prompt_cache_key that other GPT-6 Responses models get, so Chat and
Messages traffic lost its stable cache identity. Include Terra there.
2026-10-27 08:01:23 +08:00
lyy0709 bea67f4124 fix(openai): use the official Codex descriptor for GPT-6.1 Terra
The generated Terra entry copied the API model page into the Codex
catalog: it offered none, omitted ultra, defaulted to medium and fell
back to a 272k window and the GPT-5.5 prompt. Codex publishes a separate
descriptor (openai/codex 126a0ee92ed2, models.json): low by default, low
through ultra, a 500k/872k window, Fast as the only extra tier and its
own instructions. A ChatGPT Plus account's live /backend-api/codex/models
response reports the same reasoning, window and tier values.

Bundle that descriptor like GPT-6.1 Sol, take Terra's base instructions
from it, and give official accounts the same route defaults: API-key
clients stay on full Responses, OAuth keeps Responses Lite and code mode.
Account-supplied manifests remain authoritative, and API requests keep
none through max. The model list now records the 2026-10-26 release
time instead of a 2024 placeholder.
2026-10-27 08:00:05 +08:00
wucm667 3423667422 feat(openai): support GPT-6.1 Terra 2026-10-27 04:36:20 +08:00
lkon 14a5fe3050 fix(antigravity): reject malformed non-streaming tool calls 2026-10-27 03:06:58 +08:00
Yuan Liu 8dc297ce94 fix(kimi): add bundled K3.1 Pro reference pricing 2026-10-26 19:04:30 +08:00
Anderson 9c7380732d test(openai-ws): explicitly discard deferred close errors 2026-10-26 18:24:38 +08:00
Anderson 142d22cc42 fix(openai-ws): reconnect pooled OAuth sockets before search activation 2026-10-26 18:03:52 +08:00
ychy7001 390ba9905a fix(securityaudit): 审计任务入队后立即唤醒本进程 worker
异步审计 worker 每 500ms 轮询一次数据库认领任务,本进程刚入队的任务
平均要等约 250ms 才被处理。入队成功和租约回收后改为立即通知本进程的
worker 尝试认领;worker 启动时先认领一次遗留任务。500ms 轮询保留不变,
继续兜底到期重试和其他副本入队的任务。
2026-10-26 17:31:33 +08:00
Yuan Liu 28eb088cd6 fix(kimi): recognize K3.1 Pro models and enable Codex reasoning 2026-10-26 17:16:17 +08:00
ychy7001 88d9c43b3e fix(admin): 管理员保护规则返回 400 而不是 500
禁用、删除或降级最后一个管理员时,服务层返回的是普通 errors.New,
经 ErrorFrom 统一转成 500,前端只能显示通用错误。改用 BadRequest
错误码和原因,前端可以显示具体原因。
2026-10-26 17:12:35 +08:00
ychy7001 3e18e78ab1 fix(usage): DeepSeek prompt_cache_hit_tokens 计为缓存读取
DeepSeek 的 OpenAI 兼容 usage 用 prompt_cache_hit_tokens / prompt_cache_miss_tokens
表示缓存命中(prompt_tokens = hit + miss),不返回 prompt_tokens_details.cached_tokens,
OpenAI 网关解析 usage 时缓存读取恒为 0。将其作为缓存读取的兜底字段,
嵌套 cached_tokens 存在时仍以嵌套字段为准。
2026-10-26 17:12:35 +08:00
hezhaoqian1andClaude Opus 5.5 b8de5e1700 perf(keys): API 密钥列表不再等待 30 天用量统计,并为其加覆盖索引
/keys 页面要等密钥列表和每个 key 的用量统计都返回,才撤掉表格骨架屏。
用量统计(POST /usage/dashboard/api-keys-usage)按 api_key_id 汇总近 30 天的
usage_logs.actual_cost。数据量大时,要逐行回表读取几十万到上百万行,接口耗时
十几到三十几秒,甚至超时,页面就一直停在骨架屏。

- 前端:列表返回就渲染表格,用量列单独显示加载占位;统计失败时回落为 $0.0000。
- 后端:新增覆盖索引 (api_key_id, created_at) INCLUDE (actual_cost),使该统计可以
  index-only scan,不再回表。迁移采用 CONCURRENTLY 建索引;与其他 usage_logs
  索引迁移一样,重试前会先清理中断构建留下的 INVALID 索引。

Refs #5858

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 11:16:54 +08:00
SipengXie2024 cde6ddfd8f fix(images): reject oversized multipart uploads instead of truncating them
Multipart image uploads were read through io.LimitReader(part, 20MB), so any
image larger than 20MB was silently cut short. The OAuth path (and the Grok
media path) then base64-encoded the truncated bytes and sent them upstream,
which answered 400 invalid_image_file. The API key path forwards the raw
multipart body and was not affected, so the same request worked or failed
depending on which account served it.

- Raise the per-part limit to 50MB, OpenAI's documented per-image limit for
  GPT image edits, and return 400 when a part exceeds it.
- Read Grok media parts whole; the body is already bounded by the gateway
  request body limit.
- Log each upload's content type and size on the images routing line.
2026-10-26 03:10:46 +00:00
Aomsir dfc13ce7f9 fix(grok): 修复模型目录审计相关 lint 错误 2026-10-25 22:08:54 +08:00
Wesley Liddick ba81c7fd75 Merge pull request #8323 from wx-11/images-price
兼容gptimage一次性出多张图的按张计费
2026-10-25 21:48:55 +08:00
shaw 3ce09c8aff fix(billing): keep tokens for channel per-request image tiers
calculatePerRequestCost falls back to context-based tiers when the size
tier misses; dropping Tokens made those tiers never match and settled
images at $0 regardless of the image_count_billing switch.
2026-10-25 21:30:45 +08:00
Aomsir 9534f1c089 fix(grok): 提高删除图标对比度并补齐同步按钮 Label in Name 2026-10-25 18:20:24 +08:00
Aomsir 7f18239be2 fix(grok): 对齐模型编辑布局与响应式展示 2026-10-25 18:00:25 +08:00
Aomsir 21b5b49d0a fix(grok): 统一目录同步入口并保留模式隔离 2026-10-25 17:20:25 +08:00
Aomsir 32c00d6e72 fix(grok): 诊断文案不再读取继承属性 2026-10-25 17:02:27 +08:00
Aomsir c68d312372 fix(grok): 未知目录详情改为历史标题 2026-10-25 16:52:41 +08:00
Aomsir 0d374b2549 fix(grok): 精简目录诊断并按需展开详情 2026-10-25 16:43:24 +08:00
shaw 3f1c8f36ce chore: update Sponsors 2026-10-25 13:32:13 +08:00
wucm667 e6bde6b3c6 fix(billing): retain native cache creation accounting 2026-10-25 11:28:55 +08:00
wucm667 835803a702 fix(antigravity): preserve task-bearing identity preambles 2026-10-25 11:28:41 +08:00
Aomsir 02db748cd5 fix(grok): 保留受管目录快照并阻止非法时间与敏感失败日志 2026-10-25 07:48:04 +08:00
Aomsir 2db7ce3d25 fix(grok): 隔离过期目录同步并在切模式后刷新诊断 2026-10-25 07:07:13 +08:00
Aomsir ae5705da1d fix(grok): 同账号刷新不再卡住目录同步 2026-10-25 06:42:46 +08:00
Aomsir 60931bce31 fix(grok): 展示模型目录诊断并保留编辑草稿 2026-10-25 06:32:46 +08:00
Aomsir bb11e83c44 fix(grok): 裸别名无法核验且自定义 ID 保留大小写 2026-10-25 06:06:51 +08:00
Aomsir d4136cea5e fix(grok): 提供账号模型目录差异诊断 2026-10-25 05:52:29 +08:00
Aomsir 635b835350 fix(grok): 让旧后台观察测试走 CAS 持久化 2026-10-25 05:28:25 +08:00
Aomsir 41a6ff8ac1 fix(grok): 对齐手动同步与后台目录观察 2026-10-25 05:20:04 +08:00
Aomsir b1cb2eb1f3 fix(grok): 补齐取消与调用方事务的回归断言 2026-10-25 04:50:35 +08:00
Aomsir 87266a7b18 fix(grok): 原子保存模型目录观测快照 2026-10-25 04:31:24 +08:00
Aomsir 6202da0f53 fix(grok): 统一模型目录解析与观测状态 2026-10-25 04:03:49 +08:00
Aomsir d01f2eb42c fix(grok): 固定聚合前序模型审计并跳过非 Grok 2026-10-25 03:38:40 +08:00
Aomsir 7131b997ca fix(grok): 补齐聚合路径跨事件模型冲突 2026-10-25 03:18:00 +08:00
Aomsir 014cc016f9 fix(grok): 补全原生 Responses 响应模型审计 2026-10-25 03:05:31 +08:00
r266-tech 917dbdc705 fix(gemini): count fileData image outputs for billing 2026-10-24 22:15:21 +08:00
wx-11 aa1a1b11c8 fix(billing): gate per-image billing by endpoint and pricing mode
- Require per-request/image mode for group image pricing so token-mode
  group cards no longer settle images at $0.
- Force per-image billing for channel token pricing when the group switch
  is enabled, matching the OpenAI pipeline.
- Add an ImageEndpoint marker so the switch only applies to dedicated
  image endpoints; mixed Responses/Chat/WS requests keep token billing.
- Only fall back to one image when the switch is enabled, preserving the
  previous count semantics when it is off.
- Validate image_count_billing in GroupService and gate the admin
  checkbox on allow_image_generation.
- Bump the API key auth snapshot version for the new group field.
2026-10-24 18:56:31 +08:00
wx-11 cb2959245f test(api): include image_count_billing in available groups contract 2026-10-24 12:40:01 +08:00
wx-11 1487fa511b fix(billing): count only images returned in upstream response 2026-10-24 12:23:30 +08:00
wucm667 efc58486d8 fix(usage): preserve authoritative cache creation totals 2026-10-24 12:16:53 +08:00
wucm667 c91c594cc8 chore: sync latest upstream changes 2026-10-24 12:16:32 +08:00
wx-11 fd998129ec feat(billing): support per-image billing for multi-image requests
按实际出图张数计费,解析不到时回退请求 n;新增分组级 image_count_billing 开关,仅对 OpenAI 和 Composite 分组开放;前端在图片计费区域提供按张计费勾选项。
2026-10-24 11:35:27 +08:00
wucm667 6f2faba293 fix(openai): validate synthesized effort after policy mapping 2026-10-24 11:28:25 +08:00
wucm667 355675af2d chore: sync latest upstream changes 2026-10-24 11:28:25 +08:00
Wesley Liddick 37067e8e34 Merge pull request #8319 from lyen1688/feat/scoped-admin-api-keys
新增按操作和资源范围授权的管理员 API Key
2026-10-24 10:12:37 +08:00
lyen1688 e445cc3e2d 新增按操作与资源范围授权的管理员 API 密钥 2026-10-23 19:16:57 +08:00
wucm667 01a1a78db2 fix(antigravity): neutralize stale system identities on forwarding 2026-10-23 19:12:24 +08:00
github-actions[bot] 5c185c5c5d chore: sync VERSION to 0.2.18 [skip ci] 2026-10-23 07:44:16 +00:00
SipengXie2024 9aa16c8c66 fix(pagination): validate numeric ranges and reuse safe offsets
Use strconv to reject pagination values outside the native int range,
reuse PaginationParams.Offset for API key slices, and derive test bounds
from math.MaxInt. Cover parsing, response metadata, strict handlers, and
in-memory pagination at the arithmetic boundaries.
2026-10-23 15:24:24 +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
SipengXie2024 f965280489 fix(pagination): keep page offsets from overflowing int
A page such as 9223372036854775807 passed every pagination check, so
(page-1)*pageSize wrapped around. With an even page size the offset
became negative and PostgreSQL rejected the query with "OFFSET must not
be negative"; paths that slice in memory (paginateSlice, balance history
merge) panicked with a negative slice bound. Both surfaced as HTTP 500 on
list endpoints such as /api/v1/admin/users, /api/v1/usage, /api/v1/keys
and /api/v1/admin/payment/orders.

- PaginationParams.Offset saturates Page at MaxInt/limit, so offset and
  offset+limit both stay within int.
- ParsePagination clamps page the same way, which covers the repositories
  that compute (page-1)*pageSize themselves.
- The prompt audit event list and the OpenAI token stats filter parse page
  on their own; they now reject an overflowing page with 400, like other
  invalid pagination input there.
2026-10-22 16:37:56 +00:00
feeeei 4197fa6202 feat(gemini): 同账号重试次数改为可配置 gateway.max_same_account_retries_gemini
Gemini 三条转发路径(原生 v1beta、Claude 兼容、Chat 兼容)对 429/5xx 等可重试
上游错误的同号重试次数读取 gateway.max_same_account_retries_gemini(不含首次请求,
默认 4,范围 0–10),取代写死的每号 5 次请求。默认值下不涉及签名降级的请求仍是
每号最多 5 次。

Claude 兼容路径的签名错误两阶段降级重发不占用同号重试次数:每进入一个降级阶段
循环上限顺延一次,重试次数调小时第二阶段降级照常执行,循环不会带着已关闭的响应体
退出。默认配置下先降级再遇瞬时错误的请求单号最多 7 次请求。
2026-10-22 12:14:55 +08:00
coder-zhw de908ed6d2 fix(ratelimit): 国产 Coding Plan 的频率型 429 改用秒级冷却
国产 Coding Plan 账号收到 429 时一律冷却到配额快照里最早的窗口重置点
(cooldownCNProviderToQuotaSnapshotReset)。但智谱对 Coding Plan 另有一层
请求频率限制,实测文案「您的账户已达到速率限制,请您控制请求频率」,此时
窗口额度往往只用了 10%~20%:一次并发突发就会把账号停调到 5h 窗口结束
(线上实测 1.5~4.8 小时),把「限频」误伤成「额度耗尽」。

改为按响应文案区分:命中频控文案、且快照显示窗口仍有可观余量(任一窗口
< 90%)时,不再走窗口冷却,交给默认 429 兜底 apply429FallbackRateLimit
(管理端可配,默认 5s)。两条护栏:
- 文案里同时出现额度类词(额度 / quota / usage limit / insufficient 等)
  一律不降级;
- 快照缺失、或任一窗口 >= 90% 一律不降级 —— 宁可多停调,也不要把真正的
  额度耗尽当成限频反复重试。

窗口真正耗尽时行为完全不变;余额不足路径(临时停调)也不受影响。
2026-10-22 11:42:54 +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
Yuan Liu 3f4e13aaba Merge upstream main and resolve pricing comment conflict 2026-10-19 11:55:47 +08:00
wucm667 7f6673ead5 fix(apicompat): preserve Anthropic cache creation TTL details 2026-10-17 13:43:55 +08:00
wucm667 eb4ccd173e fix(openai): apply reasoning mappings to synthesized effort 2026-10-16 20:32:00 +08:00
Shumin c01b2cb817 ci: retrigger CI (previous run hit Docker Hub rate limit) 2026-10-14 03:12:15 -04:00
Yuan Liu 5db2d6956b fix(billing): retain DeepSeek V4 Pro pricing after September 14 2026-10-10 20:01:39 +08:00
Shumin 9b5407449c fix(openai): return JSON for incomplete/cancelled non-stream Responses
When a non-streaming /v1/responses request is aggregated from upstream
SSE and the stream ends with response.incomplete (e.g. max_output_tokens)
or response.cancelled instead of response.completed, the SSE-to-JSON
handlers fell back to relaying the raw SSE body. Use the terminal event's
response object as the final JSON (keeping status/incomplete_details) in
both handlePassthroughSSEToJSON and handleSSEToJSON. Usage is still
recorded. extractCodexFinalResponse is unchanged.

Refs #7978
2026-10-09 17:01:53 -04:00
Shumin 6b2fdfcac2 fix(openai): return JSON for non-stream OAuth passthrough /v1/responses
OAuth passthrough forces stream=true for the ChatGPT internal API and then
overwrote reqStream from the rewritten body, so clients sending
stream=false received the raw upstream SSE stream. Keep the client's
original stream flag (compact requests stay non-streaming) so the
non-streaming branch aggregates SSE into a single Responses object.

Also set Content-Type explicitly when the SSE-to-JSON handlers write the
aggregated body: the upstream text/event-stream header was already
copied into the response and gin's c.Data does not override an existing
Content-Type. Applies to both passthrough and non-passthrough paths.

Fixes #7978
2026-10-09 14:29:01 -04:00
1395 changed files with 133646 additions and 8171 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)
+3 -3
View File
@@ -35,7 +35,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
go version | grep -q 'go1.27.3'
go version | grep -q 'go1.27.4'
- name: Unit tests
working-directory: backend
run: make test-unit
@@ -54,7 +54,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '20'
node-version: '24'
cache: 'pnpm'
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Install frontend dependencies
@@ -75,7 +75,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
go version | grep -q 'go1.27.3'
go version | grep -q 'go1.27.4'
- name: golangci-lint
uses: golangci/golangci-lint-action@v9
with:
+11 -34
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:
@@ -92,7 +101,7 @@ jobs:
version: 9
- uses: actions/setup-node@v6
with:
node-version: '20'
node-version: '24'
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- run: pnpm install --frozen-lockfile
@@ -137,7 +146,7 @@ jobs:
check-latest: false
cache: false
- name: Verify Go version
run: go version | grep -q 'go1.27.3'
run: go version | grep -q 'go1.27.4'
- name: Restore target-specific Go cache
id: go-cache
uses: actions/cache/restore@v6
@@ -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 -2
View File
@@ -23,7 +23,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
go version | grep -q 'go1.27.3'
go version | grep -q 'go1.27.4'
- name: Run govulncheck
working-directory: backend
run: |
@@ -41,7 +41,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: '20'
node-version: '24'
cache: 'pnpm'
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Install dependencies
+5
View File
@@ -133,10 +133,15 @@ deploy/docker-compose.override.yml
.gocache/
vite.config.js
docs/*
!docs/agent-resource-safety.md
!docs/moego-json-batching.md
!docs/admin-api-keys.md
!docs/mcp.md
!docs/PAYMENT.md
!docs/PAYMENT_CN.md
!docs/ADMIN_PAYMENT_INTEGRATION_API.md
!docs/ASYNC_IMAGE_TASKS.md
!docs/OPENAI_IMAGES_CODEX.md
!docs/BATCH_IMAGE_MVP.md
!docs/COMPOSITE_GROUPS.md
!docs/PLUGIN_DEVELOPMENT.md
+1 -1
View File
@@ -53,7 +53,7 @@ npm install -g pnpm
### CI 要求
- Go 版本必须是 **1.27.0**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.0'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
- Go 版本必须是 **1.27.4**:三个 workflow 都用 `go-version-file: backend/go.mod` 取版本,随后硬断言 `go version | grep -q 'go1.27.4'`。升级 Go 时要同时改 `backend/go.mod`、`backend-ci.yml`(两处)、`release.yml`、`security-scan.yml` 里的这句断言,**以及三个 Dockerfile 里的 Go 构建镜像**(`Dockerfile` / `deploy/Dockerfile` 的 `ARG GOLANG_IMAGE`、`backend/Dockerfile` 的 `FROM golang:`)。前者漏了 CI 会在版本校验步骤直接失败;**后者漏了 CI 不会报,而是等到有人用这些 Dockerfile 构建时才失败**(`go.mod requires go >= X (running Y; GOTOOLCHAIN=local)`)。
- 前端使用 `pnpm install --frozen-lockfile`,必须提交 `pnpm-lock.yaml`
### 本地测试命令
+1 -1
View File
@@ -8,7 +8,7 @@
# =============================================================================
ARG NODE_IMAGE=node:24-alpine
ARG GOLANG_IMAGE=golang:1.27.3-alpine
ARG GOLANG_IMAGE=golang:1.27.4-alpine
ARG ALPINE_IMAGE=alpine:3.21
ARG POSTGRES_IMAGE=postgres:18-alpine
ARG GOPROXY=https://goproxy.cn,direct
+1
View File
@@ -11,6 +11,7 @@ FRONTEND_CRITICAL_VITEST := \
src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \
src/constants/__tests__/platforms.spec.ts \
src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \
src/components/account/__tests__/CNProviderQuotaCell.spec.ts \
src/components/account/__tests__/CreateAccountModal.spec.ts \
src/components/account/__tests__/EditAccountModal.spec.ts \
src/components/account/__tests__/credentialsBuilder.spec.ts \
+47 -14
View File
@@ -31,6 +31,17 @@ Please read the following carefully before using this project:
> [Want to appear here?](mailto:support@sub2api.org)
<details open>
<summary>Click to collapse</summary>
<p align="center"><a href="https://wandapi.com/go/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-en-dark.svg"><img src="assets/partners/banners/wandapi-en.svg" alt="WandAPI" width="100%"></picture></a></p>
**[WandAPI](https://wandapi.com/go/sub2api)** — an enterprise-grade, stable AI model API gateway built by a core contributor to this project. One API key gives you access to Claude, GPT, Gemini and other leading models, natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex and your existing SDKs work by simply changing the Base URL. Real-time routing by latency and upstream health with millisecond-level automatic failover keeps requests online, backed by 99.99% service availability. Pay as you go, with per-request token and cost breakdowns.
**Free trial credits**: sign up via [this exclusive link](https://wandapi.com/go/sub2api) to claim free trial credits.
---
<table>
<tr>
@@ -54,8 +65,8 @@ Please read the following carefully before using this project:
</tr>
<tr>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for sub2api users: if you register via <a href="https://api.aigocode.dev/invite/SUB2API">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/logos/aigocode-dark.png"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></picture></a></td>
<td>Thanks to AIGoCode for sponsoring this project! A subscription-based AI coding platform, not just pay-per-token. One account, one monthly plan for Claude Code, Codex and Gemini, with direct connection on the mainland and fast responses. Subscribe via <a href="https://api.aigocode.dev/invite/SUB2API">this link</a> to get an extra 10% credits!</td>
</tr>
<tr>
@@ -106,11 +117,6 @@ Please read the following carefully before using this project:
<td>Thanks to FennoAI for sponsoring this project! FennoAI is a high-stability, high-performance API relay provider for enterprise R&D teams and developers, compatible with the OpenAI and Anthropic protocols and seamlessly integrating with mainstream AI coding tools such as Codex, Claude Code, and OpenCode. The platform delivers enterprise-grade stability, supporting call volumes of 100 billion tokens per day, and supports business-to-business settlement and invoicing for both domestic and overseas entities to meet enterprise R&D and procurement needs. As an exclusive benefit for Sub2API users, purchase a subscription via the <a href="https://api.fenno.ai/s/dC4k">exclusive link</a> to get $50 worth of Coding Plan credit for only $1.99. Referral rewards are also available: invite friends to purchase and earn up to 20% commission — the more you invite, the more you earn.</td>
</tr>
<tr>
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
<td>Thank you to LanoX AI for sponsoring this project! <a href="https://lanox.ai/?c=6">LanoX AI</a> provides stable, cost-effective global model access services for developers, teams, and enterprises. 🎁 New User Benefits — Claim millions of free tokens, plus 500+ free models for easier low-cost testing, validation, and deployment 🧠 Global Leading Models — GPT · Claude · Gemini · Qwen · Grok... 🎬 Multimodal Creation — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ Enterprise-Grade Reliability — High availability 💎 native capability output 💎 no intelligence degradation 💎 no model mixing 💎 transparent usage and billing 💎 💰 Lower API Costs — Top-tier models from as low as 10% of official pricing, with clear documentation, simple integration, invoicing support, and enterprise-scale batch usage 🏢 Enterprise Choice — Ideal for AI products, Agents, content platforms, and R&D teams with high-volume model usage</td>
</tr>
<tr>
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> is a data collection proxy solution built for developers, providing stable and reliable residential proxy services. With 90M+ global residential IPs and 200+ country coverage, intelligent rotation, and precise geo-targeting, it helps projects such as web scraping, AI data training, SEO monitoring, and e-commerce data analysis break through access restrictions and improve data collection efficiency. It supports mainstream automation frameworks such as Playwright, Selenium, and Puppeteer, with prices as low as $0.65/GB — <a href="https://www.rapidproxy.io/?ref=sub2api">start your free test now</a>.</td>
@@ -127,13 +133,8 @@ Please read the following carefully before using this project:
</tr>
<tr>
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
<td>Thanks to APIMart for sponsoring this project! <a href="https://go.apimart.ai/gh-sub2api">APIMart</a> is a low-cost API platform for AI image and video generation — GPT-Image-2 from $0.006 per image, with 160+ images per dollar. One async API covers both image and video: submit a task, get an ID, and retrieve results via polling or callback. Batch tens of thousands of images without timeouts, and switch models without changing code. Pay as you go with no monthly fee — <a href="https://go.apimart.ai/gh-sub2api">sign up here</a> to get started.</td>
</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>
@@ -161,8 +162,30 @@ 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://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>
</tr>
<tr>
<td width="180"><a href="https://api.muteki.site/register?aff=Sub2"><img src="assets/partners/logos/marucode.jpg" alt="MaruCode" width="150"></a></td>
<td><a href="https://api.muteki.site/register?aff=Sub2">MaruCode</a> — a small, no-frills API site that does a bit of charity now and then. 🍟 Every Thursday it runs limited-time rate-multiplier events. In operation for over half a year, with a 3K-member main group, focused on stability and welcoming collaboration with universities, enterprises, and more — thank you 🙇. It runs a self-operated account pool with no top-up marketing gimmicks, mainly offering mainstream models such as Codex (GPT 6.2 Astra), Claude Code (Claude Opus 5.5), and GPT Image 2.6, with WebSocket protocol support, clearly published pricing (Codex 0.3x, CC 1.7x), and a transparent exchange rate (1:1).</td>
</tr>
<tr>
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> supplies Claude API access at wholesale per-token prices to businesses and high-volume developers. It serves the standard Anthropic Messages API, so it works with Claude Code, Sub2API, LiteLLM and One API without code changes. Sign up with code SUB2API for 5% off every call, then join our Telegram group @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>) and ask an admin for $10 in credits.</td>
</tr>
<tr>
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> is an all-in-one AI API platform for developers and businesses, offering unified access to leading models including OpenAI, Claude, and Gemini for AI coding and text, image, audio, and video generation. It supports popular AI coding tools such as Claude Code and Codex, with pay-as-you-go pricing, real-time usage and cost monitoring, and 24/7 technical support to simplify model integration and keep development costs under control. New users can sign up through <a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">this link</a> to claim usage credits. From coding to multimodal creation, start your AI journey in one place!</td>
</tr>
</table>
</details>
## Overview
Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions. Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
@@ -728,6 +751,16 @@ Simple Mode is designed for individual developers or internal teams who want qui
---
## OpenAI Image Output Formats
On `/v1/images/generations` and `/v1/images/edits`, OAuth / Setup Token requests use the Codex-native Images endpoints when the mapped upstream model is a supported GPT Image 1.5, 2, 2.5, or 2.6 model. Models before 2.6 can fall back to Responses if the native endpoint returns 404 or 405.
Sub2API forwards `output_format` and `output_compression`, but whether they take effect depends on the upstream account and endpoint. An upstream may reject a format with a 4xx error or return HTTP 200 with a different format: for example, requesting `jpeg` or `svg` can yield `output_format: "png"` and PNG data. This behavior has also been reported for `gpt-image-2.5-flare` requests for `jpeg`.
Before saving or serving an image, compare the returned `output_format` (including any per-image value) with the request and verify the actual image format. Use the actual output format for the filename extension and MIME type. A successful response containing a different format retains its status, image content, and usage; it can still incur charges. Automatically retrying may generate and bill another image.
---
## Asynchronous Image Tasks
Long-running OpenAI/Grok image generation and editing can be submitted through `/v1/images/generations/async` or `/v1/images/edits/async`, then polled at `/v1/images/tasks/{task_id}` without holding a CDN connection open. See [Asynchronous Image Tasks](docs/ASYNC_IMAGE_TASKS.md) for request and response examples.
+46 -17
View File
@@ -32,6 +32,17 @@
> [想出现在这里?](mailto:support@sub2api.org)
<details open>
<summary>点击折叠</summary>
<p align="center"><a href="https://wandapi.com/go/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-cn-dark.svg"><img src="assets/partners/banners/wandapi-cn.svg" alt="WandAPI" width="100%"></picture></a></p>
**[WandAPI](https://wandapi.com/go/sub2api)** —— 由该项目核心贡献者打造的企业级稳定 AI 大模型 API 网关。一个 API Key 即可调用 Claude、GPT、Gemini 等主流模型,原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex 及现有 SDK 只需修改 Base URL 即可接入。按延迟与上游健康度实时路由,毫秒级自动故障切换,请求不掉线;服务可用性达 99.99%。按量计费,每次请求的 token 与费用明细清晰可查。
**免费试用额度**:通过[专属链接](https://wandapi.com/go/sub2api)注册,即可领取免费试用额度。
---
<table>
<tr>
@@ -55,8 +66,8 @@
</tr>
<tr>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过<a href="https://api.aigocode.dev/invite/SUB2API">此链接</a>注册,首次充值可额外获得 10% 赠送额度!</td>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/logos/aigocode-dark.png"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></picture></a></td>
<td>感谢 AIGoCode 赞助了本项目!订阅制 AI 编程平台,不只按token 算钱。一个账号包月畅用 Claude Code、Codex、Gemini,国内直连、响应快。通过<a href="https://api.aigocode.dev/invite/SUB2API">此链接</a>订阅额外送 10% 额度!</td>
</tr>
<tr>
@@ -109,11 +120,6 @@
<td>感谢 FennoAI 赞助本项目!FennoAI 是一家面向企业研发团队和开发者的高稳定、高性能 API 中转服务商,兼容 OpenAI 与 Anthropic 协议,可无缝接入 Codex、Claude Code、OpenCode 等主流 AI 编程工具。平台具备企业级稳定性,可支撑千亿 Token/日的调用规模,并支持境内外主体公对公结算及开票,满足企业级研发与采购需求。作为 Sub2API 用户专属福利,通过<a href="https://api.fenno.ai/s/dC4k">专属链接</a>购买订阅,仅需 1.99 美元即可获得价值 50 美元的 Coding Plan 额度。同时支持邀请奖励,邀请好友购买最高可获得 20% 返佣,邀请越多,奖励越高。</td>
</tr>
<tr>
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
<td>感谢 LanoX AI 对本项目的赞助!<a href="https://lanox.ai/?c=6">LanoX AI</a> 为开发者、团队与企业提供稳定、高性价比的全球模型接入服务。 🎁 新用户福利 — 免费领取 百万 Token ,更有500+ 免费模型 — 低成本测试、验证、部署更轻松 🧠 全球主流模型 — GPT · Claude · Gemini · Qwen · Grok... 🎬 多模态创作 — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ 企业级稳定服务 — 高可用💎原生能力输出💎不降智💎不混模💎调用与计费透明💎 💰 更低调用成本 — 顶级模型低至官方价 1 折起,文档清晰、接入简单、支持开票与企业批量调用 🏢 企业优选 — 适用于 AI 产品、Agent、内容平台、研发团队批量调用</td>
</tr>
<tr>
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> 是面向开发者的数据采集代理解决方案,提供稳定可靠的住宅代理服务。通过 9000 万+全球住宅 IP和 200+国家覆盖、智能轮换机制和精准地区定位能力,帮助爬虫、AI 数据训练、SEO 监控、电商数据分析等项目突破访问限制,提高数据采集效率。支持 Playwright、Selenium、Puppeteer 等主流自动化框架,价格低至 $0.65/GB,<a href="https://www.rapidproxy.io/?ref=sub2api">立即免费测试吧</a>。</td>
@@ -130,13 +136,8 @@
</tr>
<tr>
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
<td>感谢 APIMart 赞助了本项目!<a href="https://go.apimart.ai/gh-sub2api">APIMart</a> 是专注于 AI 图片/视频生成的低价 API 平台,GPT-Image-2 低至 $0.006/张,1 美元可生成 160+ 张图片。图片、视频一套异步 API 通吃:提交任务获取 ID,通过轮询或回调获取结果;批量生成上万张图片也不会超时,切换模型无需修改代码。按量付费、无月费,通过<a href="https://go.apimart.ai/gh-sub2api">此注册链接</a>注册即可开始使用。</td>
</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>
@@ -164,8 +165,30 @@
<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://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>
</tr>
<tr>
<td width="180"><a href="https://api.muteki.site/register?aff=Sub2"><img src="assets/partners/logos/marucode.jpg" alt="MaruCode" width="150"></a></td>
<td><a href="https://api.muteki.site/register?aff=Sub2">MaruCode</a> ——偶尔做做慈善的小破站 API,站内 🍟每周星期四 会做 限时倍率活动 ,目前已运营半年有余,大群3K人,主打稳定、欢迎高校、企业等合作,感谢🙇,目前已经营半年有余,自营号池,不搞充值营销套路,主要提供 Codex(GPT 6.2 Astra)、Claude Code(Claude Opus 5.5)、GPT Image 2.6 等主流模型,支持 WebSocket 协议,明码标价(Codex 0.3x, CC 1.7x),透明汇率(1:1)</td>
</tr>
<tr>
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> 以批发价向企业和大用量开发者提供 Claude API。提供标准的 Anthropic Messages API,Claude Code、Sub2API、LiteLLM、One API 无需改代码即可接入。使用邀请码 SUB2API 注册,每次调用立减 5%;注册后加入 Telegram 群 @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>),向管理员申请 $10 额度。</td>
</tr>
<tr>
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> 是面向开发者与企业的一站式 AI API 服务平台,通过统一接口接入 OpenAI、Claude、Gemini 等主流模型,覆盖 AI 编程及文本、图像、音频、视频生成。支持 Claude Code、Codex 等主流 AI 编程工具,提供按量付费、实时用量与成本监控,以及 7×24 小时技术支持,让模型接入更便捷、开发成本更可控。新用户通过<a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">此链接</a>注册,可领取使用额度,从代码开发到多模态创作,一站开启 AI 应用之旅!</td>
</tr>
</table>
</details>
## 项目概述
Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的 API 配额。用户通过平台生成的 API Key 调用上游 AI 服务,平台负责鉴权、计费、负载均衡和请求转发。
@@ -719,11 +742,17 @@ go generate ./cmd/server
## OpenAI 图片模型
支持 `gpt-image-2.5-flare`、`gpt-image-2.5-sunburst` 及其 `2026-09-08` 日期快照,可通过 `/v1/images/generations`、`/v1/images/edits` 调用。`quality` 支持 `xhigh`、`max`、`auto`,合法自定义尺寸和图片 usage 明细保持透传。
支持 `gpt-image-2.6-flare`、`gpt-image-2.6-sunburst`,以及 `gpt-image-2.5-flare`、`gpt-image-2.5-sunburst` 和 2.5 的 `2026-09-08` 日期快照,可通过 `/v1/images/generations`、`/v1/images/edits` 调用。保留显式 `complexity`(`low` / `medium` / `high`);省略时不注入默认值。`quality`、自定义尺寸和图片 usage 明细保持透传。
OAuth / Setup Token 图片请求使用 Responses 主控模型调用 `image_generation` 工具,默认主控为 `gpt-5.6-luna`。可设置 `SUB2API_IMAGES_MAIN_MODEL` 切换为账号支持的文本模型;Docker Compose 用户修改 `.env` 后执行 `docker compose up -d` 重建容器。该配置不会替换所选图片模型,也不会覆盖 `/v1/responses` 请求中已经提供的文本主控模型。
OAuth / Setup Token 的 1.5、2、2.5 和 2.6 图片请求使用 Codex 原生 Images 端点。旧模型遇到端点 404 / 405 时仍可回退到 Responses;2.6 不回退,避免桥接层忽略图片模型或注入不支持的 `complexity`。其余模型继续通过 Responses 的 `image_generation` 工具调用,默认文本主控为 `gpt-5.6-luna`,可设置 `SUB2API_IMAGES_MAIN_MODEL` 切换。该配置仅影响 Responses 桥接。
升级后,无模型限制的账号自动支持新模型。已有显式账号映射或分组白名单需要加入两个 2.5 模型(日期快照按需加入);升级不会自动扩大管理员设置的模型权限。新模型内置价格包含官方文本输入、图片输入和图片输出 token 费率,远端价格表尚未更新时使用内置 2.5 价格;实际按次或按 token 计费仍由既有分组/渠道配置决定。
原生端点保留 JSON / multipart 编辑的 `markup`(图片 URL 或上传文件)、GIF 帧参数及 SVG author 参数;`response_format=url` 使用上游实际输出格式的 MIME。GIF / SVG 可用性和参数生效情况由上游账号权限及端点决定,转发支持不代表上游一定输出该格式。若编辑端点对流式请求返回完整 JSON,网关会转换为完成事件并保留 usage。
`output_format` / `output_compression` 透传不保证上游按指定格式输出。Codex 原生端点可能以 4xx 拒绝某种格式,也可能返回 HTTP 200、`output_format: "png"` 和 PNG 内容,即使请求的是 `jpeg` 或 `svg`;`gpt-image-2.5-flare` 的 JPEG 请求也已报告出现相同情况。客户端保存或交付图片前,应将返回的 `output_format`(包括图片项中的该字段,如有)与请求比较,并核验实际图片格式;文件扩展名和 MIME 应匹配实际输出。
上游已返回图片的成功响应仍保留其状态、内容和 usage。格式不匹配不代表没有产生用量或费用;自动重试可能再次生成并计费。
升级后,无模型限制的账号自动支持新模型。已有显式账号映射或分组白名单需要主动加入两个 2.6 模型;升级不会扩大已保存的模型权限。2.6 内置官方文本输入、图片输入、缓存及图片输出 token 费率,远端价格表缺失或动态价格服务不可用时仍可兜底;实际按张或按 token 计费继续由既有分组/渠道配置决定。无需数据库迁移或新增环境变量。
## 简易模式
+32 -14
View File
@@ -31,6 +31,17 @@
> [こちらに掲載しませんか?](mailto:support@sub2api.org)
<details open>
<summary>クリックで折りたたむ</summary>
<p align="center"><a href="https://wandapi.com/go/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-en-dark.svg"><img src="assets/partners/banners/wandapi-en.svg" alt="WandAPI" width="100%"></picture></a></p>
**[WandAPI](https://wandapi.com/go/sub2api)** — 本プロジェクトのコアコントリビューターが手がける、エンタープライズグレードで安定した AI モデル API ゲートウェイ。1 つの API キーで Claude、GPT、Gemini などの主要モデルを利用でき、OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex や既存の SDK も Base URL を変更するだけで接続できます。レイテンシと上流の稼働状況に応じたリアルタイムルーティングとミリ秒単位の自動フェイルオーバーでリクエストを途切れさせず、99.99% のサービス可用性を実現します。従量課金で、リクエストごとの token 数と費用の内訳を確認できます。
**無料トライアルクレジット**:[専用リンク](https://wandapi.com/go/sub2api)から登録すると、無料トライアルクレジットを受け取れます。
---
<table>
<tr>
@@ -54,8 +65,8 @@
</tr>
<tr>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:<a href="https://api.aigocode.dev/invite/SUB2API">こちらのリンク</a>から登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント!</td>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/logos/aigocode-dark.png"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></picture></a></td>
<td>AIGoCode のご支援に感謝します!トークン従量課金だけではない、サブスクリプション型の AI コーディングプラットフォームです。1 つのアカウント・月額プランで Claude Code、Codex、Gemini を使い放題。中国本土から直接接続でき、レスポンスも高速です。<a href="https://api.aigocode.dev/invite/SUB2API">こちらのリンク</a>から購読すると、10% の追加クレジットをプレゼント!</td>
</tr>
<tr>
@@ -108,11 +119,6 @@
<td>FennoAI のご支援に感謝します!FennoAI は、企業の研究開発チームと開発者向けの高安定・高性能 API 中継サービスプロバイダーです。OpenAI と Anthropic のプロトコルに対応し、Codex、Claude Code、OpenCode などの主要 AI コーディングツールにシームレスに接続できます。エンタープライズ級の安定性を備え、1 日あたり千億規模の Token 呼び出しに対応。国内外法人間の企業間決済と請求書発行もサポートし、企業の研究開発・調達ニーズに応えます。Sub2API ユーザー限定特典として、<a href="https://api.fenno.ai/s/dC4k">専用リンク</a>からサブスクリプションを購入すると、わずか 1.99 ドルで 50 ドル相当の Coding Plan クレジットを獲得できます。さらに招待報酬にも対応しており、友達の購入で最大 20% の還元を獲得可能。招待が多いほど、報酬も増えます。</td>
</tr>
<tr>
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
<td>本プロジェクトをご支援いただいている <a href="https://lanox.ai/?c=6">LanoX AI</a> に感謝します!LanoX AI は、開発者、チーム、企業向けに、安定性とコストパフォーマンスに優れたグローバルモデル接続サービスを提供しています。 🎁 新規ユーザー特典 — 数百万 Token を無料で獲得可能。さらに 500+ の無料モデルで、低コストなテスト、検証、デプロイをより簡単に 🧠 世界の主要モデル — GPT · Claude · Gemini · Qwen · Grok... 🎬 マルチモーダル制作 — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ エンタープライズ級の安定性 — 高可用性 💎 ネイティブ能力の出力 💎 性能劣化なし 💎 モデル混在なし 💎 利用量と課金が透明 💎 💰 より低い利用コスト — トップモデルを公式価格の 1 割から利用可能。明確なドキュメント、簡単な接続、請求書発行、企業向け一括利用に対応 🏢 企業に最適 — AI プロダクト、Agent、コンテンツプラットフォーム、大量利用する開発チームに最適</td>
</tr>
<tr>
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> は開発者向けのデータ収集プロキシソリューションであり、安定して信頼できる住宅用プロキシサービスを提供します。9,000 万以上のグローバル住宅 IP と 200 以上の国・地域のカバー、インテリジェントなローテーション機構、精密な地域ターゲティング機能により、クローラー、AI データ学習、SEO モニタリング、EC データ分析などのプロジェクトがアクセス制限を突破し、データ収集の効率を高めます。Playwright、Selenium、Puppeteer などの主要な自動化フレームワークに対応し、料金は $0.65/GB から。<a href="https://www.rapidproxy.io/?ref=sub2api">今すぐ無料でお試しください</a>。</td>
@@ -129,13 +135,8 @@
</tr>
<tr>
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
<td>APIMart のご支援に感謝します!<a href="https://go.apimart.ai/gh-sub2api">APIMart</a> は AI 画像・動画生成に特化した低価格 API プラットフォームです。GPT-Image-2 は 1 枚 $0.006 から、1 ドルで 160 枚以上の画像を生成できます。画像と動画の両方に対応する非同期 API を 1 つで利用でき、タスクを送信して ID を取得し、ポーリングまたはコールバックで結果を取得できます。数万枚規模のバッチ処理でもタイムアウトせず、モデルを変更してもコードの変更は不要です。月額料金なしの従量課金制で、<a href="https://go.apimart.ai/gh-sub2api">こちらの登録リンク</a>からすぐに利用を開始できます。</td>
</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>
@@ -163,8 +164,25 @@
<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://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>
</tr>
<tr>
<td width="180"><a href="https://massivetokens.com/signup?ref=SUB2API"><img src="assets/partners/logos/massivetokens.jpg" alt="Massive Tokens" width="150"></a></td>
<td><a href="https://massivetokens.com/signup?ref=SUB2API">Massive Tokens</a> は、企業や大量に利用する開発者向けに、Claude API を token 単位の卸売価格で提供しています。標準の Anthropic Messages API を提供しているため、Claude Code、Sub2API、LiteLLM、One API とコードを変更せずに連携できます。招待コード SUB2API で登録すると、すべての呼び出しが 5% オフになります。登録後は Telegram グループ @massivetokens (<a href="https://t.me/massivetokens">https://t.me/massivetokens</a>) に参加し、管理者に $10 分のクレジットをリクエストしてください。</td>
</tr>
<tr>
<td width="180"><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3"><img src="assets/partners/logos/DataEyesAI.png" alt="DataEyesAI" width="150"></a></td>
<td><a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">DataEyesAI</a> は、開発者と企業向けのワンストップ AI API プラットフォームです。統一 API を通じて OpenAI、Claude、Gemini などの主要モデルを利用でき、AI コーディングからテキスト・画像・音声・動画の生成まで幅広く対応しています。Claude Code や Codex などの主要な AI コーディングツールに対応し、従量課金、リアルタイムの利用状況・コスト監視、24時間365日のテクニカルサポートを提供。モデル連携をより手軽にし、開発コストを管理しやすくします。<a href="https://www.dataeyes.vip/?promoter_code=9dkfv2r3">こちらのリンク</a>から新規登録すると、利用クレジットを受け取れます。コード開発からマルチモーダル制作まで、AI 活用をここから始めましょう!</td>
</tr>
</table>
</details>
## 概要
Sub2API は、AI 製品のサブスクリプションから API クォータを配分・管理するために設計された AI API ゲートウェイプラットフォームです。ユーザーはプラットフォームが生成した API キーを通じて上流の AI サービスにアクセスでき、プラットフォームは認証、課金、負荷分散、リクエスト転送を処理します。
@@ -0,0 +1,57 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1760" height="220" viewBox="0 0 1760 220" role="img" aria-label="WandAPI">
<defs>
<linearGradient id="logoW" gradientUnits="userSpaceOnUse" x1="4" y1="8" x2="44" y2="44"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
<linearGradient id="band" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
<radialGradient id="bA" cx="1200" cy="-20" r="280" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#A960EE" stop-opacity="0.95"/><stop offset="1" stop-color="#A960EE" stop-opacity="0"/></radialGradient><radialGradient id="bB" cx="1720" cy="20" r="300" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#00D4FF" stop-opacity="0.9"/><stop offset="1" stop-color="#00D4FF" stop-opacity="0"/></radialGradient><radialGradient id="bC" cx="1500" cy="260" r="260" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#FF80B5" stop-opacity="0.65"/><stop offset="1" stop-color="#FF80B5" stop-opacity="0"/></radialGradient><radialGradient id="bD" cx="1000" cy="260" r="240" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7A73FF" stop-opacity="0.9"/><stop offset="1" stop-color="#7A73FF" stop-opacity="0"/></radialGradient><radialGradient id="bE" cx="1380" cy="110" r="200" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#90E0FF" stop-opacity="0.55"/><stop offset="1" stop-color="#90E0FF" stop-opacity="0"/></radialGradient>
<radialGradient id="shadow" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#000000" stop-opacity=".45"/><stop offset="1" stop-color="#000000" stop-opacity="0"/></radialGradient>
<clipPath id="frame"><rect width="1760" height="220" rx="20"/></clipPath>
<clipPath id="slant"><polygon points="980,0 1760,0 1760,220 900,220"/></clipPath>
</defs>
<g clip-path="url(#frame)">
<rect width="1760" height="220" fill="#0A2540"/>
<g clip-path="url(#slant)">
<rect x="900" width="860" height="220" fill="url(#band)"/>
<rect x="900" width="860" height="220" fill="url(#bA)"/><rect x="900" width="860" height="220" fill="url(#bB)"/><rect x="900" width="860" height="220" fill="url(#bC)"/><rect x="900" width="860" height="220" fill="url(#bD)"/><rect x="900" width="860" height="220" fill="url(#bE)"/>
</g>
<g transform="translate(72 36) scale(0.7)">
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="8">
<polyline points="4,8 14,44 24,22 34,44 44,8" stroke="url(#logoW)"/>
<g stroke="#FFFFFF"><circle cx="70" cy="32" r="12"/><line x1="82" y1="20" x2="82" y2="44"/><path d="M96 20V44M96 32a12 12 0 0 1 24 0V44"/><circle cx="146" cy="32" r="12"/><line x1="158" y1="8" x2="158" y2="44"/></g>
<g stroke="#8C86FF"><polyline points="172,44 188,8 204,44"/><path d="M218 44V8h8a10 10 0 0 1 0 20h-8"/><line x1="250" y1="8" x2="250" y2="44"/></g>
</g>
<path d="M24 -1Q24.9 5.1 31 6Q24.9 6.9 24 13Q23.1 6.9 17 6Q23.1 5.1 24 -1Z" fill="#8C86FF"/>
</g>
<path d="M73.7 107.1V113.1H116.3V107.1ZM138.1 103.8V132H143.8V103.8ZM140.9 88.9C136.2 96.7 127.8 102.3 119.1 105.6C120.6 107.2 122.2 109.3 123.1 111C129.8 107.9 136.2 103.5 141.2 97.7C148.4 105.2 154.1 108.6 159.1 111.1C160 109.2 161.7 107.1 163.2 105.8C157.9 103.8 151.6 100.4 144.5 93.4L145.9 91.2ZM174.3 128H181.2L183.6 119.3H194.5L196.9 128H204.1L193.2 93.9H185.2ZM185 114 186 110.2C187 106.7 188 102.8 188.9 99.1H189.1C190.1 102.7 191 106.7 192.1 110.2L193.1 114ZM208.1 128H214.9V115.9H219.5C226.8 115.9 232.6 112.4 232.6 104.6C232.6 96.6 226.8 93.9 219.3 93.9H208.1ZM214.9 110.5V99.3H218.8C223.5 99.3 226 100.7 226 104.6C226 108.5 223.7 110.5 219 110.5ZM238.8 128H245.6V93.9H238.8ZM264.4 128H271.2V118.4L275.7 112.7L284.5 128H292L279.7 107.3L290.1 93.9H282.6L271.4 108.7H271.2V93.9H264.4ZM306.6 128.6C309.8 128.6 313.1 127.5 315.6 125.8L313.3 121.7C311.4 122.8 309.6 123.4 307.6 123.4C303.7 123.4 300.9 121.2 300.4 117.1H316.3C316.4 116.4 316.6 115.2 316.6 113.9C316.6 106.7 312.9 101.6 305.8 101.6C299.7 101.6 293.8 106.8 293.8 115.1C293.8 123.6 299.4 128.6 306.6 128.6ZM300.3 112.5C300.8 108.8 303.2 106.8 305.9 106.8C309.3 106.8 310.8 109 310.8 112.5ZM324.4 138.3C330.2 138.3 332.9 134.9 335.2 128.8L344.3 102.2H337.8L334.3 114.2C333.6 116.6 333 119.1 332.5 121.5H332.2C331.5 119 330.8 116.5 330.1 114.2L326 102.2H319.2L329.2 127.5L328.7 129.1C328 131.3 326.5 133 323.9 133C323.3 133 322.6 132.8 322.1 132.6L320.9 137.8C321.9 138.1 322.9 138.3 324.4 138.3ZM353.8 134.3C359.5 132.6 362.9 128.4 362.9 123.2C362.9 119.3 361.2 116.9 357.9 116.9C355.5 116.9 353.4 118.4 353.4 121C353.4 123.6 355.5 125.1 357.8 125.1L358.3 125.1C358 127.5 355.9 129.5 352.4 130.6ZM399 88.9V95.4H393.1V120.1H397.1V117.8H399V132H404V117.8H410.3V95.4H404V88.9ZM406 108.6V113.2H403.6V108.6ZM406 104.3H403.6V100.1H406ZM397.1 108.6H399.5V113.2H397.1ZM397.1 104.3V100.1H399.5V104.3ZM413 109.1C413.4 108.7 415 108.5 416.6 108.4C415 112.9 412.3 116.7 408.7 119.3C409.9 119.9 411.9 121.3 412.8 122.2C416.5 119 419.9 114.1 421.7 108.4H423.6C421.3 117.2 417.1 124.4 410.7 128.7C411.9 129.4 414.1 130.9 414.9 131.7C421.3 126.6 426 118.6 428.6 108.4H429.6C428.9 120.3 428 124.9 427 126.1C426.5 126.7 426.2 126.8 425.5 126.8C424.7 126.8 423.4 126.8 421.9 126.6C422.7 128 423.3 130.3 423.3 131.8C425.3 131.9 427.1 131.8 428.3 131.6C429.7 131.4 430.8 130.9 431.8 129.5C433.4 127.5 434.3 121.5 435.2 105.6C435.3 104.9 435.3 103.2 435.3 103.2H421.6C425.4 100.5 429.4 97.1 433.1 93.5L429.2 90.5L427.8 91H411.4V96.1H422.4C419.5 98.7 416.5 100.8 415.4 101.6C413.7 102.7 412 103.8 410.7 104C411.4 105.3 412.6 107.9 413 109.1ZM440.2 92C442.4 94.7 445.1 98.3 446.3 100.6L450.8 97.5C449.5 95.2 446.6 91.8 444.4 89.3ZM449.2 104.2H438.7V109.3H444V121.8C441.9 122.8 439.6 124.5 437.5 127L441.5 132.6C443.1 129.7 445 126.5 446.3 126.5C447.4 126.5 449 128 451.1 129.2C454.6 131.2 458.5 131.7 464.6 131.7C469.5 131.7 477.2 131.4 480.5 131.2C480.6 129.6 481.5 126.7 482.2 125.1C477.4 125.8 469.8 126.3 464.8 126.3C459.5 126.3 455.1 126 452 124C450.9 123.4 450 122.8 449.2 122.3ZM454.2 110.2C454.6 109.6 456.6 109.4 458.6 109.4H465V113.5H451.5V118.7H465V125.2H470.7V118.7H480.5V113.5H470.7V109.4H478.5V104.3H470.7V99.8H465V104.3H459.6C460.7 102.4 461.7 100.4 462.7 98.2H480V93.5H464.7L465.8 90.4L460 88.9C459.6 90.4 459.1 92 458.6 93.5H451.9V98.2H456.8C456.1 100 455.4 101.4 454.9 102.1C454 103.7 453.3 104.7 452.3 105C453 106.4 453.9 109 454.2 110.2ZM505 88.5C500.4 95.7 491.9 101.6 483.7 105.1C485 106.4 486.6 108.3 487.4 109.7C488.9 109 490.4 108.2 491.8 107.3V110.4H503V115.8H492.5V120.5H503V126.1H486.4V131H525.7V126.1H508.8V120.5H519.8V115.8H508.8V110.4H520.2V107.5C521.6 108.3 523.1 109.1 524.6 109.9C525.3 108.3 526.9 106.4 528.3 105.2C521 102 514.5 97.9 509 92L509.9 90.8ZM494.6 105.6C498.7 102.8 502.6 99.6 505.9 96C509.4 99.8 513.1 102.9 517.1 105.6ZM546.4 105.4C548.1 107.9 549.9 111.4 550.6 113.6L555.1 111.5C554.4 109.3 552.4 106 550.6 103.5ZM529.9 122.5 531 127.8 544.7 123.4 547.3 127.3C550.2 124.7 553.5 121.6 556.7 118.4V126C556.7 126.7 556.5 126.9 555.7 126.9C555 126.9 552.9 126.9 550.6 126.8C551.4 128.3 552.3 130.7 552.5 132.1C556 132.1 558.3 132 559.9 131C561.5 130.2 562.1 128.7 562.1 125.9V118.7C564.2 122.5 567 125.7 570.8 128.6C571.4 127.1 572.9 125.3 574.2 124.4C570.2 121.7 567.5 118.7 565.5 114.7C567.8 112.3 570.7 108.9 573.1 105.7L568.3 103.3C567.2 105.4 565.4 107.9 563.7 110.1C563 108.1 562.5 106 562.1 103.6V101.4H573.4V96.4H569.4L572 93.8C570.9 92.4 568.4 90.5 566.5 89.2L563.5 92C565.1 93.2 567.1 95 568.3 96.4H562.1V88.9H556.7V96.4H546.1V101.4H556.7V112.5C552.9 115.7 548.8 118.9 545.8 121.1L545.2 118.1L540.6 119.5V109.9H544.6V104.8H540.6V96.7H545.2V91.6H530.6V96.7H535.4V104.8H530.8V109.9H535.4V121C533.3 121.6 531.4 122.2 529.9 122.5ZM585.2 128H592.1L594.5 119.3H605.5L607.9 128H615L604.1 93.9H596.1ZM595.9 114 597 110.2C598 106.7 598.9 102.8 599.8 99.1H600C601 102.7 602 106.7 603 110.2L604 114ZM619 128H625.8V93.9H619ZM660.3 88.9C660.3 92.7 660.3 97 659.9 101.3H643V107H659C657.1 115 652.7 122.6 642.2 12Line truncated
<rect x="72" y="148" width="266.0" height="44" rx="22" fill="#635BFF"/>
<path d="M95.9 161.8C97.2 162.4 99 163.4 99.8 164.1L101.3 162C100.4 161.4 98.6 160.5 97.3 159.9ZM94.7 167.6C96 168.3 97.8 169.2 98.7 169.9L100.1 167.8C99.1 167.2 97.3 166.3 96.1 165.7ZM95.3 177.5 97.4 179.2C98.7 177.2 100 174.8 101.1 172.6L99.3 170.9C98 173.3 96.4 175.9 95.3 177.5ZM105.5 160.3C106.1 161.4 106.6 162.7 106.9 163.6H101.3V166H106.4V169.7H102.2V172.1H106.4V176.4H100.7V178.8H114.4V176.4H109V172.1H113.1V169.7H109V166H113.8V163.6H107.4L109.4 162.8C109.2 161.9 108.4 160.6 107.8 159.6ZM126.2 161V167.9H124.6V161H117.9V167.9H115.7V170.3H117.9C117.7 172.9 117.2 175.7 115.6 177.8C116.1 178.1 117.1 179.1 117.4 179.6C119.4 177.1 120 173.4 120.2 170.3H122.2V176.7C122.2 177 122.1 177.1 121.8 177.1C121.5 177.1 120.6 177.1 119.8 177.1C120.1 177.6 120.5 178.7 120.6 179.3C122 179.3 123 179.2 123.7 178.8C124.1 178.6 124.3 178.3 124.5 177.9C125 178.3 125.8 179.1 126.1 179.5C127.8 177.1 128.4 173.4 128.6 170.3H130.8V176.6C130.8 176.9 130.7 177 130.4 177C130.1 177 129.2 177 128.4 177C128.7 177.6 129.1 178.7 129.2 179.3C130.6 179.3 131.6 179.3 132.4 178.9C133.1 178.5 133.3 177.8 133.3 176.6V170.3H135.3V167.9H133.3V161ZM120.3 163.3H122.2V167.9H120.3ZM124.6 170.3H126.2C126 172.6 125.7 175.1 124.6 177.1V176.7ZM128.6 167.9V163.3H130.8V167.9ZM140.1 166.2C140.9 167 141.8 168.1 142.3 168.8L143.9 167.6C143.4 167 142.4 166 141.6 165.3ZM146.9 164.7V174.6H149.2V166.5H153.4V174.5H155.7V164.7H151.8L152.5 162.9H156.2V160.7H146.5V162.9H150.2C150 163.5 149.8 164.1 149.6 164.7ZM150.3 167.2C150.2 174 150.1 176.4 145.4 177.8C145.8 178.2 146.4 179 146.6 179.5C149 178.8 150.4 177.7 151.2 176C152.5 177.1 154 178.5 154.8 179.4L156.4 177.9C155.6 177 153.8 175.5 152.5 174.5L151.5 175.5C152.2 173.5 152.3 170.9 152.3 167.2ZM141.4 159.6C140.4 162.1 138.6 164.9 136.4 166.6C136.9 167 137.7 167.8 138.1 168.2C139.6 167 140.9 165.3 141.9 163.5C143.2 164.9 144.6 166.4 145.3 167.5L146.8 165.8C146 164.6 144.4 162.9 143 161.6C143.2 161.1 143.4 160.7 143.5 160.2ZM138.1 168.9V171.1H143C142.4 172.2 141.8 173.4 141.1 174.4L139.9 173.3L138.2 174.5C139.7 176 141.6 178 142.4 179.2L144.3 177.8C143.9 177.2 143.3 176.6 142.7 175.9C143.8 174.2 145.2 171.9 146 169.8L144.4 168.8L144 168.9ZM174.2 164.2C173.9 166.6 173.3 168.8 172.4 170.7C171.6 168.8 171.1 166.6 170.7 164.2ZM167.7 161.9V164.2H168.4C169 167.7 169.8 170.8 171.1 173.4C170 175.2 168.6 176.6 167 177.5C167.5 178 168.2 178.8 168.6 179.4C170.1 178.4 171.3 177.2 172.4 175.7C173.4 177.1 174.5 178.3 175.9 179.2C176.3 178.6 177 177.7 177.6 177.3C176 176.4 174.8 175.1 173.8 173.5C175.4 170.5 176.4 166.8 176.9 162.2L175.3 161.8L174.9 161.9ZM157.7 174.4 158.2 176.8 163.9 175.8V179.3H166.3V175.4L168.1 175.1L168 173L166.3 173.2V162.7H167.6V160.5H157.9V162.7H159.1V174.2ZM161.5 162.7H163.9V164.9H161.5ZM161.5 167H163.9V169.3H161.5ZM161.5 171.5H163.9V173.6L161.5 173.9ZM184.4 159.6C183.3 161.7 181.3 164.1 178.4 166C179 166.4 179.8 167.3 180.2 167.9L180.9 167.4V172.1H186.2C185.2 174.2 183.1 176 178.8 177.1C179.3 177.6 180 178.6 180.2 179.2C185.5 177.7 187.8 175.2 189 172.1H189.3V176C189.3 178.3 189.9 179 192.4 179C193 179 194.8 179 195.3 179C197.4 179 198.1 178.1 198.3 175C197.6 174.9 196.6 174.5 196 174.1C196 176.4 195.8 176.7 195.1 176.7C194.6 176.7 193.2 176.7 192.8 176.7C192 176.7 191.9 176.7 191.9 176V172.1H196.6V164.9H190.9C191.7 164 192.4 162.9 192.9 162.1L191.1 160.9L190.7 161H186.5L187.1 160.1ZM183.6 164.9C184.1 164.3 184.6 163.7 185.1 163.1H189.3C188.9 163.7 188.4 164.4 187.9 164.9ZM183.4 167.1H187.3C187.2 168.1 187.1 169 186.9 169.9H183.4ZM189.9 167.1H193.9V169.9H189.6C189.7 169 189.8 168.1 189.9 167.1ZM208.6 173C207.8 175.3 206.3 176.6 199.6 177.2C200.1 177.7 200.5 178.8 200.7 179.3C208.1 178.4 210.2 176.4 211.1 173ZM209.9 176.7C212.5 177.4 216.1 178.6 217.9 179.4L219.3 177.5C217.4 176.7 213.7 175.7 211.2 175.1ZM206.1 165C206.1 165.4 206 165.7 205.9 165.9H203.6L203.8 165ZM208.3 165H210.7V165.9H208.3C208.3 165.7 208.3 165.4 208.3 165ZM201.8 163.4C201.6 164.8 201.3 166.5 201.1 167.6H204.8C203.9 168.3 202.4 168.9 199.9 169.3C200.4 169.8 201 170.7 201.2 171.2C201.7 171.1 202.2 171.1 202.6 170.9V176H205V172.3H213.9V175.8H216.5V170.2H204.7C206.3 169.5 207.2 168.6 207.7 167.6H210.7V169.8H213.1V167.6H216.3C216.3 167.9 216.2 168.1 216.2 168.2C216.1 168.3 215.9 168.3 215.7 168.3C215.5 168.3 215.1 168.3 214.6 168.2C214.8 168.7 215 169.4 215 169.8C215.8 169.9 216.6 169.9 217 169.8C217.4 169.8 217.9 169.6 218.2 169.3C218.6 168.9 218.7 168.1 218.8 166.6C218.8 166.4 218.8 165.9 218.8 165.9H213.1V165H217.5V160.7H213.1V159.7H210.7V160.7H208.4V159.7H206.1V160.7H201.2V162.4H206.1V163.4L202.7 163.4ZM208.4 162.4H210.7V163.4H208.4ZM213.1 162.4H215.2V163.4H213.1ZM222 161.5C223.2 162.5 224.6 163.9 225.3 164.8L227 163.1C226.3 162.2 224.8 160.8 223.7 159.9ZM228 168.5V170.8H229.7V175.3L228.4 175.7L228.4 175.7C228.2 175.2 227.9 174.2 227.8 173.5L225.9 174.7V166.1H221V168.6H223.5V174.9C223.5 175.8 222.9 176.5 222.4 176.8C222.8 177.3 223.4 178.4 223.5 179C223.9 178.6 224.6 178.2 227.7 176.1L228.3 178.2C230.1 177.6 232.3 177 234.5 176.4L234.Line truncated
<path d="M315.0 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#fff" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M367.6 177.5H371.1L372.3 172.4C372.6 171.3 372.8 170.2 373 168.9H373.1C373.3 170.2 373.5 171.3 373.8 172.4L375 177.5H378.6L381.5 165.7H378.7L377.4 171.5C377.2 172.7 377 173.8 376.8 175H376.7C376.5 173.8 376.2 172.7 376 171.5L374.5 165.7H371.8L370.3 171.5C370 172.7 369.8 173.8 369.6 175H369.5C369.3 173.8 369.1 172.7 369 171.5L367.7 165.7H364.6ZM386.7 177.8C388 177.8 389.2 177.1 390.2 176.2H390.3L390.5 177.5H393V170.6C393 167.2 391.5 165.4 388.5 165.4C386.7 165.4 385 166.2 383.6 167L384.7 169.1C385.8 168.4 386.9 167.9 388 167.9C389.4 167.9 389.9 168.8 390 170C385.2 170.5 383.2 171.8 383.2 174.3C383.2 176.3 384.6 177.8 386.7 177.8ZM387.7 175.4C386.8 175.4 386.1 175 386.1 174.1C386.1 173 387.1 172.2 390 171.9V174.2C389.2 175 388.6 175.4 387.7 175.4ZM396.2 177.5H399.3V169.4C400.1 168.6 400.8 168.1 401.7 168.1C402.9 168.1 403.4 168.7 403.4 170.5V177.5H406.5V170.2C406.5 167.2 405.4 165.4 402.8 165.4C401.2 165.4 400 166.3 399 167.3H398.9L398.7 165.7H396.2ZM413.8 177.8C415 177.8 416.2 177.1 417 176.3H417.1L417.4 177.5H419.9V160.7H416.8V164.9L416.9 166.7C416.1 165.9 415.2 165.4 413.9 165.4C411.4 165.4 409 167.8 409 171.6C409 175.5 410.9 177.8 413.8 177.8ZM414.6 175.3C413 175.3 412.2 174 412.2 171.6C412.2 169.2 413.3 168 414.6 168C415.3 168 416.1 168.2 416.8 168.9V174C416.1 174.9 415.4 175.3 414.6 175.3ZM426.1 177.8C427.4 177.8 428.6 177.1 429.6 176.2H429.7L429.9 177.5H432.4V170.6C432.4 167.2 430.9 165.4 427.9 165.4C426.1 165.4 424.4 166.2 423 167L424.1 169.1C425.2 168.4 426.3 167.9 427.4 167.9C428.8 167.9 429.3 168.8 429.4 170C424.6 170.5 422.6 171.8 422.6 174.3C422.6 176.3 424 177.8 426.1 177.8ZM427.1 175.4C426.2 175.4 425.5 175 425.5 174.1C425.5 173 426.5 172.2 429.4 171.9V174.2C428.6 175 428 175.4 427.1 175.4ZM435.6 182H438.7V178.4L438.6 176.5C439.5 177.3 440.5 177.8 441.5 177.8C444.1 177.8 446.5 175.5 446.5 171.4C446.5 167.8 444.7 165.4 441.9 165.4C440.6 165.4 439.4 166.1 438.4 167H438.3L438.1 165.7H435.6ZM440.8 175.3C440.2 175.3 439.4 175 438.7 174.4V169.2C439.5 168.4 440.2 168 441 168C442.6 168 443.3 169.2 443.3 171.5C443.3 174 442.2 175.3 440.8 175.3ZM449.1 177.5H452.2V165.7H449.1ZM450.7 163.8C451.7 163.8 452.5 163.2 452.5 162.1C452.5 161.1 451.7 160.5 450.7 160.5C449.6 160.5 448.9 161.1 448.9 162.1C448.9 163.2 449.6 163.8 450.7 163.8ZM457.3 177.8C458.4 177.8 459.2 176.9 459.2 175.8C459.2 174.6 458.4 173.8 457.3 173.8C456.1 173.8 455.3 174.6 455.3 175.8C455.3 176.9 456.1 177.8 457.3 177.8ZM465.2 177.8C466.6 177.8 467.7 177.1 468.7 176.2H468.9L469.1 177.5H471.6V170.6C471.6 167.2 470.1 165.4 467.1 165.4C465.2 165.4 463.5 166.2 462.2 167L463.3 169.1C464.4 168.4 465.4 167.9 466.5 167.9C467.9 167.9 468.5 168.8 468.5 170C463.8 170.5 461.7 171.8 461.7 174.3C461.7 176.3 463.1 177.8 465.2 177.8ZM466.2 175.4C465.3 175.4 464.7 175 464.7 174.1C464.7 173 465.6 172.2 468.5 171.9V174.2C467.8 175 467.1 175.4 466.2 175.4ZM474.7 177.5H477.8V165.7H474.7ZM476.3 163.8C477.3 163.8 478.1 163.2 478.1 162.1C478.1 161.1 477.3 160.5 476.3 160.5C475.2 160.5 474.5 161.1 474.5 162.1C474.5 163.2 475.2 163.8 476.3 163.8Z" fill="#8C86FF"/>
<path d="M488.5 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#8C86FF" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="1024" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1036" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1055.0 93.0) scale(1.4166666666666667)" ><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></g>
<rect x="1108" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1120" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1139.0 93.0) scale(1.4166666666666667)" fill="#FFFFFF" fill-rule="evenodd"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></g>
<rect x="1192" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1204" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1223.0 93.0) scale(1.4166666666666667)" ><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-0-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-1-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-2-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-0-_R_0_" x1="7" x2="11" y1="15.5" y2="12"><stop stop-color="#08B962"></stop><stop offset="1" stop-color="#08B962" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-1-_R_0_" x1="8" x2="11.5" y1="5.5" y2="11"><stop stop-color="#F94543"></stop><stop offset="1" stop-color="#F94543" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-2-_R_0_" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stop-color="#FABC12"></stop><stop offset=".46" stop-color="#FABC12" stop-opacity="0"></stop></linearGradient></defs></g>
<rect x="1276" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1288" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1307.0 93.0) scale(1.4166666666666667)" ><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></g>
<rect x="1360" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1372" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1391.0 93.0) scale(1.4166666666666667)" fill="#FFFFFF" fill-rule="evenodd"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></g>
<rect x="1444" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1456" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1475.0 93.0) scale(1.4166666666666667)" ><path d="M19.713 2.825h-5.907c0-.251-.066-.503-.196-.728L12.819.728A1.46 1.46 0 0 0 11.559 0h-1.58c-.52 0-1 .275-1.26.728l-2.42 4.19a1.45 1.45 0 0 0 0 1.453l.791 1.37c.26.448.74.727 1.26.727h11.36c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-.79-1.37a1.46 1.46 0 0 0-1.26-.728zM.195 9.905l2.951 5.115a1.46 1.46 0 0 0-.531.531l-.791 1.37a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h4.84c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451L5.086 7.083a1.46 1.46 0 0 0-1.26-.728h-1.58c-.52 0-1 .276-1.26.728l-.79 1.37a1.45 1.45 0 0 0 0 1.452m15.888 13.367 2.951-5.115c.217.125.469.196.728.196h1.582c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-2.42-4.191a1.46 1.46 0 0 0-1.259-.728h-1.582c-.52 0-1 .276-1.259.728l-5.678 9.838a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h1.582c.52 0 1-.275 1.26-.728z" fill="#082dff"></path></g>
<rect x="1528" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1540" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1559.0 93.0) scale(1.4166666666666667)" ><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#FFFFFF"></path></g>
<rect x="1612" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1624" y="74" width="72" height="72" rx="18" fill="#635BFF"/><rect x="1624.75" y="74.75" width="70.5" height="70.5" rx="17.25" fill="none" stroke="#fff" stroke-opacity=".35" stroke-width="1.5"/>
<path d="M1651.0 99H1669.0M1660.0 90V108" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
<path d="M1644.6 120.5V128H1646.6L1644.9 128.6C1645.5 129.4 1646.1 130.1 1646.8 130.7C1645.8 131.1 1644.4 131.4 1642.7 131.7C1643.2 132.2 1643.8 133.1 1644 133.6C1646.1 133.2 1647.7 132.6 1648.9 131.9C1651.5 133.1 1654.8 133.3 1658.8 133.4C1658.9 132.7 1659.3 131.8 1659.7 131.3C1656 131.3 1653 131.2 1650.7 130.5C1651.4 129.7 1651.8 128.9 1652 128H1657.8V120.5H1652.3V119.5H1658.9V117.5H1643.1V119.5H1650V120.5ZM1646.7 125H1650V125.6L1650 126.2H1646.7ZM1652.3 126.2 1652.3 125.6V125H1655.7V126.2ZM1646.7 122.2H1650V123.4H1646.7ZM1652.3 122.2H1655.7V123.4H1652.3ZM1649.7 128C1649.5 128.5 1649.1 129 1648.6 129.5C1648 129.1 1647.4 128.6 1646.9 128ZM1667.9 116.6C1666.6 118.1 1664.5 119.6 1661.6 120.7C1662.1 121 1662.7 121.7 1663 122.2C1664.5 121.6 1665.8 120.9 1666.9 120.1H1671.4C1670.6 120.9 1669.6 121.6 1668.4 122.2C1667.9 121.7 1667.2 121.2 1666.6 120.8L1665 121.8C1665.5 122.2 1666 122.6 1666.5 123.1C1664.8 123.7 1663 124.2 1661.1 124.4C1661.5 124.9 1661.9 125.8 1662.1 126.3C1667.3 125.3 1672.5 123.1 1674.8 118.9L1673.4 118.1L1673 118.2H1669.2C1669.5 117.9 1669.9 117.5 1670.2 117.2ZM1670.8 123.1C1669.5 124.9 1667 126.6 1663.3 127.8C1663.7 128.2 1664.3 129 1664.6 129.5C1666.6 128.7 1668.4 127.8 1669.8 126.8H1673.9C1673.1 127.8 1672.1 128.6 1670.9 129.2C1670.3 128.7 1669.7 128.2 1669.1 127.8L1667.3 128.8C1667.8 129.2 1668.4 129.7 1668.9 130.1C1666.6 130.9 1663.9 131.4 1661 131.6C1661.3 132.1 1661.7 133.1 1661.8 133.7C1668.7 133 1674.7 131.1 1677.2 125.6L1675.7 124.7L1675.3 124.9H1672.1C1672.5 124.5 1672.9 124 1673.2 123.6Z" fill="#fff"/>
</g>
<rect x=".75" y=".75" width="1758.5" height="218.5" rx="19.25" fill="none" stroke="#1F3A5C" stroke-width="1.5"/>
</svg>

After

Width:  |  Height:  |  Size: 34 KiB

+57
View File
@@ -0,0 +1,57 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1760" height="220" viewBox="0 0 1760 220" role="img" aria-label="WandAPI">
<defs>
<linearGradient id="logoW" gradientUnits="userSpaceOnUse" x1="4" y1="8" x2="44" y2="44"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
<linearGradient id="band" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
<radialGradient id="bA" cx="1200" cy="-20" r="280" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#A960EE" stop-opacity="0.95"/><stop offset="1" stop-color="#A960EE" stop-opacity="0"/></radialGradient><radialGradient id="bB" cx="1720" cy="20" r="300" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#00D4FF" stop-opacity="0.9"/><stop offset="1" stop-color="#00D4FF" stop-opacity="0"/></radialGradient><radialGradient id="bC" cx="1500" cy="260" r="260" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#FF80B5" stop-opacity="0.65"/><stop offset="1" stop-color="#FF80B5" stop-opacity="0"/></radialGradient><radialGradient id="bD" cx="1000" cy="260" r="240" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7A73FF" stop-opacity="0.9"/><stop offset="1" stop-color="#7A73FF" stop-opacity="0"/></radialGradient><radialGradient id="bE" cx="1380" cy="110" r="200" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#90E0FF" stop-opacity="0.55"/><stop offset="1" stop-color="#90E0FF" stop-opacity="0"/></radialGradient>
<radialGradient id="shadow" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#32325D" stop-opacity=".30"/><stop offset="1" stop-color="#32325D" stop-opacity="0"/></radialGradient>
<clipPath id="frame"><rect width="1760" height="220" rx="20"/></clipPath>
<clipPath id="slant"><polygon points="980,0 1760,0 1760,220 900,220"/></clipPath>
</defs>
<g clip-path="url(#frame)">
<rect width="1760" height="220" fill="#FFFFFF"/>
<g clip-path="url(#slant)">
<rect x="900" width="860" height="220" fill="url(#band)"/>
<rect x="900" width="860" height="220" fill="url(#bA)"/><rect x="900" width="860" height="220" fill="url(#bB)"/><rect x="900" width="860" height="220" fill="url(#bC)"/><rect x="900" width="860" height="220" fill="url(#bD)"/><rect x="900" width="860" height="220" fill="url(#bE)"/>
</g>
<g transform="translate(72 36) scale(0.7)">
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="8">
<polyline points="4,8 14,44 24,22 34,44 44,8" stroke="url(#logoW)"/>
<g stroke="#0A2540"><circle cx="70" cy="32" r="12"/><line x1="82" y1="20" x2="82" y2="44"/><path d="M96 20V44M96 32a12 12 0 0 1 24 0V44"/><circle cx="146" cy="32" r="12"/><line x1="158" y1="8" x2="158" y2="44"/></g>
<g stroke="#635BFF"><polyline points="172,44 188,8 204,44"/><path d="M218 44V8h8a10 10 0 0 1 0 20h-8"/><line x1="250" y1="8" x2="250" y2="44"/></g>
</g>
<path d="M24 -1Q24.9 5.1 31 6Q24.9 6.9 24 13Q23.1 6.9 17 6Q23.1 5.1 24 -1Z" fill="#635BFF"/>
</g>
<path d="M73.7 107.1V113.1H116.3V107.1ZM138.1 103.8V132H143.8V103.8ZM140.9 88.9C136.2 96.7 127.8 102.3 119.1 105.6C120.6 107.2 122.2 109.3 123.1 111C129.8 107.9 136.2 103.5 141.2 97.7C148.4 105.2 154.1 108.6 159.1 111.1C160 109.2 161.7 107.1 163.2 105.8C157.9 103.8 151.6 100.4 144.5 93.4L145.9 91.2ZM174.3 128H181.2L183.6 119.3H194.5L196.9 128H204.1L193.2 93.9H185.2ZM185 114 186 110.2C187 106.7 188 102.8 188.9 99.1H189.1C190.1 102.7 191 106.7 192.1 110.2L193.1 114ZM208.1 128H214.9V115.9H219.5C226.8 115.9 232.6 112.4 232.6 104.6C232.6 96.6 226.8 93.9 219.3 93.9H208.1ZM214.9 110.5V99.3H218.8C223.5 99.3 226 100.7 226 104.6C226 108.5 223.7 110.5 219 110.5ZM238.8 128H245.6V93.9H238.8ZM264.4 128H271.2V118.4L275.7 112.7L284.5 128H292L279.7 107.3L290.1 93.9H282.6L271.4 108.7H271.2V93.9H264.4ZM306.6 128.6C309.8 128.6 313.1 127.5 315.6 125.8L313.3 121.7C311.4 122.8 309.6 123.4 307.6 123.4C303.7 123.4 300.9 121.2 300.4 117.1H316.3C316.4 116.4 316.6 115.2 316.6 113.9C316.6 106.7 312.9 101.6 305.8 101.6C299.7 101.6 293.8 106.8 293.8 115.1C293.8 123.6 299.4 128.6 306.6 128.6ZM300.3 112.5C300.8 108.8 303.2 106.8 305.9 106.8C309.3 106.8 310.8 109 310.8 112.5ZM324.4 138.3C330.2 138.3 332.9 134.9 335.2 128.8L344.3 102.2H337.8L334.3 114.2C333.6 116.6 333 119.1 332.5 121.5H332.2C331.5 119 330.8 116.5 330.1 114.2L326 102.2H319.2L329.2 127.5L328.7 129.1C328 131.3 326.5 133 323.9 133C323.3 133 322.6 132.8 322.1 132.6L320.9 137.8C321.9 138.1 322.9 138.3 324.4 138.3ZM353.8 134.3C359.5 132.6 362.9 128.4 362.9 123.2C362.9 119.3 361.2 116.9 357.9 116.9C355.5 116.9 353.4 118.4 353.4 121C353.4 123.6 355.5 125.1 357.8 125.1L358.3 125.1C358 127.5 355.9 129.5 352.4 130.6ZM399 88.9V95.4H393.1V120.1H397.1V117.8H399V132H404V117.8H410.3V95.4H404V88.9ZM406 108.6V113.2H403.6V108.6ZM406 104.3H403.6V100.1H406ZM397.1 108.6H399.5V113.2H397.1ZM397.1 104.3V100.1H399.5V104.3ZM413 109.1C413.4 108.7 415 108.5 416.6 108.4C415 112.9 412.3 116.7 408.7 119.3C409.9 119.9 411.9 121.3 412.8 122.2C416.5 119 419.9 114.1 421.7 108.4H423.6C421.3 117.2 417.1 124.4 410.7 128.7C411.9 129.4 414.1 130.9 414.9 131.7C421.3 126.6 426 118.6 428.6 108.4H429.6C428.9 120.3 428 124.9 427 126.1C426.5 126.7 426.2 126.8 425.5 126.8C424.7 126.8 423.4 126.8 421.9 126.6C422.7 128 423.3 130.3 423.3 131.8C425.3 131.9 427.1 131.8 428.3 131.6C429.7 131.4 430.8 130.9 431.8 129.5C433.4 127.5 434.3 121.5 435.2 105.6C435.3 104.9 435.3 103.2 435.3 103.2H421.6C425.4 100.5 429.4 97.1 433.1 93.5L429.2 90.5L427.8 91H411.4V96.1H422.4C419.5 98.7 416.5 100.8 415.4 101.6C413.7 102.7 412 103.8 410.7 104C411.4 105.3 412.6 107.9 413 109.1ZM440.2 92C442.4 94.7 445.1 98.3 446.3 100.6L450.8 97.5C449.5 95.2 446.6 91.8 444.4 89.3ZM449.2 104.2H438.7V109.3H444V121.8C441.9 122.8 439.6 124.5 437.5 127L441.5 132.6C443.1 129.7 445 126.5 446.3 126.5C447.4 126.5 449 128 451.1 129.2C454.6 131.2 458.5 131.7 464.6 131.7C469.5 131.7 477.2 131.4 480.5 131.2C480.6 129.6 481.5 126.7 482.2 125.1C477.4 125.8 469.8 126.3 464.8 126.3C459.5 126.3 455.1 126 452 124C450.9 123.4 450 122.8 449.2 122.3ZM454.2 110.2C454.6 109.6 456.6 109.4 458.6 109.4H465V113.5H451.5V118.7H465V125.2H470.7V118.7H480.5V113.5H470.7V109.4H478.5V104.3H470.7V99.8H465V104.3H459.6C460.7 102.4 461.7 100.4 462.7 98.2H480V93.5H464.7L465.8 90.4L460 88.9C459.6 90.4 459.1 92 458.6 93.5H451.9V98.2H456.8C456.1 100 455.4 101.4 454.9 102.1C454 103.7 453.3 104.7 452.3 105C453 106.4 453.9 109 454.2 110.2ZM505 88.5C500.4 95.7 491.9 101.6 483.7 105.1C485 106.4 486.6 108.3 487.4 109.7C488.9 109 490.4 108.2 491.8 107.3V110.4H503V115.8H492.5V120.5H503V126.1H486.4V131H525.7V126.1H508.8V120.5H519.8V115.8H508.8V110.4H520.2V107.5C521.6 108.3 523.1 109.1 524.6 109.9C525.3 108.3 526.9 106.4 528.3 105.2C521 102 514.5 97.9 509 92L509.9 90.8ZM494.6 105.6C498.7 102.8 502.6 99.6 505.9 96C509.4 99.8 513.1 102.9 517.1 105.6ZM546.4 105.4C548.1 107.9 549.9 111.4 550.6 113.6L555.1 111.5C554.4 109.3 552.4 106 550.6 103.5ZM529.9 122.5 531 127.8 544.7 123.4 547.3 127.3C550.2 124.7 553.5 121.6 556.7 118.4V126C556.7 126.7 556.5 126.9 555.7 126.9C555 126.9 552.9 126.9 550.6 126.8C551.4 128.3 552.3 130.7 552.5 132.1C556 132.1 558.3 132 559.9 131C561.5 130.2 562.1 128.7 562.1 125.9V118.7C564.2 122.5 567 125.7 570.8 128.6C571.4 127.1 572.9 125.3 574.2 124.4C570.2 121.7 567.5 118.7 565.5 114.7C567.8 112.3 570.7 108.9 573.1 105.7L568.3 103.3C567.2 105.4 565.4 107.9 563.7 110.1C563 108.1 562.5 106 562.1 103.6V101.4H573.4V96.4H569.4L572 93.8C570.9 92.4 568.4 90.5 566.5 89.2L563.5 92C565.1 93.2 567.1 95 568.3 96.4H562.1V88.9H556.7V96.4H546.1V101.4H556.7V112.5C552.9 115.7 548.8 118.9 545.8 121.1L545.2 118.1L540.6 119.5V109.9H544.6V104.8H540.6V96.7H545.2V91.6H530.6V96.7H535.4V104.8H530.8V109.9H535.4V121C533.3 121.6 531.4 122.2 529.9 122.5ZM585.2 128H592.1L594.5 119.3H605.5L607.9 128H615L604.1 93.9H596.1ZM595.9 114 597 110.2C598 106.7 598.9 102.8 599.8 99.1H600C601 102.7 602 106.7 603 110.2L604 114ZM619 128H625.8V93.9H619ZM660.3 88.9C660.3 92.7 660.3 97 659.9 101.3H643V107H659C657.1 115 652.7 122.6 642.2 12Line truncated
<rect x="72" y="148" width="266.0" height="44" rx="22" fill="#635BFF"/>
<path d="M95.9 161.8C97.2 162.4 99 163.4 99.8 164.1L101.3 162C100.4 161.4 98.6 160.5 97.3 159.9ZM94.7 167.6C96 168.3 97.8 169.2 98.7 169.9L100.1 167.8C99.1 167.2 97.3 166.3 96.1 165.7ZM95.3 177.5 97.4 179.2C98.7 177.2 100 174.8 101.1 172.6L99.3 170.9C98 173.3 96.4 175.9 95.3 177.5ZM105.5 160.3C106.1 161.4 106.6 162.7 106.9 163.6H101.3V166H106.4V169.7H102.2V172.1H106.4V176.4H100.7V178.8H114.4V176.4H109V172.1H113.1V169.7H109V166H113.8V163.6H107.4L109.4 162.8C109.2 161.9 108.4 160.6 107.8 159.6ZM126.2 161V167.9H124.6V161H117.9V167.9H115.7V170.3H117.9C117.7 172.9 117.2 175.7 115.6 177.8C116.1 178.1 117.1 179.1 117.4 179.6C119.4 177.1 120 173.4 120.2 170.3H122.2V176.7C122.2 177 122.1 177.1 121.8 177.1C121.5 177.1 120.6 177.1 119.8 177.1C120.1 177.6 120.5 178.7 120.6 179.3C122 179.3 123 179.2 123.7 178.8C124.1 178.6 124.3 178.3 124.5 177.9C125 178.3 125.8 179.1 126.1 179.5C127.8 177.1 128.4 173.4 128.6 170.3H130.8V176.6C130.8 176.9 130.7 177 130.4 177C130.1 177 129.2 177 128.4 177C128.7 177.6 129.1 178.7 129.2 179.3C130.6 179.3 131.6 179.3 132.4 178.9C133.1 178.5 133.3 177.8 133.3 176.6V170.3H135.3V167.9H133.3V161ZM120.3 163.3H122.2V167.9H120.3ZM124.6 170.3H126.2C126 172.6 125.7 175.1 124.6 177.1V176.7ZM128.6 167.9V163.3H130.8V167.9ZM140.1 166.2C140.9 167 141.8 168.1 142.3 168.8L143.9 167.6C143.4 167 142.4 166 141.6 165.3ZM146.9 164.7V174.6H149.2V166.5H153.4V174.5H155.7V164.7H151.8L152.5 162.9H156.2V160.7H146.5V162.9H150.2C150 163.5 149.8 164.1 149.6 164.7ZM150.3 167.2C150.2 174 150.1 176.4 145.4 177.8C145.8 178.2 146.4 179 146.6 179.5C149 178.8 150.4 177.7 151.2 176C152.5 177.1 154 178.5 154.8 179.4L156.4 177.9C155.6 177 153.8 175.5 152.5 174.5L151.5 175.5C152.2 173.5 152.3 170.9 152.3 167.2ZM141.4 159.6C140.4 162.1 138.6 164.9 136.4 166.6C136.9 167 137.7 167.8 138.1 168.2C139.6 167 140.9 165.3 141.9 163.5C143.2 164.9 144.6 166.4 145.3 167.5L146.8 165.8C146 164.6 144.4 162.9 143 161.6C143.2 161.1 143.4 160.7 143.5 160.2ZM138.1 168.9V171.1H143C142.4 172.2 141.8 173.4 141.1 174.4L139.9 173.3L138.2 174.5C139.7 176 141.6 178 142.4 179.2L144.3 177.8C143.9 177.2 143.3 176.6 142.7 175.9C143.8 174.2 145.2 171.9 146 169.8L144.4 168.8L144 168.9ZM174.2 164.2C173.9 166.6 173.3 168.8 172.4 170.7C171.6 168.8 171.1 166.6 170.7 164.2ZM167.7 161.9V164.2H168.4C169 167.7 169.8 170.8 171.1 173.4C170 175.2 168.6 176.6 167 177.5C167.5 178 168.2 178.8 168.6 179.4C170.1 178.4 171.3 177.2 172.4 175.7C173.4 177.1 174.5 178.3 175.9 179.2C176.3 178.6 177 177.7 177.6 177.3C176 176.4 174.8 175.1 173.8 173.5C175.4 170.5 176.4 166.8 176.9 162.2L175.3 161.8L174.9 161.9ZM157.7 174.4 158.2 176.8 163.9 175.8V179.3H166.3V175.4L168.1 175.1L168 173L166.3 173.2V162.7H167.6V160.5H157.9V162.7H159.1V174.2ZM161.5 162.7H163.9V164.9H161.5ZM161.5 167H163.9V169.3H161.5ZM161.5 171.5H163.9V173.6L161.5 173.9ZM184.4 159.6C183.3 161.7 181.3 164.1 178.4 166C179 166.4 179.8 167.3 180.2 167.9L180.9 167.4V172.1H186.2C185.2 174.2 183.1 176 178.8 177.1C179.3 177.6 180 178.6 180.2 179.2C185.5 177.7 187.8 175.2 189 172.1H189.3V176C189.3 178.3 189.9 179 192.4 179C193 179 194.8 179 195.3 179C197.4 179 198.1 178.1 198.3 175C197.6 174.9 196.6 174.5 196 174.1C196 176.4 195.8 176.7 195.1 176.7C194.6 176.7 193.2 176.7 192.8 176.7C192 176.7 191.9 176.7 191.9 176V172.1H196.6V164.9H190.9C191.7 164 192.4 162.9 192.9 162.1L191.1 160.9L190.7 161H186.5L187.1 160.1ZM183.6 164.9C184.1 164.3 184.6 163.7 185.1 163.1H189.3C188.9 163.7 188.4 164.4 187.9 164.9ZM183.4 167.1H187.3C187.2 168.1 187.1 169 186.9 169.9H183.4ZM189.9 167.1H193.9V169.9H189.6C189.7 169 189.8 168.1 189.9 167.1ZM208.6 173C207.8 175.3 206.3 176.6 199.6 177.2C200.1 177.7 200.5 178.8 200.7 179.3C208.1 178.4 210.2 176.4 211.1 173ZM209.9 176.7C212.5 177.4 216.1 178.6 217.9 179.4L219.3 177.5C217.4 176.7 213.7 175.7 211.2 175.1ZM206.1 165C206.1 165.4 206 165.7 205.9 165.9H203.6L203.8 165ZM208.3 165H210.7V165.9H208.3C208.3 165.7 208.3 165.4 208.3 165ZM201.8 163.4C201.6 164.8 201.3 166.5 201.1 167.6H204.8C203.9 168.3 202.4 168.9 199.9 169.3C200.4 169.8 201 170.7 201.2 171.2C201.7 171.1 202.2 171.1 202.6 170.9V176H205V172.3H213.9V175.8H216.5V170.2H204.7C206.3 169.5 207.2 168.6 207.7 167.6H210.7V169.8H213.1V167.6H216.3C216.3 167.9 216.2 168.1 216.2 168.2C216.1 168.3 215.9 168.3 215.7 168.3C215.5 168.3 215.1 168.3 214.6 168.2C214.8 168.7 215 169.4 215 169.8C215.8 169.9 216.6 169.9 217 169.8C217.4 169.8 217.9 169.6 218.2 169.3C218.6 168.9 218.7 168.1 218.8 166.6C218.8 166.4 218.8 165.9 218.8 165.9H213.1V165H217.5V160.7H213.1V159.7H210.7V160.7H208.4V159.7H206.1V160.7H201.2V162.4H206.1V163.4L202.7 163.4ZM208.4 162.4H210.7V163.4H208.4ZM213.1 162.4H215.2V163.4H213.1ZM222 161.5C223.2 162.5 224.6 163.9 225.3 164.8L227 163.1C226.3 162.2 224.8 160.8 223.7 159.9ZM228 168.5V170.8H229.7V175.3L228.4 175.7L228.4 175.7C228.2 175.2 227.9 174.2 227.8 173.5L225.9 174.7V166.1H221V168.6H223.5V174.9C223.5 175.8 222.9 176.5 222.4 176.8C222.8 177.3 223.4 178.4 223.5 179C223.9 178.6 224.6 178.2 227.7 176.1L228.3 178.2C230.1 177.6 232.3 177 234.5 176.4L234.Line truncated
<path d="M315.0 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#fff" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M367.6 177.5H371.1L372.3 172.4C372.6 171.3 372.8 170.2 373 168.9H373.1C373.3 170.2 373.5 171.3 373.8 172.4L375 177.5H378.6L381.5 165.7H378.7L377.4 171.5C377.2 172.7 377 173.8 376.8 175H376.7C376.5 173.8 376.2 172.7 376 171.5L374.5 165.7H371.8L370.3 171.5C370 172.7 369.8 173.8 369.6 175H369.5C369.3 173.8 369.1 172.7 369 171.5L367.7 165.7H364.6ZM386.7 177.8C388 177.8 389.2 177.1 390.2 176.2H390.3L390.5 177.5H393V170.6C393 167.2 391.5 165.4 388.5 165.4C386.7 165.4 385 166.2 383.6 167L384.7 169.1C385.8 168.4 386.9 167.9 388 167.9C389.4 167.9 389.9 168.8 390 170C385.2 170.5 383.2 171.8 383.2 174.3C383.2 176.3 384.6 177.8 386.7 177.8ZM387.7 175.4C386.8 175.4 386.1 175 386.1 174.1C386.1 173 387.1 172.2 390 171.9V174.2C389.2 175 388.6 175.4 387.7 175.4ZM396.2 177.5H399.3V169.4C400.1 168.6 400.8 168.1 401.7 168.1C402.9 168.1 403.4 168.7 403.4 170.5V177.5H406.5V170.2C406.5 167.2 405.4 165.4 402.8 165.4C401.2 165.4 400 166.3 399 167.3H398.9L398.7 165.7H396.2ZM413.8 177.8C415 177.8 416.2 177.1 417 176.3H417.1L417.4 177.5H419.9V160.7H416.8V164.9L416.9 166.7C416.1 165.9 415.2 165.4 413.9 165.4C411.4 165.4 409 167.8 409 171.6C409 175.5 410.9 177.8 413.8 177.8ZM414.6 175.3C413 175.3 412.2 174 412.2 171.6C412.2 169.2 413.3 168 414.6 168C415.3 168 416.1 168.2 416.8 168.9V174C416.1 174.9 415.4 175.3 414.6 175.3ZM426.1 177.8C427.4 177.8 428.6 177.1 429.6 176.2H429.7L429.9 177.5H432.4V170.6C432.4 167.2 430.9 165.4 427.9 165.4C426.1 165.4 424.4 166.2 423 167L424.1 169.1C425.2 168.4 426.3 167.9 427.4 167.9C428.8 167.9 429.3 168.8 429.4 170C424.6 170.5 422.6 171.8 422.6 174.3C422.6 176.3 424 177.8 426.1 177.8ZM427.1 175.4C426.2 175.4 425.5 175 425.5 174.1C425.5 173 426.5 172.2 429.4 171.9V174.2C428.6 175 428 175.4 427.1 175.4ZM435.6 182H438.7V178.4L438.6 176.5C439.5 177.3 440.5 177.8 441.5 177.8C444.1 177.8 446.5 175.5 446.5 171.4C446.5 167.8 444.7 165.4 441.9 165.4C440.6 165.4 439.4 166.1 438.4 167H438.3L438.1 165.7H435.6ZM440.8 175.3C440.2 175.3 439.4 175 438.7 174.4V169.2C439.5 168.4 440.2 168 441 168C442.6 168 443.3 169.2 443.3 171.5C443.3 174 442.2 175.3 440.8 175.3ZM449.1 177.5H452.2V165.7H449.1ZM450.7 163.8C451.7 163.8 452.5 163.2 452.5 162.1C452.5 161.1 451.7 160.5 450.7 160.5C449.6 160.5 448.9 161.1 448.9 162.1C448.9 163.2 449.6 163.8 450.7 163.8ZM457.3 177.8C458.4 177.8 459.2 176.9 459.2 175.8C459.2 174.6 458.4 173.8 457.3 173.8C456.1 173.8 455.3 174.6 455.3 175.8C455.3 176.9 456.1 177.8 457.3 177.8ZM465.2 177.8C466.6 177.8 467.7 177.1 468.7 176.2H468.9L469.1 177.5H471.6V170.6C471.6 167.2 470.1 165.4 467.1 165.4C465.2 165.4 463.5 166.2 462.2 167L463.3 169.1C464.4 168.4 465.4 167.9 466.5 167.9C467.9 167.9 468.5 168.8 468.5 170C463.8 170.5 461.7 171.8 461.7 174.3C461.7 176.3 463.1 177.8 465.2 177.8ZM466.2 175.4C465.3 175.4 464.7 175 464.7 174.1C464.7 173 465.6 172.2 468.5 171.9V174.2C467.8 175 467.1 175.4 466.2 175.4ZM474.7 177.5H477.8V165.7H474.7ZM476.3 163.8C477.3 163.8 478.1 163.2 478.1 162.1C478.1 161.1 477.3 160.5 476.3 160.5C475.2 160.5 474.5 161.1 474.5 162.1C474.5 163.2 475.2 163.8 476.3 163.8Z" fill="#635BFF"/>
<path d="M488.5 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#635BFF" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="1024" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1036" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1055.0 93.0) scale(1.4166666666666667)" ><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></g>
<rect x="1108" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1120" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1139.0 93.0) scale(1.4166666666666667)" fill="#0A2540" fill-rule="evenodd"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></g>
<rect x="1192" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1204" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1223.0 93.0) scale(1.4166666666666667)" ><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-0-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-1-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-2-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-0-_R_0_" x1="7" x2="11" y1="15.5" y2="12"><stop stop-color="#08B962"></stop><stop offset="1" stop-color="#08B962" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-1-_R_0_" x1="8" x2="11.5" y1="5.5" y2="11"><stop stop-color="#F94543"></stop><stop offset="1" stop-color="#F94543" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-2-_R_0_" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stop-color="#FABC12"></stop><stop offset=".46" stop-color="#FABC12" stop-opacity="0"></stop></linearGradient></defs></g>
<rect x="1276" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1288" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1307.0 93.0) scale(1.4166666666666667)" ><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></g>
<rect x="1360" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1372" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1391.0 93.0) scale(1.4166666666666667)" fill="#0A2540" fill-rule="evenodd"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></g>
<rect x="1444" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1456" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1475.0 93.0) scale(1.4166666666666667)" ><path d="M19.713 2.825h-5.907c0-.251-.066-.503-.196-.728L12.819.728A1.46 1.46 0 0 0 11.559 0h-1.58c-.52 0-1 .275-1.26.728l-2.42 4.19a1.45 1.45 0 0 0 0 1.453l.791 1.37c.26.448.74.727 1.26.727h11.36c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-.79-1.37a1.46 1.46 0 0 0-1.26-.728zM.195 9.905l2.951 5.115a1.46 1.46 0 0 0-.531.531l-.791 1.37a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h4.84c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451L5.086 7.083a1.46 1.46 0 0 0-1.26-.728h-1.58c-.52 0-1 .276-1.26.728l-.79 1.37a1.45 1.45 0 0 0 0 1.452m15.888 13.367 2.951-5.115c.217.125.469.196.728.196h1.582c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-2.42-4.191a1.46 1.46 0 0 0-1.259-.728h-1.582c-.52 0-1 .276-1.259.728l-5.678 9.838a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h1.582c.52 0 1-.275 1.26-.728z" fill="#082dff"></path></g>
<rect x="1528" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1540" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1559.0 93.0) scale(1.4166666666666667)" ><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#0A2540"></path></g>
<rect x="1612" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1624" y="74" width="72" height="72" rx="18" fill="#635BFF"/><rect x="1624.75" y="74.75" width="70.5" height="70.5" rx="17.25" fill="none" stroke="#fff" stroke-opacity=".35" stroke-width="1.5"/>
<path d="M1651.0 99H1669.0M1660.0 90V108" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
<path d="M1644.6 120.5V128H1646.6L1644.9 128.6C1645.5 129.4 1646.1 130.1 1646.8 130.7C1645.8 131.1 1644.4 131.4 1642.7 131.7C1643.2 132.2 1643.8 133.1 1644 133.6C1646.1 133.2 1647.7 132.6 1648.9 131.9C1651.5 133.1 1654.8 133.3 1658.8 133.4C1658.9 132.7 1659.3 131.8 1659.7 131.3C1656 131.3 1653 131.2 1650.7 130.5C1651.4 129.7 1651.8 128.9 1652 128H1657.8V120.5H1652.3V119.5H1658.9V117.5H1643.1V119.5H1650V120.5ZM1646.7 125H1650V125.6L1650 126.2H1646.7ZM1652.3 126.2 1652.3 125.6V125H1655.7V126.2ZM1646.7 122.2H1650V123.4H1646.7ZM1652.3 122.2H1655.7V123.4H1652.3ZM1649.7 128C1649.5 128.5 1649.1 129 1648.6 129.5C1648 129.1 1647.4 128.6 1646.9 128ZM1667.9 116.6C1666.6 118.1 1664.5 119.6 1661.6 120.7C1662.1 121 1662.7 121.7 1663 122.2C1664.5 121.6 1665.8 120.9 1666.9 120.1H1671.4C1670.6 120.9 1669.6 121.6 1668.4 122.2C1667.9 121.7 1667.2 121.2 1666.6 120.8L1665 121.8C1665.5 122.2 1666 122.6 1666.5 123.1C1664.8 123.7 1663 124.2 1661.1 124.4C1661.5 124.9 1661.9 125.8 1662.1 126.3C1667.3 125.3 1672.5 123.1 1674.8 118.9L1673.4 118.1L1673 118.2H1669.2C1669.5 117.9 1669.9 117.5 1670.2 117.2ZM1670.8 123.1C1669.5 124.9 1667 126.6 1663.3 127.8C1663.7 128.2 1664.3 129 1664.6 129.5C1666.6 128.7 1668.4 127.8 1669.8 126.8H1673.9C1673.1 127.8 1672.1 128.6 1670.9 129.2C1670.3 128.7 1669.7 128.2 1669.1 127.8L1667.3 128.8C1667.8 129.2 1668.4 129.7 1668.9 130.1C1666.6 130.9 1663.9 131.4 1661 131.6C1661.3 132.1 1661.7 133.1 1661.8 133.7C1668.7 133 1674.7 131.1 1677.2 125.6L1675.7 124.7L1675.3 124.9H1672.1C1672.5 124.5 1672.9 124 1673.2 123.6Z" fill="#fff"/>
</g>
<rect x=".75" y=".75" width="1758.5" height="218.5" rx="19.25" fill="none" stroke="#E3E8EE" stroke-width="1.5"/>
</svg>

After

Width:  |  Height:  |  Size: 34 KiB

@@ -0,0 +1,57 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1760" height="220" viewBox="0 0 1760 220" role="img" aria-label="WandAPI">
<defs>
<linearGradient id="logoW" gradientUnits="userSpaceOnUse" x1="4" y1="8" x2="44" y2="44"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
<linearGradient id="band" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
<radialGradient id="bA" cx="1200" cy="-20" r="280" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#A960EE" stop-opacity="0.95"/><stop offset="1" stop-color="#A960EE" stop-opacity="0"/></radialGradient><radialGradient id="bB" cx="1720" cy="20" r="300" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#00D4FF" stop-opacity="0.9"/><stop offset="1" stop-color="#00D4FF" stop-opacity="0"/></radialGradient><radialGradient id="bC" cx="1500" cy="260" r="260" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#FF80B5" stop-opacity="0.65"/><stop offset="1" stop-color="#FF80B5" stop-opacity="0"/></radialGradient><radialGradient id="bD" cx="1000" cy="260" r="240" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7A73FF" stop-opacity="0.9"/><stop offset="1" stop-color="#7A73FF" stop-opacity="0"/></radialGradient><radialGradient id="bE" cx="1380" cy="110" r="200" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#90E0FF" stop-opacity="0.55"/><stop offset="1" stop-color="#90E0FF" stop-opacity="0"/></radialGradient>
<radialGradient id="shadow" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#000000" stop-opacity=".45"/><stop offset="1" stop-color="#000000" stop-opacity="0"/></radialGradient>
<clipPath id="frame"><rect width="1760" height="220" rx="20"/></clipPath>
<clipPath id="slant"><polygon points="980,0 1760,0 1760,220 900,220"/></clipPath>
</defs>
<g clip-path="url(#frame)">
<rect width="1760" height="220" fill="#0A2540"/>
<g clip-path="url(#slant)">
<rect x="900" width="860" height="220" fill="url(#band)"/>
<rect x="900" width="860" height="220" fill="url(#bA)"/><rect x="900" width="860" height="220" fill="url(#bB)"/><rect x="900" width="860" height="220" fill="url(#bC)"/><rect x="900" width="860" height="220" fill="url(#bD)"/><rect x="900" width="860" height="220" fill="url(#bE)"/>
</g>
<g transform="translate(72 36) scale(0.7)">
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="8">
<polyline points="4,8 14,44 24,22 34,44 44,8" stroke="url(#logoW)"/>
<g stroke="#FFFFFF"><circle cx="70" cy="32" r="12"/><line x1="82" y1="20" x2="82" y2="44"/><path d="M96 20V44M96 32a12 12 0 0 1 24 0V44"/><circle cx="146" cy="32" r="12"/><line x1="158" y1="8" x2="158" y2="44"/></g>
<g stroke="#8C86FF"><polyline points="172,44 188,8 204,44"/><path d="M218 44V8h8a10 10 0 0 1 0 20h-8"/><line x1="250" y1="8" x2="250" y2="44"/></g>
</g>
<path d="M24 -1Q24.9 5.1 31 6Q24.9 6.9 24 13Q23.1 6.9 17 6Q23.1 5.1 24 -1Z" fill="#8C86FF"/>
</g>
<path d="M89.7 128.6C98.7 128.6 104.9 121.9 104.9 110.8C104.9 99.8 98.7 93.3 89.7 93.3C80.7 93.3 74.5 99.8 74.5 110.8C74.5 121.9 80.7 128.6 89.7 128.6ZM89.7 122.8C84.7 122.8 81.5 118.1 81.5 110.8C81.5 103.5 84.7 99.2 89.7 99.2C94.8 99.2 98 103.5 98 110.8C98 118.1 94.8 122.8 89.7 122.8ZM111.1 128H117.8V110.3C119.7 108.4 121.1 107.4 123.2 107.4C125.7 107.4 126.8 108.8 126.8 112.8V128H133.5V111.9C133.5 105.5 131.2 101.6 125.6 101.6C122.1 101.6 119.5 103.4 117.2 105.6H117.1L116.6 102.2H111.1ZM151.8 128.6C154.9 128.6 158.2 127.5 160.7 125.8L158.4 121.7C156.5 122.8 154.8 123.4 152.7 123.4C148.8 123.4 146.1 121.2 145.5 117.1H161.4C161.6 116.4 161.7 115.2 161.7 113.9C161.7 106.7 158 101.6 150.9 101.6C144.8 101.6 138.9 106.8 138.9 115.1C138.9 123.6 144.5 128.6 151.8 128.6ZM145.4 112.5C145.9 108.8 148.3 106.8 151 106.8C154.4 106.8 155.9 109 155.9 112.5ZM173.9 128H180.8L183.2 119.3H194.2L196.6 128H203.7L192.8 93.9H184.8ZM184.7 114 185.7 110.2C186.7 106.7 187.6 102.8 188.6 99.1H188.7C189.8 102.7 190.7 106.7 191.7 110.2L192.8 114ZM207.7 128H214.6V115.9H219.1C226.4 115.9 232.3 112.4 232.3 104.6C232.3 96.6 226.5 93.9 218.9 93.9H207.7ZM214.6 110.5V99.3H218.4C223.1 99.3 225.6 100.7 225.6 104.6C225.6 108.5 223.3 110.5 218.6 110.5ZM238.4 128H245.2V93.9H238.4ZM263.5 128H270.2V121.5L273.8 117.3L280 128H287.4L277.7 112.9L286.5 102.2H279.1L270.4 113.3H270.2V91.3H263.5ZM302.5 128.6C305.7 128.6 308.9 127.5 311.5 125.8L309.2 121.7C307.3 122.8 305.5 123.4 303.4 123.4C299.6 123.4 296.8 121.2 296.2 117.1H312.1C312.3 116.4 312.4 115.2 312.4 113.9C312.4 106.7 308.8 101.6 301.7 101.6C295.6 101.6 289.7 106.8 289.7 115.1C289.7 123.6 295.3 128.6 302.5 128.6ZM296.1 112.5C296.7 108.8 299.1 106.8 301.8 106.8C305.1 106.8 306.6 109 306.6 112.5ZM320.3 138.3C326 138.3 328.8 134.9 331 128.8L340.2 102.2H333.7L330.2 114.2C329.5 116.6 328.9 119.1 328.3 121.5H328.1C327.3 119 326.7 116.5 325.9 114.2L321.8 102.2H315L325 127.5L324.6 129.1C323.8 131.3 322.4 133 319.8 133C319.2 133 318.4 132.8 318 132.6L316.7 137.8C317.7 138.1 318.7 138.3 320.3 138.3ZM348.3 128.6C350.7 128.6 352.5 126.7 352.5 124.2C352.5 121.7 350.7 119.8 348.3 119.8C345.8 119.8 344 121.7 344 124.2C344 126.7 345.8 128.6 348.3 128.6ZM370.4 128H391.7V122.3H377.2V113.2H389.1V107.5H377.2V99.6H391.2V93.9H370.4ZM403.9 128H411.7L420.3 102.2H413.8L410.1 115.1C409.4 117.6 408.7 120.3 408 122.9H407.8C407 120.3 406.4 117.6 405.6 115.1L401.9 102.2H395.1ZM435.8 128.6C439 128.6 442.3 127.5 444.8 125.8L442.5 121.7C440.6 122.8 438.8 123.4 436.7 123.4C432.9 123.4 430.1 121.2 429.6 117.1H445.4C445.6 116.4 445.7 115.2 445.7 113.9C445.7 106.7 442.1 101.6 435 101.6C428.9 101.6 423 106.8 423 115.1C423 123.6 428.6 128.6 435.8 128.6ZM429.4 112.5C430 108.8 432.4 106.8 435.1 106.8C438.4 106.8 440 109 440 112.5ZM451.3 128H458.1V112.6C459.5 108.9 461.9 107.6 463.9 107.6C465 107.6 465.8 107.7 466.7 108L467.8 102.1C467 101.8 466.2 101.6 464.8 101.6C462.1 101.6 459.4 103.4 457.5 106.8H457.3L456.8 102.2H451.3ZM473.6 138.3C479.4 138.3 482.1 134.9 484.4 128.8L493.5 102.2H487.1L483.5 114.2C482.9 116.6 482.2 119.1 481.7 121.5H481.4C480.7 119 480.1 116.5 479.3 114.2L475.2 102.2H468.4L478.4 127.5L477.9 129.1C477.2 131.3 475.7 133 473.1 133C472.5 133 471.8 132.8 471.3 132.6L470.1 137.8C471.1 138.1 472.1 138.3 473.6 138.3ZM517.6 128.6C519.9 128.6 521.7 128.1 523.1 127.7L522 122.8C521.3 123 520.3 123.3 519.4 123.3C517.1 123.3 515.9 121.9 515.9 119V107.6H522.3V102.2H515.9V95.3H510.3L509.6 102.2L505.5 102.6V107.6H509.2V119C509.2 124.7 511.5 128.6 517.6 128.6ZM538.3 128.6C544.8 128.6 550.7 123.7 550.7 115.1C550.7 106.6 544.8 101.6 538.3 101.6C531.9 101.6 526 106.6 526 115.1C526 123.7 531.9 128.6 538.3 128.6ZM538.3 123.1C534.8 123.1 532.9 120 532.9 115.1C532.9 110.3 534.8 107.1 538.3 107.1C541.8 107.1 543.8 110.3 543.8 115.1C543.8 120 541.8 123.1 538.3 123.1ZM556.4 137.9H563.1V130L562.9 125.8C564.8 127.6 567.1 128.6 569.3 128.6C575 128.6 580.3 123.5 580.3 114.7C580.3 106.8 576.4 101.6 570.1 101.6C567.3 101.6 564.7 103.1 562.5 104.9H562.4L561.9 102.2H556.4ZM567.8 123.1C566.4 123.1 564.8 122.6 563.1 121.1V109.8C564.9 108 566.5 107.2 568.2 107.2C571.7 107.2 573.3 109.9 573.3 114.8C573.3 120.4 570.9 123.1 567.8 123.1ZM592.6 128H599.5L601.9 119.3H612.9L615.3 128H622.5L611.6 93.9H603.5ZM603.4 114 604.4 110.2C605.4 106.7 606.4 102.8 607.3 99.1H607.5C608.5 102.7 609.4 106.7 610.5 110.2L611.5 114ZM626.5 128H633.3V93.9H626.5ZM651.6 128H658.3V110.3C660.1 108.3 661.8 107.4 663.2 107.4C665.7 107.4 666.9 108.8 666.9 112.8V128H673.6V110.3C675.4 108.3 677.1 107.4 678.6 107.4C681 107.4 682.1 108.8 682.1 112.8V128H688.9V111.9C688.9 105.5 686.4 101.6 680.9 101.6C677.6 101.6 675.1 103.6 672.7 106.1C671.5 103.3 669.3 101.6 665.6 101.6C662.3 101.6 659.9 103.4 657.7 105.7H657.6L657.1 102.2H651.6ZM706.7 128.6C713.1 128.6 719 123.7 719 115.1C719 106.6 713.1 101.6 706.7 101.6C700.2 101.6 694.3 106.6 694.3 115.1C694.3 123.7 700.2 128.6 706.7 128.6ZM706.7 123.1C703.1 123.1 701.2 120 701.2 115.1C701.2 110.3 703.1 107.1 706.7 107.1C710.2 107.1 712.1 110.3 712.1 11Line truncated
<rect x="72" y="148" width="262.7" height="44" rx="22" fill="#635BFF"/>
<path d="M102.6 177.8C104.7 177.8 106.6 177 107.7 175.9V168.9H102.1V171.5H104.9V174.5C104.4 174.9 103.7 175.1 102.9 175.1C99.9 175.1 98.3 173.1 98.3 169.7C98.3 166.3 100.1 164.3 102.7 164.3C104.1 164.3 105 164.9 105.7 165.6L107.4 163.7C106.4 162.6 104.8 161.7 102.6 161.7C98.5 161.7 95.1 164.7 95.1 169.8C95.1 175 98.4 177.8 102.6 177.8ZM115.8 177.8C117.3 177.8 118.8 177.3 119.9 176.5L118.9 174.6C118 175.1 117.2 175.4 116.3 175.4C114.5 175.4 113.2 174.4 113 172.5H120.2C120.3 172.2 120.4 171.6 120.4 171.1C120.4 167.8 118.7 165.4 115.5 165.4C112.7 165.4 110 167.8 110 171.6C110 175.5 112.5 177.8 115.8 177.8ZM112.9 170.4C113.2 168.7 114.3 167.8 115.5 167.8C117 167.8 117.7 168.8 117.7 170.4ZM127.2 177.8C128.3 177.8 129.1 177.5 129.7 177.4L129.2 175.1C128.9 175.2 128.4 175.4 128 175.4C127 175.4 126.4 174.7 126.4 173.4V168.2H129.3V165.7H126.4V162.6H123.9L123.5 165.7L121.7 165.9V168.2H123.4V173.4C123.4 176 124.4 177.8 127.2 177.8ZM135.5 168.2H137.1V177.5H140.1V168.2H142.4V165.7H140.1V164.7C140.1 163.4 140.6 162.9 141.5 162.9C142 162.9 142.4 163 142.8 163.2L143.4 160.8C142.8 160.6 142 160.4 141.1 160.4C138.2 160.4 137.1 162.4 137.1 164.8V165.8L135.5 165.9ZM144.3 177.5H147.4V170.5C148.1 168.8 149.2 168.2 150.1 168.2C150.6 168.2 150.9 168.2 151.4 168.4L151.9 165.7C151.5 165.6 151.1 165.4 150.5 165.4C149.3 165.4 148 166.3 147.2 167.8H147.1L146.9 165.7H144.3ZM158.6 177.8C160.1 177.8 161.6 177.3 162.7 176.5L161.7 174.6C160.8 175.1 160 175.4 159 175.4C157.3 175.4 156 174.4 155.8 172.5H163C163.1 172.2 163.2 171.6 163.2 171.1C163.2 167.8 161.5 165.4 158.2 165.4C155.4 165.4 152.8 167.8 152.8 171.6C152.8 175.5 155.3 177.8 158.6 177.8ZM155.7 170.4C156 168.7 157 167.8 158.3 167.8C159.8 167.8 160.5 168.8 160.5 170.4ZM170.8 177.8C172.3 177.8 173.8 177.3 174.9 176.5L173.9 174.6C173 175.1 172.2 175.4 171.2 175.4C169.5 175.4 168.2 174.4 168 172.5H175.2C175.3 172.2 175.4 171.6 175.4 171.1C175.4 167.8 173.7 165.4 170.4 165.4C167.6 165.4 165 167.8 165 171.6C165 175.5 167.5 177.8 170.8 177.8ZM167.9 170.4C168.2 168.7 169.2 167.8 170.5 167.8C172 167.8 172.7 168.8 172.7 170.4ZM187 177.8C188 177.8 188.8 177.5 189.5 177.4L188.9 175.1C188.6 175.2 188.2 175.4 187.8 175.4C186.7 175.4 186.2 174.7 186.2 173.4V168.2H189.1V165.7H186.2V162.6H183.6L183.3 165.7L181.4 165.9V168.2H183.1V173.4C183.1 176 184.2 177.8 187 177.8ZM191.5 177.5H194.6V170.5C195.3 168.8 196.4 168.2 197.3 168.2C197.8 168.2 198.1 168.2 198.5 168.4L199 165.7C198.7 165.6 198.3 165.4 197.7 165.4C196.4 165.4 195.2 166.3 194.3 167.8H194.3L194 165.7H191.5ZM200.7 177.5H203.7V165.7H200.7ZM202.2 163.8C203.3 163.8 204 163.2 204 162.1C204 161.1 203.3 160.5 202.2 160.5C201.1 160.5 200.4 161.1 200.4 162.1C200.4 163.2 201.1 163.8 202.2 163.8ZM209.9 177.8C211.3 177.8 212.5 177.1 213.5 176.2H213.6L213.8 177.5H216.3V170.6C216.3 167.2 214.8 165.4 211.8 165.4C209.9 165.4 208.3 166.2 206.9 167L208 169.1C209.1 168.4 210.1 167.9 211.2 167.9C212.7 167.9 213.2 168.8 213.2 170C208.5 170.5 206.5 171.8 206.5 174.3C206.5 176.3 207.8 177.8 209.9 177.8ZM210.9 175.4C210 175.4 209.4 175 209.4 174.1C209.4 173 210.3 172.2 213.2 171.9V174.2C212.5 175 211.8 175.4 210.9 175.4ZM222.4 177.8C223.1 177.8 223.6 177.7 223.9 177.5L223.6 175.2C223.4 175.3 223.3 175.3 223.2 175.3C222.9 175.3 222.5 175 222.5 174.3V160.7H219.5V174.2C219.5 176.4 220.2 177.8 222.4 177.8ZM235.8 177.8C237.1 177.8 238.6 177.4 239.7 176.4L238.5 174.3C237.8 174.9 237 175.3 236.2 175.3C234.5 175.3 233.3 173.8 233.3 171.6C233.3 169.4 234.5 168 236.3 168C236.9 168 237.5 168.2 238.1 168.7L239.5 166.8C238.7 166 237.6 165.4 236.1 165.4C232.9 165.4 230.1 167.7 230.1 171.6C230.1 175.5 232.6 177.8 235.8 177.8ZM241.9 177.5H245V170.5C245.7 168.8 246.8 168.2 247.7 168.2C248.2 168.2 248.5 168.2 248.9 168.4L249.4 165.7C249.1 165.6 248.7 165.4 248.1 165.4C246.8 165.4 245.6 166.3 244.7 167.8H244.7L244.4 165.7H241.9ZM256.2 177.8C257.6 177.8 259.1 177.3 260.3 176.5L259.2 174.6C258.4 175.1 257.5 175.4 256.6 175.4C254.8 175.4 253.6 174.4 253.3 172.5H260.6C260.7 172.2 260.7 171.6 260.7 171.1C260.7 167.8 259 165.4 255.8 165.4C253 165.4 250.3 167.8 250.3 171.6C250.3 175.5 252.9 177.8 256.2 177.8ZM253.3 170.4C253.5 168.7 254.6 167.8 255.8 167.8C257.4 167.8 258.1 168.8 258.1 170.4ZM267.4 177.8C268.6 177.8 269.8 177.1 270.7 176.3H270.7L271 177.5H273.5V160.7H270.4V164.9L270.5 166.7C269.7 165.9 268.8 165.4 267.5 165.4C265 165.4 262.6 167.8 262.6 171.6C262.6 175.5 264.5 177.8 267.4 177.8ZM268.2 175.3C266.6 175.3 265.8 174 265.8 171.6C265.8 169.2 266.9 168 268.2 168C269 168 269.7 168.2 270.4 168.9V174C269.7 174.9 269 175.3 268.2 175.3ZM276.8 177.5H279.9V165.7H276.8ZM278.3 163.8C279.4 163.8 280.1 163.2 280.1 162.1C280.1 161.1 279.4 160.5 278.3 160.5C277.2 160.5 276.6 161.1 276.6 162.1C276.6 163.2 277.2 163.8 278.3 163.8ZM287.5 177.8C288.5 177.8 289.3 177.5 290 177.4L289.4 175.1C289.1 175.2 288.7 175.4 288.3 175.4C287.2 175.4 286.7 174.7 286.7 173.4V168.2H289.6V165.7H286.7V162.6H284.1L283.8 165.7L282 165.9V168.2H283.6V173.4C283.6 176 284.7 177.8 287.5 177.8ZM295.4 177.8C298.4 177.8 30Line truncated
<path d="M311.7 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#fff" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M364.4 177.5H367.9L369.1 172.4C369.3 171.3 369.5 170.2 369.7 168.9H369.8C370 170.2 370.3 171.3 370.5 172.4L371.7 177.5H375.4L378.3 165.7H375.4L374.1 171.5C373.9 172.7 373.8 173.8 373.6 175H373.5C373.2 173.8 373 172.7 372.7 171.5L371.2 165.7H368.5L367.1 171.5C366.8 172.7 366.6 173.8 366.4 175H366.2C366.1 173.8 365.9 172.7 365.7 171.5L364.4 165.7H361.3ZM383.4 177.8C384.8 177.8 385.9 177.1 387 176.2H387.1L387.3 177.5H389.8V170.6C389.8 167.2 388.3 165.4 385.3 165.4C383.4 165.4 381.7 166.2 380.4 167L381.5 169.1C382.6 168.4 383.6 167.9 384.7 167.9C386.2 167.9 386.7 168.8 386.7 170C382 170.5 379.9 171.8 379.9 174.3C379.9 176.3 381.3 177.8 383.4 177.8ZM384.4 175.4C383.5 175.4 382.9 175 382.9 174.1C382.9 173 383.8 172.2 386.7 171.9V174.2C386 175 385.3 175.4 384.4 175.4ZM392.9 177.5H396V169.4C396.9 168.6 397.5 168.1 398.5 168.1C399.6 168.1 400.1 168.7 400.1 170.5V177.5H403.2V170.2C403.2 167.2 402.1 165.4 399.6 165.4C398 165.4 396.8 166.3 395.8 167.3H395.7L395.5 165.7H392.9ZM410.5 177.8C411.8 177.8 412.9 177.1 413.8 176.3H413.9L414.1 177.5H416.6V160.7H413.5V164.9L413.6 166.7C412.8 165.9 412 165.4 410.7 165.4C408.1 165.4 405.7 167.8 405.7 171.6C405.7 175.5 407.6 177.8 410.5 177.8ZM411.3 175.3C409.8 175.3 408.9 174 408.9 171.6C408.9 169.2 410 168 411.3 168C412.1 168 412.8 168.2 413.5 168.9V174C412.9 174.9 412.2 175.3 411.3 175.3ZM422.8 177.8C424.2 177.8 425.3 177.1 426.3 176.2H426.5L426.7 177.5H429.2V170.6C429.2 167.2 427.7 165.4 424.7 165.4C422.8 165.4 421.1 166.2 419.8 167L420.9 169.1C422 168.4 423 167.9 424.1 167.9C425.6 167.9 426.1 168.8 426.1 170C421.4 170.5 419.3 171.8 419.3 174.3C419.3 176.3 420.7 177.8 422.8 177.8ZM423.8 175.4C422.9 175.4 422.3 175 422.3 174.1C422.3 173 423.2 172.2 426.1 171.9V174.2C425.4 175 424.7 175.4 423.8 175.4ZM432.3 182H435.4V178.4L435.3 176.5C436.2 177.3 437.2 177.8 438.2 177.8C440.8 177.8 443.2 175.5 443.2 171.4C443.2 167.8 441.5 165.4 438.6 165.4C437.3 165.4 436.1 166.1 435.1 167H435.1L434.9 165.7H432.3ZM437.6 175.3C436.9 175.3 436.2 175 435.4 174.4V169.2C436.2 168.4 436.9 168 437.7 168C439.3 168 440.1 169.2 440.1 171.5C440.1 174 438.9 175.3 437.6 175.3ZM445.9 177.5H448.9V165.7H445.9ZM447.4 163.8C448.5 163.8 449.2 163.2 449.2 162.1C449.2 161.1 448.5 160.5 447.4 160.5C446.3 160.5 445.6 161.1 445.6 162.1C445.6 163.2 446.3 163.8 447.4 163.8ZM454 177.8C455.1 177.8 455.9 176.9 455.9 175.8C455.9 174.6 455.1 173.8 454 173.8C452.9 173.8 452.1 174.6 452.1 175.8C452.1 176.9 452.9 177.8 454 177.8ZM461.9 177.8C463.3 177.8 464.5 177.1 465.5 176.2H465.6L465.8 177.5H468.3V170.6C468.3 167.2 466.8 165.4 463.8 165.4C462 165.4 460.3 166.2 458.9 167L460 169.1C461.1 168.4 462.2 167.9 463.2 167.9C464.7 167.9 465.2 168.8 465.2 170C460.5 170.5 458.5 171.8 458.5 174.3C458.5 176.3 459.8 177.8 461.9 177.8ZM463 175.4C462.1 175.4 461.4 175 461.4 174.1C461.4 173 462.4 172.2 465.2 171.9V174.2C464.5 175 463.9 175.4 463 175.4ZM471.5 177.5H474.6V165.7H471.5ZM473 163.8C474.1 163.8 474.8 163.2 474.8 162.1C474.8 161.1 474.1 160.5 473 160.5C471.9 160.5 471.2 161.1 471.2 162.1C471.2 163.2 471.9 163.8 473 163.8Z" fill="#8C86FF"/>
<path d="M485.2 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#8C86FF" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="1024" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1036" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1055.0 93.0) scale(1.4166666666666667)" ><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></g>
<rect x="1108" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1120" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1139.0 93.0) scale(1.4166666666666667)" fill="#FFFFFF" fill-rule="evenodd"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></g>
<rect x="1192" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1204" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1223.0 93.0) scale(1.4166666666666667)" ><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-0-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-1-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-2-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-0-_R_0_" x1="7" x2="11" y1="15.5" y2="12"><stop stop-color="#08B962"></stop><stop offset="1" stop-color="#08B962" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-1-_R_0_" x1="8" x2="11.5" y1="5.5" y2="11"><stop stop-color="#F94543"></stop><stop offset="1" stop-color="#F94543" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-2-_R_0_" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stop-color="#FABC12"></stop><stop offset=".46" stop-color="#FABC12" stop-opacity="0"></stop></linearGradient></defs></g>
<rect x="1276" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1288" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1307.0 93.0) scale(1.4166666666666667)" ><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></g>
<rect x="1360" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1372" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1391.0 93.0) scale(1.4166666666666667)" fill="#FFFFFF" fill-rule="evenodd"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></g>
<rect x="1444" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1456" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1475.0 93.0) scale(1.4166666666666667)" ><path d="M19.713 2.825h-5.907c0-.251-.066-.503-.196-.728L12.819.728A1.46 1.46 0 0 0 11.559 0h-1.58c-.52 0-1 .275-1.26.728l-2.42 4.19a1.45 1.45 0 0 0 0 1.453l.791 1.37c.26.448.74.727 1.26.727h11.36c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-.79-1.37a1.46 1.46 0 0 0-1.26-.728zM.195 9.905l2.951 5.115a1.46 1.46 0 0 0-.531.531l-.791 1.37a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h4.84c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451L5.086 7.083a1.46 1.46 0 0 0-1.26-.728h-1.58c-.52 0-1 .276-1.26.728l-.79 1.37a1.45 1.45 0 0 0 0 1.452m15.888 13.367 2.951-5.115c.217.125.469.196.728.196h1.582c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-2.42-4.191a1.46 1.46 0 0 0-1.259-.728h-1.582c-.52 0-1 .276-1.259.728l-5.678 9.838a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h1.582c.52 0 1-.275 1.26-.728z" fill="#082dff"></path></g>
<rect x="1528" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1540" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
<g transform="translate(1559.0 93.0) scale(1.4166666666666667)" ><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#FFFFFF"></path></g>
<rect x="1612" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1624" y="74" width="72" height="72" rx="18" fill="#635BFF"/><rect x="1624.75" y="74.75" width="70.5" height="70.5" rx="17.25" fill="none" stroke="#fff" stroke-opacity=".35" stroke-width="1.5"/>
<path d="M1651.0 99H1669.0M1660.0 90V108" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
<path d="M1639.2 132H1641.6V126.4C1641.6 125.2 1641.4 123.3 1641.2 122.1H1641.3L1642.4 125.2L1644.4 130.8H1646L1648 125.2L1649.1 122.1H1649.2C1649 123.3 1648.8 125.2 1648.8 126.4V132H1651.3V118.7H1648.3L1646.1 124.9C1645.8 125.7 1645.6 126.6 1645.3 127.5H1645.2C1644.9 126.6 1644.7 125.7 1644.4 124.9L1642.1 118.7H1639.2ZM1658.5 132.3C1661 132.3 1663.4 130.3 1663.4 127C1663.4 123.6 1661 121.7 1658.5 121.7C1656 121.7 1653.7 123.6 1653.7 127C1653.7 130.3 1656 132.3 1658.5 132.3ZM1658.5 130.1C1657.1 130.1 1656.4 128.9 1656.4 127C1656.4 125.1 1657.1 123.8 1658.5 123.8C1659.9 123.8 1660.7 125.1 1660.7 127C1660.7 128.9 1659.9 130.1 1658.5 130.1ZM1665.6 132H1668.2V126C1668.8 124.5 1669.7 124 1670.5 124C1670.9 124 1671.2 124.1 1671.6 124.2L1672 121.9C1671.7 121.8 1671.4 121.7 1670.9 121.7C1669.8 121.7 1668.7 122.4 1668 123.7H1667.9L1667.7 121.9H1665.6ZM1677.8 132.3C1679.1 132.3 1680.3 131.8 1681.3 131.1L1680.4 129.5C1679.7 130 1679 130.2 1678.2 130.2C1676.7 130.2 1675.6 129.4 1675.4 127.7H1681.6C1681.7 127.5 1681.7 127 1681.7 126.5C1681.7 123.7 1680.3 121.7 1677.5 121.7C1675.1 121.7 1672.8 123.7 1672.8 127C1672.8 130.3 1675 132.3 1677.8 132.3ZM1675.3 125.9C1675.5 124.5 1676.5 123.7 1677.5 123.7C1678.8 123.7 1679.4 124.6 1679.4 125.9Z" fill="#fff"/>
</g>
<rect x=".75" y=".75" width="1758.5" height="218.5" rx="19.25" fill="none" stroke="#1F3A5C" stroke-width="1.5"/>
</svg>

After

Width:  |  Height:  |  Size: 31 KiB

+57
View File
@@ -0,0 +1,57 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1760" height="220" viewBox="0 0 1760 220" role="img" aria-label="WandAPI">
<defs>
<linearGradient id="logoW" gradientUnits="userSpaceOnUse" x1="4" y1="8" x2="44" y2="44"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
<linearGradient id="band" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
<radialGradient id="bA" cx="1200" cy="-20" r="280" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#A960EE" stop-opacity="0.95"/><stop offset="1" stop-color="#A960EE" stop-opacity="0"/></radialGradient><radialGradient id="bB" cx="1720" cy="20" r="300" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#00D4FF" stop-opacity="0.9"/><stop offset="1" stop-color="#00D4FF" stop-opacity="0"/></radialGradient><radialGradient id="bC" cx="1500" cy="260" r="260" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#FF80B5" stop-opacity="0.65"/><stop offset="1" stop-color="#FF80B5" stop-opacity="0"/></radialGradient><radialGradient id="bD" cx="1000" cy="260" r="240" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7A73FF" stop-opacity="0.9"/><stop offset="1" stop-color="#7A73FF" stop-opacity="0"/></radialGradient><radialGradient id="bE" cx="1380" cy="110" r="200" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#90E0FF" stop-opacity="0.55"/><stop offset="1" stop-color="#90E0FF" stop-opacity="0"/></radialGradient>
<radialGradient id="shadow" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#32325D" stop-opacity=".30"/><stop offset="1" stop-color="#32325D" stop-opacity="0"/></radialGradient>
<clipPath id="frame"><rect width="1760" height="220" rx="20"/></clipPath>
<clipPath id="slant"><polygon points="980,0 1760,0 1760,220 900,220"/></clipPath>
</defs>
<g clip-path="url(#frame)">
<rect width="1760" height="220" fill="#FFFFFF"/>
<g clip-path="url(#slant)">
<rect x="900" width="860" height="220" fill="url(#band)"/>
<rect x="900" width="860" height="220" fill="url(#bA)"/><rect x="900" width="860" height="220" fill="url(#bB)"/><rect x="900" width="860" height="220" fill="url(#bC)"/><rect x="900" width="860" height="220" fill="url(#bD)"/><rect x="900" width="860" height="220" fill="url(#bE)"/>
</g>
<g transform="translate(72 36) scale(0.7)">
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="8">
<polyline points="4,8 14,44 24,22 34,44 44,8" stroke="url(#logoW)"/>
<g stroke="#0A2540"><circle cx="70" cy="32" r="12"/><line x1="82" y1="20" x2="82" y2="44"/><path d="M96 20V44M96 32a12 12 0 0 1 24 0V44"/><circle cx="146" cy="32" r="12"/><line x1="158" y1="8" x2="158" y2="44"/></g>
<g stroke="#635BFF"><polyline points="172,44 188,8 204,44"/><path d="M218 44V8h8a10 10 0 0 1 0 20h-8"/><line x1="250" y1="8" x2="250" y2="44"/></g>
</g>
<path d="M24 -1Q24.9 5.1 31 6Q24.9 6.9 24 13Q23.1 6.9 17 6Q23.1 5.1 24 -1Z" fill="#635BFF"/>
</g>
<path d="M89.7 128.6C98.7 128.6 104.9 121.9 104.9 110.8C104.9 99.8 98.7 93.3 89.7 93.3C80.7 93.3 74.5 99.8 74.5 110.8C74.5 121.9 80.7 128.6 89.7 128.6ZM89.7 122.8C84.7 122.8 81.5 118.1 81.5 110.8C81.5 103.5 84.7 99.2 89.7 99.2C94.8 99.2 98 103.5 98 110.8C98 118.1 94.8 122.8 89.7 122.8ZM111.1 128H117.8V110.3C119.7 108.4 121.1 107.4 123.2 107.4C125.7 107.4 126.8 108.8 126.8 112.8V128H133.5V111.9C133.5 105.5 131.2 101.6 125.6 101.6C122.1 101.6 119.5 103.4 117.2 105.6H117.1L116.6 102.2H111.1ZM151.8 128.6C154.9 128.6 158.2 127.5 160.7 125.8L158.4 121.7C156.5 122.8 154.8 123.4 152.7 123.4C148.8 123.4 146.1 121.2 145.5 117.1H161.4C161.6 116.4 161.7 115.2 161.7 113.9C161.7 106.7 158 101.6 150.9 101.6C144.8 101.6 138.9 106.8 138.9 115.1C138.9 123.6 144.5 128.6 151.8 128.6ZM145.4 112.5C145.9 108.8 148.3 106.8 151 106.8C154.4 106.8 155.9 109 155.9 112.5ZM173.9 128H180.8L183.2 119.3H194.2L196.6 128H203.7L192.8 93.9H184.8ZM184.7 114 185.7 110.2C186.7 106.7 187.6 102.8 188.6 99.1H188.7C189.8 102.7 190.7 106.7 191.7 110.2L192.8 114ZM207.7 128H214.6V115.9H219.1C226.4 115.9 232.3 112.4 232.3 104.6C232.3 96.6 226.5 93.9 218.9 93.9H207.7ZM214.6 110.5V99.3H218.4C223.1 99.3 225.6 100.7 225.6 104.6C225.6 108.5 223.3 110.5 218.6 110.5ZM238.4 128H245.2V93.9H238.4ZM263.5 128H270.2V121.5L273.8 117.3L280 128H287.4L277.7 112.9L286.5 102.2H279.1L270.4 113.3H270.2V91.3H263.5ZM302.5 128.6C305.7 128.6 308.9 127.5 311.5 125.8L309.2 121.7C307.3 122.8 305.5 123.4 303.4 123.4C299.6 123.4 296.8 121.2 296.2 117.1H312.1C312.3 116.4 312.4 115.2 312.4 113.9C312.4 106.7 308.8 101.6 301.7 101.6C295.6 101.6 289.7 106.8 289.7 115.1C289.7 123.6 295.3 128.6 302.5 128.6ZM296.1 112.5C296.7 108.8 299.1 106.8 301.8 106.8C305.1 106.8 306.6 109 306.6 112.5ZM320.3 138.3C326 138.3 328.8 134.9 331 128.8L340.2 102.2H333.7L330.2 114.2C329.5 116.6 328.9 119.1 328.3 121.5H328.1C327.3 119 326.7 116.5 325.9 114.2L321.8 102.2H315L325 127.5L324.6 129.1C323.8 131.3 322.4 133 319.8 133C319.2 133 318.4 132.8 318 132.6L316.7 137.8C317.7 138.1 318.7 138.3 320.3 138.3ZM348.3 128.6C350.7 128.6 352.5 126.7 352.5 124.2C352.5 121.7 350.7 119.8 348.3 119.8C345.8 119.8 344 121.7 344 124.2C344 126.7 345.8 128.6 348.3 128.6ZM370.4 128H391.7V122.3H377.2V113.2H389.1V107.5H377.2V99.6H391.2V93.9H370.4ZM403.9 128H411.7L420.3 102.2H413.8L410.1 115.1C409.4 117.6 408.7 120.3 408 122.9H407.8C407 120.3 406.4 117.6 405.6 115.1L401.9 102.2H395.1ZM435.8 128.6C439 128.6 442.3 127.5 444.8 125.8L442.5 121.7C440.6 122.8 438.8 123.4 436.7 123.4C432.9 123.4 430.1 121.2 429.6 117.1H445.4C445.6 116.4 445.7 115.2 445.7 113.9C445.7 106.7 442.1 101.6 435 101.6C428.9 101.6 423 106.8 423 115.1C423 123.6 428.6 128.6 435.8 128.6ZM429.4 112.5C430 108.8 432.4 106.8 435.1 106.8C438.4 106.8 440 109 440 112.5ZM451.3 128H458.1V112.6C459.5 108.9 461.9 107.6 463.9 107.6C465 107.6 465.8 107.7 466.7 108L467.8 102.1C467 101.8 466.2 101.6 464.8 101.6C462.1 101.6 459.4 103.4 457.5 106.8H457.3L456.8 102.2H451.3ZM473.6 138.3C479.4 138.3 482.1 134.9 484.4 128.8L493.5 102.2H487.1L483.5 114.2C482.9 116.6 482.2 119.1 481.7 121.5H481.4C480.7 119 480.1 116.5 479.3 114.2L475.2 102.2H468.4L478.4 127.5L477.9 129.1C477.2 131.3 475.7 133 473.1 133C472.5 133 471.8 132.8 471.3 132.6L470.1 137.8C471.1 138.1 472.1 138.3 473.6 138.3ZM517.6 128.6C519.9 128.6 521.7 128.1 523.1 127.7L522 122.8C521.3 123 520.3 123.3 519.4 123.3C517.1 123.3 515.9 121.9 515.9 119V107.6H522.3V102.2H515.9V95.3H510.3L509.6 102.2L505.5 102.6V107.6H509.2V119C509.2 124.7 511.5 128.6 517.6 128.6ZM538.3 128.6C544.8 128.6 550.7 123.7 550.7 115.1C550.7 106.6 544.8 101.6 538.3 101.6C531.9 101.6 526 106.6 526 115.1C526 123.7 531.9 128.6 538.3 128.6ZM538.3 123.1C534.8 123.1 532.9 120 532.9 115.1C532.9 110.3 534.8 107.1 538.3 107.1C541.8 107.1 543.8 110.3 543.8 115.1C543.8 120 541.8 123.1 538.3 123.1ZM556.4 137.9H563.1V130L562.9 125.8C564.8 127.6 567.1 128.6 569.3 128.6C575 128.6 580.3 123.5 580.3 114.7C580.3 106.8 576.4 101.6 570.1 101.6C567.3 101.6 564.7 103.1 562.5 104.9H562.4L561.9 102.2H556.4ZM567.8 123.1C566.4 123.1 564.8 122.6 563.1 121.1V109.8C564.9 108 566.5 107.2 568.2 107.2C571.7 107.2 573.3 109.9 573.3 114.8C573.3 120.4 570.9 123.1 567.8 123.1ZM592.6 128H599.5L601.9 119.3H612.9L615.3 128H622.5L611.6 93.9H603.5ZM603.4 114 604.4 110.2C605.4 106.7 606.4 102.8 607.3 99.1H607.5C608.5 102.7 609.4 106.7 610.5 110.2L611.5 114ZM626.5 128H633.3V93.9H626.5ZM651.6 128H658.3V110.3C660.1 108.3 661.8 107.4 663.2 107.4C665.7 107.4 666.9 108.8 666.9 112.8V128H673.6V110.3C675.4 108.3 677.1 107.4 678.6 107.4C681 107.4 682.1 108.8 682.1 112.8V128H688.9V111.9C688.9 105.5 686.4 101.6 680.9 101.6C677.6 101.6 675.1 103.6 672.7 106.1C671.5 103.3 669.3 101.6 665.6 101.6C662.3 101.6 659.9 103.4 657.7 105.7H657.6L657.1 102.2H651.6ZM706.7 128.6C713.1 128.6 719 123.7 719 115.1C719 106.6 713.1 101.6 706.7 101.6C700.2 101.6 694.3 106.6 694.3 115.1C694.3 123.7 700.2 128.6 706.7 128.6ZM706.7 123.1C703.1 123.1 701.2 120 701.2 115.1C701.2 110.3 703.1 107.1 706.7 107.1C710.2 107.1 712.1 110.3 712.1 11Line truncated
<rect x="72" y="148" width="262.7" height="44" rx="22" fill="#635BFF"/>
<path d="M102.6 177.8C104.7 177.8 106.6 177 107.7 175.9V168.9H102.1V171.5H104.9V174.5C104.4 174.9 103.7 175.1 102.9 175.1C99.9 175.1 98.3 173.1 98.3 169.7C98.3 166.3 100.1 164.3 102.7 164.3C104.1 164.3 105 164.9 105.7 165.6L107.4 163.7C106.4 162.6 104.8 161.7 102.6 161.7C98.5 161.7 95.1 164.7 95.1 169.8C95.1 175 98.4 177.8 102.6 177.8ZM115.8 177.8C117.3 177.8 118.8 177.3 119.9 176.5L118.9 174.6C118 175.1 117.2 175.4 116.3 175.4C114.5 175.4 113.2 174.4 113 172.5H120.2C120.3 172.2 120.4 171.6 120.4 171.1C120.4 167.8 118.7 165.4 115.5 165.4C112.7 165.4 110 167.8 110 171.6C110 175.5 112.5 177.8 115.8 177.8ZM112.9 170.4C113.2 168.7 114.3 167.8 115.5 167.8C117 167.8 117.7 168.8 117.7 170.4ZM127.2 177.8C128.3 177.8 129.1 177.5 129.7 177.4L129.2 175.1C128.9 175.2 128.4 175.4 128 175.4C127 175.4 126.4 174.7 126.4 173.4V168.2H129.3V165.7H126.4V162.6H123.9L123.5 165.7L121.7 165.9V168.2H123.4V173.4C123.4 176 124.4 177.8 127.2 177.8ZM135.5 168.2H137.1V177.5H140.1V168.2H142.4V165.7H140.1V164.7C140.1 163.4 140.6 162.9 141.5 162.9C142 162.9 142.4 163 142.8 163.2L143.4 160.8C142.8 160.6 142 160.4 141.1 160.4C138.2 160.4 137.1 162.4 137.1 164.8V165.8L135.5 165.9ZM144.3 177.5H147.4V170.5C148.1 168.8 149.2 168.2 150.1 168.2C150.6 168.2 150.9 168.2 151.4 168.4L151.9 165.7C151.5 165.6 151.1 165.4 150.5 165.4C149.3 165.4 148 166.3 147.2 167.8H147.1L146.9 165.7H144.3ZM158.6 177.8C160.1 177.8 161.6 177.3 162.7 176.5L161.7 174.6C160.8 175.1 160 175.4 159 175.4C157.3 175.4 156 174.4 155.8 172.5H163C163.1 172.2 163.2 171.6 163.2 171.1C163.2 167.8 161.5 165.4 158.2 165.4C155.4 165.4 152.8 167.8 152.8 171.6C152.8 175.5 155.3 177.8 158.6 177.8ZM155.7 170.4C156 168.7 157 167.8 158.3 167.8C159.8 167.8 160.5 168.8 160.5 170.4ZM170.8 177.8C172.3 177.8 173.8 177.3 174.9 176.5L173.9 174.6C173 175.1 172.2 175.4 171.2 175.4C169.5 175.4 168.2 174.4 168 172.5H175.2C175.3 172.2 175.4 171.6 175.4 171.1C175.4 167.8 173.7 165.4 170.4 165.4C167.6 165.4 165 167.8 165 171.6C165 175.5 167.5 177.8 170.8 177.8ZM167.9 170.4C168.2 168.7 169.2 167.8 170.5 167.8C172 167.8 172.7 168.8 172.7 170.4ZM187 177.8C188 177.8 188.8 177.5 189.5 177.4L188.9 175.1C188.6 175.2 188.2 175.4 187.8 175.4C186.7 175.4 186.2 174.7 186.2 173.4V168.2H189.1V165.7H186.2V162.6H183.6L183.3 165.7L181.4 165.9V168.2H183.1V173.4C183.1 176 184.2 177.8 187 177.8ZM191.5 177.5H194.6V170.5C195.3 168.8 196.4 168.2 197.3 168.2C197.8 168.2 198.1 168.2 198.5 168.4L199 165.7C198.7 165.6 198.3 165.4 197.7 165.4C196.4 165.4 195.2 166.3 194.3 167.8H194.3L194 165.7H191.5ZM200.7 177.5H203.7V165.7H200.7ZM202.2 163.8C203.3 163.8 204 163.2 204 162.1C204 161.1 203.3 160.5 202.2 160.5C201.1 160.5 200.4 161.1 200.4 162.1C200.4 163.2 201.1 163.8 202.2 163.8ZM209.9 177.8C211.3 177.8 212.5 177.1 213.5 176.2H213.6L213.8 177.5H216.3V170.6C216.3 167.2 214.8 165.4 211.8 165.4C209.9 165.4 208.3 166.2 206.9 167L208 169.1C209.1 168.4 210.1 167.9 211.2 167.9C212.7 167.9 213.2 168.8 213.2 170C208.5 170.5 206.5 171.8 206.5 174.3C206.5 176.3 207.8 177.8 209.9 177.8ZM210.9 175.4C210 175.4 209.4 175 209.4 174.1C209.4 173 210.3 172.2 213.2 171.9V174.2C212.5 175 211.8 175.4 210.9 175.4ZM222.4 177.8C223.1 177.8 223.6 177.7 223.9 177.5L223.6 175.2C223.4 175.3 223.3 175.3 223.2 175.3C222.9 175.3 222.5 175 222.5 174.3V160.7H219.5V174.2C219.5 176.4 220.2 177.8 222.4 177.8ZM235.8 177.8C237.1 177.8 238.6 177.4 239.7 176.4L238.5 174.3C237.8 174.9 237 175.3 236.2 175.3C234.5 175.3 233.3 173.8 233.3 171.6C233.3 169.4 234.5 168 236.3 168C236.9 168 237.5 168.2 238.1 168.7L239.5 166.8C238.7 166 237.6 165.4 236.1 165.4C232.9 165.4 230.1 167.7 230.1 171.6C230.1 175.5 232.6 177.8 235.8 177.8ZM241.9 177.5H245V170.5C245.7 168.8 246.8 168.2 247.7 168.2C248.2 168.2 248.5 168.2 248.9 168.4L249.4 165.7C249.1 165.6 248.7 165.4 248.1 165.4C246.8 165.4 245.6 166.3 244.7 167.8H244.7L244.4 165.7H241.9ZM256.2 177.8C257.6 177.8 259.1 177.3 260.3 176.5L259.2 174.6C258.4 175.1 257.5 175.4 256.6 175.4C254.8 175.4 253.6 174.4 253.3 172.5H260.6C260.7 172.2 260.7 171.6 260.7 171.1C260.7 167.8 259 165.4 255.8 165.4C253 165.4 250.3 167.8 250.3 171.6C250.3 175.5 252.9 177.8 256.2 177.8ZM253.3 170.4C253.5 168.7 254.6 167.8 255.8 167.8C257.4 167.8 258.1 168.8 258.1 170.4ZM267.4 177.8C268.6 177.8 269.8 177.1 270.7 176.3H270.7L271 177.5H273.5V160.7H270.4V164.9L270.5 166.7C269.7 165.9 268.8 165.4 267.5 165.4C265 165.4 262.6 167.8 262.6 171.6C262.6 175.5 264.5 177.8 267.4 177.8ZM268.2 175.3C266.6 175.3 265.8 174 265.8 171.6C265.8 169.2 266.9 168 268.2 168C269 168 269.7 168.2 270.4 168.9V174C269.7 174.9 269 175.3 268.2 175.3ZM276.8 177.5H279.9V165.7H276.8ZM278.3 163.8C279.4 163.8 280.1 163.2 280.1 162.1C280.1 161.1 279.4 160.5 278.3 160.5C277.2 160.5 276.6 161.1 276.6 162.1C276.6 163.2 277.2 163.8 278.3 163.8ZM287.5 177.8C288.5 177.8 289.3 177.5 290 177.4L289.4 175.1C289.1 175.2 288.7 175.4 288.3 175.4C287.2 175.4 286.7 174.7 286.7 173.4V168.2H289.6V165.7H286.7V162.6H284.1L283.8 165.7L282 165.9V168.2H283.6V173.4C283.6 176 284.7 177.8 287.5 177.8ZM295.4 177.8C298.4 177.8 30Line truncated
<path d="M311.7 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#fff" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M364.4 177.5H367.9L369.1 172.4C369.3 171.3 369.5 170.2 369.7 168.9H369.8C370 170.2 370.3 171.3 370.5 172.4L371.7 177.5H375.4L378.3 165.7H375.4L374.1 171.5C373.9 172.7 373.8 173.8 373.6 175H373.5C373.2 173.8 373 172.7 372.7 171.5L371.2 165.7H368.5L367.1 171.5C366.8 172.7 366.6 173.8 366.4 175H366.2C366.1 173.8 365.9 172.7 365.7 171.5L364.4 165.7H361.3ZM383.4 177.8C384.8 177.8 385.9 177.1 387 176.2H387.1L387.3 177.5H389.8V170.6C389.8 167.2 388.3 165.4 385.3 165.4C383.4 165.4 381.7 166.2 380.4 167L381.5 169.1C382.6 168.4 383.6 167.9 384.7 167.9C386.2 167.9 386.7 168.8 386.7 170C382 170.5 379.9 171.8 379.9 174.3C379.9 176.3 381.3 177.8 383.4 177.8ZM384.4 175.4C383.5 175.4 382.9 175 382.9 174.1C382.9 173 383.8 172.2 386.7 171.9V174.2C386 175 385.3 175.4 384.4 175.4ZM392.9 177.5H396V169.4C396.9 168.6 397.5 168.1 398.5 168.1C399.6 168.1 400.1 168.7 400.1 170.5V177.5H403.2V170.2C403.2 167.2 402.1 165.4 399.6 165.4C398 165.4 396.8 166.3 395.8 167.3H395.7L395.5 165.7H392.9ZM410.5 177.8C411.8 177.8 412.9 177.1 413.8 176.3H413.9L414.1 177.5H416.6V160.7H413.5V164.9L413.6 166.7C412.8 165.9 412 165.4 410.7 165.4C408.1 165.4 405.7 167.8 405.7 171.6C405.7 175.5 407.6 177.8 410.5 177.8ZM411.3 175.3C409.8 175.3 408.9 174 408.9 171.6C408.9 169.2 410 168 411.3 168C412.1 168 412.8 168.2 413.5 168.9V174C412.9 174.9 412.2 175.3 411.3 175.3ZM422.8 177.8C424.2 177.8 425.3 177.1 426.3 176.2H426.5L426.7 177.5H429.2V170.6C429.2 167.2 427.7 165.4 424.7 165.4C422.8 165.4 421.1 166.2 419.8 167L420.9 169.1C422 168.4 423 167.9 424.1 167.9C425.6 167.9 426.1 168.8 426.1 170C421.4 170.5 419.3 171.8 419.3 174.3C419.3 176.3 420.7 177.8 422.8 177.8ZM423.8 175.4C422.9 175.4 422.3 175 422.3 174.1C422.3 173 423.2 172.2 426.1 171.9V174.2C425.4 175 424.7 175.4 423.8 175.4ZM432.3 182H435.4V178.4L435.3 176.5C436.2 177.3 437.2 177.8 438.2 177.8C440.8 177.8 443.2 175.5 443.2 171.4C443.2 167.8 441.5 165.4 438.6 165.4C437.3 165.4 436.1 166.1 435.1 167H435.1L434.9 165.7H432.3ZM437.6 175.3C436.9 175.3 436.2 175 435.4 174.4V169.2C436.2 168.4 436.9 168 437.7 168C439.3 168 440.1 169.2 440.1 171.5C440.1 174 438.9 175.3 437.6 175.3ZM445.9 177.5H448.9V165.7H445.9ZM447.4 163.8C448.5 163.8 449.2 163.2 449.2 162.1C449.2 161.1 448.5 160.5 447.4 160.5C446.3 160.5 445.6 161.1 445.6 162.1C445.6 163.2 446.3 163.8 447.4 163.8ZM454 177.8C455.1 177.8 455.9 176.9 455.9 175.8C455.9 174.6 455.1 173.8 454 173.8C452.9 173.8 452.1 174.6 452.1 175.8C452.1 176.9 452.9 177.8 454 177.8ZM461.9 177.8C463.3 177.8 464.5 177.1 465.5 176.2H465.6L465.8 177.5H468.3V170.6C468.3 167.2 466.8 165.4 463.8 165.4C462 165.4 460.3 166.2 458.9 167L460 169.1C461.1 168.4 462.2 167.9 463.2 167.9C464.7 167.9 465.2 168.8 465.2 170C460.5 170.5 458.5 171.8 458.5 174.3C458.5 176.3 459.8 177.8 461.9 177.8ZM463 175.4C462.1 175.4 461.4 175 461.4 174.1C461.4 173 462.4 172.2 465.2 171.9V174.2C464.5 175 463.9 175.4 463 175.4ZM471.5 177.5H474.6V165.7H471.5ZM473 163.8C474.1 163.8 474.8 163.2 474.8 162.1C474.8 161.1 474.1 160.5 473 160.5C471.9 160.5 471.2 161.1 471.2 162.1C471.2 163.2 471.9 163.8 473 163.8Z" fill="#635BFF"/>
<path d="M485.2 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#635BFF" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
<rect x="1024" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1036" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1055.0 93.0) scale(1.4166666666666667)" ><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></g>
<rect x="1108" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1120" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1139.0 93.0) scale(1.4166666666666667)" fill="#0A2540" fill-rule="evenodd"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></g>
<rect x="1192" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1204" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1223.0 93.0) scale(1.4166666666666667)" ><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-0-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-1-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-2-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-0-_R_0_" x1="7" x2="11" y1="15.5" y2="12"><stop stop-color="#08B962"></stop><stop offset="1" stop-color="#08B962" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-1-_R_0_" x1="8" x2="11.5" y1="5.5" y2="11"><stop stop-color="#F94543"></stop><stop offset="1" stop-color="#F94543" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-2-_R_0_" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stop-color="#FABC12"></stop><stop offset=".46" stop-color="#FABC12" stop-opacity="0"></stop></linearGradient></defs></g>
<rect x="1276" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1288" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1307.0 93.0) scale(1.4166666666666667)" ><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></g>
<rect x="1360" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1372" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1391.0 93.0) scale(1.4166666666666667)" fill="#0A2540" fill-rule="evenodd"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></g>
<rect x="1444" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1456" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1475.0 93.0) scale(1.4166666666666667)" ><path d="M19.713 2.825h-5.907c0-.251-.066-.503-.196-.728L12.819.728A1.46 1.46 0 0 0 11.559 0h-1.58c-.52 0-1 .275-1.26.728l-2.42 4.19a1.45 1.45 0 0 0 0 1.453l.791 1.37c.26.448.74.727 1.26.727h11.36c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-.79-1.37a1.46 1.46 0 0 0-1.26-.728zM.195 9.905l2.951 5.115a1.46 1.46 0 0 0-.531.531l-.791 1.37a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h4.84c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451L5.086 7.083a1.46 1.46 0 0 0-1.26-.728h-1.58c-.52 0-1 .276-1.26.728l-.79 1.37a1.45 1.45 0 0 0 0 1.452m15.888 13.367 2.951-5.115c.217.125.469.196.728.196h1.582c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-2.42-4.191a1.46 1.46 0 0 0-1.259-.728h-1.582c-.52 0-1 .276-1.259.728l-5.678 9.838a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h1.582c.52 0 1-.275 1.26-.728z" fill="#082dff"></path></g>
<rect x="1528" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1540" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
<g transform="translate(1559.0 93.0) scale(1.4166666666666667)" ><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#0A2540"></path></g>
<rect x="1612" y="82" width="96" height="94" fill="url(#shadow)"/>
<rect x="1624" y="74" width="72" height="72" rx="18" fill="#635BFF"/><rect x="1624.75" y="74.75" width="70.5" height="70.5" rx="17.25" fill="none" stroke="#fff" stroke-opacity=".35" stroke-width="1.5"/>
<path d="M1651.0 99H1669.0M1660.0 90V108" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
<path d="M1639.2 132H1641.6V126.4C1641.6 125.2 1641.4 123.3 1641.2 122.1H1641.3L1642.4 125.2L1644.4 130.8H1646L1648 125.2L1649.1 122.1H1649.2C1649 123.3 1648.8 125.2 1648.8 126.4V132H1651.3V118.7H1648.3L1646.1 124.9C1645.8 125.7 1645.6 126.6 1645.3 127.5H1645.2C1644.9 126.6 1644.7 125.7 1644.4 124.9L1642.1 118.7H1639.2ZM1658.5 132.3C1661 132.3 1663.4 130.3 1663.4 127C1663.4 123.6 1661 121.7 1658.5 121.7C1656 121.7 1653.7 123.6 1653.7 127C1653.7 130.3 1656 132.3 1658.5 132.3ZM1658.5 130.1C1657.1 130.1 1656.4 128.9 1656.4 127C1656.4 125.1 1657.1 123.8 1658.5 123.8C1659.9 123.8 1660.7 125.1 1660.7 127C1660.7 128.9 1659.9 130.1 1658.5 130.1ZM1665.6 132H1668.2V126C1668.8 124.5 1669.7 124 1670.5 124C1670.9 124 1671.2 124.1 1671.6 124.2L1672 121.9C1671.7 121.8 1671.4 121.7 1670.9 121.7C1669.8 121.7 1668.7 122.4 1668 123.7H1667.9L1667.7 121.9H1665.6ZM1677.8 132.3C1679.1 132.3 1680.3 131.8 1681.3 131.1L1680.4 129.5C1679.7 130 1679 130.2 1678.2 130.2C1676.7 130.2 1675.6 129.4 1675.4 127.7H1681.6C1681.7 127.5 1681.7 127 1681.7 126.5C1681.7 123.7 1680.3 121.7 1677.5 121.7C1675.1 121.7 1672.8 123.7 1672.8 127C1672.8 130.3 1675 132.3 1677.8 132.3ZM1675.3 125.9C1675.5 124.5 1676.5 123.7 1677.5 123.7C1678.8 123.7 1679.4 124.6 1679.4 125.9Z" fill="#fff"/>
</g>
<rect x=".75" y=".75" width="1758.5" height="218.5" rx="19.25" fill="none" stroke="#E3E8EE" stroke-width="1.5"/>
</svg>

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.27.2-alpine
FROM golang:1.27.4-alpine
WORKDIR /app
+1 -1
View File
@@ -1 +1 @@
0.2.17
0.2.27
+19
View File
@@ -111,6 +111,9 @@ func provideCleanup(
emailQueue *service.EmailQueueService,
billingCache *service.BillingCacheService,
usageRecordWorkerPool *service.UsageRecordWorkerPool,
usageBillingLanes *service.UsageBillingLaneCombiner,
balanceNotify *service.BalanceNotifyService,
digestSessions *service.DigestSessionStore,
subscriptionService *service.SubscriptionService,
oauth *service.OAuthService,
openaiOAuth *service.OpenAIOAuthService,
@@ -143,6 +146,18 @@ func provideCleanup(
// 应用层清理步骤可并行执行,基础设施资源(Redis/Ent)最后按顺序关闭。
parallelSteps := []cleanupStep{
{"DigestSessionStore", func() error {
if digestSessions != nil {
digestSessions.Close()
}
return nil
}},
{"BalanceNotifyService", func() error {
if balanceNotify != nil {
balanceNotify.Stop()
}
return nil
}},
{"PluginManager", func() error {
if pluginManager != nil {
pluginManager.Stop()
@@ -317,6 +332,10 @@ func provideCleanup(
}
return nil
}},
{"UsageBillingLaneCombiner", func() error {
usageBillingLanes.Stop()
return nil
}},
{"OAuthService", func() error {
oauth.Stop()
return nil
+33 -8
View File
@@ -49,10 +49,11 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
redeemCodeRepository := repository.NewRedeemCodeRepository(client)
redisClient := repository.ProvideRedis(configConfig)
refreshTokenCache := repository.NewRefreshTokenCache(redisClient)
scopedAdminKeyRepository := repository.NewScopedAdminKeyRepository(db)
settingRepository := repository.NewSettingRepository(client)
groupRepository := repository.NewGroupRepository(client, db)
proxyRepository := repository.NewProxyRepository(client, db)
settingService := service.ProvideSettingService(settingRepository, groupRepository, proxyRepository, configConfig)
settingService := service.ProvideSettingService(scopedAdminKeyRepository, settingRepository, groupRepository, proxyRepository, configConfig)
emailCache := repository.NewEmailCache(redisClient)
emailService := service.NewEmailService(settingRepository, emailCache)
turnstileVerifier := repository.NewTurnstileVerifier()
@@ -82,7 +83,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService, client, configConfig)
affiliateRepository := repository.NewAffiliateRepository(client, db)
affiliateService := service.NewAffiliateService(affiliateRepository, settingService, apiKeyAuthCacheInvalidator, billingCacheService)
authService := service.ProvideAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, tencentCaptchaService, aliyunCaptchaService, emailQueueService, promoService, subscriptionService, affiliateService, serviceUserPlatformQuotaRepository)
mcpoAuthRepository := repository.NewMCPOAuthRepository(client, db)
mcpoAuthService := service.NewMCPOAuthService(mcpoAuthRepository, userRepository)
authService := service.ProvideAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, tencentCaptchaService, aliyunCaptchaService, emailQueueService, promoService, subscriptionService, affiliateService, serviceUserPlatformQuotaRepository, mcpoAuthService)
userService := service.NewUserService(userRepository, settingRepository, apiKeyAuthCacheInvalidator, billingCache)
redeemCache := repository.NewRedeemCache(redisClient)
redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client, apiKeyAuthCacheInvalidator, affiliateService)
@@ -97,11 +100,14 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository)
authHandler := handler.NewAuthHandler(configConfig, authService, userService, settingService, promoService, redeemService, totpService, userAttributeService)
userHandler := handler.NewUserHandler(userService, authService, emailService, emailCache, affiliateService, serviceUserPlatformQuotaRepository)
mcpoAuthHandler := handler.NewMCPOAuthHandler(mcpoAuthService, totpService, userService, settingService, configConfig)
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
usageLogRepository := repository.NewUsageLogRepository(client, db)
usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator)
opsRepository := repository.NewOpsRepository(db)
usageBillingRepository := repository.NewUsageBillingRepository(client, db)
usageBillingBatchRepository := repository.NewUsageBillingRepository(client, db)
usageBillingLaneCombiner := service.NewUsageBillingLaneCombiner(usageBillingBatchRepository)
usageBillingRepository := service.ProvideUsageBillingRepository(usageBillingLaneCombiner)
gatewayCache := repository.NewGatewayCache(redisClient)
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig)
@@ -169,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)
@@ -191,7 +197,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService)
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, serviceUserPlatformQuotaRepository)
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService)
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
groupHandler := admin.NewGroupHandlerWithConfig(adminService, dashboardService, groupCapacityService, configConfig)
@@ -202,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)
@@ -327,7 +333,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler)
idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig)
openAIQuotaAutoResetService := service.ProvideOpenAIQuotaAutoResetService(accountRepository, openAIQuotaService, rateLimitService, idempotencyCoordinator, auditLogService, settingService, leaderLockCache)
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService)
handlers := handler.ProvideHandlers(authHandler, userHandler, mcpoAuthHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService)
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService, settingService, auditLogService)
optionalJWTAuthMiddleware := middleware.NewOptionalJWTAuthMiddleware(authService, userService, settingService, auditLogService)
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService, auditLogService)
@@ -355,7 +361,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher)
channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService)
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, usageBillingLaneCombiner, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
application := &Application{
Server: httpServer,
PromptAudit: promptService,
@@ -422,6 +428,9 @@ func provideCleanup(
emailQueue *service.EmailQueueService,
billingCache *service.BillingCacheService,
usageRecordWorkerPool *service.UsageRecordWorkerPool,
usageBillingLanes *service.UsageBillingLaneCombiner,
balanceNotify *service.BalanceNotifyService,
digestSessions *service.DigestSessionStore,
subscriptionService *service.SubscriptionService,
oauth *service.OAuthService,
openaiOAuth *service.OpenAIOAuthService,
@@ -453,6 +462,18 @@ func provideCleanup(
}
parallelSteps := []cleanupStep{
{"DigestSessionStore", func() error {
if digestSessions != nil {
digestSessions.Close()
}
return nil
}},
{"BalanceNotifyService", func() error {
if balanceNotify != nil {
balanceNotify.Stop()
}
return nil
}},
{"PluginManager", func() error {
if pluginManager != nil {
pluginManager.Stop()
@@ -627,6 +648,10 @@ func provideCleanup(
}
return nil
}},
{"UsageBillingLaneCombiner", func() error {
usageBillingLanes.Stop()
return nil
}},
{"OAuthService", func() error {
oauth.Stop()
return nil
+3
View File
@@ -81,6 +81,9 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
emailQueueSvc,
billingCacheSvc,
&service.UsageRecordWorkerPool{},
nil, // usageBillingLanes
service.ProvideBalanceNotifyService(nil, nil, nil, nil),
service.NewDigestSessionStore(),
&service.SubscriptionService{},
oauthSvc,
openAIOAuthSvc,
+23 -1
View File
@@ -64,6 +64,8 @@ type Group struct {
AllowImageGeneration bool `json:"allow_image_generation,omitempty"`
// 是否允许该分组使用批量图片生成能力
AllowBatchImageGeneration bool `json:"allow_batch_image_generation,omitempty"`
// 图片生成是否按实际出图张数计费
ImageCountBilling bool `json:"image_count_billing,omitempty"`
// 图片生成是否使用独立倍率;false 表示共享分组有效倍率
ImageRateIndependent bool `json:"image_rate_independent,omitempty"`
// 图片生成独立倍率,仅 image_rate_independent=true 时生效
@@ -126,6 +128,8 @@ type Group struct {
AllowLive bool `json:"allow_live,omitempty"`
// 是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority
ForceOpenaiFast bool `json:"force_openai_fast,omitempty"`
// 是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)
ForceOpenaiUltrafast bool `json:"force_openai_ultrafast,omitempty"`
// 是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费
FreeOpenaiFast bool `json:"free_openai_fast,omitempty"`
// 仅允许非 apikey 类型账号关联到此分组
@@ -262,7 +266,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
switch columns[i] {
case group.FieldI18n, group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings:
values[i] = new([]byte)
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageCountBilling, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldForceOpenaiUltrafast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
values[i] = new(sql.NullBool)
case group.FieldRateMultiplier, group.FieldPeakRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k, group.FieldBatchImageDiscountMultiplier, group.FieldBatchImageHoldMultiplier, group.FieldVideoRateMultiplier, group.FieldVideoPrice480p, group.FieldVideoPrice720p, group.FieldVideoPrice1080p, group.FieldWebSearchPricePerCall, group.FieldSearchPricePer1k, group.FieldAudioRealtimePricePerMin, group.FieldAudioTtsPricePerMillionChars, group.FieldAudioSttPricePerHour, group.FieldProfitMinMargin, group.FieldProfitSafetyBuffer:
values[i] = new(sql.NullFloat64)
@@ -433,6 +437,12 @@ func (_m *Group) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.AllowBatchImageGeneration = value.Bool
}
case group.FieldImageCountBilling:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field image_count_billing", values[i])
} else if value.Valid {
_m.ImageCountBilling = value.Bool
}
case group.FieldImageRateIndependent:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field image_rate_independent", values[i])
@@ -640,6 +650,12 @@ func (_m *Group) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.ForceOpenaiFast = value.Bool
}
case group.FieldForceOpenaiUltrafast:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field force_openai_ultrafast", values[i])
} else if value.Valid {
_m.ForceOpenaiUltrafast = value.Bool
}
case group.FieldFreeOpenaiFast:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field free_openai_fast", values[i])
@@ -886,6 +902,9 @@ func (_m *Group) String() string {
builder.WriteString("allow_batch_image_generation=")
builder.WriteString(fmt.Sprintf("%v", _m.AllowBatchImageGeneration))
builder.WriteString(", ")
builder.WriteString("image_count_billing=")
builder.WriteString(fmt.Sprintf("%v", _m.ImageCountBilling))
builder.WriteString(", ")
builder.WriteString("image_rate_independent=")
builder.WriteString(fmt.Sprintf("%v", _m.ImageRateIndependent))
builder.WriteString(", ")
@@ -1005,6 +1024,9 @@ func (_m *Group) String() string {
builder.WriteString("force_openai_fast=")
builder.WriteString(fmt.Sprintf("%v", _m.ForceOpenaiFast))
builder.WriteString(", ")
builder.WriteString("force_openai_ultrafast=")
builder.WriteString(fmt.Sprintf("%v", _m.ForceOpenaiUltrafast))
builder.WriteString(", ")
builder.WriteString("free_openai_fast=")
builder.WriteString(fmt.Sprintf("%v", _m.FreeOpenaiFast))
builder.WriteString(", ")
+20
View File
@@ -60,6 +60,8 @@ const (
FieldAllowImageGeneration = "allow_image_generation"
// FieldAllowBatchImageGeneration holds the string denoting the allow_batch_image_generation field in the database.
FieldAllowBatchImageGeneration = "allow_batch_image_generation"
// FieldImageCountBilling holds the string denoting the image_count_billing field in the database.
FieldImageCountBilling = "image_count_billing"
// FieldImageRateIndependent holds the string denoting the image_rate_independent field in the database.
FieldImageRateIndependent = "image_rate_independent"
// FieldImageRateMultiplier holds the string denoting the image_rate_multiplier field in the database.
@@ -122,6 +124,8 @@ const (
FieldAllowLive = "allow_live"
// FieldForceOpenaiFast holds the string denoting the force_openai_fast field in the database.
FieldForceOpenaiFast = "force_openai_fast"
// FieldForceOpenaiUltrafast holds the string denoting the force_openai_ultrafast field in the database.
FieldForceOpenaiUltrafast = "force_openai_ultrafast"
// FieldFreeOpenaiFast holds the string denoting the free_openai_fast field in the database.
FieldFreeOpenaiFast = "free_openai_fast"
// FieldRequireOauthOnly holds the string denoting the require_oauth_only field in the database.
@@ -247,6 +251,7 @@ var Columns = []string{
FieldDefaultValidityDays,
FieldAllowImageGeneration,
FieldAllowBatchImageGeneration,
FieldImageCountBilling,
FieldImageRateIndependent,
FieldImageRateMultiplier,
FieldImagePrice1k,
@@ -278,6 +283,7 @@ var Columns = []string{
FieldAllowMessagesDispatch,
FieldAllowLive,
FieldForceOpenaiFast,
FieldForceOpenaiUltrafast,
FieldFreeOpenaiFast,
FieldRequireOauthOnly,
FieldRequirePrivacySet,
@@ -367,6 +373,8 @@ var (
DefaultAllowImageGeneration bool
// DefaultAllowBatchImageGeneration holds the default value on creation for the "allow_batch_image_generation" field.
DefaultAllowBatchImageGeneration bool
// DefaultImageCountBilling holds the default value on creation for the "image_count_billing" field.
DefaultImageCountBilling bool
// DefaultImageRateIndependent holds the default value on creation for the "image_rate_independent" field.
DefaultImageRateIndependent bool
// DefaultImageRateMultiplier holds the default value on creation for the "image_rate_multiplier" field.
@@ -405,6 +413,8 @@ var (
DefaultAllowLive bool
// DefaultForceOpenaiFast holds the default value on creation for the "force_openai_fast" field.
DefaultForceOpenaiFast bool
// DefaultForceOpenaiUltrafast holds the default value on creation for the "force_openai_ultrafast" field.
DefaultForceOpenaiUltrafast bool
// DefaultFreeOpenaiFast holds the default value on creation for the "free_openai_fast" field.
DefaultFreeOpenaiFast bool
// DefaultRequireOauthOnly holds the default value on creation for the "require_oauth_only" field.
@@ -554,6 +564,11 @@ func ByAllowBatchImageGeneration(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAllowBatchImageGeneration, opts...).ToFunc()
}
// ByImageCountBilling orders the results by the image_count_billing field.
func ByImageCountBilling(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldImageCountBilling, opts...).ToFunc()
}
// ByImageRateIndependent orders the results by the image_rate_independent field.
func ByImageRateIndependent(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldImageRateIndependent, opts...).ToFunc()
@@ -689,6 +704,11 @@ func ByForceOpenaiFast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldForceOpenaiFast, opts...).ToFunc()
}
// ByForceOpenaiUltrafast orders the results by the force_openai_ultrafast field.
func ByForceOpenaiUltrafast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldForceOpenaiUltrafast, opts...).ToFunc()
}
// ByFreeOpenaiFast orders the results by the free_openai_fast field.
func ByFreeOpenaiFast(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFreeOpenaiFast, opts...).ToFunc()
+30
View File
@@ -160,6 +160,11 @@ func AllowBatchImageGeneration(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldAllowBatchImageGeneration, v))
}
// ImageCountBilling applies equality check predicate on the "image_count_billing" field. It's identical to ImageCountBillingEQ.
func ImageCountBilling(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldImageCountBilling, v))
}
// ImageRateIndependent applies equality check predicate on the "image_rate_independent" field. It's identical to ImageRateIndependentEQ.
func ImageRateIndependent(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldImageRateIndependent, v))
@@ -295,6 +300,11 @@ func ForceOpenaiFast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiFast, v))
}
// ForceOpenaiUltrafast applies equality check predicate on the "force_openai_ultrafast" field. It's identical to ForceOpenaiUltrafastEQ.
func ForceOpenaiUltrafast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiUltrafast, v))
}
// FreeOpenaiFast applies equality check predicate on the "free_openai_fast" field. It's identical to FreeOpenaiFastEQ.
func FreeOpenaiFast(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldFreeOpenaiFast, v))
@@ -1325,6 +1335,16 @@ func AllowBatchImageGenerationNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldAllowBatchImageGeneration, v))
}
// ImageCountBillingEQ applies the EQ predicate on the "image_count_billing" field.
func ImageCountBillingEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldImageCountBilling, v))
}
// ImageCountBillingNEQ applies the NEQ predicate on the "image_count_billing" field.
func ImageCountBillingNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldImageCountBilling, v))
}
// ImageRateIndependentEQ applies the EQ predicate on the "image_rate_independent" field.
func ImageRateIndependentEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldImageRateIndependent, v))
@@ -2295,6 +2315,16 @@ func ForceOpenaiFastNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldForceOpenaiFast, v))
}
// ForceOpenaiUltrafastEQ applies the EQ predicate on the "force_openai_ultrafast" field.
func ForceOpenaiUltrafastEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldForceOpenaiUltrafast, v))
}
// ForceOpenaiUltrafastNEQ applies the NEQ predicate on the "force_openai_ultrafast" field.
func ForceOpenaiUltrafastNEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldForceOpenaiUltrafast, v))
}
// FreeOpenaiFastEQ applies the EQ predicate on the "free_openai_fast" field.
func FreeOpenaiFastEQ(v bool) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldFreeOpenaiFast, v))
+130
View File
@@ -322,6 +322,20 @@ func (_c *GroupCreate) SetNillableAllowBatchImageGeneration(v *bool) *GroupCreat
return _c
}
// SetImageCountBilling sets the "image_count_billing" field.
func (_c *GroupCreate) SetImageCountBilling(v bool) *GroupCreate {
_c.mutation.SetImageCountBilling(v)
return _c
}
// SetNillableImageCountBilling sets the "image_count_billing" field if the given value is not nil.
func (_c *GroupCreate) SetNillableImageCountBilling(v *bool) *GroupCreate {
if v != nil {
_c.SetImageCountBilling(*v)
}
return _c
}
// SetImageRateIndependent sets the "image_rate_independent" field.
func (_c *GroupCreate) SetImageRateIndependent(v bool) *GroupCreate {
_c.mutation.SetImageRateIndependent(v)
@@ -724,6 +738,20 @@ func (_c *GroupCreate) SetNillableForceOpenaiFast(v *bool) *GroupCreate {
return _c
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_c *GroupCreate) SetForceOpenaiUltrafast(v bool) *GroupCreate {
_c.mutation.SetForceOpenaiUltrafast(v)
return _c
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_c *GroupCreate) SetNillableForceOpenaiUltrafast(v *bool) *GroupCreate {
if v != nil {
_c.SetForceOpenaiUltrafast(*v)
}
return _c
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_c *GroupCreate) SetFreeOpenaiFast(v bool) *GroupCreate {
_c.mutation.SetFreeOpenaiFast(v)
@@ -1105,6 +1133,10 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultAllowBatchImageGeneration
_c.mutation.SetAllowBatchImageGeneration(v)
}
if _, ok := _c.mutation.ImageCountBilling(); !ok {
v := group.DefaultImageCountBilling
_c.mutation.SetImageCountBilling(v)
}
if _, ok := _c.mutation.ImageRateIndependent(); !ok {
v := group.DefaultImageRateIndependent
_c.mutation.SetImageRateIndependent(v)
@@ -1165,6 +1197,10 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultForceOpenaiFast
_c.mutation.SetForceOpenaiFast(v)
}
if _, ok := _c.mutation.ForceOpenaiUltrafast(); !ok {
v := group.DefaultForceOpenaiUltrafast
_c.mutation.SetForceOpenaiUltrafast(v)
}
if _, ok := _c.mutation.FreeOpenaiFast(); !ok {
v := group.DefaultFreeOpenaiFast
_c.mutation.SetFreeOpenaiFast(v)
@@ -1309,6 +1345,9 @@ func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.AllowBatchImageGeneration(); !ok {
return &ValidationError{Name: "allow_batch_image_generation", err: errors.New(`ent: missing required field "Group.allow_batch_image_generation"`)}
}
if _, ok := _c.mutation.ImageCountBilling(); !ok {
return &ValidationError{Name: "image_count_billing", err: errors.New(`ent: missing required field "Group.image_count_billing"`)}
}
if _, ok := _c.mutation.ImageRateIndependent(); !ok {
return &ValidationError{Name: "image_rate_independent", err: errors.New(`ent: missing required field "Group.image_rate_independent"`)}
}
@@ -1374,6 +1413,9 @@ func (_c *GroupCreate) check() error {
if _, ok := _c.mutation.ForceOpenaiFast(); !ok {
return &ValidationError{Name: "force_openai_fast", err: errors.New(`ent: missing required field "Group.force_openai_fast"`)}
}
if _, ok := _c.mutation.ForceOpenaiUltrafast(); !ok {
return &ValidationError{Name: "force_openai_ultrafast", err: errors.New(`ent: missing required field "Group.force_openai_ultrafast"`)}
}
if _, ok := _c.mutation.FreeOpenaiFast(); !ok {
return &ValidationError{Name: "free_openai_fast", err: errors.New(`ent: missing required field "Group.free_openai_fast"`)}
}
@@ -1546,6 +1588,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldAllowBatchImageGeneration, field.TypeBool, value)
_node.AllowBatchImageGeneration = value
}
if value, ok := _c.mutation.ImageCountBilling(); ok {
_spec.SetField(group.FieldImageCountBilling, field.TypeBool, value)
_node.ImageCountBilling = value
}
if value, ok := _c.mutation.ImageRateIndependent(); ok {
_spec.SetField(group.FieldImageRateIndependent, field.TypeBool, value)
_node.ImageRateIndependent = value
@@ -1670,6 +1716,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
_node.ForceOpenaiFast = value
}
if value, ok := _c.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
_node.ForceOpenaiUltrafast = value
}
if value, ok := _c.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
_node.FreeOpenaiFast = value
@@ -2188,6 +2238,18 @@ func (u *GroupUpsert) UpdateAllowBatchImageGeneration() *GroupUpsert {
return u
}
// SetImageCountBilling sets the "image_count_billing" field.
func (u *GroupUpsert) SetImageCountBilling(v bool) *GroupUpsert {
u.Set(group.FieldImageCountBilling, v)
return u
}
// UpdateImageCountBilling sets the "image_count_billing" field to the value that was provided on create.
func (u *GroupUpsert) UpdateImageCountBilling() *GroupUpsert {
u.SetExcluded(group.FieldImageCountBilling)
return u
}
// SetImageRateIndependent sets the "image_rate_independent" field.
func (u *GroupUpsert) SetImageRateIndependent(v bool) *GroupUpsert {
u.Set(group.FieldImageRateIndependent, v)
@@ -2764,6 +2826,18 @@ func (u *GroupUpsert) UpdateForceOpenaiFast() *GroupUpsert {
return u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsert) SetForceOpenaiUltrafast(v bool) *GroupUpsert {
u.Set(group.FieldForceOpenaiUltrafast, v)
return u
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsert) UpdateForceOpenaiUltrafast() *GroupUpsert {
u.SetExcluded(group.FieldForceOpenaiUltrafast)
return u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsert) SetFreeOpenaiFast(v bool) *GroupUpsert {
u.Set(group.FieldFreeOpenaiFast, v)
@@ -3355,6 +3429,20 @@ func (u *GroupUpsertOne) UpdateAllowBatchImageGeneration() *GroupUpsertOne {
})
}
// SetImageCountBilling sets the "image_count_billing" field.
func (u *GroupUpsertOne) SetImageCountBilling(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetImageCountBilling(v)
})
}
// UpdateImageCountBilling sets the "image_count_billing" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdateImageCountBilling() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdateImageCountBilling()
})
}
// SetImageRateIndependent sets the "image_rate_independent" field.
func (u *GroupUpsertOne) SetImageRateIndependent(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
@@ -4027,6 +4115,20 @@ func (u *GroupUpsertOne) UpdateForceOpenaiFast() *GroupUpsertOne {
})
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsertOne) SetForceOpenaiUltrafast(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetForceOpenaiUltrafast(v)
})
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdateForceOpenaiUltrafast() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdateForceOpenaiUltrafast()
})
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsertOne) SetFreeOpenaiFast(v bool) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
@@ -4815,6 +4917,20 @@ func (u *GroupUpsertBulk) UpdateAllowBatchImageGeneration() *GroupUpsertBulk {
})
}
// SetImageCountBilling sets the "image_count_billing" field.
func (u *GroupUpsertBulk) SetImageCountBilling(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetImageCountBilling(v)
})
}
// UpdateImageCountBilling sets the "image_count_billing" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdateImageCountBilling() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdateImageCountBilling()
})
}
// SetImageRateIndependent sets the "image_rate_independent" field.
func (u *GroupUpsertBulk) SetImageRateIndependent(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
@@ -5487,6 +5603,20 @@ func (u *GroupUpsertBulk) UpdateForceOpenaiFast() *GroupUpsertBulk {
})
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (u *GroupUpsertBulk) SetForceOpenaiUltrafast(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetForceOpenaiUltrafast(v)
})
}
// UpdateForceOpenaiUltrafast sets the "force_openai_ultrafast" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdateForceOpenaiUltrafast() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdateForceOpenaiUltrafast()
})
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (u *GroupUpsertBulk) SetFreeOpenaiFast(v bool) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
+68
View File
@@ -373,6 +373,20 @@ func (_u *GroupUpdate) SetNillableAllowBatchImageGeneration(v *bool) *GroupUpdat
return _u
}
// SetImageCountBilling sets the "image_count_billing" field.
func (_u *GroupUpdate) SetImageCountBilling(v bool) *GroupUpdate {
_u.mutation.SetImageCountBilling(v)
return _u
}
// SetNillableImageCountBilling sets the "image_count_billing" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableImageCountBilling(v *bool) *GroupUpdate {
if v != nil {
_u.SetImageCountBilling(*v)
}
return _u
}
// SetImageRateIndependent sets the "image_rate_independent" field.
func (_u *GroupUpdate) SetImageRateIndependent(v bool) *GroupUpdate {
_u.mutation.SetImageRateIndependent(v)
@@ -1009,6 +1023,20 @@ func (_u *GroupUpdate) SetNillableForceOpenaiFast(v *bool) *GroupUpdate {
return _u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_u *GroupUpdate) SetForceOpenaiUltrafast(v bool) *GroupUpdate {
_u.mutation.SetForceOpenaiUltrafast(v)
return _u
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_u *GroupUpdate) SetNillableForceOpenaiUltrafast(v *bool) *GroupUpdate {
if v != nil {
_u.SetForceOpenaiUltrafast(*v)
}
return _u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_u *GroupUpdate) SetFreeOpenaiFast(v bool) *GroupUpdate {
_u.mutation.SetFreeOpenaiFast(v)
@@ -1665,6 +1693,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.AllowBatchImageGeneration(); ok {
_spec.SetField(group.FieldAllowBatchImageGeneration, field.TypeBool, value)
}
if value, ok := _u.mutation.ImageCountBilling(); ok {
_spec.SetField(group.FieldImageCountBilling, field.TypeBool, value)
}
if value, ok := _u.mutation.ImageRateIndependent(); ok {
_spec.SetField(group.FieldImageRateIndependent, field.TypeBool, value)
}
@@ -1870,6 +1901,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.ForceOpenaiFast(); ok {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
}
if value, ok := _u.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
}
if value, ok := _u.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
}
@@ -2576,6 +2610,20 @@ func (_u *GroupUpdateOne) SetNillableAllowBatchImageGeneration(v *bool) *GroupUp
return _u
}
// SetImageCountBilling sets the "image_count_billing" field.
func (_u *GroupUpdateOne) SetImageCountBilling(v bool) *GroupUpdateOne {
_u.mutation.SetImageCountBilling(v)
return _u
}
// SetNillableImageCountBilling sets the "image_count_billing" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableImageCountBilling(v *bool) *GroupUpdateOne {
if v != nil {
_u.SetImageCountBilling(*v)
}
return _u
}
// SetImageRateIndependent sets the "image_rate_independent" field.
func (_u *GroupUpdateOne) SetImageRateIndependent(v bool) *GroupUpdateOne {
_u.mutation.SetImageRateIndependent(v)
@@ -3212,6 +3260,20 @@ func (_u *GroupUpdateOne) SetNillableForceOpenaiFast(v *bool) *GroupUpdateOne {
return _u
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (_u *GroupUpdateOne) SetForceOpenaiUltrafast(v bool) *GroupUpdateOne {
_u.mutation.SetForceOpenaiUltrafast(v)
return _u
}
// SetNillableForceOpenaiUltrafast sets the "force_openai_ultrafast" field if the given value is not nil.
func (_u *GroupUpdateOne) SetNillableForceOpenaiUltrafast(v *bool) *GroupUpdateOne {
if v != nil {
_u.SetForceOpenaiUltrafast(*v)
}
return _u
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (_u *GroupUpdateOne) SetFreeOpenaiFast(v bool) *GroupUpdateOne {
_u.mutation.SetFreeOpenaiFast(v)
@@ -3898,6 +3960,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if value, ok := _u.mutation.AllowBatchImageGeneration(); ok {
_spec.SetField(group.FieldAllowBatchImageGeneration, field.TypeBool, value)
}
if value, ok := _u.mutation.ImageCountBilling(); ok {
_spec.SetField(group.FieldImageCountBilling, field.TypeBool, value)
}
if value, ok := _u.mutation.ImageRateIndependent(); ok {
_spec.SetField(group.FieldImageRateIndependent, field.TypeBool, value)
}
@@ -4103,6 +4168,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if value, ok := _u.mutation.ForceOpenaiFast(); ok {
_spec.SetField(group.FieldForceOpenaiFast, field.TypeBool, value)
}
if value, ok := _u.mutation.ForceOpenaiUltrafast(); ok {
_spec.SetField(group.FieldForceOpenaiUltrafast, field.TypeBool, value)
}
if value, ok := _u.mutation.FreeOpenaiFast(); ok {
_spec.SetField(group.FieldFreeOpenaiFast, field.TypeBool, value)
}
+19 -15
View File
@@ -925,6 +925,7 @@ var (
{Name: "default_validity_days", Type: field.TypeInt, Default: 30},
{Name: "allow_image_generation", Type: field.TypeBool, Default: false},
{Name: "allow_batch_image_generation", Type: field.TypeBool, Default: false},
{Name: "image_count_billing", Type: field.TypeBool, Default: false},
{Name: "image_rate_independent", Type: field.TypeBool, Default: false},
{Name: "image_rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "image_price_1k", Type: field.TypeFloat64, Nullable: true, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
@@ -956,6 +957,7 @@ var (
{Name: "allow_messages_dispatch", Type: field.TypeBool, Default: false},
{Name: "allow_live", Type: field.TypeBool, Default: false},
{Name: "force_openai_fast", Type: field.TypeBool, Default: false},
{Name: "force_openai_ultrafast", Type: field.TypeBool, Default: false},
{Name: "free_openai_fast", Type: field.TypeBool, Default: false},
{Name: "require_oauth_only", Type: field.TypeBool, Default: false},
{Name: "require_privacy_set", Type: field.TypeBool, Default: false},
@@ -1005,7 +1007,7 @@ var (
{
Name: "group_sort_order",
Unique: false,
Columns: []*schema.Column{GroupsColumns[50]},
Columns: []*schema.Column{GroupsColumns[51]},
},
{
Name: "idx_groups_duplicate_operation_id_active",
@@ -1654,6 +1656,8 @@ var (
{Name: "cache_read_tokens", Type: field.TypeInt, Default: 0},
{Name: "cache_creation_5m_tokens", Type: field.TypeInt, Default: 0},
{Name: "cache_creation_1h_tokens", Type: field.TypeInt, Default: 0},
{Name: "cache_creation_30m_tokens", Type: field.TypeInt, Default: 0},
{Name: "cache_creation_12h_tokens", Type: field.TypeInt, Default: 0},
{Name: "input_cost", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "output_cost", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
{Name: "cache_creation_cost", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,10)"}},
@@ -1694,31 +1698,31 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "usage_logs_api_keys_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[43]},
Columns: []*schema.Column{UsageLogsColumns[45]},
RefColumns: []*schema.Column{APIKeysColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_accounts_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[44]},
Columns: []*schema.Column{UsageLogsColumns[46]},
RefColumns: []*schema.Column{AccountsColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_groups_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[45]},
Columns: []*schema.Column{UsageLogsColumns[47]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.SetNull,
},
{
Symbol: "usage_logs_users_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[46]},
Columns: []*schema.Column{UsageLogsColumns[48]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "usage_logs_user_subscriptions_usage_logs",
Columns: []*schema.Column{UsageLogsColumns[47]},
Columns: []*schema.Column{UsageLogsColumns[49]},
RefColumns: []*schema.Column{UserSubscriptionsColumns[0]},
OnDelete: schema.SetNull,
},
@@ -1727,32 +1731,32 @@ var (
{
Name: "usagelog_user_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[46]},
Columns: []*schema.Column{UsageLogsColumns[48]},
},
{
Name: "usagelog_api_key_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[43]},
Columns: []*schema.Column{UsageLogsColumns[45]},
},
{
Name: "usagelog_account_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[44]},
Columns: []*schema.Column{UsageLogsColumns[46]},
},
{
Name: "usagelog_group_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[45]},
Columns: []*schema.Column{UsageLogsColumns[47]},
},
{
Name: "usagelog_subscription_id",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[47]},
Columns: []*schema.Column{UsageLogsColumns[49]},
},
{
Name: "usagelog_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[44]},
},
{
Name: "usagelog_model",
@@ -1772,17 +1776,17 @@ var (
{
Name: "usagelog_user_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[46], UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[48], UsageLogsColumns[44]},
},
{
Name: "usagelog_api_key_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[43], UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[45], UsageLogsColumns[44]},
},
{
Name: "usagelog_group_id_created_at",
Unique: false,
Columns: []*schema.Column{UsageLogsColumns[45], UsageLogsColumns[42]},
Columns: []*schema.Column{UsageLogsColumns[47], UsageLogsColumns[44]},
},
},
}
+284 -2
View File
@@ -22109,6 +22109,7 @@ type GroupMutation struct {
adddefault_validity_days *int
allow_image_generation *bool
allow_batch_image_generation *bool
image_count_billing *bool
image_rate_independent *bool
image_rate_multiplier *float64
addimage_rate_multiplier *float64
@@ -22160,6 +22161,7 @@ type GroupMutation struct {
allow_messages_dispatch *bool
allow_live *bool
force_openai_fast *bool
force_openai_ultrafast *bool
free_openai_fast *bool
require_oauth_only *bool
require_privacy_set *bool
@@ -23293,6 +23295,42 @@ func (m *GroupMutation) ResetAllowBatchImageGeneration() {
m.allow_batch_image_generation = nil
}
// SetImageCountBilling sets the "image_count_billing" field.
func (m *GroupMutation) SetImageCountBilling(b bool) {
m.image_count_billing = &b
}
// ImageCountBilling returns the value of the "image_count_billing" field in the mutation.
func (m *GroupMutation) ImageCountBilling() (r bool, exists bool) {
v := m.image_count_billing
if v == nil {
return
}
return *v, true
}
// OldImageCountBilling returns the old "image_count_billing" field's value of the Group entity.
// If the Group object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupMutation) OldImageCountBilling(ctx context.Context) (v bool, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldImageCountBilling is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldImageCountBilling requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldImageCountBilling: %w", err)
}
return oldValue.ImageCountBilling, nil
}
// ResetImageCountBilling resets all changes to the "image_count_billing" field.
func (m *GroupMutation) ResetImageCountBilling() {
m.image_count_billing = nil
}
// SetImageRateIndependent sets the "image_rate_independent" field.
func (m *GroupMutation) SetImageRateIndependent(b bool) {
m.image_rate_independent = &b
@@ -25021,6 +25059,42 @@ func (m *GroupMutation) ResetForceOpenaiFast() {
m.force_openai_fast = nil
}
// SetForceOpenaiUltrafast sets the "force_openai_ultrafast" field.
func (m *GroupMutation) SetForceOpenaiUltrafast(b bool) {
m.force_openai_ultrafast = &b
}
// ForceOpenaiUltrafast returns the value of the "force_openai_ultrafast" field in the mutation.
func (m *GroupMutation) ForceOpenaiUltrafast() (r bool, exists bool) {
v := m.force_openai_ultrafast
if v == nil {
return
}
return *v, true
}
// OldForceOpenaiUltrafast returns the old "force_openai_ultrafast" field's value of the Group entity.
// If the Group object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupMutation) OldForceOpenaiUltrafast(ctx context.Context) (v bool, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldForceOpenaiUltrafast is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldForceOpenaiUltrafast requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldForceOpenaiUltrafast: %w", err)
}
return oldValue.ForceOpenaiUltrafast, nil
}
// ResetForceOpenaiUltrafast resets all changes to the "force_openai_ultrafast" field.
func (m *GroupMutation) ResetForceOpenaiUltrafast() {
m.force_openai_ultrafast = nil
}
// SetFreeOpenaiFast sets the "free_openai_fast" field.
func (m *GroupMutation) SetFreeOpenaiFast(b bool) {
m.free_openai_fast = &b
@@ -25958,7 +26032,7 @@ func (m *GroupMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *GroupMutation) Fields() []string {
fields := make([]string, 0, 67)
fields := make([]string, 0, 69)
if m.created_at != nil {
fields = append(fields, group.FieldCreatedAt)
}
@@ -26025,6 +26099,9 @@ func (m *GroupMutation) Fields() []string {
if m.allow_batch_image_generation != nil {
fields = append(fields, group.FieldAllowBatchImageGeneration)
}
if m.image_count_billing != nil {
fields = append(fields, group.FieldImageCountBilling)
}
if m.image_rate_independent != nil {
fields = append(fields, group.FieldImageRateIndependent)
}
@@ -26118,6 +26195,9 @@ func (m *GroupMutation) Fields() []string {
if m.force_openai_fast != nil {
fields = append(fields, group.FieldForceOpenaiFast)
}
if m.force_openai_ultrafast != nil {
fields = append(fields, group.FieldForceOpenaiUltrafast)
}
if m.free_openai_fast != nil {
fields = append(fields, group.FieldFreeOpenaiFast)
}
@@ -26212,6 +26292,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
return m.AllowImageGeneration()
case group.FieldAllowBatchImageGeneration:
return m.AllowBatchImageGeneration()
case group.FieldImageCountBilling:
return m.ImageCountBilling()
case group.FieldImageRateIndependent:
return m.ImageRateIndependent()
case group.FieldImageRateMultiplier:
@@ -26274,6 +26356,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
return m.AllowLive()
case group.FieldForceOpenaiFast:
return m.ForceOpenaiFast()
case group.FieldForceOpenaiUltrafast:
return m.ForceOpenaiUltrafast()
case group.FieldFreeOpenaiFast:
return m.FreeOpenaiFast()
case group.FieldRequireOauthOnly:
@@ -26355,6 +26439,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldAllowImageGeneration(ctx)
case group.FieldAllowBatchImageGeneration:
return m.OldAllowBatchImageGeneration(ctx)
case group.FieldImageCountBilling:
return m.OldImageCountBilling(ctx)
case group.FieldImageRateIndependent:
return m.OldImageRateIndependent(ctx)
case group.FieldImageRateMultiplier:
@@ -26417,6 +26503,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldAllowLive(ctx)
case group.FieldForceOpenaiFast:
return m.OldForceOpenaiFast(ctx)
case group.FieldForceOpenaiUltrafast:
return m.OldForceOpenaiUltrafast(ctx)
case group.FieldFreeOpenaiFast:
return m.OldFreeOpenaiFast(ctx)
case group.FieldRequireOauthOnly:
@@ -26608,6 +26696,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
}
m.SetAllowBatchImageGeneration(v)
return nil
case group.FieldImageCountBilling:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetImageCountBilling(v)
return nil
case group.FieldImageRateIndependent:
v, ok := value.(bool)
if !ok {
@@ -26825,6 +26920,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
}
m.SetForceOpenaiFast(v)
return nil
case group.FieldForceOpenaiUltrafast:
v, ok := value.(bool)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetForceOpenaiUltrafast(v)
return nil
case group.FieldFreeOpenaiFast:
v, ok := value.(bool)
if !ok {
@@ -27500,6 +27602,9 @@ func (m *GroupMutation) ResetField(name string) error {
case group.FieldAllowBatchImageGeneration:
m.ResetAllowBatchImageGeneration()
return nil
case group.FieldImageCountBilling:
m.ResetImageCountBilling()
return nil
case group.FieldImageRateIndependent:
m.ResetImageRateIndependent()
return nil
@@ -27593,6 +27698,9 @@ func (m *GroupMutation) ResetField(name string) error {
case group.FieldForceOpenaiFast:
m.ResetForceOpenaiFast()
return nil
case group.FieldForceOpenaiUltrafast:
m.ResetForceOpenaiUltrafast()
return nil
case group.FieldFreeOpenaiFast:
m.ResetFreeOpenaiFast()
return nil
@@ -44694,6 +44802,10 @@ type UsageLogMutation struct {
addcache_creation_5m_tokens *int
cache_creation_1h_tokens *int
addcache_creation_1h_tokens *int
cache_creation_30m_tokens *int
addcache_creation_30m_tokens *int
cache_creation_12h_tokens *int
addcache_creation_12h_tokens *int
input_cost *float64
addinput_cost *float64
output_cost *float64
@@ -45875,6 +45987,118 @@ func (m *UsageLogMutation) ResetCacheCreation1hTokens() {
m.addcache_creation_1h_tokens = nil
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (m *UsageLogMutation) SetCacheCreation30mTokens(i int) {
m.cache_creation_30m_tokens = &i
m.addcache_creation_30m_tokens = nil
}
// CacheCreation30mTokens returns the value of the "cache_creation_30m_tokens" field in the mutation.
func (m *UsageLogMutation) CacheCreation30mTokens() (r int, exists bool) {
v := m.cache_creation_30m_tokens
if v == nil {
return
}
return *v, true
}
// OldCacheCreation30mTokens returns the old "cache_creation_30m_tokens" field's value of the UsageLog entity.
// If the UsageLog object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageLogMutation) OldCacheCreation30mTokens(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCacheCreation30mTokens is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCacheCreation30mTokens requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCacheCreation30mTokens: %w", err)
}
return oldValue.CacheCreation30mTokens, nil
}
// AddCacheCreation30mTokens adds i to the "cache_creation_30m_tokens" field.
func (m *UsageLogMutation) AddCacheCreation30mTokens(i int) {
if m.addcache_creation_30m_tokens != nil {
*m.addcache_creation_30m_tokens += i
} else {
m.addcache_creation_30m_tokens = &i
}
}
// AddedCacheCreation30mTokens returns the value that was added to the "cache_creation_30m_tokens" field in this mutation.
func (m *UsageLogMutation) AddedCacheCreation30mTokens() (r int, exists bool) {
v := m.addcache_creation_30m_tokens
if v == nil {
return
}
return *v, true
}
// ResetCacheCreation30mTokens resets all changes to the "cache_creation_30m_tokens" field.
func (m *UsageLogMutation) ResetCacheCreation30mTokens() {
m.cache_creation_30m_tokens = nil
m.addcache_creation_30m_tokens = nil
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (m *UsageLogMutation) SetCacheCreation12hTokens(i int) {
m.cache_creation_12h_tokens = &i
m.addcache_creation_12h_tokens = nil
}
// CacheCreation12hTokens returns the value of the "cache_creation_12h_tokens" field in the mutation.
func (m *UsageLogMutation) CacheCreation12hTokens() (r int, exists bool) {
v := m.cache_creation_12h_tokens
if v == nil {
return
}
return *v, true
}
// OldCacheCreation12hTokens returns the old "cache_creation_12h_tokens" field's value of the UsageLog entity.
// If the UsageLog object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *UsageLogMutation) OldCacheCreation12hTokens(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCacheCreation12hTokens is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCacheCreation12hTokens requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCacheCreation12hTokens: %w", err)
}
return oldValue.CacheCreation12hTokens, nil
}
// AddCacheCreation12hTokens adds i to the "cache_creation_12h_tokens" field.
func (m *UsageLogMutation) AddCacheCreation12hTokens(i int) {
if m.addcache_creation_12h_tokens != nil {
*m.addcache_creation_12h_tokens += i
} else {
m.addcache_creation_12h_tokens = &i
}
}
// AddedCacheCreation12hTokens returns the value that was added to the "cache_creation_12h_tokens" field in this mutation.
func (m *UsageLogMutation) AddedCacheCreation12hTokens() (r int, exists bool) {
v := m.addcache_creation_12h_tokens
if v == nil {
return
}
return *v, true
}
// ResetCacheCreation12hTokens resets all changes to the "cache_creation_12h_tokens" field.
func (m *UsageLogMutation) ResetCacheCreation12hTokens() {
m.cache_creation_12h_tokens = nil
m.addcache_creation_12h_tokens = nil
}
// SetInputCost sets the "input_cost" field.
func (m *UsageLogMutation) SetInputCost(f float64) {
m.input_cost = &f
@@ -47420,7 +47644,7 @@ func (m *UsageLogMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *UsageLogMutation) Fields() []string {
fields := make([]string, 0, 47)
fields := make([]string, 0, 49)
if m.user != nil {
fields = append(fields, usagelog.FieldUserID)
}
@@ -47484,6 +47708,12 @@ func (m *UsageLogMutation) Fields() []string {
if m.cache_creation_1h_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation1hTokens)
}
if m.cache_creation_30m_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation30mTokens)
}
if m.cache_creation_12h_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation12hTokens)
}
if m.input_cost != nil {
fields = append(fields, usagelog.FieldInputCost)
}
@@ -47612,6 +47842,10 @@ func (m *UsageLogMutation) Field(name string) (ent.Value, bool) {
return m.CacheCreation5mTokens()
case usagelog.FieldCacheCreation1hTokens:
return m.CacheCreation1hTokens()
case usagelog.FieldCacheCreation30mTokens:
return m.CacheCreation30mTokens()
case usagelog.FieldCacheCreation12hTokens:
return m.CacheCreation12hTokens()
case usagelog.FieldInputCost:
return m.InputCost()
case usagelog.FieldOutputCost:
@@ -47715,6 +47949,10 @@ func (m *UsageLogMutation) OldField(ctx context.Context, name string) (ent.Value
return m.OldCacheCreation5mTokens(ctx)
case usagelog.FieldCacheCreation1hTokens:
return m.OldCacheCreation1hTokens(ctx)
case usagelog.FieldCacheCreation30mTokens:
return m.OldCacheCreation30mTokens(ctx)
case usagelog.FieldCacheCreation12hTokens:
return m.OldCacheCreation12hTokens(ctx)
case usagelog.FieldInputCost:
return m.OldInputCost(ctx)
case usagelog.FieldOutputCost:
@@ -47923,6 +48161,20 @@ func (m *UsageLogMutation) SetField(name string, value ent.Value) error {
}
m.SetCacheCreation1hTokens(v)
return nil
case usagelog.FieldCacheCreation30mTokens:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCacheCreation30mTokens(v)
return nil
case usagelog.FieldCacheCreation12hTokens:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCacheCreation12hTokens(v)
return nil
case usagelog.FieldInputCost:
v, ok := value.(float64)
if !ok {
@@ -48134,6 +48386,12 @@ func (m *UsageLogMutation) AddedFields() []string {
if m.addcache_creation_1h_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation1hTokens)
}
if m.addcache_creation_30m_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation30mTokens)
}
if m.addcache_creation_12h_tokens != nil {
fields = append(fields, usagelog.FieldCacheCreation12hTokens)
}
if m.addinput_cost != nil {
fields = append(fields, usagelog.FieldInputCost)
}
@@ -48198,6 +48456,10 @@ func (m *UsageLogMutation) AddedField(name string) (ent.Value, bool) {
return m.AddedCacheCreation5mTokens()
case usagelog.FieldCacheCreation1hTokens:
return m.AddedCacheCreation1hTokens()
case usagelog.FieldCacheCreation30mTokens:
return m.AddedCacheCreation30mTokens()
case usagelog.FieldCacheCreation12hTokens:
return m.AddedCacheCreation12hTokens()
case usagelog.FieldInputCost:
return m.AddedInputCost()
case usagelog.FieldOutputCost:
@@ -48284,6 +48546,20 @@ func (m *UsageLogMutation) AddField(name string, value ent.Value) error {
}
m.AddCacheCreation1hTokens(v)
return nil
case usagelog.FieldCacheCreation30mTokens:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddCacheCreation30mTokens(v)
return nil
case usagelog.FieldCacheCreation12hTokens:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddCacheCreation12hTokens(v)
return nil
case usagelog.FieldInputCost:
v, ok := value.(float64)
if !ok {
@@ -48607,6 +48883,12 @@ func (m *UsageLogMutation) ResetField(name string) error {
case usagelog.FieldCacheCreation1hTokens:
m.ResetCacheCreation1hTokens()
return nil
case usagelog.FieldCacheCreation30mTokens:
m.ResetCacheCreation30mTokens()
return nil
case usagelog.FieldCacheCreation12hTokens:
m.ResetCacheCreation12hTokens()
return nil
case usagelog.FieldInputCost:
m.ResetInputCost()
return nil
+70 -54
View File
@@ -1103,142 +1103,150 @@ func init() {
groupDescAllowBatchImageGeneration := groupFields[18].Descriptor()
// group.DefaultAllowBatchImageGeneration holds the default value on creation for the allow_batch_image_generation field.
group.DefaultAllowBatchImageGeneration = groupDescAllowBatchImageGeneration.Default.(bool)
// groupDescImageCountBilling is the schema descriptor for image_count_billing field.
groupDescImageCountBilling := groupFields[19].Descriptor()
// group.DefaultImageCountBilling holds the default value on creation for the image_count_billing field.
group.DefaultImageCountBilling = groupDescImageCountBilling.Default.(bool)
// groupDescImageRateIndependent is the schema descriptor for image_rate_independent field.
groupDescImageRateIndependent := groupFields[19].Descriptor()
groupDescImageRateIndependent := groupFields[20].Descriptor()
// group.DefaultImageRateIndependent holds the default value on creation for the image_rate_independent field.
group.DefaultImageRateIndependent = groupDescImageRateIndependent.Default.(bool)
// groupDescImageRateMultiplier is the schema descriptor for image_rate_multiplier field.
groupDescImageRateMultiplier := groupFields[20].Descriptor()
groupDescImageRateMultiplier := groupFields[21].Descriptor()
// group.DefaultImageRateMultiplier holds the default value on creation for the image_rate_multiplier field.
group.DefaultImageRateMultiplier = groupDescImageRateMultiplier.Default.(float64)
// groupDescBatchImageDiscountMultiplier is the schema descriptor for batch_image_discount_multiplier field.
groupDescBatchImageDiscountMultiplier := groupFields[24].Descriptor()
groupDescBatchImageDiscountMultiplier := groupFields[25].Descriptor()
// group.DefaultBatchImageDiscountMultiplier holds the default value on creation for the batch_image_discount_multiplier field.
group.DefaultBatchImageDiscountMultiplier = groupDescBatchImageDiscountMultiplier.Default.(float64)
// groupDescBatchImageHoldMultiplier is the schema descriptor for batch_image_hold_multiplier field.
groupDescBatchImageHoldMultiplier := groupFields[25].Descriptor()
groupDescBatchImageHoldMultiplier := groupFields[26].Descriptor()
// group.DefaultBatchImageHoldMultiplier holds the default value on creation for the batch_image_hold_multiplier field.
group.DefaultBatchImageHoldMultiplier = groupDescBatchImageHoldMultiplier.Default.(float64)
// groupDescVideoRateIndependent is the schema descriptor for video_rate_independent field.
groupDescVideoRateIndependent := groupFields[26].Descriptor()
groupDescVideoRateIndependent := groupFields[27].Descriptor()
// group.DefaultVideoRateIndependent holds the default value on creation for the video_rate_independent field.
group.DefaultVideoRateIndependent = groupDescVideoRateIndependent.Default.(bool)
// groupDescVideoRateMultiplier is the schema descriptor for video_rate_multiplier field.
groupDescVideoRateMultiplier := groupFields[27].Descriptor()
groupDescVideoRateMultiplier := groupFields[28].Descriptor()
// group.DefaultVideoRateMultiplier holds the default value on creation for the video_rate_multiplier field.
group.DefaultVideoRateMultiplier = groupDescVideoRateMultiplier.Default.(float64)
// groupDescSearchPricePer1k is the schema descriptor for search_price_per_1k field.
groupDescSearchPricePer1k := groupFields[33].Descriptor()
groupDescSearchPricePer1k := groupFields[34].Descriptor()
// group.SearchPricePer1kValidator is a validator for the "search_price_per_1k" field. It is called by the builders before save.
group.SearchPricePer1kValidator = groupDescSearchPricePer1k.Validators[0].(func(float64) error)
// groupDescAudioRealtimePricePerMin is the schema descriptor for audio_realtime_price_per_min field.
groupDescAudioRealtimePricePerMin := groupFields[34].Descriptor()
groupDescAudioRealtimePricePerMin := groupFields[35].Descriptor()
// group.AudioRealtimePricePerMinValidator is a validator for the "audio_realtime_price_per_min" field. It is called by the builders before save.
group.AudioRealtimePricePerMinValidator = groupDescAudioRealtimePricePerMin.Validators[0].(func(float64) error)
// groupDescAudioTtsPricePerMillionChars is the schema descriptor for audio_tts_price_per_million_chars field.
groupDescAudioTtsPricePerMillionChars := groupFields[35].Descriptor()
groupDescAudioTtsPricePerMillionChars := groupFields[36].Descriptor()
// group.AudioTtsPricePerMillionCharsValidator is a validator for the "audio_tts_price_per_million_chars" field. It is called by the builders before save.
group.AudioTtsPricePerMillionCharsValidator = groupDescAudioTtsPricePerMillionChars.Validators[0].(func(float64) error)
// groupDescAudioSttPricePerHour is the schema descriptor for audio_stt_price_per_hour field.
groupDescAudioSttPricePerHour := groupFields[36].Descriptor()
groupDescAudioSttPricePerHour := groupFields[37].Descriptor()
// group.AudioSttPricePerHourValidator is a validator for the "audio_stt_price_per_hour" field. It is called by the builders before save.
group.AudioSttPricePerHourValidator = groupDescAudioSttPricePerHour.Validators[0].(func(float64) error)
// groupDescLongContextPricingEnabled is the schema descriptor for long_context_pricing_enabled field.
groupDescLongContextPricingEnabled := groupFields[37].Descriptor()
groupDescLongContextPricingEnabled := groupFields[38].Descriptor()
// group.DefaultLongContextPricingEnabled holds the default value on creation for the long_context_pricing_enabled field.
group.DefaultLongContextPricingEnabled = groupDescLongContextPricingEnabled.Default.(bool)
// groupDescClaudeCodeOnly is the schema descriptor for claude_code_only field.
groupDescClaudeCodeOnly := groupFields[39].Descriptor()
groupDescClaudeCodeOnly := groupFields[40].Descriptor()
// group.DefaultClaudeCodeOnly holds the default value on creation for the claude_code_only field.
group.DefaultClaudeCodeOnly = groupDescClaudeCodeOnly.Default.(bool)
// groupDescModelRoutingEnabled is the schema descriptor for model_routing_enabled field.
groupDescModelRoutingEnabled := groupFields[43].Descriptor()
groupDescModelRoutingEnabled := groupFields[44].Descriptor()
// group.DefaultModelRoutingEnabled holds the default value on creation for the model_routing_enabled field.
group.DefaultModelRoutingEnabled = groupDescModelRoutingEnabled.Default.(bool)
// groupDescMcpXMLInject is the schema descriptor for mcp_xml_inject field.
groupDescMcpXMLInject := groupFields[44].Descriptor()
groupDescMcpXMLInject := groupFields[45].Descriptor()
// group.DefaultMcpXMLInject holds the default value on creation for the mcp_xml_inject field.
group.DefaultMcpXMLInject = groupDescMcpXMLInject.Default.(bool)
// groupDescSupportedModelScopes is the schema descriptor for supported_model_scopes field.
groupDescSupportedModelScopes := groupFields[45].Descriptor()
groupDescSupportedModelScopes := groupFields[46].Descriptor()
// group.DefaultSupportedModelScopes holds the default value on creation for the supported_model_scopes field.
group.DefaultSupportedModelScopes = groupDescSupportedModelScopes.Default.([]string)
// groupDescSortOrder is the schema descriptor for sort_order field.
groupDescSortOrder := groupFields[46].Descriptor()
groupDescSortOrder := groupFields[47].Descriptor()
// group.DefaultSortOrder holds the default value on creation for the sort_order field.
group.DefaultSortOrder = groupDescSortOrder.Default.(int)
// groupDescAllowMessagesDispatch is the schema descriptor for allow_messages_dispatch field.
groupDescAllowMessagesDispatch := groupFields[47].Descriptor()
groupDescAllowMessagesDispatch := groupFields[48].Descriptor()
// group.DefaultAllowMessagesDispatch holds the default value on creation for the allow_messages_dispatch field.
group.DefaultAllowMessagesDispatch = groupDescAllowMessagesDispatch.Default.(bool)
// groupDescAllowLive is the schema descriptor for allow_live field.
groupDescAllowLive := groupFields[48].Descriptor()
groupDescAllowLive := groupFields[49].Descriptor()
// group.DefaultAllowLive holds the default value on creation for the allow_live field.
group.DefaultAllowLive = groupDescAllowLive.Default.(bool)
// groupDescForceOpenaiFast is the schema descriptor for force_openai_fast field.
groupDescForceOpenaiFast := groupFields[49].Descriptor()
groupDescForceOpenaiFast := groupFields[50].Descriptor()
// group.DefaultForceOpenaiFast holds the default value on creation for the force_openai_fast field.
group.DefaultForceOpenaiFast = groupDescForceOpenaiFast.Default.(bool)
// groupDescForceOpenaiUltrafast is the schema descriptor for force_openai_ultrafast field.
groupDescForceOpenaiUltrafast := groupFields[51].Descriptor()
// group.DefaultForceOpenaiUltrafast holds the default value on creation for the force_openai_ultrafast field.
group.DefaultForceOpenaiUltrafast = groupDescForceOpenaiUltrafast.Default.(bool)
// groupDescFreeOpenaiFast is the schema descriptor for free_openai_fast field.
groupDescFreeOpenaiFast := groupFields[50].Descriptor()
groupDescFreeOpenaiFast := groupFields[52].Descriptor()
// group.DefaultFreeOpenaiFast holds the default value on creation for the free_openai_fast field.
group.DefaultFreeOpenaiFast = groupDescFreeOpenaiFast.Default.(bool)
// groupDescRequireOauthOnly is the schema descriptor for require_oauth_only field.
groupDescRequireOauthOnly := groupFields[51].Descriptor()
groupDescRequireOauthOnly := groupFields[53].Descriptor()
// group.DefaultRequireOauthOnly holds the default value on creation for the require_oauth_only field.
group.DefaultRequireOauthOnly = groupDescRequireOauthOnly.Default.(bool)
// groupDescRequirePrivacySet is the schema descriptor for require_privacy_set field.
groupDescRequirePrivacySet := groupFields[52].Descriptor()
groupDescRequirePrivacySet := groupFields[54].Descriptor()
// group.DefaultRequirePrivacySet holds the default value on creation for the require_privacy_set field.
group.DefaultRequirePrivacySet = groupDescRequirePrivacySet.Default.(bool)
// groupDescDefaultMappedModel is the schema descriptor for default_mapped_model field.
groupDescDefaultMappedModel := groupFields[53].Descriptor()
groupDescDefaultMappedModel := groupFields[55].Descriptor()
// group.DefaultDefaultMappedModel holds the default value on creation for the default_mapped_model field.
group.DefaultDefaultMappedModel = groupDescDefaultMappedModel.Default.(string)
// group.DefaultMappedModelValidator is a validator for the "default_mapped_model" field. It is called by the builders before save.
group.DefaultMappedModelValidator = groupDescDefaultMappedModel.Validators[0].(func(string) error)
// groupDescMessagesDispatchModelConfig is the schema descriptor for messages_dispatch_model_config field.
groupDescMessagesDispatchModelConfig := groupFields[54].Descriptor()
groupDescMessagesDispatchModelConfig := groupFields[56].Descriptor()
// group.DefaultMessagesDispatchModelConfig holds the default value on creation for the messages_dispatch_model_config field.
group.DefaultMessagesDispatchModelConfig = groupDescMessagesDispatchModelConfig.Default.(domain.OpenAIMessagesDispatchModelConfig)
// groupDescModelAllowlist is the schema descriptor for model_allowlist field.
groupDescModelAllowlist := groupFields[55].Descriptor()
groupDescModelAllowlist := groupFields[57].Descriptor()
// group.DefaultModelAllowlist holds the default value on creation for the model_allowlist field.
group.DefaultModelAllowlist = groupDescModelAllowlist.Default.(domain.GroupModelAllowlist)
// groupDescCodexModelsManifestConfig is the schema descriptor for codex_models_manifest_config field.
groupDescCodexModelsManifestConfig := groupFields[56].Descriptor()
groupDescCodexModelsManifestConfig := groupFields[58].Descriptor()
// group.DefaultCodexModelsManifestConfig holds the default value on creation for the codex_models_manifest_config field.
group.DefaultCodexModelsManifestConfig = groupDescCodexModelsManifestConfig.Default.(domain.GroupCodexModelsManifestConfig)
// groupDescRpmLimit is the schema descriptor for rpm_limit field.
groupDescRpmLimit := groupFields[57].Descriptor()
groupDescRpmLimit := groupFields[59].Descriptor()
// group.DefaultRpmLimit holds the default value on creation for the rpm_limit field.
group.DefaultRpmLimit = groupDescRpmLimit.Default.(int)
// groupDescMaxReasoningEffort is the schema descriptor for max_reasoning_effort field.
groupDescMaxReasoningEffort := groupFields[58].Descriptor()
groupDescMaxReasoningEffort := groupFields[60].Descriptor()
// group.DefaultMaxReasoningEffort holds the default value on creation for the max_reasoning_effort field.
group.DefaultMaxReasoningEffort = groupDescMaxReasoningEffort.Default.(string)
// group.MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save.
group.MaxReasoningEffortValidator = groupDescMaxReasoningEffort.Validators[0].(func(string) error)
// groupDescMaxReasoningEffortOverLimit is the schema descriptor for max_reasoning_effort_over_limit field.
groupDescMaxReasoningEffortOverLimit := groupFields[59].Descriptor()
groupDescMaxReasoningEffortOverLimit := groupFields[61].Descriptor()
// group.DefaultMaxReasoningEffortOverLimit holds the default value on creation for the max_reasoning_effort_over_limit field.
group.DefaultMaxReasoningEffortOverLimit = groupDescMaxReasoningEffortOverLimit.Default.(string)
// group.MaxReasoningEffortOverLimitValidator is a validator for the "max_reasoning_effort_over_limit" field. It is called by the builders before save.
group.MaxReasoningEffortOverLimitValidator = groupDescMaxReasoningEffortOverLimit.Validators[0].(func(string) error)
// groupDescReasoningEffortMappings is the schema descriptor for reasoning_effort_mappings field.
groupDescReasoningEffortMappings := groupFields[60].Descriptor()
groupDescReasoningEffortMappings := groupFields[62].Descriptor()
// group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field.
group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping)
// groupDescProfitControlEnabled is the schema descriptor for profit_control_enabled field.
groupDescProfitControlEnabled := groupFields[61].Descriptor()
groupDescProfitControlEnabled := groupFields[63].Descriptor()
// group.DefaultProfitControlEnabled holds the default value on creation for the profit_control_enabled field.
group.DefaultProfitControlEnabled = groupDescProfitControlEnabled.Default.(bool)
// groupDescProfitMinMargin is the schema descriptor for profit_min_margin field.
groupDescProfitMinMargin := groupFields[62].Descriptor()
groupDescProfitMinMargin := groupFields[64].Descriptor()
// group.DefaultProfitMinMargin holds the default value on creation for the profit_min_margin field.
group.DefaultProfitMinMargin = groupDescProfitMinMargin.Default.(float64)
// groupDescProfitSafetyBuffer is the schema descriptor for profit_safety_buffer field.
groupDescProfitSafetyBuffer := groupFields[63].Descriptor()
groupDescProfitSafetyBuffer := groupFields[65].Descriptor()
// group.DefaultProfitSafetyBuffer holds the default value on creation for the profit_safety_buffer field.
group.DefaultProfitSafetyBuffer = groupDescProfitSafetyBuffer.Default.(float64)
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
@@ -2074,88 +2082,96 @@ func init() {
usagelogDescCacheCreation1hTokens := usagelogFields[20].Descriptor()
// usagelog.DefaultCacheCreation1hTokens holds the default value on creation for the cache_creation_1h_tokens field.
usagelog.DefaultCacheCreation1hTokens = usagelogDescCacheCreation1hTokens.Default.(int)
// usagelogDescCacheCreation30mTokens is the schema descriptor for cache_creation_30m_tokens field.
usagelogDescCacheCreation30mTokens := usagelogFields[21].Descriptor()
// usagelog.DefaultCacheCreation30mTokens holds the default value on creation for the cache_creation_30m_tokens field.
usagelog.DefaultCacheCreation30mTokens = usagelogDescCacheCreation30mTokens.Default.(int)
// usagelogDescCacheCreation12hTokens is the schema descriptor for cache_creation_12h_tokens field.
usagelogDescCacheCreation12hTokens := usagelogFields[22].Descriptor()
// usagelog.DefaultCacheCreation12hTokens holds the default value on creation for the cache_creation_12h_tokens field.
usagelog.DefaultCacheCreation12hTokens = usagelogDescCacheCreation12hTokens.Default.(int)
// usagelogDescInputCost is the schema descriptor for input_cost field.
usagelogDescInputCost := usagelogFields[21].Descriptor()
usagelogDescInputCost := usagelogFields[23].Descriptor()
// usagelog.DefaultInputCost holds the default value on creation for the input_cost field.
usagelog.DefaultInputCost = usagelogDescInputCost.Default.(float64)
// usagelogDescOutputCost is the schema descriptor for output_cost field.
usagelogDescOutputCost := usagelogFields[22].Descriptor()
usagelogDescOutputCost := usagelogFields[24].Descriptor()
// usagelog.DefaultOutputCost holds the default value on creation for the output_cost field.
usagelog.DefaultOutputCost = usagelogDescOutputCost.Default.(float64)
// usagelogDescCacheCreationCost is the schema descriptor for cache_creation_cost field.
usagelogDescCacheCreationCost := usagelogFields[23].Descriptor()
usagelogDescCacheCreationCost := usagelogFields[25].Descriptor()
// usagelog.DefaultCacheCreationCost holds the default value on creation for the cache_creation_cost field.
usagelog.DefaultCacheCreationCost = usagelogDescCacheCreationCost.Default.(float64)
// usagelogDescCacheReadCost is the schema descriptor for cache_read_cost field.
usagelogDescCacheReadCost := usagelogFields[24].Descriptor()
usagelogDescCacheReadCost := usagelogFields[26].Descriptor()
// usagelog.DefaultCacheReadCost holds the default value on creation for the cache_read_cost field.
usagelog.DefaultCacheReadCost = usagelogDescCacheReadCost.Default.(float64)
// usagelogDescTotalCost is the schema descriptor for total_cost field.
usagelogDescTotalCost := usagelogFields[25].Descriptor()
usagelogDescTotalCost := usagelogFields[27].Descriptor()
// usagelog.DefaultTotalCost holds the default value on creation for the total_cost field.
usagelog.DefaultTotalCost = usagelogDescTotalCost.Default.(float64)
// usagelogDescActualCost is the schema descriptor for actual_cost field.
usagelogDescActualCost := usagelogFields[26].Descriptor()
usagelogDescActualCost := usagelogFields[28].Descriptor()
// usagelog.DefaultActualCost holds the default value on creation for the actual_cost field.
usagelog.DefaultActualCost = usagelogDescActualCost.Default.(float64)
// usagelogDescRateMultiplier is the schema descriptor for rate_multiplier field.
usagelogDescRateMultiplier := usagelogFields[27].Descriptor()
usagelogDescRateMultiplier := usagelogFields[29].Descriptor()
// usagelog.DefaultRateMultiplier holds the default value on creation for the rate_multiplier field.
usagelog.DefaultRateMultiplier = usagelogDescRateMultiplier.Default.(float64)
// usagelogDescLongContextBillingApplied is the schema descriptor for long_context_billing_applied field.
usagelogDescLongContextBillingApplied := usagelogFields[28].Descriptor()
usagelogDescLongContextBillingApplied := usagelogFields[30].Descriptor()
// usagelog.DefaultLongContextBillingApplied holds the default value on creation for the long_context_billing_applied field.
usagelog.DefaultLongContextBillingApplied = usagelogDescLongContextBillingApplied.Default.(bool)
// usagelogDescBillingType is the schema descriptor for billing_type field.
usagelogDescBillingType := usagelogFields[30].Descriptor()
usagelogDescBillingType := usagelogFields[32].Descriptor()
// usagelog.DefaultBillingType holds the default value on creation for the billing_type field.
usagelog.DefaultBillingType = usagelogDescBillingType.Default.(int8)
// usagelogDescStream is the schema descriptor for stream field.
usagelogDescStream := usagelogFields[31].Descriptor()
usagelogDescStream := usagelogFields[33].Descriptor()
// usagelog.DefaultStream holds the default value on creation for the stream field.
usagelog.DefaultStream = usagelogDescStream.Default.(bool)
// usagelogDescUserAgent is the schema descriptor for user_agent field.
usagelogDescUserAgent := usagelogFields[34].Descriptor()
usagelogDescUserAgent := usagelogFields[36].Descriptor()
// usagelog.UserAgentValidator is a validator for the "user_agent" field. It is called by the builders before save.
usagelog.UserAgentValidator = usagelogDescUserAgent.Validators[0].(func(string) error)
// usagelogDescIPAddress is the schema descriptor for ip_address field.
usagelogDescIPAddress := usagelogFields[35].Descriptor()
usagelogDescIPAddress := usagelogFields[37].Descriptor()
// usagelog.IPAddressValidator is a validator for the "ip_address" field. It is called by the builders before save.
usagelog.IPAddressValidator = usagelogDescIPAddress.Validators[0].(func(string) error)
// usagelogDescImageCount is the schema descriptor for image_count field.
usagelogDescImageCount := usagelogFields[36].Descriptor()
usagelogDescImageCount := usagelogFields[38].Descriptor()
// usagelog.DefaultImageCount holds the default value on creation for the image_count field.
usagelog.DefaultImageCount = usagelogDescImageCount.Default.(int)
// usagelogDescImageSize is the schema descriptor for image_size field.
usagelogDescImageSize := usagelogFields[37].Descriptor()
usagelogDescImageSize := usagelogFields[39].Descriptor()
// usagelog.ImageSizeValidator is a validator for the "image_size" field. It is called by the builders before save.
usagelog.ImageSizeValidator = usagelogDescImageSize.Validators[0].(func(string) error)
// usagelogDescImageInputSize is the schema descriptor for image_input_size field.
usagelogDescImageInputSize := usagelogFields[38].Descriptor()
usagelogDescImageInputSize := usagelogFields[40].Descriptor()
// usagelog.ImageInputSizeValidator is a validator for the "image_input_size" field. It is called by the builders before save.
usagelog.ImageInputSizeValidator = usagelogDescImageInputSize.Validators[0].(func(string) error)
// usagelogDescImageOutputSize is the schema descriptor for image_output_size field.
usagelogDescImageOutputSize := usagelogFields[39].Descriptor()
usagelogDescImageOutputSize := usagelogFields[41].Descriptor()
// usagelog.ImageOutputSizeValidator is a validator for the "image_output_size" field. It is called by the builders before save.
usagelog.ImageOutputSizeValidator = usagelogDescImageOutputSize.Validators[0].(func(string) error)
// usagelogDescImageSizeSource is the schema descriptor for image_size_source field.
usagelogDescImageSizeSource := usagelogFields[40].Descriptor()
usagelogDescImageSizeSource := usagelogFields[42].Descriptor()
// usagelog.ImageSizeSourceValidator is a validator for the "image_size_source" field. It is called by the builders before save.
usagelog.ImageSizeSourceValidator = usagelogDescImageSizeSource.Validators[0].(func(string) error)
// usagelogDescVideoCount is the schema descriptor for video_count field.
usagelogDescVideoCount := usagelogFields[42].Descriptor()
usagelogDescVideoCount := usagelogFields[44].Descriptor()
// usagelog.DefaultVideoCount holds the default value on creation for the video_count field.
usagelog.DefaultVideoCount = usagelogDescVideoCount.Default.(int)
// usagelogDescVideoResolution is the schema descriptor for video_resolution field.
usagelogDescVideoResolution := usagelogFields[43].Descriptor()
usagelogDescVideoResolution := usagelogFields[45].Descriptor()
// usagelog.VideoResolutionValidator is a validator for the "video_resolution" field. It is called by the builders before save.
usagelog.VideoResolutionValidator = usagelogDescVideoResolution.Validators[0].(func(string) error)
// usagelogDescCacheTTLOverridden is the schema descriptor for cache_ttl_overridden field.
usagelogDescCacheTTLOverridden := usagelogFields[45].Descriptor()
usagelogDescCacheTTLOverridden := usagelogFields[47].Descriptor()
// usagelog.DefaultCacheTTLOverridden holds the default value on creation for the cache_ttl_overridden field.
usagelog.DefaultCacheTTLOverridden = usagelogDescCacheTTLOverridden.Default.(bool)
// usagelogDescCreatedAt is the schema descriptor for created_at field.
usagelogDescCreatedAt := usagelogFields[46].Descriptor()
usagelogDescCreatedAt := usagelogFields[48].Descriptor()
// usagelog.DefaultCreatedAt holds the default value on creation for the created_at field.
usagelog.DefaultCreatedAt = usagelogDescCreatedAt.Default.(func() time.Time)
userMixin := schema.User{}.Mixin()
+6
View File
@@ -109,6 +109,9 @@ func (Group) Fields() []ent.Field {
field.Bool("allow_batch_image_generation").
Default(false).
Comment("是否允许该分组使用批量图片生成能力"),
field.Bool("image_count_billing").
Default(false).
Comment("图片生成是否按实际出图张数计费"),
field.Bool("image_rate_independent").
Default(false).
Comment("图片生成是否使用独立倍率;false 表示共享分组有效倍率"),
@@ -250,6 +253,9 @@ func (Group) Fields() []ent.Field {
field.Bool("force_openai_fast").
Default(false).
Comment("是否强制此 OpenAI/Composite 分组请求使用 service_tier=priority"),
field.Bool("force_openai_ultrafast").
Default(false).
Comment("是否对支持 Ultrafast 的模型强制使用 service_tier=ultrafast(优先于 force_openai_fast)"),
field.Bool("free_openai_fast").
Default(false).
Comment("是否让此 OpenAI/Composite 分组的 Fast 请求按 Standard 价格计费"),
+4
View File
@@ -88,6 +88,10 @@ func (UsageLog) Fields() []ent.Field {
Default(0),
field.Int("cache_creation_1h_tokens").
Default(0),
field.Int("cache_creation_30m_tokens").
Default(0),
field.Int("cache_creation_12h_tokens").
Default(0),
// 成本字段
field.Float("input_cost").
+23 -1
View File
@@ -65,6 +65,10 @@ type UsageLog struct {
CacheCreation5mTokens int `json:"cache_creation_5m_tokens,omitempty"`
// CacheCreation1hTokens holds the value of the "cache_creation_1h_tokens" field.
CacheCreation1hTokens int `json:"cache_creation_1h_tokens,omitempty"`
// CacheCreation30mTokens holds the value of the "cache_creation_30m_tokens" field.
CacheCreation30mTokens int `json:"cache_creation_30m_tokens,omitempty"`
// CacheCreation12hTokens holds the value of the "cache_creation_12h_tokens" field.
CacheCreation12hTokens int `json:"cache_creation_12h_tokens,omitempty"`
// InputCost holds the value of the "input_cost" field.
InputCost float64 `json:"input_cost,omitempty"`
// OutputCost holds the value of the "output_cost" field.
@@ -206,7 +210,7 @@ func (*UsageLog) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullBool)
case usagelog.FieldInputCost, usagelog.FieldOutputCost, usagelog.FieldCacheCreationCost, usagelog.FieldCacheReadCost, usagelog.FieldTotalCost, usagelog.FieldActualCost, usagelog.FieldRateMultiplier, usagelog.FieldAccountRateMultiplier:
values[i] = new(sql.NullFloat64)
case usagelog.FieldID, usagelog.FieldUserID, usagelog.FieldAPIKeyID, usagelog.FieldAccountID, usagelog.FieldChannelID, usagelog.FieldGroupID, usagelog.FieldSubscriptionID, usagelog.FieldInputTokens, usagelog.FieldOutputTokens, usagelog.FieldCacheCreationTokens, usagelog.FieldCacheReadTokens, usagelog.FieldCacheCreation5mTokens, usagelog.FieldCacheCreation1hTokens, usagelog.FieldBillingType, usagelog.FieldDurationMs, usagelog.FieldFirstTokenMs, usagelog.FieldImageCount, usagelog.FieldVideoCount, usagelog.FieldVideoDurationSeconds:
case usagelog.FieldID, usagelog.FieldUserID, usagelog.FieldAPIKeyID, usagelog.FieldAccountID, usagelog.FieldChannelID, usagelog.FieldGroupID, usagelog.FieldSubscriptionID, usagelog.FieldInputTokens, usagelog.FieldOutputTokens, usagelog.FieldCacheCreationTokens, usagelog.FieldCacheReadTokens, usagelog.FieldCacheCreation5mTokens, usagelog.FieldCacheCreation1hTokens, usagelog.FieldCacheCreation30mTokens, usagelog.FieldCacheCreation12hTokens, usagelog.FieldBillingType, usagelog.FieldDurationMs, usagelog.FieldFirstTokenMs, usagelog.FieldImageCount, usagelog.FieldVideoCount, usagelog.FieldVideoDurationSeconds:
values[i] = new(sql.NullInt64)
case usagelog.FieldRequestID, usagelog.FieldModel, usagelog.FieldRequestedModel, usagelog.FieldUpstreamModel, usagelog.FieldUpstreamResponseModel, usagelog.FieldModelMappingChain, usagelog.FieldBillingTier, usagelog.FieldBillingMode, usagelog.FieldUserAgent, usagelog.FieldIPAddress, usagelog.FieldImageSize, usagelog.FieldImageInputSize, usagelog.FieldImageOutputSize, usagelog.FieldImageSizeSource, usagelog.FieldVideoResolution:
values[i] = new(sql.NullString)
@@ -369,6 +373,18 @@ func (_m *UsageLog) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.CacheCreation1hTokens = int(value.Int64)
}
case usagelog.FieldCacheCreation30mTokens:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field cache_creation_30m_tokens", values[i])
} else if value.Valid {
_m.CacheCreation30mTokens = int(value.Int64)
}
case usagelog.FieldCacheCreation12hTokens:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field cache_creation_12h_tokens", values[i])
} else if value.Valid {
_m.CacheCreation12hTokens = int(value.Int64)
}
case usagelog.FieldInputCost:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field input_cost", values[i])
@@ -682,6 +698,12 @@ func (_m *UsageLog) String() string {
builder.WriteString("cache_creation_1h_tokens=")
builder.WriteString(fmt.Sprintf("%v", _m.CacheCreation1hTokens))
builder.WriteString(", ")
builder.WriteString("cache_creation_30m_tokens=")
builder.WriteString(fmt.Sprintf("%v", _m.CacheCreation30mTokens))
builder.WriteString(", ")
builder.WriteString("cache_creation_12h_tokens=")
builder.WriteString(fmt.Sprintf("%v", _m.CacheCreation12hTokens))
builder.WriteString(", ")
builder.WriteString("input_cost=")
builder.WriteString(fmt.Sprintf("%v", _m.InputCost))
builder.WriteString(", ")
+20
View File
@@ -56,6 +56,10 @@ const (
FieldCacheCreation5mTokens = "cache_creation_5m_tokens"
// FieldCacheCreation1hTokens holds the string denoting the cache_creation_1h_tokens field in the database.
FieldCacheCreation1hTokens = "cache_creation_1h_tokens"
// FieldCacheCreation30mTokens holds the string denoting the cache_creation_30m_tokens field in the database.
FieldCacheCreation30mTokens = "cache_creation_30m_tokens"
// FieldCacheCreation12hTokens holds the string denoting the cache_creation_12h_tokens field in the database.
FieldCacheCreation12hTokens = "cache_creation_12h_tokens"
// FieldInputCost holds the string denoting the input_cost field in the database.
FieldInputCost = "input_cost"
// FieldOutputCost holds the string denoting the output_cost field in the database.
@@ -181,6 +185,8 @@ var Columns = []string{
FieldCacheReadTokens,
FieldCacheCreation5mTokens,
FieldCacheCreation1hTokens,
FieldCacheCreation30mTokens,
FieldCacheCreation12hTokens,
FieldInputCost,
FieldOutputCost,
FieldCacheCreationCost,
@@ -248,6 +254,10 @@ var (
DefaultCacheCreation5mTokens int
// DefaultCacheCreation1hTokens holds the default value on creation for the "cache_creation_1h_tokens" field.
DefaultCacheCreation1hTokens int
// DefaultCacheCreation30mTokens holds the default value on creation for the "cache_creation_30m_tokens" field.
DefaultCacheCreation30mTokens int
// DefaultCacheCreation12hTokens holds the default value on creation for the "cache_creation_12h_tokens" field.
DefaultCacheCreation12hTokens int
// DefaultInputCost holds the default value on creation for the "input_cost" field.
DefaultInputCost float64
// DefaultOutputCost holds the default value on creation for the "output_cost" field.
@@ -405,6 +415,16 @@ func ByCacheCreation1hTokens(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCacheCreation1hTokens, opts...).ToFunc()
}
// ByCacheCreation30mTokens orders the results by the cache_creation_30m_tokens field.
func ByCacheCreation30mTokens(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCacheCreation30mTokens, opts...).ToFunc()
}
// ByCacheCreation12hTokens orders the results by the cache_creation_12h_tokens field.
func ByCacheCreation12hTokens(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCacheCreation12hTokens, opts...).ToFunc()
}
// ByInputCost orders the results by the input_cost field.
func ByInputCost(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldInputCost, opts...).ToFunc()
+90
View File
@@ -160,6 +160,16 @@ func CacheCreation1hTokens(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation1hTokens, v))
}
// CacheCreation30mTokens applies equality check predicate on the "cache_creation_30m_tokens" field. It's identical to CacheCreation30mTokensEQ.
func CacheCreation30mTokens(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation30mTokens, v))
}
// CacheCreation12hTokens applies equality check predicate on the "cache_creation_12h_tokens" field. It's identical to CacheCreation12hTokensEQ.
func CacheCreation12hTokens(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation12hTokens, v))
}
// InputCost applies equality check predicate on the "input_cost" field. It's identical to InputCostEQ.
func InputCost(v float64) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldInputCost, v))
@@ -1295,6 +1305,86 @@ func CacheCreation1hTokensLTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLTE(FieldCacheCreation1hTokens, v))
}
// CacheCreation30mTokensEQ applies the EQ predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensEQ(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensNEQ applies the NEQ predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensNEQ(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNEQ(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensIn applies the In predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensIn(vs ...int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldIn(FieldCacheCreation30mTokens, vs...))
}
// CacheCreation30mTokensNotIn applies the NotIn predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensNotIn(vs ...int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNotIn(FieldCacheCreation30mTokens, vs...))
}
// CacheCreation30mTokensGT applies the GT predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensGT(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldGT(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensGTE applies the GTE predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensGTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldGTE(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensLT applies the LT predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensLT(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLT(FieldCacheCreation30mTokens, v))
}
// CacheCreation30mTokensLTE applies the LTE predicate on the "cache_creation_30m_tokens" field.
func CacheCreation30mTokensLTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLTE(FieldCacheCreation30mTokens, v))
}
// CacheCreation12hTokensEQ applies the EQ predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensEQ(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensNEQ applies the NEQ predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensNEQ(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNEQ(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensIn applies the In predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensIn(vs ...int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldIn(FieldCacheCreation12hTokens, vs...))
}
// CacheCreation12hTokensNotIn applies the NotIn predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensNotIn(vs ...int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldNotIn(FieldCacheCreation12hTokens, vs...))
}
// CacheCreation12hTokensGT applies the GT predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensGT(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldGT(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensGTE applies the GTE predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensGTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldGTE(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensLT applies the LT predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensLT(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLT(FieldCacheCreation12hTokens, v))
}
// CacheCreation12hTokensLTE applies the LTE predicate on the "cache_creation_12h_tokens" field.
func CacheCreation12hTokensLTE(v int) predicate.UsageLog {
return predicate.UsageLog(sql.FieldLTE(FieldCacheCreation12hTokens, v))
}
// InputCostEQ applies the EQ predicate on the "input_cost" field.
func InputCostEQ(v float64) predicate.UsageLog {
return predicate.UsageLog(sql.FieldEQ(FieldInputCost, v))
+170
View File
@@ -281,6 +281,34 @@ func (_c *UsageLogCreate) SetNillableCacheCreation1hTokens(v *int) *UsageLogCrea
return _c
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (_c *UsageLogCreate) SetCacheCreation30mTokens(v int) *UsageLogCreate {
_c.mutation.SetCacheCreation30mTokens(v)
return _c
}
// SetNillableCacheCreation30mTokens sets the "cache_creation_30m_tokens" field if the given value is not nil.
func (_c *UsageLogCreate) SetNillableCacheCreation30mTokens(v *int) *UsageLogCreate {
if v != nil {
_c.SetCacheCreation30mTokens(*v)
}
return _c
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (_c *UsageLogCreate) SetCacheCreation12hTokens(v int) *UsageLogCreate {
_c.mutation.SetCacheCreation12hTokens(v)
return _c
}
// SetNillableCacheCreation12hTokens sets the "cache_creation_12h_tokens" field if the given value is not nil.
func (_c *UsageLogCreate) SetNillableCacheCreation12hTokens(v *int) *UsageLogCreate {
if v != nil {
_c.SetCacheCreation12hTokens(*v)
}
return _c
}
// SetInputCost sets the "input_cost" field.
func (_c *UsageLogCreate) SetInputCost(v float64) *UsageLogCreate {
_c.mutation.SetInputCost(v)
@@ -721,6 +749,14 @@ func (_c *UsageLogCreate) defaults() {
v := usagelog.DefaultCacheCreation1hTokens
_c.mutation.SetCacheCreation1hTokens(v)
}
if _, ok := _c.mutation.CacheCreation30mTokens(); !ok {
v := usagelog.DefaultCacheCreation30mTokens
_c.mutation.SetCacheCreation30mTokens(v)
}
if _, ok := _c.mutation.CacheCreation12hTokens(); !ok {
v := usagelog.DefaultCacheCreation12hTokens
_c.mutation.SetCacheCreation12hTokens(v)
}
if _, ok := _c.mutation.InputCost(); !ok {
v := usagelog.DefaultInputCost
_c.mutation.SetInputCost(v)
@@ -854,6 +890,12 @@ func (_c *UsageLogCreate) check() error {
if _, ok := _c.mutation.CacheCreation1hTokens(); !ok {
return &ValidationError{Name: "cache_creation_1h_tokens", err: errors.New(`ent: missing required field "UsageLog.cache_creation_1h_tokens"`)}
}
if _, ok := _c.mutation.CacheCreation30mTokens(); !ok {
return &ValidationError{Name: "cache_creation_30m_tokens", err: errors.New(`ent: missing required field "UsageLog.cache_creation_30m_tokens"`)}
}
if _, ok := _c.mutation.CacheCreation12hTokens(); !ok {
return &ValidationError{Name: "cache_creation_12h_tokens", err: errors.New(`ent: missing required field "UsageLog.cache_creation_12h_tokens"`)}
}
if _, ok := _c.mutation.InputCost(); !ok {
return &ValidationError{Name: "input_cost", err: errors.New(`ent: missing required field "UsageLog.input_cost"`)}
}
@@ -1031,6 +1073,14 @@ func (_c *UsageLogCreate) createSpec() (*UsageLog, *sqlgraph.CreateSpec) {
_spec.SetField(usagelog.FieldCacheCreation1hTokens, field.TypeInt, value)
_node.CacheCreation1hTokens = value
}
if value, ok := _c.mutation.CacheCreation30mTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
_node.CacheCreation30mTokens = value
}
if value, ok := _c.mutation.CacheCreation12hTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
_node.CacheCreation12hTokens = value
}
if value, ok := _c.mutation.InputCost(); ok {
_spec.SetField(usagelog.FieldInputCost, field.TypeFloat64, value)
_node.InputCost = value
@@ -1626,6 +1676,42 @@ func (u *UsageLogUpsert) AddCacheCreation1hTokens(v int) *UsageLogUpsert {
return u
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsert) SetCacheCreation30mTokens(v int) *UsageLogUpsert {
u.Set(usagelog.FieldCacheCreation30mTokens, v)
return u
}
// UpdateCacheCreation30mTokens sets the "cache_creation_30m_tokens" field to the value that was provided on create.
func (u *UsageLogUpsert) UpdateCacheCreation30mTokens() *UsageLogUpsert {
u.SetExcluded(usagelog.FieldCacheCreation30mTokens)
return u
}
// AddCacheCreation30mTokens adds v to the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsert) AddCacheCreation30mTokens(v int) *UsageLogUpsert {
u.Add(usagelog.FieldCacheCreation30mTokens, v)
return u
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsert) SetCacheCreation12hTokens(v int) *UsageLogUpsert {
u.Set(usagelog.FieldCacheCreation12hTokens, v)
return u
}
// UpdateCacheCreation12hTokens sets the "cache_creation_12h_tokens" field to the value that was provided on create.
func (u *UsageLogUpsert) UpdateCacheCreation12hTokens() *UsageLogUpsert {
u.SetExcluded(usagelog.FieldCacheCreation12hTokens)
return u
}
// AddCacheCreation12hTokens adds v to the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsert) AddCacheCreation12hTokens(v int) *UsageLogUpsert {
u.Add(usagelog.FieldCacheCreation12hTokens, v)
return u
}
// SetInputCost sets the "input_cost" field.
func (u *UsageLogUpsert) SetInputCost(v float64) *UsageLogUpsert {
u.Set(usagelog.FieldInputCost, v)
@@ -2540,6 +2626,48 @@ func (u *UsageLogUpsertOne) UpdateCacheCreation1hTokens() *UsageLogUpsertOne {
})
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsertOne) SetCacheCreation30mTokens(v int) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.SetCacheCreation30mTokens(v)
})
}
// AddCacheCreation30mTokens adds v to the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsertOne) AddCacheCreation30mTokens(v int) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.AddCacheCreation30mTokens(v)
})
}
// UpdateCacheCreation30mTokens sets the "cache_creation_30m_tokens" field to the value that was provided on create.
func (u *UsageLogUpsertOne) UpdateCacheCreation30mTokens() *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateCacheCreation30mTokens()
})
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsertOne) SetCacheCreation12hTokens(v int) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.SetCacheCreation12hTokens(v)
})
}
// AddCacheCreation12hTokens adds v to the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsertOne) AddCacheCreation12hTokens(v int) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.AddCacheCreation12hTokens(v)
})
}
// UpdateCacheCreation12hTokens sets the "cache_creation_12h_tokens" field to the value that was provided on create.
func (u *UsageLogUpsertOne) UpdateCacheCreation12hTokens() *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateCacheCreation12hTokens()
})
}
// SetInputCost sets the "input_cost" field.
func (u *UsageLogUpsertOne) SetInputCost(v float64) *UsageLogUpsertOne {
return u.Update(func(s *UsageLogUpsert) {
@@ -3696,6 +3824,48 @@ func (u *UsageLogUpsertBulk) UpdateCacheCreation1hTokens() *UsageLogUpsertBulk {
})
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsertBulk) SetCacheCreation30mTokens(v int) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.SetCacheCreation30mTokens(v)
})
}
// AddCacheCreation30mTokens adds v to the "cache_creation_30m_tokens" field.
func (u *UsageLogUpsertBulk) AddCacheCreation30mTokens(v int) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.AddCacheCreation30mTokens(v)
})
}
// UpdateCacheCreation30mTokens sets the "cache_creation_30m_tokens" field to the value that was provided on create.
func (u *UsageLogUpsertBulk) UpdateCacheCreation30mTokens() *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateCacheCreation30mTokens()
})
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsertBulk) SetCacheCreation12hTokens(v int) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.SetCacheCreation12hTokens(v)
})
}
// AddCacheCreation12hTokens adds v to the "cache_creation_12h_tokens" field.
func (u *UsageLogUpsertBulk) AddCacheCreation12hTokens(v int) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.AddCacheCreation12hTokens(v)
})
}
// UpdateCacheCreation12hTokens sets the "cache_creation_12h_tokens" field to the value that was provided on create.
func (u *UsageLogUpsertBulk) UpdateCacheCreation12hTokens() *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
s.UpdateCacheCreation12hTokens()
})
}
// SetInputCost sets the "input_cost" field.
func (u *UsageLogUpsertBulk) SetInputCost(v float64) *UsageLogUpsertBulk {
return u.Update(func(s *UsageLogUpsert) {
+108
View File
@@ -435,6 +435,48 @@ func (_u *UsageLogUpdate) AddCacheCreation1hTokens(v int) *UsageLogUpdate {
return _u
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (_u *UsageLogUpdate) SetCacheCreation30mTokens(v int) *UsageLogUpdate {
_u.mutation.ResetCacheCreation30mTokens()
_u.mutation.SetCacheCreation30mTokens(v)
return _u
}
// SetNillableCacheCreation30mTokens sets the "cache_creation_30m_tokens" field if the given value is not nil.
func (_u *UsageLogUpdate) SetNillableCacheCreation30mTokens(v *int) *UsageLogUpdate {
if v != nil {
_u.SetCacheCreation30mTokens(*v)
}
return _u
}
// AddCacheCreation30mTokens adds value to the "cache_creation_30m_tokens" field.
func (_u *UsageLogUpdate) AddCacheCreation30mTokens(v int) *UsageLogUpdate {
_u.mutation.AddCacheCreation30mTokens(v)
return _u
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (_u *UsageLogUpdate) SetCacheCreation12hTokens(v int) *UsageLogUpdate {
_u.mutation.ResetCacheCreation12hTokens()
_u.mutation.SetCacheCreation12hTokens(v)
return _u
}
// SetNillableCacheCreation12hTokens sets the "cache_creation_12h_tokens" field if the given value is not nil.
func (_u *UsageLogUpdate) SetNillableCacheCreation12hTokens(v *int) *UsageLogUpdate {
if v != nil {
_u.SetCacheCreation12hTokens(*v)
}
return _u
}
// AddCacheCreation12hTokens adds value to the "cache_creation_12h_tokens" field.
func (_u *UsageLogUpdate) AddCacheCreation12hTokens(v int) *UsageLogUpdate {
_u.mutation.AddCacheCreation12hTokens(v)
return _u
}
// SetInputCost sets the "input_cost" field.
func (_u *UsageLogUpdate) SetInputCost(v float64) *UsageLogUpdate {
_u.mutation.ResetInputCost()
@@ -1228,6 +1270,18 @@ func (_u *UsageLogUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.AddedCacheCreation1hTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation1hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.CacheCreation30mTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCacheCreation30mTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.CacheCreation12hTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCacheCreation12hTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.InputCost(); ok {
_spec.SetField(usagelog.FieldInputCost, field.TypeFloat64, value)
}
@@ -1949,6 +2003,48 @@ func (_u *UsageLogUpdateOne) AddCacheCreation1hTokens(v int) *UsageLogUpdateOne
return _u
}
// SetCacheCreation30mTokens sets the "cache_creation_30m_tokens" field.
func (_u *UsageLogUpdateOne) SetCacheCreation30mTokens(v int) *UsageLogUpdateOne {
_u.mutation.ResetCacheCreation30mTokens()
_u.mutation.SetCacheCreation30mTokens(v)
return _u
}
// SetNillableCacheCreation30mTokens sets the "cache_creation_30m_tokens" field if the given value is not nil.
func (_u *UsageLogUpdateOne) SetNillableCacheCreation30mTokens(v *int) *UsageLogUpdateOne {
if v != nil {
_u.SetCacheCreation30mTokens(*v)
}
return _u
}
// AddCacheCreation30mTokens adds value to the "cache_creation_30m_tokens" field.
func (_u *UsageLogUpdateOne) AddCacheCreation30mTokens(v int) *UsageLogUpdateOne {
_u.mutation.AddCacheCreation30mTokens(v)
return _u
}
// SetCacheCreation12hTokens sets the "cache_creation_12h_tokens" field.
func (_u *UsageLogUpdateOne) SetCacheCreation12hTokens(v int) *UsageLogUpdateOne {
_u.mutation.ResetCacheCreation12hTokens()
_u.mutation.SetCacheCreation12hTokens(v)
return _u
}
// SetNillableCacheCreation12hTokens sets the "cache_creation_12h_tokens" field if the given value is not nil.
func (_u *UsageLogUpdateOne) SetNillableCacheCreation12hTokens(v *int) *UsageLogUpdateOne {
if v != nil {
_u.SetCacheCreation12hTokens(*v)
}
return _u
}
// AddCacheCreation12hTokens adds value to the "cache_creation_12h_tokens" field.
func (_u *UsageLogUpdateOne) AddCacheCreation12hTokens(v int) *UsageLogUpdateOne {
_u.mutation.AddCacheCreation12hTokens(v)
return _u
}
// SetInputCost sets the "input_cost" field.
func (_u *UsageLogUpdateOne) SetInputCost(v float64) *UsageLogUpdateOne {
_u.mutation.ResetInputCost()
@@ -2772,6 +2868,18 @@ func (_u *UsageLogUpdateOne) sqlSave(ctx context.Context) (_node *UsageLog, err
if value, ok := _u.mutation.AddedCacheCreation1hTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation1hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.CacheCreation30mTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCacheCreation30mTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation30mTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.CacheCreation12hTokens(); ok {
_spec.SetField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCacheCreation12hTokens(); ok {
_spec.AddField(usagelog.FieldCacheCreation12hTokens, field.TypeInt, value)
}
if value, ok := _u.mutation.InputCost(); ok {
_spec.SetField(usagelog.FieldInputCost, field.TypeFloat64, value)
}
+19 -12
View File
@@ -1,16 +1,17 @@
module github.com/Wei-Shaw/sub2api
go 1.27.3
go 1.27.4
require (
entgo.io/ent v0.14.5
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/MoeForge/moego v0.1.0-alpha.1
github.com/alibabacloud-go/captcha-20230305 v1.1.3
github.com/alibabacloud-go/darabonba-openapi/v2 v2.1.13
github.com/alibabacloud-go/tea v1.3.13
github.com/alicebob/miniredis/v2 v2.38.0
github.com/alitto/pond/v2 v2.6.2
github.com/andybalholm/brotli v1.2.0
github.com/andybalholm/brotli v1.2.7
github.com/aws/aws-sdk-go-v2 v1.41.5
github.com/aws/aws-sdk-go-v2/config v1.32.10
github.com/aws/aws-sdk-go-v2/credentials v1.19.10
@@ -22,14 +23,16 @@ require (
github.com/go-playground/validator/v10 v10.14.0
github.com/go-webauthn/webauthn v0.17.4
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/jsonschema-go v0.4.2
github.com/google/uuid v1.6.0
github.com/google/wire v0.7.0
github.com/gorilla/websocket v1.5.3
github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4
github.com/hashicorp/go-hclog v1.6.3
github.com/hashicorp/go-plugin v1.8.0
github.com/imroc/req/v3 v3.59.0
github.com/klauspost/compress v1.18.2
github.com/klauspost/compress v1.20.2
github.com/lib/pq v1.10.9
github.com/modelcontextprotocol/go-sdk v1.4.1
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pquerna/otp v1.5.0
github.com/redis/go-redis/v9 v9.22.0
@@ -51,12 +54,12 @@ require (
github.com/wechatpay-apiv3/wechatpay-go v0.2.21
github.com/zeromicro/go-zero v1.9.4
go.uber.org/zap v1.24.0
golang.org/x/crypto v0.57.0
golang.org/x/image v0.41.0
golang.org/x/crypto v0.58.0
golang.org/x/image v0.45.0
golang.org/x/mod v0.41.0
golang.org/x/net v0.60.0
golang.org/x/sync v0.23.0
golang.org/x/term v0.46.0
golang.org/x/net v0.62.0
golang.org/x/sync v0.24.0
golang.org/x/term v0.47.0
google.golang.org/grpc v1.83.2
google.golang.org/protobuf v1.36.11
gopkg.in/natefinch/lumberjack.v2 v2.2.1
@@ -167,6 +170,8 @@ require (
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/smartwalle/ncrypto v1.0.4 // indirect
github.com/smartwalle/ngx v1.1.0 // indirect
@@ -187,6 +192,7 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
github.com/zclconf/go-cty v1.14.4 // indirect
@@ -201,10 +207,11 @@ require (
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
golang.org/x/time v0.12.0 // indirect
golang.org/x/tools v0.50.0 // indirect
golang.org/x/tools v0.51.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
modernc.org/libc v1.67.6 // indirect
+44 -36
View File
@@ -14,6 +14,8 @@ github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7Oputl
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/MoeForge/moego v0.1.0-alpha.1 h1:d+asBZu+2oKnBj1kzdvdANMStbIKw9BLCpknuWjiR28=
github.com/MoeForge/moego v0.1.0-alpha.1/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA=
github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/agiledragon/gomonkey v2.0.2+incompatible h1:eXKi9/piiC3cjJD1658mEE2o3NjkJ5vDLgYjCQu0Xlw=
@@ -68,8 +70,8 @@ github.com/aliyun/credentials-go v1.3.1/go.mod h1:8jKYhQuDawt8x2+fusqa1Y6mPxemTs
github.com/aliyun/credentials-go v1.3.6/go.mod h1:1LxUuX7L5YrZUWzBrRyk0SwSdH4OmPrib8NVePL3fxM=
github.com/aliyun/credentials-go v1.4.5 h1:O76WYKgdy1oQYYiJkERjlA2dxGuvLRrzuO2ScrtGWSk=
github.com/aliyun/credentials-go v1.4.5/go.mod h1:Jm6d+xIgwJVLVWT561vy67ZRP4lPTQxMbEYRuT2Ti1U=
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=
github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=
github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=
@@ -251,6 +253,8 @@ github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLzH5KDR0gKc0zcktin6KSAwL7+jWKBYceddTc=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -261,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=
@@ -295,8 +301,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo=
github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
@@ -325,6 +331,8 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
@@ -349,6 +357,8 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
github.com/modelcontextprotocol/go-sdk v1.4.1 h1:M4x9GyIPj+HoIlHNGpK2hq5o3BFhC+78PkEaldQRphc=
github.com/modelcontextprotocol/go-sdk v1.4.1/go.mod h1:Bo/mS87hPQqHSRkMv4dQq1XCu6zv4INdXnFZabkNU6s=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -363,6 +373,8 @@ github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJm
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
@@ -397,6 +409,8 @@ github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEv
github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
@@ -405,6 +419,10 @@ github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6ke
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
github.com/shirou/gopsutil/v4 v4.25.6 h1:kLysI2JsKorfaFPcYmcJqbzROzsBWEOAtw6A7dIfqXs=
@@ -432,6 +450,8 @@ github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ=
@@ -498,6 +518,8 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
@@ -562,15 +584,15 @@ golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDf
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
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=
@@ -580,8 +602,6 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -605,11 +625,11 @@ golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -620,10 +640,8 @@ golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -655,10 +673,8 @@ golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@@ -671,10 +687,8 @@ golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@@ -685,10 +699,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -703,12 +715,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+155 -15
View File
@@ -7,13 +7,16 @@ import (
"fmt"
"log/slog"
"math"
"net/netip"
"net/textproto"
"net/url"
"os"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/sysutil"
"github.com/spf13/viper"
"golang.org/x/net/http/httpguts"
)
@@ -69,6 +72,7 @@ type Config struct {
Server ServerConfig `mapstructure:"server"`
Log LogConfig `mapstructure:"log"`
CORS CORSConfig `mapstructure:"cors"`
MCP MCPConfig `mapstructure:"mcp"`
Security SecurityConfig `mapstructure:"security"`
Billing BillingConfig `mapstructure:"billing"`
Turnstile TurnstileConfig `mapstructure:"turnstile"`
@@ -111,9 +115,67 @@ 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.
// Setting it is also the explicit opt-in that enables MCP.
type MCPConfig struct {
PublicURL string `mapstructure:"public_url"`
}
// Enabled reports whether the operator opted in to the management MCP endpoint.
func (c MCPConfig) Enabled() bool { return strings.TrimSpace(c.PublicURL) != "" }
// Validate normalizes the configured resource URL without trusting request headers.
// An empty URL keeps MCP and its OAuth endpoints disabled.
func (c *MCPConfig) Validate() error {
raw := strings.TrimSpace(c.PublicURL)
if raw == "" {
c.PublicURL = ""
return nil
}
u, err := url.Parse(raw)
if err != nil {
return fmt.Errorf("mcp.public_url invalid: %w", err)
}
if !u.IsAbs() || u.Hostname() == "" || !httpguts.ValidHostHeader(u.Host) || strings.ContainsAny(u.Host, "*%") {
return fmt.Errorf("mcp.public_url must be an absolute URL with a valid host")
}
if u.User != nil || u.RawQuery != "" || u.ForceQuery || strings.Contains(raw, "#") {
return fmt.Errorf("mcp.public_url must not include userinfo, query, or fragment")
}
if u.Path != "/api/v1/mcp" || u.EscapedPath() != "/api/v1/mcp" {
return fmt.Errorf("mcp.public_url must have the exact path /api/v1/mcp without a trailing slash")
}
if port := u.Port(); port != "" {
n, err := strconv.Atoi(port)
if err != nil || n < 1 || n > 65535 {
return fmt.Errorf("mcp.public_url must have a valid port")
}
}
u.Scheme = strings.ToLower(u.Scheme)
u.Host = strings.ToLower(u.Host)
host := u.Hostname()
addr, _ := netip.ParseAddr(host)
localDevelopment := host == "localhost" || addr.IsLoopback()
if u.Scheme != "https" && (u.Scheme != "http" || !localDevelopment) {
return fmt.Errorf("mcp.public_url must use HTTPS (HTTP is allowed only for localhost or loopback IPs)")
}
c.PublicURL = u.String()
return nil
}
// PluginConfig 控制管理员手动上传的本地进程插件。
@@ -514,6 +576,24 @@ func shouldApplyLegacyWeChatEnv(configKey, envKey string) bool {
return !hasNewEnv
}
// detectMemoryLimitBytes is replaced in tests so defaults do not depend on the host.
var detectMemoryLimitBytes = sysutil.MemoryLimitBytes
const (
defaultRequestBodyMemoryBudgetBytes = int64(1 << 30)
// requestBodyMemoryBudgetDivisor leaves the rest of memory for conversion
// state, SSE buffers, caches and GC headroom.
requestBodyMemoryBudgetDivisor = 4
)
// autoRequestBodyMemoryBudget sizes the unconfigured ingress budget to a
// quarter of the process memory limit. It never goes below the historical
// 1 GiB default, so small instances keep their previous behavior.
func autoRequestBodyMemoryBudget(memoryLimitBytes uint64) int64 {
// uint64 / 4 always fits in int64.
return max(int64(memoryLimitBytes/requestBodyMemoryBudgetDivisor), defaultRequestBodyMemoryBudgetBytes)
}
func hasExplicitConfigOrEnv(configKey, envKey string) bool {
if viper.InConfig(configKey) {
return true
@@ -955,7 +1035,7 @@ type CircuitBreakerConfig struct {
}
type ConcurrencyConfig struct {
// PingInterval: 并发等待期间的 SSE ping 间隔(秒)
// PingInterval: 并发等待期间的 SSE ping 间隔(秒),0 禁用 ping
PingInterval int `mapstructure:"ping_interval"`
}
@@ -987,7 +1067,8 @@ type GatewayConfig struct {
ResponseHeaderTimeout int `mapstructure:"response_header_timeout"`
// OpenAIResponseHeaderTimeout: OpenAI/Codex 上游等待响应头的超时时间(秒),0表示无超时
// OpenAI/Codex 请求可能在上游排队较久;默认不使用通用响应头超时截断。
OpenAIResponseHeaderTimeout int `mapstructure:"openai_response_header_timeout"`
OpenAIResponseHeaderTimeout int `mapstructure:"openai_response_header_timeout"`
DisableOpenAITransportErrorCooldown bool `mapstructure:"disable_openai_transport_error_cooldown"`
// GrokResponseHeaderTimeout bounds the pre-first-byte wait for xAI/Grok.
// A zero value uses the provider-safe default instead of the generic gateway timeout.
GrokResponseHeaderTimeout int `mapstructure:"grok_response_header_timeout"`
@@ -998,6 +1079,13 @@ type GatewayConfig struct {
OpenAIHighEffortFirstOutputTimeoutSeconds int `mapstructure:"openai_high_effort_first_output_timeout_seconds"`
// 请求体最大字节数,用于网关请求体大小限制
MaxBodySize int64 `mapstructure:"max_body_size"`
// RequestBodyMemoryBudgetBytes bounds buffered ingress allocations per instance; 0 disables it.
// When unset in config and env it defaults to 1/4 of the memory limit (at least 1 GiB).
RequestBodyMemoryBudgetBytes int64 `mapstructure:"request_body_memory_budget_bytes"`
// RequestBodyReadTimeoutSeconds bounds each socket read during upload; 0 disables it.
RequestBodyReadTimeoutSeconds int `mapstructure:"request_body_read_timeout_seconds"`
// DownstreamWriteTimeoutSeconds bounds each HTTP write/flush, not the lifetime of a stream.
DownstreamWriteTimeoutSeconds int `mapstructure:"downstream_write_timeout_seconds"`
// TextMaxBodySize limits endpoints that cannot carry inline image/video payloads.
TextMaxBodySize int64 `mapstructure:"text_max_body_size"`
// 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大
@@ -1092,12 +1180,18 @@ type GatewayConfig struct {
// ImageNonstreamKeepaliveInterval: 图片非流式 JSON keepalive 间隔(秒),0表示禁用
ImageNonstreamKeepaliveInterval int `mapstructure:"image_nonstream_keepalive_interval"`
// MaxLineSize: 上游 SSE 单行最大字节数(0使用默认值)
MaxLineSize int `mapstructure:"max_line_size"`
MaxLineSize int `mapstructure:"max_line_size"`
SSEQueueMaxBytes int64 `mapstructure:"sse_queue_max_bytes"`
SSEEventMaxBytes int64 `mapstructure:"sse_event_max_bytes"`
SSEEventMaxLines int `mapstructure:"sse_event_max_lines"`
// 是否记录上游错误响应体摘要(避免输出请求内容)
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"`
@@ -1109,7 +1203,11 @@ type GatewayConfig struct {
MaxAccountSwitches int `mapstructure:"max_account_switches"`
// Gemini 账户切换最大次数(Gemini 平台单独配置,因 API 限制更严格)
MaxAccountSwitchesGemini int `mapstructure:"max_account_switches_gemini"`
// 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"`
@@ -1202,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"`
}
@@ -1301,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
@@ -1872,6 +1974,15 @@ func load(allowMissingJWTSecret bool) (*Config, error) {
cfg.Security.ForwardedClientIPHeaders = normalizeStringSlice(strings.Split(forwardedClientIPHeadersEnv, ","))
}
cfg.Server.TrustedProxiesConfigured = trustedProxiesConfigured
// Mirror viper's own precedence: an empty environment variable is ignored by
// viper, so it must not pin the static default either (e.g. Compose ${VAR:-}).
if !viper.InConfig("gateway.request_body_memory_budget_bytes") && os.Getenv("GATEWAY_REQUEST_BODY_MEMORY_BUDGET_BYTES") == "" {
memoryLimit := detectMemoryLimitBytes()
cfg.Gateway.RequestBodyMemoryBudgetBytes = autoRequestBodyMemoryBudget(memoryLimit)
slog.Info("gateway.request_body_memory_budget_bytes auto-sized from memory limit",
"budget_bytes", cfg.Gateway.RequestBodyMemoryBudgetBytes,
"memory_limit_bytes", memoryLimit)
}
if cfg.Gateway.OpenAIScheduler.StickyEscapeTTFTMs == 0 {
cfg.Gateway.OpenAIScheduler.StickyEscapeTTFTMs = 15000
}
@@ -2040,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
@@ -2082,6 +2194,7 @@ func setDefaults() {
// CORS
viper.SetDefault("cors.allowed_origins", []string{})
viper.SetDefault("cors.allow_credentials", true)
viper.SetDefault("mcp.public_url", "")
// WebAuthn / Passkeys are opt-in because every deployment must explicitly
// declare its relying-party domain and trusted browser origins.
@@ -2425,15 +2538,18 @@ func setDefaults() {
// Gateway
viper.SetDefault("gateway.response_header_timeout", 600) // 600秒(10分钟)等待上游响应头,LLM高负载时可能排队较久
viper.SetDefault("gateway.openai_response_header_timeout", 0)
viper.SetDefault("gateway.disable_openai_transport_error_cooldown", false)
viper.SetDefault("gateway.grok_response_header_timeout", 120)
viper.SetDefault("gateway.openai_first_output_timeout_seconds", 0)
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)
viper.SetDefault("gateway.max_account_switches_gemini", 3)
viper.SetDefault("gateway.max_same_account_retries_gemini", 4)
viper.SetDefault("gateway.force_codex_cli", false)
viper.SetDefault("gateway.disable_codex_identity_enforcement", false)
viper.SetDefault("gateway.disable_codex_originator_normalization", false)
@@ -2458,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)
@@ -2526,9 +2642,15 @@ 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))
// Without explicit config or env, load() replaces this with a size derived
// from the memory limit (see autoRequestBodyMemoryBudget).
viper.SetDefault("gateway.request_body_memory_budget_bytes", defaultRequestBodyMemoryBudgetBytes)
viper.SetDefault("gateway.request_body_read_timeout_seconds", 120)
viper.SetDefault("gateway.downstream_write_timeout_seconds", 120)
viper.SetDefault("gateway.text_max_body_size", int64(32*1024*1024))
viper.SetDefault("gateway.upstream_response_read_max_bytes", DefaultUpstreamResponseReadMaxBytes)
viper.SetDefault("gateway.models_list_read_max_bytes", DefaultModelsListReadMaxBytes)
@@ -2550,6 +2672,9 @@ func setDefaults() {
viper.SetDefault("gateway.image_stream_keepalive_interval", 10)
viper.SetDefault("gateway.image_nonstream_keepalive_interval", 0)
viper.SetDefault("gateway.max_line_size", 500*1024*1024)
viper.SetDefault("gateway.sse_queue_max_bytes", int64(8*1024*1024))
viper.SetDefault("gateway.sse_event_max_bytes", int64(0))
viper.SetDefault("gateway.sse_event_max_lines", 4096)
viper.SetDefault("gateway.scheduling.sticky_session_max_waiting", 3)
viper.SetDefault("gateway.scheduling.sticky_session_wait_timeout", 120*time.Second)
viper.SetDefault("gateway.scheduling.fallback_wait_timeout", 30*time.Second)
@@ -2856,6 +2981,9 @@ func (c *Config) Validate() error {
return fmt.Errorf("gemini.oauth.client_id and gemini.oauth.client_secret must be both set or both empty")
}
if err := c.MCP.Validate(); err != nil {
return err
}
if strings.TrimSpace(c.Server.FrontendURL) != "" {
if err := ValidateAbsoluteHTTPURL(c.Server.FrontendURL); err != nil {
return fmt.Errorf("server.frontend_url invalid: %w", err)
@@ -3350,6 +3478,18 @@ func (c *Config) Validate() error {
if c.Gateway.MaxBodySize <= 0 {
return fmt.Errorf("gateway.max_body_size must be positive")
}
if c.Gateway.RequestBodyMemoryBudgetBytes < 0 {
return fmt.Errorf("gateway.request_body_memory_budget_bytes must be non-negative")
}
if c.Gateway.RequestBodyReadTimeoutSeconds < 0 || c.Gateway.RequestBodyReadTimeoutSeconds > 3600 {
return fmt.Errorf("gateway.request_body_read_timeout_seconds must be between 0 and 3600")
}
if c.Gateway.DownstreamWriteTimeoutSeconds < 0 || c.Gateway.DownstreamWriteTimeoutSeconds > 3600 {
return fmt.Errorf("gateway.downstream_write_timeout_seconds must be between 0 and 3600")
}
if c.Gateway.SSEQueueMaxBytes < 0 || c.Gateway.SSEEventMaxBytes < 0 || c.Gateway.SSEEventMaxLines < 0 {
return fmt.Errorf("gateway.sse_queue_max_bytes, sse_event_max_bytes and sse_event_max_lines must be non-negative")
}
if c.Gateway.TextMaxBodySize <= 0 || c.Gateway.TextMaxBodySize > c.Gateway.MaxBodySize {
return fmt.Errorf("gateway.text_max_body_size must be positive and no greater than gateway.max_body_size")
}
@@ -3371,6 +3511,9 @@ func (c *Config) Validate() error {
if c.Gateway.GrokResponseHeaderTimeout < 0 || c.Gateway.GrokResponseHeaderTimeout > 1800 {
return fmt.Errorf("gateway.grok_response_header_timeout must be between 0-1800 seconds")
}
if c.Gateway.MaxSameAccountRetriesGemini < 0 || c.Gateway.MaxSameAccountRetriesGemini > 10 {
return fmt.Errorf("gateway.max_same_account_retries_gemini must be between 0-10")
}
if c.Gateway.OpenAIFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIFirstOutputTimeoutSeconds > 600 ||
(c.Gateway.OpenAIFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIFirstOutputTimeoutSeconds < 30) {
return fmt.Errorf("gateway.openai_first_output_timeout_seconds must be 0 or between 30-600 seconds")
@@ -3528,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")
}
@@ -3766,8 +3906,8 @@ func (c *Config) Validate() error {
if c.Ops.Cleanup.Enabled && strings.TrimSpace(c.Ops.Cleanup.Schedule) == "" {
return fmt.Errorf("ops.cleanup.schedule is required when ops.cleanup.enabled=true")
}
if c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30 {
return fmt.Errorf("concurrency.ping_interval must be between 5-30 seconds")
if c.Concurrency.PingInterval != 0 && (c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30) {
return fmt.Errorf("concurrency.ping_interval must be 0 (disabled) or between 5-30 seconds")
}
if c.Gateway.Grok.FreeQuotaSoftGateEnabled {
if c.Gateway.Grok.FreeQuotaTokenLimit <= 0 {
+175 -14
View File
@@ -22,6 +22,92 @@ func resetViperWithJWTSecret(t *testing.T) {
t.Setenv("CONFIG_FILE", "")
t.Setenv("DATA_DIR", "")
t.Setenv("JWT_SECRET", strings.Repeat("x", 32))
stubMemoryLimit(t, 0)
}
func stubMemoryLimit(t *testing.T, limit uint64) {
t.Helper()
original := detectMemoryLimitBytes
detectMemoryLimitBytes = func() uint64 { return limit }
t.Cleanup(func() { detectMemoryLimitBytes = original })
}
func TestAutoRequestBodyMemoryBudget(t *testing.T) {
require.Equal(t, int64(1<<30), autoRequestBodyMemoryBudget(0))
require.Equal(t, int64(1<<30), autoRequestBodyMemoryBudget(2<<30))
require.Equal(t, int64(2<<30), autoRequestBodyMemoryBudget(8<<30))
require.Equal(t, int64(32<<30), autoRequestBodyMemoryBudget(128<<30))
require.Equal(t, int64(math.MaxUint64/4), autoRequestBodyMemoryBudget(math.MaxUint64))
}
func TestLoadRequestBodyMemoryBudget(t *testing.T) {
t.Run("auto-sized from memory limit when unset", func(t *testing.T) {
resetViperWithJWTSecret(t)
stubMemoryLimit(t, 128<<30)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, int64(32<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes)
})
t.Run("explicit environment value wins, including 0", func(t *testing.T) {
resetViperWithJWTSecret(t)
stubMemoryLimit(t, 128<<30)
t.Setenv("GATEWAY_REQUEST_BODY_MEMORY_BUDGET_BYTES", "0")
cfg, err := Load()
require.NoError(t, err)
require.Zero(t, cfg.Gateway.RequestBodyMemoryBudgetBytes)
})
t.Run("empty environment value is ignored like viper does", func(t *testing.T) {
resetViperWithJWTSecret(t)
stubMemoryLimit(t, 128<<30)
t.Setenv("GATEWAY_REQUEST_BODY_MEMORY_BUDGET_BYTES", "")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, int64(32<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes)
})
t.Run("explicit environment value wins over auto-sizing", func(t *testing.T) {
resetViperWithJWTSecret(t)
stubMemoryLimit(t, 128<<30)
t.Setenv("GATEWAY_REQUEST_BODY_MEMORY_BUDGET_BYTES", "2147483648")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, int64(2<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes)
})
t.Run("explicit config file 0 disables the budget", func(t *testing.T) {
resetViperWithJWTSecret(t)
stubMemoryLimit(t, 128<<30)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte("gateway:\n request_body_memory_budget_bytes: 0\n"), 0o600))
t.Setenv("CONFIG_FILE", configFile)
cfg, err := Load()
require.NoError(t, err)
require.Zero(t, cfg.Gateway.RequestBodyMemoryBudgetBytes)
})
t.Run("config file without the key is auto-sized", func(t *testing.T) {
resetViperWithJWTSecret(t)
stubMemoryLimit(t, 128<<30)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte("gateway:\n max_body_size: 268435456\n"), 0o600))
t.Setenv("CONFIG_FILE", configFile)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, int64(32<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes)
})
t.Run("explicit config file value wins", func(t *testing.T) {
resetViperWithJWTSecret(t)
stubMemoryLimit(t, 128<<30)
configFile := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configFile, []byte("gateway:\n request_body_memory_budget_bytes: 1073741824\n"), 0o600))
t.Setenv("CONFIG_FILE", configFile)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, int64(1<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes)
})
}
func TestLoadDefaultModelsListReadMaxBytes(t *testing.T) {
@@ -46,6 +132,27 @@ 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()
require.NoError(t, err)
require.Equal(t, 4, cfg.Gateway.MaxSameAccountRetriesGemini)
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_MAX_SAME_ACCOUNT_RETRIES_GEMINI", "0")
cfg, err = Load()
require.NoError(t, err)
require.Zero(t, cfg.Gateway.MaxSameAccountRetriesGemini)
}
func TestValidateMinOutputTokensMinimum(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
@@ -112,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")
@@ -131,6 +264,12 @@ func TestLoadHTTPIngressSafetyDefaults(t *testing.T) {
require.False(t, cfg.Server.TrustedProxiesConfigured)
require.True(t, cfg.TrustForwardedIPForAPIKeyACL())
require.Equal(t, int64(32*1024*1024), cfg.Gateway.TextMaxBodySize)
require.Equal(t, int64(1<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes)
require.Equal(t, 120, cfg.Gateway.RequestBodyReadTimeoutSeconds)
require.Equal(t, 120, cfg.Gateway.DownstreamWriteTimeoutSeconds)
require.Equal(t, 500<<20, cfg.Gateway.MaxLineSize)
require.Equal(t, int64(8<<20), cfg.Gateway.SSEQueueMaxBytes)
require.Equal(t, 4096, cfg.Gateway.SSEEventMaxLines)
require.True(t, cfg.APIKeyAuth.InvalidAbuse.Enabled)
require.Equal(t, 120, cfg.APIKeyAuth.InvalidAbuse.Threshold)
require.Equal(t, 16384, cfg.APIKeyAuth.InvalidAbuse.Capacity)
@@ -533,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)
@@ -1472,18 +1611,20 @@ func TestValidateOpsCleanupScheduleRequired(t *testing.T) {
func TestValidateConcurrencyPingInterval(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
cfg.Concurrency.PingInterval = 3
err = cfg.Validate()
if err == nil {
t.Fatalf("Validate() expected error for concurrency.ping_interval")
}
if !strings.Contains(err.Error(), "concurrency.ping_interval") {
t.Fatalf("Validate() expected concurrency.ping_interval error, got: %v", err)
for _, interval := range []int{-1, 0, 1, 3, 4, 5, 10, 30, 31} {
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
cfg.Concurrency.PingInterval = interval
err = cfg.Validate()
valid := interval == 0 || (interval >= 5 && interval <= 30)
if valid && err != nil {
t.Errorf("Validate() interval %d: %v", interval, err)
}
if !valid && (err == nil || !strings.Contains(err.Error(), "concurrency.ping_interval")) {
t.Errorf("Validate() interval %d: expected concurrency.ping_interval error, got %v", interval, err)
}
}
}
@@ -1621,6 +1762,16 @@ func TestValidateConfigErrors(t *testing.T) {
mutate func(*Config)
wantErr string
}{
{
name: "negative ingress memory budget",
mutate: func(c *Config) { c.Gateway.RequestBodyMemoryBudgetBytes = -1 },
wantErr: "gateway.request_body_memory_budget_bytes",
},
{
name: "negative upload timeout",
mutate: func(c *Config) { c.Gateway.RequestBodyReadTimeoutSeconds = -1 },
wantErr: "gateway.request_body_read_timeout_seconds",
},
{
name: "server read header timeout",
mutate: func(c *Config) { c.Server.ReadHeaderTimeout = 0 },
@@ -1887,6 +2038,16 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Gateway.OpenAIResponseHeaderTimeout = -1 },
wantErr: "gateway.openai_response_header_timeout",
},
{
name: "gateway gemini same account retries negative",
mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = -1 },
wantErr: "gateway.max_same_account_retries_gemini",
},
{
name: "gateway gemini same account retries too large",
mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = 11 },
wantErr: "gateway.max_same_account_retries_gemini",
},
{
name: "gateway openai first output timeout below minimum",
mutate: func(c *Config) { c.Gateway.OpenAIFirstOutputTimeoutSeconds = 29 },
@@ -0,0 +1,64 @@
package config
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestMCPConfigValidatePublicURL(t *testing.T) {
for _, tc := range []struct {
name, value, want string
}{
{"unset", "", ""},
{"blank", " ", ""},
{"https", "https://api.example.com/api/v1/mcp", "https://api.example.com/api/v1/mcp"},
{"normalize", " HTTPS://API.Example.COM:8443/api/v1/mcp ", "https://api.example.com:8443/api/v1/mcp"},
{"localhost", "http://localhost:8080/api/v1/mcp", "http://localhost:8080/api/v1/mcp"},
{"loopback IPv4", "http://127.0.0.2:8080/api/v1/mcp", "http://127.0.0.2:8080/api/v1/mcp"},
{"loopback IPv6", "http://[::1]:8080/api/v1/mcp", "http://[::1]:8080/api/v1/mcp"},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := MCPConfig{PublicURL: tc.value}
require.NoError(t, cfg.Validate())
require.Equal(t, tc.want, cfg.PublicURL)
})
}
for _, value := range []string{
"/api/v1/mcp", "//example.com/api/v1/mcp", "https:///api/v1/mcp",
"https://:443/api/v1/mcp", "https://*.example.com/api/v1/mcp",
"http://example.com/api/v1/mcp", "http://localhost.example.com/api/v1/mcp",
"http://10.0.0.1/api/v1/mcp", "http://[::2]/api/v1/mcp",
"ftp://localhost/api/v1/mcp", "https://example.com/api/v1/mcp/",
"https://example.com/mcp", "https://example.com/api/v1/%6dcp",
"https://example.com/api/v1/mcp?", "https://example.com/api/v1/mcp?x=1",
"https://example.com/api/v1/mcp#", "https://example.com/api/v1/mcp#fragment",
"https://user:password@example.com/api/v1/mcp", "https://user@example.com/api/v1/mcp",
"https://example.com:0/api/v1/mcp", "https://example.com:65536/api/v1/mcp",
"https://example.com:invalid/api/v1/mcp", "http://[::1%25eth0]/api/v1/mcp",
} {
t.Run(value, func(t *testing.T) {
cfg := MCPConfig{PublicURL: value}
require.ErrorContains(t, cfg.Validate(), "mcp.public_url")
})
}
}
func TestLoadMCPPublicURLFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("MCP_PUBLIC_URL", "HTTPS://MCP.Example.COM/api/v1/mcp")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, "https://mcp.example.com/api/v1/mcp", cfg.MCP.PublicURL)
cfg.MCP.PublicURL = "http://example.com/api/v1/mcp"
require.ErrorContains(t, cfg.Validate(), "mcp.public_url must use HTTPS")
}
func TestLoadMCPPublicURLDefault(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("MCP_PUBLIC_URL", "")
cfg, err := Load()
require.NoError(t, err)
require.Empty(t, cfg.MCP.PublicURL)
}
@@ -0,0 +1,40 @@
//go:build unit
package config
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestLoadOpenAITransportErrorCooldown(t *testing.T) {
for _, testCase := range []struct {
name string
yaml string
env string
disabled bool
}{
{name: "default"},
{name: "env_true", env: "true", disabled: true},
{name: "env_false", env: "false"},
{name: "yaml_true", yaml: "true", disabled: true},
{name: "env_overrides_yaml", yaml: "true", env: "false"},
} {
t.Run(testCase.name, func(t *testing.T) {
resetViperWithJWTSecret(t)
t.Chdir(t.TempDir())
t.Setenv("GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN", testCase.env)
if testCase.yaml != "" {
configPath := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configPath, []byte("gateway:\n disable_openai_transport_error_cooldown: "+testCase.yaml+"\n"), 0600))
t.Setenv("CONFIG_FILE", configPath)
}
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, testCase.disabled, cfg.Gateway.DisableOpenAITransportErrorCooldown)
})
}
}
@@ -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"`
}
+7 -3
View File
@@ -178,7 +178,9 @@ var DefaultAntigravityModelMapping = map[string]string{
"gemini-3.8-flash-low": "gemini-3.8-flash-low",
"gemini-3.8-flash-medium": "gemini-3.8-flash-medium",
"gemini-3.8-flash-tiered": "gemini-3.8-flash-tiered",
// Gemini 4 Argon tiered models
// Gemini 4 models
// Carbon uses the published model ID; do not infer Argon-style tier aliases.
"gemini-4-carbon": "gemini-4-carbon",
"gemini-4-argon": "gemini-4-argon-high",
"gemini-4-argon-high": "gemini-4-argon-high",
"gemini-4-argon-low": "gemini-4-argon-low",
@@ -197,8 +199,10 @@ var DefaultAntigravityModelMapping = map[string]string{
// aws_region 自动调整为匹配的区域前缀(如 eu.、apac.、jp. 等)
var DefaultBedrockModelMapping = map[string]string{
// Claude Fable
"claude-fable-5-1": "anthropic.claude-fable-5-1",
"claude-fable-5": "anthropic.claude-fable-5",
"claude-fable-5-2": "anthropic.claude-fable-5-2",
"claude-mythos-5-2": "anthropic.claude-mythos-5-2",
"claude-fable-5-1": "anthropic.claude-fable-5-1",
"claude-fable-5": "anthropic.claude-fable-5",
// Claude Opus
"claude-opus-5": "us.anthropic.claude-opus-5-v1",
"claude-opus-4-8": "us.anthropic.claude-opus-4-8-v1",
@@ -107,6 +107,7 @@ func TestDefaultAntigravityModelMapping_Gemini38FlashModels(t *testing.T) {
func TestDefaultAntigravityModelMapping_Gemini4ArgonAndClaude55Models(t *testing.T) {
cases := map[string]string{
"gemini-4-carbon": "gemini-4-carbon",
"gemini-4-argon": "gemini-4-argon-high",
"gemini-4-argon-high": "gemini-4-argon-high",
"gemini-4-argon-low": "gemini-4-argon-low",
@@ -131,6 +132,8 @@ func TestDefaultBedrockModelMapping_ContainsNewClaudeModels(t *testing.T) {
t.Parallel()
cases := map[string]string{
"claude-fable-5-2": "anthropic.claude-fable-5-2",
"claude-mythos-5-2": "anthropic.claude-mythos-5-2",
"claude-fable-5-1": "anthropic.claude-fable-5-1",
"claude-fable-5": "anthropic.claude-fable-5",
"claude-opus-4-8": "us.anthropic.claude-opus-4-8-v1",
@@ -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"` // 用户确认混合渠道风险
}
@@ -964,7 +966,11 @@ func (h *AccountHandler) GetByID(c *gin.Context) {
}
}
response.Success(c, h.buildAccountResponseWithRuntime(c.Request.Context(), account))
result := h.buildAccountResponseWithRuntime(c.Request.Context(), account)
if h.accountTestService != nil && account != nil && account.IsGrok() {
result.GrokModelDiagnostics = h.accountTestService.GetGrokModelDiagnostics(c.Request.Context(), account)
}
response.Success(c, result)
}
// CheckMixedChannel handles checking mixed channel risk for account-group binding.
@@ -1058,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 {
@@ -1190,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,
})
@@ -1419,7 +1427,9 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
tokenInfo, err := h.openaiOAuthService.RefreshAccountToken(ctx, account)
if err != nil {
// 刷新失败但 access_token 可能仍有效,尝试设置隐私
h.adminService.EnsureOpenAIPrivacy(ctx, account)
service.AfterAccountCommit(ctx, func(committed context.Context) {
h.adminService.EnsureOpenAIPrivacy(committed, account)
})
return nil, "", err
}
@@ -1471,7 +1481,10 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
if updateErr != nil {
return nil, "", fmt.Errorf("failed to update credentials: %w", updateErr)
}
h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount)
h.invalidateScopedAccountToken(ctx, updatedAccount)
service.AfterAccountCommit(ctx, func(committed context.Context) {
h.adminService.EnsureAntigravityPrivacy(committed, updatedAccount)
})
return updatedAccount, "missing_project_id_temporary", nil
}
@@ -1527,17 +1540,19 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
return nil, "", err
}
// 刷新成功后,清除 token 缓存,确保下次请求使用新 token
if h.tokenCacheInvalidator != nil {
if invalidateErr := h.tokenCacheInvalidator.InvalidateToken(ctx, updatedAccount); invalidateErr != nil {
log.Printf("[WARN] Failed to invalidate token cache for account %d: %v", updatedAccount.ID, invalidateErr)
service.AfterAccountCommit(ctx, func(ctx context.Context) {
// 刷新成功后,清除 token 缓存,确保下次请求使用新 token
if h.tokenCacheInvalidator != nil {
if invalidateErr := h.tokenCacheInvalidator.InvalidateToken(ctx, updatedAccount); invalidateErr != nil {
log.Printf("[WARN] Failed to invalidate token cache for account %d: %v", updatedAccount.ID, invalidateErr)
}
}
}
// OpenAI OAuth: 刷新成功后检查并设置 privacy_mode
h.adminService.EnsureOpenAIPrivacy(ctx, updatedAccount)
// Antigravity OAuth: 刷新成功后检查并设置 privacy_mode
h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount)
// OpenAI OAuth: 刷新成功后检查并设置 privacy_mode
h.adminService.EnsureOpenAIPrivacy(ctx, updatedAccount)
// Antigravity OAuth: 刷新成功后检查并设置 privacy_mode
h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount)
})
return updatedAccount, "", nil
}
@@ -1723,7 +1738,7 @@ func (h *AccountHandler) GetStats(c *gin.Context) {
stats, err := h.accountUsageService.GetAccountUsageStats(c.Request.Context(), accountID, startTime, endTime)
if err != nil {
response.ErrorFrom(c, err)
scopedOpenAIError(c, err)
return
}
@@ -2804,6 +2819,10 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
return
}
h.respondAvailableModels(c, account)
}
func (h *AccountHandler) respondAvailableModels(c *gin.Context, account *service.Account) {
// Handle OpenAI accounts
if account.IsOpenAI() {
// Prefer the shared, account-keyed upstream catalog. If discovery fails,
@@ -3079,6 +3098,11 @@ func (h *AccountHandler) SyncUpstreamModels(c *gin.Context) {
response.Error(c, http.StatusBadGateway, "Failed to sync upstream models from upstream")
return
}
if catalog != nil && account != nil && account.IsGrok() && account.ID > 0 && h.accountTestService != nil {
if latest, readErr := h.adminService.GetAccount(c.Request.Context(), account.ID); readErr == nil && latest != nil {
catalog.GrokModelDiagnostics = h.accountTestService.GetGrokModelDiagnostics(c.Request.Context(), latest)
}
}
response.Success(c, catalog)
}
@@ -0,0 +1,347 @@
package admin
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"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/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestAccountHandlerGrokModelDiagnosticsGetByID(t *testing.T) {
gin.SetMode(gin.TestMode)
upstream := &grokDiagHandlerUpstream{}
account := grokDiagDetailAccount(t)
account.Credentials["access_token"] = "access-secret"
account.Credentials["refresh_token"] = "refresh-secret"
handler, router := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: account}, upstream)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/accounts/25", nil))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
body := rec.Body.String()
require.Contains(t, body, `"current_concurrency"`)
diag := grokDiagResponseObject(t, body)
require.Equal(t, "fresh", diag["state"])
require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", diag["endpoint"])
require.Equal(t, []any{"grok-4.7"}, diag["models"])
mappings, ok := diag["mappings"].([]any)
require.True(t, ok)
require.NotEmpty(t, mappings)
got := grokDiagMappingsByRequested(t, mappings)
require.Equal(t, "listed", got["friendly"]["status"])
require.Equal(t, "grok-4.7", got["friendly"]["upstream"])
require.Equal(t, "not_listed", got["composer-2.5"]["status"])
require.Equal(t, "grok-composer-2.5-fast", got["composer-2.5"]["upstream"])
require.Zero(t, upstream.calls)
require.NotContains(t, body, "access-secret")
require.NotContains(t, body, "refresh-secret")
require.NotContains(t, body, `"models":null`)
require.NotContains(t, body, `"mappings":null`)
raw, err := json.Marshal(handler.buildAccountResponseWithRuntime(context.Background(), &account))
require.NoError(t, err)
require.NotContains(t, string(raw), "grok_model_diagnostics")
}
func TestAccountHandlerGrokModelDiagnosticsOmitsNonGrokAndMissingSnapshot(t *testing.T) {
gin.SetMode(gin.TestMode)
nonGrok := service.Account{ID: 3, Name: "claude", Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth, Status: service.StatusActive}
_, nonGrokRouter := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: nonGrok}, &grokDiagHandlerUpstream{})
nonGrokRec := httptest.NewRecorder()
nonGrokRouter.ServeHTTP(nonGrokRec, httptest.NewRequest(http.MethodGet, "/accounts/3", nil))
require.Equal(t, http.StatusOK, nonGrokRec.Code, nonGrokRec.Body.String())
require.NotContains(t, nonGrokRec.Body.String(), "grok_model_diagnostics")
old := service.Account{
ID: 25, Name: "old-grok", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, Status: service.StatusActive,
Credentials: map[string]any{"access_token": "old-access-secret"},
}
_, oldRouter := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: old}, &grokDiagHandlerUpstream{})
oldRec := httptest.NewRecorder()
oldRouter.ServeHTTP(oldRec, httptest.NewRequest(http.MethodGet, "/accounts/25", nil))
require.Equal(t, http.StatusOK, oldRec.Code, oldRec.Body.String())
diag := grokDiagResponseObject(t, oldRec.Body.String())
require.Equal(t, "unknown", diag["state"])
require.Empty(t, diag["models"])
require.IsType(t, []any{}, diag["models"])
require.IsType(t, []any{}, diag["mappings"])
require.NotContains(t, oldRec.Body.String(), "old-access-secret")
require.NotContains(t, oldRec.Body.String(), `"models":null`)
require.NotContains(t, oldRec.Body.String(), `"mappings":null`)
}
func TestAccountHandlerGrokModelDiagnosticsSyncRereadsLatestAccount(t *testing.T) {
gin.SetMode(gin.TestMode)
initial := &service.Account{
ID: 25, Name: "grok", Platform: service.PlatformGrok, Type: service.AccountTypeAPIKey, Status: service.StatusActive,
Credentials: map[string]any{
"api_key": "sync-secret",
"base_url": "https://relay.example.com/v1",
"model_mapping": map[string]any{"friendly": "grok-4.7"},
},
}
scope, err := service.NewGrokCatalogScope(25, service.AccountTypeAPIKey, "https://relay.example.com/v1/models")
require.NoError(t, err)
latestSnap := &service.GrokObservedModelsSnapshot{
Models: []string{"grok-from-reread"},
FetchedAt: time.Now().UTC().Add(-time.Minute).Format(time.RFC3339Nano),
Scope: scope,
}
rawSnap, err := json.Marshal(latestSnap)
require.NoError(t, err)
var decoded map[string]any
require.NoError(t, json.Unmarshal(rawSnap, &decoded))
latest := *initial
latest.Extra = map[string]any{"grok_observed_models": decoded}
adminSvc := &grokDiagRereadAdmin{stubAdminService: newStubAdminService(), first: initial, latest: &latest}
repo := &grokDiagCatalogRepo{account: cloneGrokDiagAccount(initial)}
upstream := &grokDiagHandlerUpstream{responses: []*http.Response{
{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`))},
{StatusCode: http.StatusBadGateway, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":"registry-down"}`))},
}}
router := newGrokDiagSyncRouter(adminSvc, repo, upstream)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/25/models/sync-upstream", nil))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
body := rec.Body.String()
var payload struct {
Data struct {
Models []string `json:"models"`
DiscoverySource string `json:"discovery_source"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
require.Equal(t, []string{"grok-4.7"}, payload.Data.Models)
require.Equal(t, "upstream", payload.Data.DiscoverySource)
diag := grokDiagResponseObject(t, body)
require.Equal(t, []any{"grok-from-reread"}, diag["models"])
require.Equal(t, "fresh", diag["state"])
require.GreaterOrEqual(t, adminSvc.calls, 2)
require.NotContains(t, body, "sync-secret")
require.NotContains(t, body, "registry-down")
require.NotContains(t, body, `"models":null`)
require.NotContains(t, body, `"mappings":null`)
}
func TestAccountHandlerGrokModelDiagnosticsSyncErrorAndPreviewStayUnchanged(t *testing.T) {
gin.SetMode(gin.TestMode)
adminSvc := &simpleModeAccountService{stubAdminService: newStubAdminService(), account: service.Account{
ID: 44, Platform: service.PlatformGrok, Type: service.AccountTypeAPIKey, Status: service.StatusActive,
Credentials: map[string]any{"base_url": "https://relay.example.com/v1"},
}}
router := newGrokDiagSyncRouter(adminSvc, nil, &grokDiagHandlerUpstream{})
errorRec := httptest.NewRecorder()
router.ServeHTTP(errorRec, httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/44/models/sync-upstream", nil))
require.Equal(t, http.StatusBadRequest, errorRec.Code, errorRec.Body.String())
require.Contains(t, errorRec.Body.String(), "No Grok API key is available")
require.NotContains(t, errorRec.Body.String(), "grok_model_diagnostics")
previewRouter := newGrokDiagSyncRouter(newStubAdminService(), nil, &grokDiagHandlerUpstream{responses: []*http.Response{
{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`))},
{StatusCode: http.StatusBadGateway, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":"registry-secret"}`))},
}})
previewRec := httptest.NewRecorder()
previewReq := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/models/sync-upstream-preview", bytes.NewBufferString(`{
"platform":"grok","type":"apikey","base_url":"https://relay.example.com/v1","api_key":"preview-secret",
"model_mapping":{"friendly":"grok-4.7"}
}`))
previewReq.Header.Set("Content-Type", "application/json")
previewRouter.ServeHTTP(previewRec, previewReq)
require.Equal(t, http.StatusOK, previewRec.Code, previewRec.Body.String())
require.Contains(t, previewRec.Body.String(), `"models":["grok-4.7"]`)
require.NotContains(t, previewRec.Body.String(), "grok_model_diagnostics")
require.NotContains(t, previewRec.Body.String(), "preview-secret")
require.NotContains(t, previewRec.Body.String(), "registry-secret")
}
func newGrokDiagDetailRouter(adminSvc service.AdminService, upstream *grokDiagHandlerUpstream) (*AccountHandler, *gin.Engine) {
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, newGrokDiagTestService(nil, upstream), nil, nil, nil, nil, nil)
router := gin.New()
router.GET("/accounts/:id", handler.GetByID)
return handler, router
}
func newGrokDiagSyncRouter(adminSvc service.AdminService, repo service.AccountRepository, upstream *grokDiagHandlerUpstream) *gin.Engine {
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, newGrokDiagTestService(repo, upstream), nil, nil, nil, nil, nil)
router := gin.New()
router.POST("/api/v1/admin/accounts/:id/models/sync-upstream", handler.SyncUpstreamModels)
router.POST("/api/v1/admin/accounts/models/sync-upstream-preview", handler.SyncUpstreamModelsPreview)
return router
}
func newGrokDiagTestService(repo service.AccountRepository, upstream service.HTTPUpstream) *service.AccountTestService {
return service.NewAccountTestService(repo, nil, nil, nil, nil, upstream, &config.Config{
Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}},
}, nil)
}
func grokDiagDetailAccount(t *testing.T) service.Account {
t.Helper()
scope, err := service.NewGrokCatalogScope(25, service.AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models")
require.NoError(t, err)
snap := &service.GrokObservedModelsSnapshot{
Models: []string{"grok-4.7"},
FetchedAt: time.Now().UTC().Add(-time.Hour).Format(time.RFC3339Nano),
Scope: scope,
}
raw, err := json.Marshal(snap)
require.NoError(t, err)
var decoded map[string]any
require.NoError(t, json.Unmarshal(raw, &decoded))
return service.Account{
ID: 25, Name: "grok", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, Status: service.StatusActive,
Credentials: map[string]any{"model_mapping": map[string]any{
"friendly": "grok-4.7",
"composer-2.5": "composer-2.5",
}},
Extra: map[string]any{"grok_observed_models": decoded},
}
}
func grokDiagResponseObject(t *testing.T, body string) map[string]any {
t.Helper()
var payload map[string]any
require.NoError(t, json.Unmarshal([]byte(body), &payload))
data, ok := payload["data"].(map[string]any)
require.True(t, ok, body)
diag, ok := data["grok_model_diagnostics"].(map[string]any)
require.True(t, ok, body)
return diag
}
func grokDiagMappingsByRequested(t *testing.T, mappings []any) map[string]map[string]any {
t.Helper()
out := make(map[string]map[string]any, len(mappings))
for _, raw := range mappings {
item, ok := raw.(map[string]any)
require.True(t, ok)
requested, _ := item["requested"].(string)
out[requested] = item
}
return out
}
type grokDiagRereadAdmin struct {
*stubAdminService
first *service.Account
latest *service.Account
calls int
}
func (s *grokDiagRereadAdmin) GetAccount(context.Context, int64) (*service.Account, error) {
s.calls++
if s.calls == 1 {
return cloneGrokDiagAccount(s.first), nil
}
return cloneGrokDiagAccount(s.latest), nil
}
type grokDiagCatalogRepo struct {
service.AccountRepository
mu sync.Mutex
account *service.Account
}
func (r *grokDiagCatalogRepo) GetByID(_ context.Context, id int64) (*service.Account, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.account == nil || r.account.ID != id {
return nil, service.ErrAccountNotFound
}
return cloneGrokDiagAccount(r.account), nil
}
func (r *grokDiagCatalogRepo) UpdateExtra(context.Context, int64, map[string]any) error {
return nil
}
func (r *grokDiagCatalogRepo) CompareAndSwapGrokObservedModels(_ context.Context, id int64, expected, next json.RawMessage) (bool, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.account == nil || r.account.ID != id {
return false, nil
}
var current any
if r.account.Extra != nil {
current = r.account.Extra["grok_observed_models"]
}
currentJSON, err := json.Marshal(current)
if err != nil {
return false, err
}
var expectedValue any
var currentValue any
if err := json.Unmarshal(expected, &expectedValue); err != nil {
return false, err
}
if err := json.Unmarshal(currentJSON, &currentValue); err != nil {
return false, err
}
if !reflect.DeepEqual(expectedValue, currentValue) {
return false, nil
}
var decoded any
if err := json.Unmarshal(next, &decoded); err != nil {
return false, err
}
if r.account.Extra == nil {
r.account.Extra = map[string]any{}
}
r.account.Extra["grok_observed_models"] = decoded
return true, nil
}
func cloneGrokDiagAccount(src *service.Account) *service.Account {
if src == nil {
return nil
}
raw, err := json.Marshal(src)
if err != nil {
copied := *src
return &copied
}
var dst service.Account
if err := json.Unmarshal(raw, &dst); err != nil {
copied := *src
return &copied
}
return &dst
}
type grokDiagHandlerUpstream struct {
mu sync.Mutex
calls int
responses []*http.Response
}
func (u *grokDiagHandlerUpstream) Do(*http.Request, string, int64, int) (*http.Response, error) {
u.mu.Lock()
defer u.mu.Unlock()
u.calls++
if len(u.responses) == 0 {
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`)), Header: make(http.Header)}, nil
}
resp := u.responses[0]
u.responses = u.responses[1:]
return resp, nil
}
func (u *grokDiagHandlerUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
return u.Do(req, proxyURL, accountID, accountConcurrency)
}
@@ -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()
@@ -2,6 +2,8 @@ package admin
import (
"encoding/json"
"fmt"
"math"
"net/http"
"net/http/httptest"
"net/netip"
@@ -136,6 +138,7 @@ func TestParseOpsOpenAITokenStatsFilter_InvalidParams(t *testing.T) {
"/?page=0",
"/?page_size=0",
"/?page_size=101",
"/?page=9223372036854775807",
}
gin.SetMode(gin.TestMode)
@@ -149,6 +152,32 @@ func TestParseOpsOpenAITokenStatsFilter_InvalidParams(t *testing.T) {
}
}
func TestParseOpsOpenAITokenStatsFilter_PaginationBoundaries(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, size := range []int{1, 20, 21, 100} {
bound := math.MaxInt / size
pages := []int{bound}
if bound < math.MaxInt {
pages = append(pages, bound+1)
}
for _, page := range pages {
query := fmt.Sprintf("/?page=%d&page_size=%d", page, size)
t.Run(query, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, query, nil)
filter, err := parseOpsOpenAITokenStatsFilter(c)
if page > bound {
require.ErrorContains(t, err, "invalid page")
return
}
require.NoError(t, err)
require.Equal(t, page, filter.Page)
require.Equal(t, size, filter.PageSize)
})
}
}
}
func TestParseOpsTimeRange(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
@@ -208,6 +208,14 @@ func (s *stubAdminService) BatchUpdateLimits(ctx context.Context, userIDs []int6
return len(userIDs), nil
}
func (s *stubAdminService) FindActiveUsersByBlacklistedEmails(ctx context.Context, emails []string) ([]service.User, error) {
return []service.User{}, nil
}
func (s *stubAdminService) BatchDisableUsers(ctx context.Context, userIDs []int64) (int, error) {
return len(userIDs), nil
}
func (s *stubAdminService) GetUserAPIKeys(ctx context.Context, userID int64, page, pageSize int, sortBy, sortOrder string) ([]service.APIKey, int64, error) {
return s.apiKeys, int64(len(s.apiKeys)), nil
}
@@ -580,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
@@ -590,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) {
@@ -252,5 +252,5 @@ func (h *AnnouncementHandler) ListReadStatus(c *gin.Context) {
return
}
response.Paginated(c, items, paginationResult.Total, page, pageSize)
response.Paginated(c, adminAnnouncementReadResponse(c, items), paginationResult.Total, page, pageSize)
}
@@ -110,13 +110,13 @@ type auditLogClearRequest struct {
// 安全要求(与需求对齐):
// 1. 每次清空都必须现场验证 TOTP 码(不复用 step-up sudo 窗口)
// 2. 未启用 TOTP 的管理员不允许清空
// 3. admin API key(机器凭证)不允许清空
// 3. 机器凭证(admin API key、MCP OAuth 等非浏览器会话)不允许清空
// 4. 清空完成后同步写入一条留痕记录(操作者、IP、UA、删除行数)
func (h *AuditLogHandler) Clear(c *gin.Context) {
if c.GetString("auth_method") == service.AuditAuthMethodAdminAPIKey {
if reason, machine := middleware.MachineCredentialReason(c); machine {
response.ErrorWithDetails(c, http.StatusForbidden,
"Admin API key cannot clear audit logs; a two-factor verified admin session is required",
"STEP_UP_ADMIN_API_KEY_FORBIDDEN", nil)
"Machine credentials cannot clear audit logs; a two-factor verified admin session is required",
reason, nil)
return
}
@@ -65,9 +65,11 @@ type channelModelPricingRequest struct {
OutputPrice *float64 `json:"output_price" binding:"omitempty,min=0"`
CacheWritePrice *float64 `json:"cache_write_price" binding:"omitempty,min=0"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price" binding:"omitempty,min=0"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price" binding:"omitempty,min=0"`
CacheReadPrice *float64 `json:"cache_read_price" binding:"omitempty,min=0"`
FastMultiplier *float64 `json:"fast_multiplier" binding:"omitempty,gt=0"`
FlexMultiplier *float64 `json:"flex_multiplier" binding:"omitempty,gt=0"`
UltrafastMultiplier *float64 `json:"ultrafast_multiplier" binding:"omitempty,gt=0"`
ReasoningEffortMultipliers map[string]float64 `json:"reasoning_effort_multipliers"`
ImageInputPrice *float64 `json:"image_input_price" binding:"omitempty,min=0"`
ImageOutputPrice *float64 `json:"image_output_price" binding:"omitempty,min=0"`
@@ -96,6 +98,7 @@ type pricingIntervalRequest struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
InputMultiplier *float64 `json:"input_multiplier" binding:"omitempty,gt=0"`
OutputMultiplier *float64 `json:"output_multiplier" binding:"omitempty,gt=0"`
@@ -139,9 +142,11 @@ type channelModelPricingResponse struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
FastMultiplier *float64 `json:"fast_multiplier"`
FlexMultiplier *float64 `json:"flex_multiplier"`
UltrafastMultiplier *float64 `json:"ultrafast_multiplier"`
ReasoningEffortMultipliers map[string]float64 `json:"reasoning_effort_multipliers"`
ImageInputPrice *float64 `json:"image_input_price"`
ImageOutputPrice *float64 `json:"image_output_price"`
@@ -171,6 +176,7 @@ type pricingIntervalResponse struct {
OutputPrice *float64 `json:"output_price"`
CacheWritePrice *float64 `json:"cache_write_price"`
CacheWrite1hPrice *float64 `json:"cache_write_1h_price"`
CacheWrite12hPrice *float64 `json:"cache_write_12h_price"`
CacheReadPrice *float64 `json:"cache_read_price"`
InputMultiplier *float64 `json:"input_multiplier"`
OutputMultiplier *float64 `json:"output_multiplier"`
@@ -269,9 +275,11 @@ func pricingToResponse(p *service.ChannelModelPricing) channelModelPricingRespon
OutputPrice: p.OutputPrice,
CacheWritePrice: p.CacheWritePrice,
CacheWrite1hPrice: p.CacheWrite1hPrice,
CacheWrite12hPrice: p.CacheWrite12hPrice,
CacheReadPrice: p.CacheReadPrice,
FastMultiplier: p.FastMultiplier,
FlexMultiplier: p.FlexMultiplier,
UltrafastMultiplier: p.UltrafastMultiplier,
ReasoningEffortMultipliers: p.ReasoningEffortMultipliers,
ImageInputPrice: p.ImageInputPrice,
ImageOutputPrice: p.ImageOutputPrice,
@@ -310,6 +318,7 @@ func intervalToResponse(iv service.PricingInterval) pricingIntervalResponse {
OutputPrice: iv.OutputPrice,
CacheWritePrice: iv.CacheWritePrice,
CacheWrite1hPrice: iv.CacheWrite1hPrice,
CacheWrite12hPrice: iv.CacheWrite12hPrice,
CacheReadPrice: iv.CacheReadPrice,
InputMultiplier: iv.InputMultiplier,
OutputMultiplier: iv.OutputMultiplier,
@@ -345,6 +354,7 @@ func pricingRequestToService(reqs []channelModelPricingRequest, allowChannelMult
OutputPrice: iv.OutputPrice,
CacheWritePrice: iv.CacheWritePrice,
CacheWrite1hPrice: iv.CacheWrite1hPrice,
CacheWrite12hPrice: iv.CacheWrite12hPrice,
CacheReadPrice: iv.CacheReadPrice,
InputMultiplier: inputMultiplier,
OutputMultiplier: outputMultiplier,
@@ -354,10 +364,11 @@ func pricingRequestToService(reqs []channelModelPricingRequest, allowChannelMult
SortOrder: iv.SortOrder,
})
}
var fastMultiplier, flexMultiplier *float64
var fastMultiplier, flexMultiplier, ultrafastMultiplier *float64
if allowChannelMultipliers {
fastMultiplier = r.FastMultiplier
flexMultiplier = r.FlexMultiplier
ultrafastMultiplier = r.UltrafastMultiplier
}
result = append(result, service.ChannelModelPricing{
Platform: platform,
@@ -367,9 +378,11 @@ func pricingRequestToService(reqs []channelModelPricingRequest, allowChannelMult
OutputPrice: r.OutputPrice,
CacheWritePrice: r.CacheWritePrice,
CacheWrite1hPrice: r.CacheWrite1hPrice,
CacheWrite12hPrice: r.CacheWrite12hPrice,
CacheReadPrice: r.CacheReadPrice,
FastMultiplier: fastMultiplier,
FlexMultiplier: flexMultiplier,
UltrafastMultiplier: ultrafastMultiplier,
ReasoningEffortMultipliers: r.ReasoningEffortMultipliers,
ImageInputPrice: r.ImageInputPrice,
ImageOutputPrice: r.ImageOutputPrice,
@@ -625,6 +638,7 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) {
"output_price": pricing.OutputPricePerToken,
"cache_write_price": cacheWritePrice,
"cache_write_1h_price": cacheWrite1hPrice,
"cache_write_12h_price": pricing.CacheCreation12hPricePerToken,
"cache_read_price": pricing.CacheReadPricePerToken,
"reasoning_effort_multipliers": pricing.ReasoningEffortMultipliers,
"image_input_price": pricing.ImageInputPricePerToken,
@@ -632,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) {
@@ -652,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})
}
@@ -11,6 +11,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/stretchr/testify/require"
)
@@ -320,16 +321,17 @@ func TestPricingRequestToService_Defaults(t *testing.T) {
func TestPricingRequestToService_WithAllFields(t *testing.T) {
reqs := []channelModelPricingRequest{
{
Platform: "openai",
Models: []string{"gpt-4", "gpt-4o"},
BillingMode: "per_request",
InputPrice: float64Ptr(0.01),
OutputPrice: float64Ptr(0.03),
CacheWritePrice: float64Ptr(0.005),
CacheWrite1hPrice: float64Ptr(0.008),
CacheReadPrice: float64Ptr(0.002),
ImageOutputPrice: float64Ptr(0.04),
PerRequestPrice: float64Ptr(0.5),
Platform: "openai",
Models: []string{"gpt-4", "gpt-4o"},
BillingMode: "per_request",
InputPrice: float64Ptr(0.01),
OutputPrice: float64Ptr(0.03),
CacheWritePrice: float64Ptr(0.005),
CacheWrite1hPrice: float64Ptr(0.008),
CacheWrite12hPrice: float64Ptr(0.01),
CacheReadPrice: float64Ptr(0.002),
ImageOutputPrice: float64Ptr(0.04),
PerRequestPrice: float64Ptr(0.5),
},
}
@@ -343,6 +345,7 @@ func TestPricingRequestToService_WithAllFields(t *testing.T) {
require.Equal(t, float64Ptr(0.03), r.OutputPrice)
require.Equal(t, float64Ptr(0.005), r.CacheWritePrice)
require.Equal(t, float64Ptr(0.008), r.CacheWrite1hPrice)
require.Equal(t, float64Ptr(0.01), r.CacheWrite12hPrice)
require.Equal(t, float64Ptr(0.002), r.CacheReadPrice)
require.Equal(t, float64Ptr(0.04), r.ImageOutputPrice)
require.Equal(t, float64Ptr(0.5), r.PerRequestPrice)
@@ -355,16 +358,17 @@ func TestPricingRequestToService_WithIntervals(t *testing.T) {
BillingMode: "per_request",
Intervals: []pricingIntervalRequest{
{
MinTokens: 0,
MaxTokens: intPtr(2000),
TierLabel: "small",
InputPrice: float64Ptr(0.01),
OutputPrice: float64Ptr(0.02),
CacheWritePrice: float64Ptr(0.003),
CacheWrite1hPrice: float64Ptr(0.006),
CacheReadPrice: float64Ptr(0.001),
PerRequestPrice: float64Ptr(0.1),
SortOrder: 1,
MinTokens: 0,
MaxTokens: intPtr(2000),
TierLabel: "small",
InputPrice: float64Ptr(0.01),
OutputPrice: float64Ptr(0.02),
CacheWritePrice: float64Ptr(0.003),
CacheWrite1hPrice: float64Ptr(0.006),
CacheWrite12hPrice: float64Ptr(0),
CacheReadPrice: float64Ptr(0.001),
PerRequestPrice: float64Ptr(0.1),
SortOrder: 1,
},
{
MinTokens: 2000,
@@ -388,6 +392,7 @@ func TestPricingRequestToService_WithIntervals(t *testing.T) {
require.Equal(t, float64Ptr(0.02), iv0.OutputPrice)
require.Equal(t, float64Ptr(0.003), iv0.CacheWritePrice)
require.Equal(t, float64Ptr(0.006), iv0.CacheWrite1hPrice)
require.Equal(t, float64Ptr(0), iv0.CacheWrite12hPrice)
require.Equal(t, float64Ptr(0.001), iv0.CacheReadPrice)
require.Equal(t, float64Ptr(0.1), iv0.PerRequestPrice)
require.Equal(t, 1, iv0.SortOrder)
@@ -456,6 +461,7 @@ func TestPricingRequestToService_MultipliersGatedByFlag(t *testing.T) {
BillingMode: "token",
FastMultiplier: float64Ptr(2.5),
FlexMultiplier: float64Ptr(0.5),
UltrafastMultiplier: float64Ptr(3),
ReasoningEffortMultipliers: map[string]float64{"high": 1.5, "max": 3},
Intervals: []pricingIntervalRequest{{
MinTokens: 272000,
@@ -469,6 +475,7 @@ func TestPricingRequestToService_MultipliersGatedByFlag(t *testing.T) {
allowed := pricingRequestToService([]channelModelPricingRequest{req}, true)
require.Equal(t, float64Ptr(2.5), allowed[0].FastMultiplier)
require.Equal(t, float64Ptr(0.5), allowed[0].FlexMultiplier)
require.Equal(t, float64Ptr(3), allowed[0].UltrafastMultiplier)
require.Equal(t, req.ReasoningEffortMultipliers, allowed[0].ReasoningEffortMultipliers)
require.Equal(t, float64Ptr(2), allowed[0].Intervals[0].InputMultiplier)
require.Equal(t, float64Ptr(1.5), allowed[0].Intervals[0].OutputMultiplier)
@@ -478,6 +485,7 @@ func TestPricingRequestToService_MultipliersGatedByFlag(t *testing.T) {
dropped := pricingRequestToService([]channelModelPricingRequest{req}, false)
require.Nil(t, dropped[0].FastMultiplier)
require.Nil(t, dropped[0].FlexMultiplier)
require.Nil(t, dropped[0].UltrafastMultiplier)
require.Equal(t, req.ReasoningEffortMultipliers, dropped[0].ReasoningEffortMultipliers)
require.Nil(t, dropped[0].Intervals[0].InputMultiplier)
require.Nil(t, dropped[0].Intervals[0].OutputMultiplier)
@@ -487,6 +495,22 @@ func TestPricingRequestToService_MultipliersGatedByFlag(t *testing.T) {
require.Equal(t, 272000, dropped[0].Intervals[0].MinTokens)
}
func TestPricingRequestAndResponse_UltrafastMultiplier(t *testing.T) {
var req channelModelPricingRequest
require.NoError(t, json.Unmarshal([]byte(`{"models":["gpt-6-astra"],"ultrafast_multiplier":1.25}`), &req))
pricing := pricingRequestToService([]channelModelPricingRequest{req}, true)
require.Equal(t, float64Ptr(1.25), pricing[0].UltrafastMultiplier)
got := pricingToResponse(&pricing[0])
require.Equal(t, float64Ptr(1.25), got.UltrafastMultiplier)
data, err := json.Marshal(got)
require.NoError(t, err)
require.Contains(t, string(data), `"ultrafast_multiplier":1.25`)
req = channelModelPricingRequest{}
require.NoError(t, json.Unmarshal([]byte(`{"models":["gpt-6-astra"],"ultrafast_multiplier":0}`), &req))
require.Error(t, binding.Validator.ValidateStruct(&req))
}
func TestPricingToResponse_TimePricing(t *testing.T) {
got := pricingToResponse(&service.ChannelModelPricing{
BillingMode: service.BillingModeToken,
@@ -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 == "" {
@@ -0,0 +1,329 @@
package admin
import (
"context"
"encoding/json"
"slices"
"strconv"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
func scopedAdminAccountDTO(a *service.Account, p adminaccess.Policy) gin.H {
resource := adminaccess.Account{ID: a.ID, Type: a.Type, Platform: a.Platform, GroupIDs: a.GroupIDs}
groups := []int64{}
for _, g := range a.GroupIDs {
if p.AllowsGroup("accounts.read", resource, g) {
groups = append(groups, g)
}
}
result := gin.H{"id": a.ID, "name": a.Name, "notes": a.Notes, "platform": a.Platform, "type": a.Type, "status": a.Status, "schedulable": a.Schedulable, "concurrency": a.Concurrency, "priority": a.Priority, "group_ids": groups, "expires_at": a.ExpiresAt, "rate_limit_reset_at": a.RateLimitResetAt, "overload_until": a.OverloadUntil, "temp_unschedulable_until": a.TempUnschedulableUntil}
// 兼容原账户读取结构,仅返回模型映射,凭证及扩展字段继续脱敏。
if p.AllowsAccount("accounts.read", resource) {
mapping := map[string]string{}
switch raw := a.Credentials["model_mapping"].(type) {
case map[string]string:
for source, target := range raw {
mapping[source] = target
}
case map[string]any:
for source, target := range raw {
if value, ok := target.(string); ok {
mapping[source] = value
}
}
}
result["credentials"] = gin.H{"model_mapping": mapping}
}
if p.AllowsAccount("accounts.identity.read", resource) {
credentials, _ := result["credentials"].(gin.H)
if credentials == nil {
credentials = gin.H{}
}
for _, key := range []string{"email", "plan_type", "subscription_expires_at"} {
if value, ok := a.Credentials[key].(string); ok {
credentials[key] = value
}
}
result["credentials"] = credentials
// 保留两处邮箱供调用方检查一致性,禁止回传其他扩展字段。
extra := gin.H{}
if value, ok := a.Extra["email"].(string); ok {
extra["email"] = value
}
result["extra"] = extra
result["created_at"] = a.CreatedAt
}
if p.AllowsAccount("accounts.usage.read", resource) {
extra, _ := result["extra"].(gin.H)
if extra == nil {
extra = gin.H{}
}
for _, key := range []string{"codex_usage_updated_at", "codex_7d_used_percent", "codex_7d_reset_at"} {
if value, ok := a.Extra[key]; ok {
extra[key] = value
}
}
result["extra"] = extra
}
return result
}
// ScopedAdminKeyAccounts 在原处理器前完成独立授权和安全输出。
func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) {
principal := adminaccess.RestrictedFromContext(c.Request.Context())
if principal == nil {
return
}
path := c.FullPath()
if !strings.HasPrefix(path, "/api/v1/admin/accounts") {
return
}
c.Abort()
base := "/api/v1/admin/accounts"
// 静态默认映射不读取任何账户;权限独立于账户查看及凭证写入。
if path == base+"/antigravity/default-model-mapping" && c.Request.Method == "GET" {
if !adminaccess.RouteAllowed(principal.Policy, c.Request.Method, path) {
response.Error(c, 403, "默认模型读取未授权")
return
}
h.GetAntigravityDefaultModelMapping(c)
return
}
if path == base+"/import/codex-session" && c.Request.Method == "POST" {
h.scopedAdminImportCodexSession(c)
return
}
if h.scopedAdminStatistics(c) {
return
}
api, ok := h.adminService.(service.ScopedAdminAccounts)
if !ok {
response.Error(c, 503, "受限账户服务不可用")
return
}
ctx := c.Request.Context()
if path == base && c.Request.Method == "GET" {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if page < 1 {
page = 1
}
if size < 1 || size > 100 {
size = 20
}
groupID := int64(0)
// 空分组筛选与省略参数均表示不按分组筛选。
if raw := c.Query("group"); raw != "" {
var err error
groupID, err = strconv.ParseInt(raw, 10, 64)
if err != nil || groupID < -1 {
response.BadRequest(c, "分组筛选无效")
return
}
}
accounts, total, err := api.ScopedAdminList(ctx, pagination.PaginationParams{Page: page, PageSize: size}, c.Query("platform"), c.Query("type"), c.Query("status"), c.Query("search"), groupID)
if err != nil {
response.Error(c, 503, "账户查询失败")
return
}
items := make([]gin.H, 0, len(accounts))
for i := range accounts {
if principal.Policy.AllowsAccount("accounts.read", adminaccess.Account{ID: accounts[i].ID, GroupIDs: accounts[i].GroupIDs, Type: accounts[i].Type, Platform: accounts[i].Platform}) {
items = append(items, scopedAdminAccountDTO(&accounts[i], principal.Policy))
}
}
response.Paginated(c, items, total, page, size)
return
}
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
if (path == base+"/:id" || path == base+"/:id/models") && c.Request.Method == "GET" {
a, err := h.adminService.GetAccount(ctx, id)
if err != nil || a == nil || !principal.Policy.AllowsAccount("accounts.read", adminaccess.Account{ID: id, GroupIDs: accountGroupIDs(a), Type: accountType(a), Platform: accountPlatform(a)}) {
response.Error(c, 404, "账户不存在")
return
}
if path == base+"/:id/models" {
h.respondAvailableModels(c, a)
return
}
response.Success(c, scopedAdminAccountDTO(a, principal.Policy))
return
}
if path == base+"/bulk-update" && c.Request.Method == "POST" {
h.scopedAdminBulkUpdate(c, api)
return
}
fields := map[string]json.RawMessage{}
action := ""
var run func(context.Context, *service.Account) (*service.Account, error)
switch {
case path == base && c.Request.Method == "POST":
id = 0
if c.ShouldBindJSON(&fields) != nil || fields == nil {
response.Error(c, 400, "请求格式无效")
return
}
case path == base+"/:id" && c.Request.Method == "PUT":
if c.ShouldBindJSON(&fields) != nil || len(fields) == 0 {
response.Error(c, 400, "请求格式无效")
return
}
case path == base+"/:id" && c.Request.Method == "DELETE":
action = "accounts.delete"
case path == base+"/:id/schedulable" && c.Request.Method == "POST":
if c.ShouldBindJSON(&fields) != nil || len(fields) != 1 || fields["schedulable"] == nil {
response.Error(c, 400, "仅支持 schedulable 字段")
return
}
case path == base+"/:id/clear-error" && c.Request.Method == "POST":
action = "accounts.recover"
case path == base+"/:id/refresh" && c.Request.Method == "POST":
action = "accounts.refresh"
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, 60*time.Second)
defer cancel()
a, err := h.adminService.GetAccount(ctx, id)
if err != nil || a == nil || !principal.Policy.AllowsAccount(action, adminaccess.Account{ID: id, GroupIDs: accountGroupIDs(a), Type: accountType(a), Platform: accountPlatform(a)}) {
response.Error(c, 404, "账户不存在")
return
}
run = func(txctx context.Context, a *service.Account) (*service.Account, error) {
updated, _, err := h.refreshSingleAccount(txctx, a)
if err != nil {
code := infraerrors.Code(err)
if code != 400 && code != 403 && code != 404 && code != 409 && code != 503 {
return nil, infraerrors.New(502, "SCOPED_REFRESH_FAILED", "上游刷新失败")
}
}
return updated, err
}
default:
response.Error(c, 403, "此账户操作未开放给受限管理密钥")
return
}
if id <= 0 && path != base {
response.Error(c, 400, "账户 ID 无效")
return
}
a, err := api.ScopedAdminWrite(ctx, id, action, fields, run)
if err != nil {
scopedAdminAccountError(c, err)
return
}
if id > 0 && fields["credentials"] != nil {
h.invalidateScopedAccountToken(ctx, a)
}
response.Success(c, gin.H{"id": a.ID, "status": a.Status})
}
func accountGroupIDs(a *service.Account) []int64 {
if a == nil {
return nil
}
return a.GroupIDs
}
func accountType(a *service.Account) string {
if a == nil {
return ""
}
return a.Type
}
func accountPlatform(a *service.Account) string {
if a == nil {
return ""
}
return a.Platform
}
func scopedAdminAccountError(c *gin.Context, err error) {
code, message := scopedAdminAccountErrorDetails(err)
response.Error(c, code, message)
}
func scopedAdminAccountErrorDetails(err error) (int, string) {
code := infraerrors.Code(err)
message := "账户服务暂不可用"
switch code {
case 400:
message = "请求参数无效"
case 403:
message = "操作未授权"
case 404:
message = "账户不存在"
case 409:
message = "账户正在处理,请稍后重试"
case 502:
message = "上游刷新失败"
default:
code = 503
}
return code, message
}
// scopedAdminBulkUpdate 沿用旧批量接口与结果结构,每个账户仍走锁内逐字段验权。
func (h *AccountHandler) scopedAdminBulkUpdate(c *gin.Context, api service.ScopedAdminAccounts) {
var fields map[string]json.RawMessage
if c.ShouldBindJSON(&fields) != nil || fields == nil {
response.Error(c, 400, "请求格式无效")
return
}
var ids []int64
if json.Unmarshal(fields["account_ids"], &ids) != nil || len(ids) == 0 || len(ids) > 100 {
response.Error(c, 400, "请明确指定 1 至 100 个账户 ID")
return
}
delete(fields, "account_ids")
// 不把全站筛选条件传给原批量服务,以免绕开账户范围。
if _, exists := fields["filters"]; exists || len(fields) == 0 {
response.Error(c, 400, "受限批量更新须明确指定账户及修改字段")
return
}
uniqueIDs := make([]int64, 0, len(ids))
for _, id := range ids {
if id <= 0 {
response.Error(c, 400, "账户 ID 无效")
return
}
if !slices.Contains(uniqueIDs, id) {
uniqueIDs = append(uniqueIDs, id)
}
}
result := service.BulkUpdateAccountsResult{SuccessIDs: []int64{}, FailedIDs: []int64{}, Results: []service.BulkUpdateAccountResult{}}
for _, id := range uniqueIDs {
account, err := api.ScopedAdminWrite(c.Request.Context(), id, "", fields, nil)
item := service.BulkUpdateAccountResult{AccountID: id, Success: err == nil}
if err != nil {
_, item.Error = scopedAdminAccountErrorDetails(err)
result.Failed++
result.FailedIDs = append(result.FailedIDs, id)
} else {
if fields["credentials"] != nil {
h.invalidateScopedAccountToken(c.Request.Context(), account)
}
result.Success++
result.SuccessIDs = append(result.SuccessIDs, id)
}
result.Results = append(result.Results, item)
}
response.Success(c, result)
}
// 凭证写入必须在数据库提交成功后清理令牌缓存,回滚不能发布旧状态。
func (h *AccountHandler) invalidateScopedAccountToken(ctx context.Context, account *service.Account) {
if h.tokenCacheInvalidator == nil || account == nil {
return
}
service.AfterAccountCommit(ctx, func(committed context.Context) {
_ = h.tokenCacheInvalidator.InvalidateToken(committed, account)
})
}
@@ -0,0 +1,150 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestScopedAdminAccountDTORedactsSecretsAndForeignGroups(t *testing.T) {
p := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}
a := &service.Account{ID: 9, Type: "oauth", GroupIDs: []int64{1, 2}, Credentials: map[string]any{"access_token": "TOP_SECRET", "refresh_token": "REFRESH_SECRET", "base_url": "URL_SECRET", "model_mapping": map[string]any{"alias": "target", "invalid": map[string]any{"token": "NESTED_SECRET"}}}, Extra: map[string]any{"private": "EXTRA_SECRET"}}
body, _ := json.Marshal(scopedAdminAccountDTO(a, p))
s := string(body)
if strings.Contains(s, "SECRET") || strings.Contains(s, "extra") {
t.Fatalf("泄漏敏感字段: %s", s)
}
require.Contains(t, s, `"credentials":{"model_mapping":{"alias":"target"}}`)
if !strings.Contains(s, `"group_ids":[1]`) {
t.Fatalf("泄漏越权组: %s", s)
}
}
func TestScopedAdminAccountErrorsAreClassifiedAndRedacted(t *testing.T) {
for _, code := range []int{400, 403, 404, 409, 502, 503, 500} {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
scopedAdminAccountError(c, infraerrors.New(code, "secret", "TOP_SECRET"))
want := code
if code == 500 {
want = 503
}
if w.Code != want || strings.Contains(w.Body.String(), "TOP_SECRET") {
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
}
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
scopedAdminAccountError(c, errors.New("TOP_SECRET"))
if w.Code != 503 || strings.Contains(w.Body.String(), "TOP_SECRET") {
t.Fatal(w.Body.String())
}
}
func TestScopedAdminAccountMiddlewareKeepsJWTAndDeniesUnavailableService(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, restricted := range []bool{false, true} {
r := gin.New()
h := &AccountHandler{}
r.Use(func(c *gin.Context) {
if restricted {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{}))
}
})
r.Use(h.ScopedAdminKeyAccounts)
r.GET("/api/v1/admin/accounts", func(c *gin.Context) { c.Status(204) })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts", nil))
want := 204
if restricted {
want = 503
}
if w.Code != want {
t.Fatalf("restricted=%v status=%d", restricted, w.Code)
}
}
}
// 批量入口必须使用受限服务,不得回落到嵌入的全权 BulkUpdateAccounts。
type scopedBulkAccountService struct {
service.AdminService
calls []int64
fields map[string]json.RawMessage
}
func (s *scopedBulkAccountService) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]service.Account, int64, error) {
panic("不应读取全站账户")
}
func (s *scopedBulkAccountService) ScopedAdminWrite(_ context.Context, id int64, _ string, fields map[string]json.RawMessage, _ func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) {
s.calls = append(s.calls, id)
s.fields = fields
switch id {
case 2:
return nil, infraerrors.NotFound("SECRET", "TOP_SECRET")
case 3:
return nil, infraerrors.Forbidden("SECRET", "TOP_SECRET")
case 4:
return nil, errors.New("TOP_SECRET")
}
return &service.Account{ID: id}, nil
}
func TestScopedAdminBulkUpdateValidatesTargetsAndRedactsResults(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
body string
status int
ids []int64
}{
{`{"account_ids":[1,2,1,3,4],"credentials":{"model_mapping":{"alias":"target"}}}`, 200, []int64{1, 2, 3, 4}},
{`null`, 400, nil},
{`{"credentials":{"model_mapping":{}}}`, 400, nil},
{`{"account_ids":[],"credentials":{"model_mapping":{}}}`, 400, nil},
{`{"account_ids":[1,0],"credentials":{"model_mapping":{}}}`, 400, nil},
{`{"account_ids":[1,-1],"credentials":{"model_mapping":{}}}`, 400, nil},
{`{"account_ids":[1]}`, 400, nil},
{`{"account_ids":[1],"filters":{},"credentials":{"model_mapping":{}}}`, 400, nil},
{`{"account_ids":[1.5],"credentials":{"model_mapping":{}}}`, 400, nil},
{`{"account_ids":[` + strings.Repeat("1,", 100) + `1],"credentials":{"model_mapping":{}}}`, 400, nil},
} {
t.Run(tc.body, func(t *testing.T) {
svc := &scopedBulkAccountService{}
h := &AccountHandler{adminService: svc}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/api/v1/admin/accounts/bulk-update", strings.NewReader(tc.body))
h.scopedAdminBulkUpdate(c, svc)
require.Equal(t, tc.status, w.Code, w.Body.String())
require.Equal(t, tc.ids, svc.calls)
require.NotContains(t, w.Body.String(), "SECRET")
if tc.status == 200 {
body, err := json.Marshal(svc.fields)
require.NoError(t, err)
require.JSONEq(t, `{"credentials":{"model_mapping":{"alias":"target"}}}`, string(body))
var result struct {
Data service.BulkUpdateAccountsResult `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
require.Equal(t, 1, result.Data.Success)
require.Equal(t, 3, result.Data.Failed)
require.Equal(t, []int64{1}, result.Data.SuccessIDs)
require.Equal(t, []int64{2, 3, 4}, result.Data.FailedIDs)
require.Equal(t, "账户不存在", result.Data.Results[1].Error)
require.Equal(t, "操作未授权", result.Data.Results[2].Error)
require.Equal(t, "账户服务暂不可用", result.Data.Results[3].Error)
}
})
}
}
@@ -0,0 +1,189 @@
package admin
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
type scopedCodexSessionImportRequest struct {
CodexSessionImportRequest
ProxyMode string `json:"proxy_mode"`
RandomProxy bool `json:"random_proxy"`
}
func validateScopedCodexRequest(req scopedCodexSessionImportRequest) error {
if _, err := service.NormalizeAccountProxyMode(req.ProxyMode, req.ProxyID, req.RandomProxy); err != nil {
return err
}
if req.GroupIDs == nil || (req.ConfirmMixedChannelRisk != nil && *req.ConfirmMixedChannelRisk) {
return infraerrors.BadRequest("SCOPED_CODEX_INPUT", "须明确提供 group_ids,不能跳过分组风险检查")
}
if (req.Concurrency != nil && *req.Concurrency < 0) || (req.Priority != nil && *req.Priority < 0) || (req.LoadFactor != nil && (*req.LoadFactor < 1 || *req.LoadFactor > 10000)) || (req.RateMultiplier != nil && *req.RateMultiplier < 0) {
return infraerrors.BadRequest("SCOPED_CODEX_INPUT", "导入参数无效")
}
for key := range req.CredentialExtras {
if key != "base_url" && key != "model_mapping" {
return infraerrors.BadRequest("SCOPED_CODEX_FIELD", "credential_extras 仅支持独立授权的 base_url 和 model_mapping")
}
}
for key, value := range req.Extra {
valid := false
switch key {
case "codex_fingerprint_mode", "openai_oauth_responses_websockets_v2_mode":
_, valid = value.(string)
case "openai_oauth_responses_websockets_v2_enabled":
_, valid = value.(bool)
}
if !valid {
return infraerrors.BadRequest("SCOPED_CODEX_FIELD", "extra 包含不支持的字段或值类型")
}
}
return nil
}
func (h *AccountHandler) scopedAdminImportCodexSession(c *gin.Context) {
var req scopedCodexSessionImportRequest
if c.ShouldBindJSON(&req) != nil {
response.BadRequest(c, "导入请求格式无效")
return
}
if err := validateScopedCodexRequest(req); err != nil {
response.ErrorFrom(c, err)
return
}
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
if err != nil || len(entries) == 0 {
response.BadRequest(c, "请输入有效的 accessToken 或 Codex session JSON")
return
}
api, ok := h.adminService.(service.ScopedAdminCodexAccounts)
if !ok {
response.Error(c, 503, "受限导入服务不可用")
return
}
principal := adminaccess.FromContext(c.Request.Context())
if principal == nil || !adminaccess.RouteAllowed(principal.Policy, c.Request.Method, c.FullPath()) {
response.Error(c, 403, "导入未授权")
return
}
// 隔离完整管理员、不同 Key 和权限修改前后的幂等结果。
policy, _ := json.Marshal(principal.Policy)
digest := sha256.Sum256(policy)
scope := "scoped.codex:" + principal.KeyID + ":" + hex.EncodeToString(digest[:])
executeAdminIdempotentJSON(c, scope, req, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) {
result, err := h.importScopedCodexSessions(ctx, api, req, entries)
if err != nil {
code, message := scopedAdminAccountErrorDetails(err)
return nil, infraerrors.New(code, "SCOPED_CODEX_FAILED", message)
}
return result, nil
})
}
func (h *AccountHandler) importScopedCodexSessions(ctx context.Context, api service.ScopedAdminCodexAccounts, req scopedCodexSessionImportRequest, entries []codexImportEntry) (CodexSessionImportResult, error) {
proxyMode, err := service.NormalizeAccountProxyMode(req.ProxyMode, req.ProxyID, req.RandomProxy)
if err != nil {
return CodexSessionImportResult{}, err
}
result := CodexSessionImportResult{Total: len(entries), Items: make([]CodexSessionImportItem, 0, len(entries))}
updateExisting := req.UpdateExisting == nil || *req.UpdateExisting
seen := map[string]codexSeenIdentity{}
fail := func(entry int, err error) {
_, message := scopedAdminAccountErrorDetails(err)
result.Failed++
result.Items = append(result.Items, CodexSessionImportItem{Index: entry, Action: "failed", Message: message})
result.Errors = append(result.Errors, CodexSessionImportMessage{Index: entry, Message: message})
}
for _, entry := range entries {
item, err := normalizeCodexImportEntry(entry)
if err != nil {
fail(entry.Index, infraerrors.BadRequest("SCOPED_CODEX_PARSE", "认证内容无效"))
continue
}
expires, credentialExpiry, autoPause, warnings, err := resolveCodexImportExpiry(req.CodexSessionImportRequest, item)
if err != nil {
fail(entry.Index, infraerrors.BadRequest("SCOPED_CODEX_EXPIRY", "认证有效期无效"))
continue
}
if credentialExpiry != nil {
item.Credentials["expires_at"] = credentialExpiry.Format(time.RFC3339)
}
if _, duplicate := firstSeenCodexIdentity(seen, item.IdentityKeys, item.UserID); duplicate {
result.Skipped++
result.Items = append(result.Items, CodexSessionImportItem{Index: entry.Index, Action: "skipped", Message: "同批次重复导入项"})
continue
}
markCodexIdentitySeen(seen, item.IdentityKeys, entry.Index, item.UserID)
credentials := mergeCodexImportMap(item.Credentials, req.CredentialExtras)
extra := mergeCodexImportMap(req.Extra, item.Extra)
name := buildCodexCreateAccountName(req.Name, item, entry.Index, len(entries))
var account *service.Account
action := "created"
var existing *service.Account
if updateExisting {
candidates, lookupErr := api.ScopedAdminCodexCandidates(ctx, service.ScopedCodexIdentity{
AccountID: item.AccountID, UserID: item.UserID, Email: item.Email, AccessToken: item.AccessToken,
AccessTokenOnly: item.RefreshToken == "" && item.AccessToken != "", AgentIdentity: item.IsAgentIdentity,
})
if lookupErr != nil {
return result, lookupErr
}
existing, _ = buildCodexAccountIndex(candidates).Find(item.IdentityKeys, item.UserID)
}
if updateExisting && existing != nil {
action = "updated"
input := &service.UpdateAccountInput{ProxyMode: proxyMode, Credentials: credentials, Extra: extra, ProxyID: req.ProxyID, Concurrency: req.Concurrency, Priority: req.Priority, RateMultiplier: req.RateMultiplier, LoadFactor: req.LoadFactor, ExpiresAt: expires, AutoPauseOnExpired: autoPause}
if len(req.GroupIDs) > 0 {
input.GroupIDs = &req.GroupIDs
}
account, err = api.ScopedAdminUpdateCodex(ctx, existing.ID, input, func(current *service.Account, safe *service.UpdateAccountInput) error {
// 锁内重新匹配,不能将候选快照匹配结果应用到已被其他操作换绑的身份。
fresh := buildCodexAccountIndex([]service.Account{*current})
if matched, _ := fresh.Find(item.IdentityKeys, item.UserID); matched == nil {
return infraerrors.Conflict("SCOPED_CODEX_CHANGED", "账户身份已变更")
}
safe.Credentials = mergeCodexImportCredentials(current.Credentials, credentials, item)
safe.Extra = mergeCodexImportMap(current.Extra, extra)
if item.RefreshToken == "" && codexCredentialString(current.Credentials, "refresh_token") != "" {
safe.ExpiresAt = nil
safe.AutoPauseOnExpired = nil
}
return nil
})
} else {
concurrency, priority := 3, 50
if req.Concurrency != nil {
concurrency = *req.Concurrency
}
if req.Priority != nil {
priority = *req.Priority
}
account, err = api.ScopedAdminCreateCodex(ctx, &service.CreateAccountInput{ProxyMode: proxyMode, Name: name, Notes: req.Notes, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: credentials, Extra: extra, GroupIDs: req.GroupIDs, ProxyID: req.ProxyID, Concurrency: concurrency, Priority: priority, RateMultiplier: req.RateMultiplier, LoadFactor: req.LoadFactor, ExpiresAt: expires, AutoPauseOnExpired: autoPause, SkipDefaultGroupBind: true})
}
if err != nil {
fail(entry.Index, err)
continue
}
if action == "updated" {
result.Updated++
h.invalidateScopedAccountToken(ctx, account)
} else {
result.Created++
}
// 不返回候选名称或任何已有凭证,仅返回本次操作结果。
result.Items = append(result.Items, CodexSessionImportItem{Index: entry.Index, Action: action, AccountID: account.ID})
for _, warning := range append(item.WarningTexts, warnings...) {
result.Warnings = append(result.Warnings, CodexSessionImportMessage{Index: entry.Index, Message: warning})
}
}
return result, nil
}
@@ -0,0 +1,249 @@
package admin
import (
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type scopedCodexMemoryService struct {
*codexImportMemoryAdminService
fresh *service.Account
err error
lookups []service.ScopedCodexIdentity
}
func (s *scopedCodexMemoryService) ScopedAdminCodexCandidates(_ context.Context, identity service.ScopedCodexIdentity) ([]service.Account, error) {
s.lookups = append(s.lookups, identity)
return s.accounts, nil
}
func (s *scopedCodexMemoryService) ScopedAdminCreateCodex(ctx context.Context, input *service.CreateAccountInput) (*service.Account, error) {
if s.err != nil {
return nil, s.err
}
return s.CreateAccount(ctx, input)
}
func (s *scopedCodexMemoryService) ScopedAdminUpdateCodex(ctx context.Context, id int64, input *service.UpdateAccountInput, prepare func(*service.Account, *service.UpdateAccountInput) error) (*service.Account, error) {
current := s.fresh
if current == nil {
var err error
current, err = s.GetAccount(ctx, id)
if err != nil {
return nil, err
}
}
if err := prepare(current, input); err != nil {
return nil, err
}
return s.UpdateAccount(ctx, id, input)
}
func TestScopedCodexImportCapturedRequestAndSafeResponse(t *testing.T) {
gin.SetMode(gin.TestMode)
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)}
h := &AccountHandler{adminService: memory}
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{KeyID: "fixture", Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials", "accounts.schedule", "accounts.network"}, AllGroups: true, AccountTypes: []string{"oauth"}}}}})
r := gin.New()
r.Use(func(c *gin.Context) { c.Request = c.Request.WithContext(ctx) })
r.Use(h.ScopedAdminKeyAccounts)
r.POST("/api/v1/admin/accounts/import/codex-session", func(c *gin.Context) { t.Fatal("不能回退到完整管理员导入") })
content := `{"access_token":"private-access-fixture","refresh_token":"private-refresh-fixture","email":"test@example.com"}`
req := map[string]any{"content": content, "name": "推送账户", "notes": "测试", "group_ids": []int64{2, 14}, "concurrency": 40, "priority": 0, "expires_at": nil, "auto_pause_on_expired": true, "proxy_id": nil, "rate_multiplier": 1, "update_existing": true, "extra": map[string]any{"codex_fingerprint_mode": "off", "openai_oauth_responses_websockets_v2_enabled": true, "openai_oauth_responses_websockets_v2_mode": "shared"}}
raw, err := json.Marshal(req)
require.NoError(t, err)
call := func() *httptest.ResponseRecorder {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/api/v1/admin/accounts/import/codex-session", strings.NewReader(string(raw))))
return w
}
w := call()
require.Equal(t, 200, w.Code, w.Body.String())
require.Contains(t, w.Body.String(), `"created":1`)
require.NotContains(t, w.Body.String(), "private-")
require.Len(t, memory.createdAccounts, 1)
input := memory.createdAccounts[0]
require.Equal(t, []int64{2, 14}, input.GroupIDs)
require.Equal(t, 40, input.Concurrency)
require.True(t, input.SkipDefaultGroupBind)
require.Equal(t, "private-refresh-fixture", input.Credentials["refresh_token"])
require.Equal(t, "off", input.Extra["codex_fingerprint_mode"])
memory.err = infraerrors.BadRequest("UPSTREAM_SECRET", "private-refresh-fixture")
// update_existing=false 沿用原接口语义:新建;错误也必须脱敏。
req["update_existing"] = false
raw, err = json.Marshal(req)
require.NoError(t, err)
w = call()
require.Equal(t, 200, w.Code)
require.Contains(t, w.Body.String(), `"failed":1`)
require.NotContains(t, w.Body.String(), "private-")
}
func TestScopedCodexImportRevalidatesIdentityAndMergesFreshCredentials(t *testing.T) {
token := buildCodexAccessToken(t, "account", "user", time.Now().Add(time.Hour))
stale := service.Account{ID: 1, Credentials: map[string]any{"access_token": token, "refresh_token": "stale"}, Extra: map[string]any{"quota_used": 1}}
fresh := stale
fresh.Credentials = map[string]any{"access_token": token, "refresh_token": "latest", "base_url": "https://example.com"}
fresh.Extra = map[string]any{"quota_used": 9}
for _, changed := range []bool{false, true} {
t.Run(map[bool]string{false: "锁内合并", true: "身份已更换"}[changed], func(t *testing.T) {
current := fresh
if changed {
current.Credentials = map[string]any{"access_token": "different", "refresh_token": "other"}
}
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService([]service.Account{stale}), fresh: &current}
h := &AccountHandler{adminService: memory}
req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: token, GroupIDs: []int64{1}}}
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
require.NoError(t, err)
result, err := h.importScopedCodexSessions(context.Background(), memory, req, entries)
require.NoError(t, err)
if changed {
require.Equal(t, 1, result.Failed)
require.Empty(t, memory.updatedAccounts)
return
}
require.Equal(t, 1, result.Updated)
require.Len(t, memory.updatedAccounts, 1)
input := memory.updatedAccounts[0].input
require.Equal(t, "latest", input.Credentials["refresh_token"])
require.Equal(t, "https://example.com", input.Credentials["base_url"])
require.Equal(t, 9, input.Extra["quota_used"])
require.Nil(t, input.ExpiresAt)
require.Nil(t, input.AutoPauseOnExpired)
})
}
}
func TestScopedCodexRequestRejectsUnopenedFields(t *testing.T) {
for _, body := range []string{`{"content":"x"}`, `{"group_ids":[1],"confirm_mixed_channel_risk":true}`, `{"group_ids":[1],"extra":{"quota_used":0}}`, `{"group_ids":[1],"credential_extras":{"refresh_token":"x"}}`, `{"group_ids":[1],"extra":{"openai_oauth_responses_websockets_v2_enabled":"true"}}`} {
var req scopedCodexSessionImportRequest
require.NoError(t, json.Unmarshal([]byte(body), &req))
require.Error(t, validateScopedCodexRequest(req), body)
}
}
func TestScopedCodexImportIdempotencySeparatesKeysAndPolicy(t *testing.T) {
gin.SetMode(gin.TestMode)
previous := service.DefaultIdempotencyCoordinator()
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) })
repo := newMemoryIdempotencyRepoStub()
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)}
h := &AccountHandler{adminService: memory}
principal := &adminaccess.Principal{KeyID: "aaaaaaaaaaaaaaaaaaaaaaaa", Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials", "accounts.schedule", "accounts.network"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}}}
r := gin.New()
r.Use(func(c *gin.Context) {
if principal != nil {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), principal))
}
})
r.Use(h.ScopedAdminKeyAccounts)
r.POST("/api/v1/admin/accounts/import/codex-session", h.ImportCodexSession)
call := func() *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", "/api/v1/admin/accounts/import/codex-session", strings.NewReader(`{"content":"{\"access_token\":\"fixture-access\",\"refresh_token\":\"fixture-refresh\"}","group_ids":[2],"update_existing":false}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "same-import")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, 200, w.Code, w.Body.String())
require.NotContains(t, w.Body.String(), "fixture-")
return w
}
first := call()
require.Len(t, memory.createdAccounts, 1)
replay := call()
require.Equal(t, "true", replay.Header().Get("X-Idempotency-Replayed"))
require.JSONEq(t, first.Body.String(), replay.Body.String())
require.Len(t, memory.createdAccounts, 1)
principal.KeyID = "bbbbbbbbbbbbbbbbbbbbbbbb"
other := call()
require.Empty(t, other.Header().Get("X-Idempotency-Replayed"))
require.Len(t, memory.createdAccounts, 2)
principal.Policy.Rules[0].Permissions = []string{"accounts.create"}
memory.err = infraerrors.Forbidden("SCOPED_CODEX_FORBIDDEN", "权限已收回")
restricted := call()
require.Empty(t, restricted.Header().Get("X-Idempotency-Replayed"))
require.Contains(t, restricted.Body.String(), `"failed":1`)
require.Len(t, memory.createdAccounts, 2)
principal = nil
memory.err = nil
full := call()
require.Empty(t, full.Header().Get("X-Idempotency-Replayed"))
require.Len(t, memory.createdAccounts, 3)
for _, record := range repo.data {
require.LessOrEqual(t, len(record.Scope), 128, "生产数据库 scope 最大长度")
}
}
func TestScopedCodexImportProxyModeForwarding(t *testing.T) {
for _, tc := range []struct {
body, mode string
id int64
}{
{`"proxy_id":7`, "", 7}, {`"proxy_mode":"specified","proxy_id":7`, "specified", 7},
{`"random_proxy":true`, "random", 0}, {`"proxy_mode":"random"`, "random", 0},
{`"proxy_mode":"least_used"`, "least_used", 0}, {`"proxy_mode":"direct"`, "direct", 0},
} {
t.Run(tc.body, func(t *testing.T) {
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)}
h := &AccountHandler{adminService: memory}
var req scopedCodexSessionImportRequest
require.NoError(t, json.Unmarshal([]byte(`{"content":"{\"access_token\":\"fixture\",\"refresh_token\":\"refresh\"}","group_ids":[1],`+tc.body+`}`), &req))
require.NoError(t, validateScopedCodexRequest(req))
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
require.NoError(t, err)
result, err := h.importScopedCodexSessions(context.Background(), memory, req, entries)
require.NoError(t, err)
require.Equal(t, 1, result.Created)
require.Len(t, memory.createdAccounts, 1)
require.Equal(t, tc.mode, memory.createdAccounts[0].ProxyMode)
if tc.id > 0 {
require.Equal(t, tc.id, *memory.createdAccounts[0].ProxyID)
}
})
}
}
func TestScopedCodexImportLooksUpOnlyValidatedEntryIdentity(t *testing.T) {
token := buildCodexAccessToken(t, "workspace", "member", time.Now().Add(time.Hour))
for _, tc := range []struct {
name string
content string
update bool
wantLookups int
wantSkipped int
onlyAccess bool
}{
{"有效身份与批内重复", token + "\n" + token, true, 1, 1, true},
{"无效内容无需读取候选", `{"refresh_token":"fixture"}`, true, 0, 0, false},
{"禁用更新无需读取候选", token, false, 0, 0, true},
{"有refresh保留身份匹配", `{"access_token":"` + token + `","refresh_token":"fixture"}`, true, 1, 0, false},
} {
t.Run(tc.name, func(t *testing.T) {
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)}
req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: tc.content, GroupIDs: []int64{1}, UpdateExisting: &tc.update}}
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
require.NoError(t, err)
result, err := (&AccountHandler{adminService: memory}).importScopedCodexSessions(context.Background(), memory, req, entries)
require.NoError(t, err)
require.Equal(t, tc.wantSkipped, result.Skipped)
require.Len(t, memory.lookups, tc.wantLookups)
if tc.wantLookups > 0 {
lookup := memory.lookups[0]
require.Equal(t, "workspace", lookup.AccountID)
require.Equal(t, "member", lookup.UserID)
require.Equal(t, token, lookup.AccessToken)
require.Equal(t, tc.onlyAccess, lookup.AccessTokenOnly)
}
})
}
}
@@ -0,0 +1,199 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"errors"
"net/http/httptest"
"strings"
"testing"
"time"
"entgo.io/ent/dialect"
entsql "entgo.io/ent/dialect/sql"
"github.com/DATA-DOG/go-sqlmock"
dbent "github.com/Wei-Shaw/sub2api/ent"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type scopedCommitInvalidator struct {
ids []int64
transactionContexts int
}
func (s *scopedCommitInvalidator) InvalidateToken(ctx context.Context, account *service.Account) error {
s.ids = append(s.ids, account.ID)
if dbent.TxFromContext(ctx) != nil {
s.transactionContexts++
}
return nil
}
type scopedCommitAccounts struct {
service.AdminService
fail bool
}
func (*scopedCommitAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]service.Account, int64, error) {
panic("不应查询列表")
}
func (s *scopedCommitAccounts) ScopedAdminWrite(_ context.Context, id int64, _ string, _ map[string]json.RawMessage, _ func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) {
if s.fail {
return nil, errors.New("模拟写入失败")
}
return &service.Account{ID: id, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth}, nil
}
func TestScopedAdminCredentialWritesInvalidateAfterCommit(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, endpoint := range []string{"single", "bulk"} {
for _, mode := range []string{"commit", "rollback", "commit_failure", "write_failure", "name_only"} {
t.Run(endpoint+"/"+mode, func(t *testing.T) {
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer db.Close()
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
mock.ExpectBegin()
tx, err := client.Tx(context.Background())
require.NoError(t, err)
ctx := dbent.NewTxContext(context.Background(), tx)
ctx = adminaccess.WithPrincipal(ctx, &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.credentials"}, AllGroups: true}}}})
cache := &scopedCommitInvalidator{}
h := &AccountHandler{adminService: &scopedCommitAccounts{fail: mode == "write_failure"}, tokenCacheInvalidator: cache}
r := gin.New()
r.Use(func(c *gin.Context) { c.Request = c.Request.WithContext(ctx) })
r.Use(h.ScopedAdminKeyAccounts)
r.PUT("/api/v1/admin/accounts/:id", func(*gin.Context) { t.Fatal("不得进入完整管理员处理器") })
r.POST("/api/v1/admin/accounts/bulk-update", func(*gin.Context) { t.Fatal("不得进入完整管理员处理器") })
method, path, body := "PUT", "/api/v1/admin/accounts/7", `{"credentials":{"access_token":"fixture"}}`
if mode == "name_only" {
body = `{"name":"新名称"}`
}
if endpoint == "bulk" {
method, path = "POST", "/api/v1/admin/accounts/bulk-update"
body = `{"account_ids":[7],` + body[1:]
}
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
want := 200
if mode == "write_failure" && endpoint == "single" {
want = 503
}
require.Equal(t, want, w.Code, w.Body.String())
require.Empty(t, cache.ids, "事务提交前不得使令牌缓存失效")
if mode == "rollback" || mode == "write_failure" {
mock.ExpectRollback()
require.NoError(t, tx.Rollback())
} else if mode == "commit_failure" {
mock.ExpectCommit().WillReturnError(errors.New("提交失败"))
require.Error(t, tx.Commit())
} else {
mock.ExpectCommit()
require.NoError(t, tx.Commit())
}
if mode == "commit" {
require.Equal(t, []int64{7}, cache.ids)
} else {
require.Empty(t, cache.ids)
}
require.Zero(t, cache.transactionContexts, "提交后的缓存清理不能携带已关闭事务")
require.NoError(t, mock.ExpectationsWereMet())
})
}
}
}
type scopedRefreshPrivacyService struct {
*stubAdminService
privacy int
}
func (s *scopedRefreshPrivacyService) EnsureOpenAIPrivacy(context.Context, *service.Account) string {
s.privacy++
return ""
}
func (s *scopedRefreshPrivacyService) EnsureAntigravityPrivacy(context.Context, *service.Account) string {
s.privacy++
return ""
}
func TestScopedAdminRefreshFailureDoesNotTriggerPrivacyBeforeRollback(t *testing.T) {
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer db.Close()
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
mock.ExpectBegin()
tx, err := client.Tx(context.Background())
require.NoError(t, err)
svc := &scopedRefreshPrivacyService{stubAdminService: newStubAdminService()}
h := &AccountHandler{adminService: svc, openaiOAuthService: service.NewOpenAIOAuthService(nil, nil)}
_, _, err = h.refreshSingleAccount(dbent.NewTxContext(context.Background(), tx), &service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth})
require.Error(t, err)
require.Zero(t, svc.privacy, "刷新失败导致回滚时,不应提前调用上游隐私接口")
mock.ExpectRollback()
require.NoError(t, tx.Rollback())
require.Zero(t, svc.privacy)
require.NoError(t, mock.ExpectationsWereMet())
// 完整管理员没有外层事务,沿用原刷新失败后的隐私检查行为。
_, _, err = h.refreshSingleAccount(context.Background(), &service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth})
require.Error(t, err)
require.Equal(t, 1, svc.privacy)
}
func TestScopedAdminCodexUpdatesInvalidateOnlyAfterCommit(t *testing.T) {
for _, mode := range []string{"commit", "rollback", "commit_failure", "identity_changed"} {
t.Run(mode, func(t *testing.T) {
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer db.Close()
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
mock.ExpectBegin()
tx, err := client.Tx(context.Background())
require.NoError(t, err)
token := buildCodexAccessToken(t, "account", "user", time.Now().Add(time.Hour))
existing := service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": token, "auth_mode": service.OpenAIAuthModePersonalAccessToken}}
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService([]service.Account{existing})}
if mode == "identity_changed" {
memory.fresh = &service.Account{ID: 7, Credentials: map[string]any{"access_token": "changed-private"}}
}
cache := &scopedCommitInvalidator{}
h := &AccountHandler{adminService: memory, tokenCacheInvalidator: cache}
req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: token, GroupIDs: []int64{1}}}
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
require.NoError(t, err)
result, err := h.importScopedCodexSessions(dbent.NewTxContext(context.Background(), tx), memory, req, entries)
require.NoError(t, err)
require.Empty(t, cache.ids)
if mode == "rollback" || mode == "identity_changed" {
mock.ExpectRollback()
require.NoError(t, tx.Rollback())
} else if mode == "commit_failure" {
mock.ExpectCommit().WillReturnError(errors.New("提交失败"))
require.Error(t, tx.Commit())
} else {
mock.ExpectCommit()
require.NoError(t, tx.Commit())
}
if mode == "commit" {
require.Equal(t, []int64{7}, cache.ids)
} else {
require.Empty(t, cache.ids)
}
if mode == "identity_changed" {
require.Equal(t, 1, result.Failed)
} else {
require.Equal(t, 1, result.Updated)
require.Equal(t, service.OpenAIAuthModePersonalAccessToken, memory.updatedAccounts[0].input.Credentials["auth_mode"])
}
require.Zero(t, cache.transactionContexts)
require.NoError(t, mock.ExpectationsWereMet())
})
}
}
@@ -0,0 +1,176 @@
package admin
import (
"bytes"
"context"
"encoding/json"
"net/http"
"slices"
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
func scopedAdminGroupModelsDTO(g *service.Group) gin.H {
return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "status": g.Status, "model_allowlist": g.ModelAllowlist}
}
// ScopedAdminKeyGroupModels 接管分组模型接口,禁止复用可修改费率等字段的完整处理器。
func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) {
p := adminaccess.RestrictedFromContext(c.Request.Context())
if p == nil {
return
}
base := "/api/v1/admin/groups/:id"
path := c.FullPath()
fullRead := slices.Contains(p.Policy.GlobalPermissions, "groups.read")
if c.Request.Method == http.MethodGet && (path == "/api/v1/admin/groups" || path == "/api/v1/admin/groups/all") {
if fullRead {
return
}
c.Abort()
h.scopedAdminListGroupModels(c)
return
}
// 完整分组读取继续沿用原处理器的简易模式响应。
if fullRead && path == base && c.Request.Method == http.MethodGet && h.isSimpleMode() {
return
}
candidates := path == base+"/model-allowlist-candidates"
if !candidates && path != base {
return
}
c.Abort()
if h.rejectUnsupportedSimpleModeOperation(c, "advanced") {
return
}
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || id < 0 || (id == 0 && !candidates) {
response.BadRequest(c, "分组 ID 无效")
return
}
if candidates && c.Request.Method == http.MethodGet && id == 0 {
if !slices.Contains(p.Policy.GlobalPermissions, "models.defaults.read") {
response.Error(c, 403, "默认模型读取未授权")
return
}
h.GetGroupModelAllowlistCandidates(c)
return
}
g, err := h.adminService.GetGroup(c.Request.Context(), id)
if err != nil || g == nil {
response.Error(c, 404, "分组不存在")
return
}
permission := "groups.models.read"
if c.Request.Method == http.MethodPut {
permission = "groups.models.write"
}
basicRead := c.Request.Method == http.MethodGet && path == base && p.Policy.AllowsGroupConfig("groups.list.read", g.ID, g.Platform)
allowed := basicRead || p.Policy.AllowsGroupConfig(permission, g.ID, g.Platform) || (c.Request.Method == http.MethodGet && fullRead)
if !allowed {
response.Error(c, 404, "分组不存在")
return
}
if c.Request.Method == http.MethodGet {
if candidates {
if platform := strings.TrimSpace(c.Query("platform")); platform != "" && platform != g.Platform {
response.BadRequest(c, "候选模型平台必须与分组一致")
return
}
h.GetGroupModelAllowlistCandidates(c)
return
}
if fullRead {
response.Success(c, dto.GroupFromServiceAdmin(g))
} else {
response.Success(c, scopedAdminGroupReadDTO(g, p.Policy))
}
return
}
if c.Request.Method != http.MethodPut || candidates {
response.Error(c, 403, "此分组操作未开放给受限管理密钥")
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 65536)
var fields map[string]json.RawMessage
if c.ShouldBindJSON(&fields) != nil || len(fields) != 1 {
response.BadRequest(c, "仅支持单独提交 model_allowlist")
return
}
raw := fields["model_allowlist"]
var cfg *service.GroupModelAllowlist
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.DisallowUnknownFields()
if decoder.Decode(&cfg) != nil || cfg == nil {
response.BadRequest(c, "模型白名单格式无效")
return
}
api, ok := h.adminService.(interface {
ScopedAdminUpdateGroupModels(context.Context, int64, service.GroupModelAllowlist) (*service.Group, error)
})
if !ok {
response.Error(c, 503, "受限分组模型服务不可用")
return
}
updated, err := api.ScopedAdminUpdateGroupModels(c.Request.Context(), id, *cfg)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, scopedAdminGroupModelsDTO(updated))
}
func (h *GroupHandler) scopedAdminListGroupModels(c *gin.Context) {
if h.rejectUnsupportedSimpleModeOperation(c, "advanced") {
return
}
api, ok := h.adminService.(interface {
ScopedAdminListGroupModels(context.Context, pagination.PaginationParams, bool, string, string, string) ([]service.Group, int64, error)
})
if !ok {
response.Error(c, 503, "受限分组模型服务不可用")
return
}
page, size := response.ParsePagination(c)
all := strings.HasSuffix(c.FullPath(), "/all")
status := c.Query("status")
if all {
status = service.StatusActive
if c.Query("include_inactive") == "true" {
status = ""
}
}
search := strings.TrimSpace(c.Query("search"))
if len(search) > 100 {
search = search[:100]
}
groups, total, err := api.ScopedAdminListGroupModels(c.Request.Context(), pagination.PaginationParams{Page: page, PageSize: size}, all, c.Query("platform"), status, search)
if err != nil {
response.ErrorFrom(c, err)
return
}
out := make([]gin.H, 0, len(groups))
for i := range groups {
out = append(out, scopedAdminGroupReadDTO(&groups[i], adminaccess.FromContext(c.Request.Context()).Policy))
}
if all {
response.Success(c, out)
} else {
response.Paginated(c, out, total, page, size)
}
}
// 基本分组读取不能隐式获得模型配置。
func scopedAdminGroupReadDTO(g *service.Group, policy adminaccess.Policy) gin.H {
if policy.AllowsGroupConfig("groups.models.read", g.ID, g.Platform) {
return scopedAdminGroupModelsDTO(g)
}
return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "status": g.Status}
}
@@ -0,0 +1,30 @@
//go:build unit
package admin
import (
"context"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"net/http/httptest"
"testing"
)
func TestAdminFullAccessIdempotencyScopeIsolation(t *testing.T) {
scope := func(p *adminaccess.Principal) string {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("POST", "/", nil)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9})
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(context.Background(), p))
return adminActorScope(c)
}
jwt := scope(nil)
full := scope(&adminaccess.Principal{KeyID: "one", Policy: adminaccess.Policy{FullAccess: true}})
restricted := scope(&adminaccess.Principal{KeyID: "one", Policy: adminaccess.Policy{}})
other := scope(&adminaccess.Principal{KeyID: "two", Policy: adminaccess.Policy{FullAccess: true}})
require.NotEqual(t, jwt, full)
require.NotEqual(t, full, restricted)
require.NotEqual(t, full, other)
}
@@ -0,0 +1,109 @@
package admin
import (
"strconv"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
func (h *OpenAIOAuthHandler) scopedOpenAIAllowed(c *gin.Context, id int64, action string, parent bool) bool {
if adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return true
}
_, ok := scopedAuthorizedAccount(c, h.adminService, id, action, parent)
return ok
}
func (h *OpenAIOAuthHandler) scopedOpenAIHasPermission(c *gin.Context, id int64, action string, parent bool) bool {
p := adminaccess.RestrictedFromContext(c.Request.Context())
if p == nil {
return true
}
if h.adminService == nil {
return false
}
a, err := h.adminService.GetAccount(c.Request.Context(), id)
if err != nil || a == nil || !p.Policy.AllowsAccount(action, scopedAccountResource(a)) {
return false
}
if parent && a.IsShadow() {
if a.ParentAccountID == nil {
return false
}
source, err := h.adminService.GetAccount(c.Request.Context(), *a.ParentAccountID)
return err == nil && source != nil && !source.IsShadow() && p.Policy.AllowsAccount(action, scopedAccountResource(source))
}
return true
}
func scopedOpenAIError(c *gin.Context, err error) {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
scopedAdminAccountError(c, err)
return
}
response.ErrorFrom(c, err)
}
func (h *OpenAIOAuthHandler) scopedQuotaDTO(c *gin.Context, id int64, u *service.OpenAIQuotaUsage) *service.OpenAIQuotaUsage {
if u == nil {
return nil
}
safe := *u
p := adminaccess.RestrictedFromContext(c.Request.Context())
if p == nil {
return &safe
}
identity := h.scopedOpenAIHasPermission(c, id, "accounts.identity.read", true)
if !identity {
safe.UserID = ""
safe.AccountID = ""
safe.Email = ""
safe.PlanType = ""
}
return &safe
}
func (h *OpenAIOAuthHandler) scopedOpenAIQuota(c *gin.Context, refresh bool) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || id <= 0 {
response.BadRequest(c, "账户 ID 无效")
return
}
if !h.scopedOpenAIAllowed(c, id, "openai.quota.read", true) {
return
}
if h.quotaService == nil {
response.Error(c, 503, "账户额度服务不可用")
return
}
u, err := h.quotaService.QueryUsage(c.Request.Context(), id)
if err != nil {
scopedOpenAIError(c, err)
return
}
if u == nil {
response.Error(c, 502, "账户额度查询失败")
return
}
safe := h.scopedQuotaDTO(c, id, u)
// 读取只更新展示快照,绝不通知可能消耗重置次数的自动任务。
if !refresh {
response.Success(c, safe)
return
}
result := openAIQuotaRefreshResponse{OpenAIQuotaUsage: *safe}
result.CreditsCachePersisted = h.quotaService.CacheCreditsSnapshot(c.Request.Context(), id, safe) == nil
result.CachePersisted = h.quotaService.CacheResetCreditsSnapshot(c.Request.Context(), id, safe.RateLimitResetCredits) == nil
response.Success(c, result)
}
func (h *OpenAIOAuthHandler) scopedReferralDTO(c *gin.Context, e *service.OpenAIReferralEligibility) *service.OpenAIReferralEligibility {
if e == nil || adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return e
}
// 邀请资格只展示容量和流程字段,不回传上游自由文本及收件人资料。
return &service.OpenAIReferralEligibility{ShouldShow: e.ShouldShow, RemainingSendCapacity: e.RemainingSendCapacity, RemainingRewardCapacity: e.RemainingRewardCapacity, RequiresExplicitConfirmation: e.RequiresExplicitConfirmation, OfferID: e.OfferID, ProgramID: e.ProgramID, AvailableInvites: e.AvailableInvites, FetchedAt: e.FetchedAt}
}
@@ -0,0 +1,175 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type permissionsProxyService struct {
service.AdminService
proxy *service.Proxy
}
func (s *permissionsProxyService) GetProxy(context.Context, int64) (*service.Proxy, error) {
return s.proxy, nil
}
func TestScopedAdminPermissionsRefreshRejectsUnavailableProxyBeforeNetwork(t *testing.T) {
gin.SetMode(gin.TestMode)
expired := time.Now().Add(-time.Hour)
for _, proxy := range []*service.Proxy{nil, {Status: "inactive"}, {Status: "active", ExpiresAt: &expired}} {
h := &OpenAIOAuthHandler{adminService: &permissionsProxyService{proxy: proxy}}
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"openai.tokens.refresh"}}}))
})
r.POST("/api/v1/admin/openai/refresh-token", h.RefreshToken)
req := httptest.NewRequest("POST", "/api/v1/admin/openai/refresh-token", strings.NewReader(`{"refresh_token":"TEST_SECRET","proxy_id":14}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, 400, w.Code)
require.NotContains(t, w.Body.String(), "SECRET")
}
}
type scopedPermissionAccountService struct {
scopedBulkAccountService
listGroupID int64
}
func (s *scopedPermissionAccountService) ScopedAdminList(_ context.Context, _ pagination.PaginationParams, _, _, _, _ string, groupID int64) ([]service.Account, int64, error) {
s.listGroupID = groupID
return []service.Account{{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}, 1, nil
}
func TestScopedAdminPermissionPaginationContract(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name, query string
groupID int64
invalid bool
}{
{"无筛选", "page=1&page_size=100", 0, false},
{"空分组", "group=", 0, false},
{"补号前全局查重", "platform=openai&type=oauth&status=&group=&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 0, false},
{"监控分组", "platform=openai&type=oauth&status=&group=2&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 2, false},
{"查询限流账户", "platform=openai&type=oauth&status=rate_limited&group=2&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 2, false},
{"未分组", "group=-1", -1, false},
{"非法负数", "group=-2", 0, true},
{"非法文本", "group=invalid", 0, true},
{"空白字符", "group=%20", 0, true},
{"溢出数值", "group=9999999999999999999999", 0, true},
} {
t.Run(tc.name, func(t *testing.T) {
r := gin.New()
svc := &scopedPermissionAccountService{listGroupID: -99}
h := &AccountHandler{adminService: svc}
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}}}))
})
r.Use(h.ScopedAdminKeyAccounts)
r.GET("/api/v1/admin/accounts", func(c *gin.Context) { t.Fatal("不应调用全权处理器") })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts?"+tc.query, nil))
if tc.invalid {
require.Equal(t, 400, w.Code, w.Body.String())
require.Equal(t, int64(-99), svc.listGroupID, "无效筛选不能触达账户查询")
return
}
require.Equal(t, 200, w.Code, "账户查询失败(HTTP %d):%s", w.Code, w.Body.String())
require.Equal(t, tc.groupID, svc.listGroupID)
var body struct {
Data map[string]any `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, float64(1), body.Data["pages"], "标准分页必须包含 pages")
require.Equal(t, float64(1), body.Data["page"])
})
}
}
func (s *scopedPermissionAccountService) GetAccount(context.Context, int64) (*service.Account, error) {
return &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2, 3}, Credentials: map[string]any{"email": "test@example.com", "plan_type": "plus", "access_token": "SECRET"}, Extra: map[string]any{"email": "test@example.com", "codex_usage_updated_at": "2026-10-24T00:00:00Z", "codex_7d_used_percent": 100, "codex_7d_reset_at": "2026-10-30T00:00:00Z", "private": "SECRET"}}, nil
}
func TestScopedAdminPermissionIdentityAndUsageAreIndependent(t *testing.T) {
for _, permissions := range [][]string{{"accounts.read"}, {"accounts.read", "accounts.identity.read"}, {"accounts.read", "accounts.usage.read"}, {"accounts.read", "accounts.identity.read", "accounts.usage.read"}} {
r := gin.New()
policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: permissions, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}
h := &AccountHandler{adminService: &scopedPermissionAccountService{}}
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy}))
})
r.Use(h.ScopedAdminKeyAccounts)
r.GET("/api/v1/admin/accounts/:id", func(c *gin.Context) { t.Fatal("不能调用全权读取") })
r.GET("/api/v1/admin/accounts/:id/usage", func(c *gin.Context) { t.Fatal("不能绕过额度授权") })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1", nil))
require.Equal(t, 200, w.Code)
require.NotContains(t, w.Body.String(), "SECRET")
require.Contains(t, w.Body.String(), `"group_ids":[2]`)
a := adminaccess.Account{ID: 1, GroupIDs: []int64{2}, Type: "oauth", Platform: "openai"}
require.Equal(t, policy.AllowsAccount("accounts.identity.read", a), strings.Contains(w.Body.String(), "test@example.com"))
require.Equal(t, policy.AllowsAccount("accounts.usage.read", a), strings.Contains(w.Body.String(), "codex_7d_used_percent"))
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1/usage?source=active&force=true", nil))
want := 404
if policy.AllowsAccount("accounts.usage.read", a) {
want = 503
} // 已授权才会触达尚未接线的额度服务。
require.Equal(t, want, w.Code)
policy.Rules[0].GroupIDs = []int64{99}
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1/usage", nil))
require.Equal(t, 404, w.Code)
}
}
type scopedBasicGroupService struct{ service.AdminService }
func (*scopedBasicGroupService) GetGroup(context.Context, int64) (*service.Group, error) {
return &service.Group{ID: 1, Name: "基本组", Platform: "openai", Status: "active"}, nil
}
func TestScopedAdminBasicGroupReadDoesNotReturnModels(t *testing.T) {
policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.list.read"}, GroupIDs: []int64{1}, Platforms: []string{"openai"}}}}
h := &GroupHandler{adminService: &scopedBasicGroupService{}}
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy}))
})
r.Use(h.ScopedAdminKeyGroupModels)
r.GET("/api/v1/admin/groups/:id", func(c *gin.Context) { t.Fatal("不能调用完整处理器") })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/groups/1", nil))
require.Equal(t, 200, w.Code, w.Body.String())
require.JSONEq(t, `{"code":0,"message":"success","data":{"id":1,"name":"基本组","platform":"openai","status":"active"}}`, w.Body.String())
}
func TestScopedAdminPermissionRefreshRejectsMissingGlobalGrant(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, policy := range []adminaccess.Policy{{}, {Rules: []adminaccess.Rule{{Permissions: []string{"accounts.refresh"}, AllGroups: true, AccountTypes: []string{"oauth"}}}}} {
h := &OpenAIOAuthHandler{}
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy}))
})
r.POST("/api/v1/admin/openai/refresh-token", h.RefreshToken)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/api/v1/admin/openai/refresh-token", strings.NewReader(`{"refresh_token":"SECRET"}`)))
require.Equal(t, 403, w.Code)
require.NotContains(t, w.Body.String(), "SECRET")
}
}
@@ -0,0 +1,163 @@
package admin
import (
"context"
"fmt"
"slices"
"strconv"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// scopedProxyOption 显式列出可公开字段,不能复用含用户名、密码的管理 DTO。
type scopedProxyOption struct {
ID int64 `json:"id"`
Name string `json:"name"`
Protocol string `json:"protocol"`
Host string `json:"host"`
Port int `json:"port"`
Status string `json:"status"`
ExpiresAt *time.Time `json:"expires_at"`
}
func scopedProxyDTO(p service.Proxy) scopedProxyOption {
return scopedProxyOption{ID: p.ID, Name: p.Name, Protocol: p.Protocol, Host: p.Host, Port: p.Port, Status: p.Status, ExpiresAt: p.ExpiresAt}
}
// scopedAdminProxyRead 对代理读取限定数量;无分页的 /all 从全池抽样。
func (h *ProxyHandler) scopedAdminProxyRead(c *gin.Context) bool {
principal := adminaccess.RestrictedFromContext(c.Request.Context())
if principal == nil {
return false
}
if !slices.Contains(principal.Policy.GlobalPermissions, "proxies.read") {
response.Error(c, 403, "代理读取未授权")
return true
}
if raw := c.Param("id"); raw != "" {
id, err := strconv.ParseInt(raw, 10, 64)
if err != nil || id < 1 {
response.BadRequest(c, "代理 ID 无效")
return true
}
p, err := h.adminService.GetProxy(c.Request.Context(), id)
if err != nil || p == nil {
response.Error(c, 404, "代理不存在")
return true
}
response.Success(c, scopedProxyDTO(*p))
return true
}
page, size := 1, 50
for key, dest := range map[string]*int{"page": &page, "page_size": &size} {
if raw, ok := c.GetQuery(key); ok {
n, err := strconv.Atoi(raw)
if err != nil || n < 1 || n > 1000000 {
response.BadRequest(c, "分页参数必须为正整数且不超过 1000000")
return true
}
*dest = n
}
}
if size > 100 {
size = 100
}
var proxies []service.Proxy
var total int64
var err error
if raw, ok := c.Request.URL.Query()["ids"]; ok {
ids := []int64{}
for _, part := range strings.Split(strings.Join(raw, ","), ",") {
if strings.TrimSpace(part) == "" {
continue
}
id, e := strconv.ParseInt(strings.TrimSpace(part), 10, 64)
if e != nil || id < 1 {
response.BadRequest(c, "代理 ID 无效")
return true
}
if !slices.Contains(ids, id) {
ids = append(ids, id)
}
if len(ids) > 100 {
response.BadRequest(c, "一次最多读取 100 个已选代理")
return true
}
}
if len(ids) > 0 {
proxies, err = h.adminService.GetProxiesByIDs(c.Request.Context(), ids)
}
// 最多 100 个 ID 的回显按实际存在的记录分页,保留请求顺序。
byID := make(map[int64]service.Proxy, len(proxies))
for _, p := range proxies {
byID[p.ID] = p
}
proxies = nil
for _, id := range ids {
if p, ok := byID[id]; ok {
proxies = append(proxies, p)
}
}
total = int64(len(proxies))
start := (page - 1) * size
if start < len(proxies) {
proxies = proxies[start:min(start+size, len(proxies))]
} else {
proxies = nil
}
} else {
search := strings.TrimSpace(c.Query("search"))
if len(search) > 100 {
response.BadRequest(c, "搜索关键词不能超过 100 字节")
return true
}
query := c.Request.URL.Query()
if strings.HasSuffix(c.FullPath(), "/proxies/all") && !query.Has("page") && !query.Has("page_size") {
sampler, ok := h.adminService.(interface {
SampleProxyOptions(context.Context, string) ([]service.Proxy, int64, error)
})
if !ok {
response.Error(c, 503, "代理查询暂不可用")
return true
}
proxies, total, err = sampler.SampleProxyOptions(c.Request.Context(), search)
// 旧客户端重复加载时必须重新抽样,不能复用上一次缓存的候选。
c.Header("Cache-Control", "no-store")
} else {
proxies, total, err = scopedProxyOptions(c.Request.Context(), h.adminService, page, size, search)
}
}
if err != nil {
response.Error(c, 503, "代理查询暂不可用")
return true
}
out := make([]scopedProxyOption, 0, min(len(proxies), size))
for _, p := range proxies[:min(len(proxies), size)] {
out = append(out, scopedProxyDTO(p))
}
if strings.HasSuffix(c.FullPath(), "/proxies/all") {
c.Header("X-Total-Count", strconv.FormatInt(total, 10))
c.Header("X-Page", strconv.Itoa(page))
c.Header("X-Page-Size", strconv.Itoa(size))
c.Header("X-Total-Pages", strconv.FormatInt((total+int64(size)-1)/int64(size), 10))
response.Success(c, out)
} else {
response.Paginated(c, out, total, page, size)
}
return true
}
func scopedProxyOptions(ctx context.Context, admin service.AdminService, page, size int, search string) ([]service.Proxy, int64, error) {
api, ok := admin.(interface {
ListProxyOptions(context.Context, int, int, string) ([]service.Proxy, int64, error)
})
if !ok {
return nil, 0, fmt.Errorf("代理查询不可用")
}
return api.ListProxyOptions(ctx, page, size, search)
}
@@ -0,0 +1,198 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type scopedProxyReadTestService struct {
service.AdminService
page, size, calls int
ids []int64
}
func (s *scopedProxyReadTestService) ListProxyOptions(_ context.Context, page, size int, _ string) ([]service.Proxy, int64, error) {
s.page = page
s.size = size
s.calls++
items := make([]service.Proxy, size)
for i := range items {
items[i] = service.Proxy{ID: int64((page-1)*size + i + 1), Host: "192.0.2.1", Username: "secret-user", Password: "secret-password", Status: service.StatusActive}
}
return items, 20001, nil
}
func (s *scopedProxyReadTestService) GetProxiesByIDs(_ context.Context, ids []int64) ([]service.Proxy, error) {
s.ids = ids
s.calls++
items := []service.Proxy{}
for _, id := range ids {
if id == 999 {
continue
}
items = append(items, service.Proxy{ID: id, Username: "secret-user", Password: "secret-password"})
}
return items, nil
}
func (s *scopedProxyReadTestService) GetProxy(_ context.Context, id int64) (*service.Proxy, error) {
s.calls++
return &service.Proxy{ID: id, Username: "secret-user", Password: "secret-password"}, nil
}
func TestScopedProxyReadBoundedPaginationAndProjection(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
query string
status, page, size, count int
}{
{"", 200, 1, 50, 50}, {"?page=2&page_size=50000", 200, 2, 100, 100}, {"?page=201&page_size=100", 200, 201, 100, 100},
{"?page=-1", 400, 0, 0, 0}, {"?page_size=0", 400, 0, 0, 0}, {"?page_size=no", 400, 0, 0, 0}, {"?page=999999999999999999999", 400, 0, 0, 0},
{"?ids=1,2,3&page=2&page_size=2", 200, 2, 2, 1}, {"?ids=", 200, 1, 50, 0},
{"?ids=999,1&page_size=1", 200, 1, 1, 1}, {"?ids=1,2,2&page=4&page_size=1", 200, 4, 1, 0},
} {
t.Run(tc.query, func(t *testing.T) {
svc := &scopedProxyReadTestService{}
h := NewProxyHandler(svc)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"proxies.read"}}}))
})
r.GET("/proxies", h.List)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies"+tc.query, nil))
require.Equal(t, tc.status, w.Code, w.Body.String())
require.NotContains(t, w.Body.String(), "secret-")
require.NotContains(t, w.Body.String(), "username")
require.NotContains(t, w.Body.String(), "password")
if tc.status != 200 {
require.Zero(t, svc.calls)
return
}
var body struct {
Data struct {
Items []map[string]any `json:"items"`
Page int `json:"page"`
PageSize int `json:"page_size"`
Total int64 `json:"total"`
}
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, tc.page, body.Data.Page)
require.Equal(t, tc.size, body.Data.PageSize)
require.Len(t, body.Data.Items, tc.count)
if strings.Contains(tc.query, "ids=999,1") {
require.EqualValues(t, 1, body.Data.Total)
require.EqualValues(t, 1, body.Data.Items[0]["id"])
}
if strings.Contains(tc.query, "ids=1,2,3") {
require.Equal(t, []int64{1, 2, 3}, svc.ids)
}
})
}
}
func TestScopedProxyReadRejectsLargeIDBatchAndRequiresPermission(t *testing.T) {
for _, allowed := range []bool{false, true} {
svc := &scopedProxyReadTestService{}
h := NewProxyHandler(svc)
r := gin.New()
p := &adminaccess.Principal{}
if allowed {
p.Policy.GlobalPermissions = []string{"proxies.read"}
}
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(context.Background(), p))
})
r.GET("/proxies", h.GetAll)
r.GET("/proxies/:id", h.GetByID)
ids := []string{}
for i := 1; i <= 101; i++ {
ids = append(ids, strconv.Itoa(i))
}
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies?ids="+strings.Join(ids, ","), nil))
if allowed {
require.Equal(t, 400, w.Code)
} else {
require.Equal(t, 403, w.Code)
}
require.Zero(t, svc.calls)
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies/1", nil))
if allowed {
require.Equal(t, 200, w.Code)
require.NotContains(t, w.Body.String(), "secret-")
require.NotContains(t, w.Body.String(), "username")
} else {
require.Equal(t, 403, w.Code)
}
}
}
type scopedProxySampleTestService struct {
scopedProxyReadTestService
samples int
search string
}
func (s *scopedProxySampleTestService) SampleProxyOptions(_ context.Context, search string) ([]service.Proxy, int64, error) {
s.samples++
s.search = search
return []service.Proxy{{ID: 12345, Host: "192.0.2.1", Username: "secret-user", Password: "secret-password"}}, 20000, nil
}
func TestScopedProxyAllSamplesOnlyWithoutPagination(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
path, query string
sample bool
status int
}{
{"/api/v1/admin/proxies/all", "", true, 200},
{"/api/v1/admin/proxies/all", "?search=region", true, 200},
{"/api/v1/admin/proxies/all", "?page=1", false, 200},
{"/api/v1/admin/proxies/all", "?page_size=100", false, 200},
{"/api/v1/admin/proxies/all", "?page=", false, 400},
{"/api/v1/admin/proxies/all", "?ids=1,2", false, 200},
{"/api/v1/admin/proxies", "", false, 200},
} {
t.Run(tc.path+tc.query, func(t *testing.T) {
svc := &scopedProxySampleTestService{}
h := NewProxyHandler(svc)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"proxies.read"}}}))
})
r.GET("/api/v1/admin/proxies/all", h.GetAll)
r.GET("/api/v1/admin/proxies", h.List)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", tc.path+tc.query, nil))
require.Equal(t, tc.status, w.Code, w.Body.String())
if tc.sample {
require.Equal(t, 1, svc.samples)
require.Zero(t, svc.calls)
require.Contains(t, w.Body.String(), `"data":[`)
require.Contains(t, w.Body.String(), `"id":12345`)
require.Equal(t, "20000", w.Header().Get("X-Total-Count"))
require.Equal(t, "50", w.Header().Get("X-Page-Size"))
require.Equal(t, "no-store", w.Header().Get("Cache-Control"))
if tc.query != "" {
require.Equal(t, "region", svc.search)
}
} else {
require.Zero(t, svc.samples)
}
require.NotContains(t, w.Body.String(), "secret-")
require.NotContains(t, w.Body.String(), "password")
})
}
}
@@ -0,0 +1,233 @@
package admin
import (
"context"
"slices"
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
type scopedAccountReader interface {
GetAccount(context.Context, int64) (*service.Account, error)
}
func scopedAccountResource(a *service.Account) adminaccess.Account {
return adminaccess.Account{ID: a.ID, GroupIDs: a.GroupIDs, Platform: a.Platform, Type: a.Type}
}
// 仅校验实际读取对象;上游凭证来自母账户时,母账户必须同时获授权。
func scopedAuthorizedAccount(c *gin.Context, reader scopedAccountReader, id int64, action string, parent bool) (*service.Account, bool) {
p := adminaccess.RestrictedFromContext(c.Request.Context())
if p == nil {
return nil, true
}
if reader == nil || id <= 0 {
response.Error(c, 404, "账户不存在")
return nil, false
}
a, err := reader.GetAccount(c.Request.Context(), id)
if err != nil || a == nil || !p.Policy.AllowsAccount(action, scopedAccountResource(a)) {
response.Error(c, 404, "账户不存在")
return nil, false
}
if parent && a.IsShadow() {
if a.ParentAccountID == nil || *a.ParentAccountID == id {
response.Error(c, 404, "账户不存在")
return nil, false
}
source, err := reader.GetAccount(c.Request.Context(), *a.ParentAccountID)
if err != nil || source == nil || source.IsShadow() || !p.Policy.AllowsAccount(action, scopedAccountResource(source)) {
response.Error(c, 404, "账户不存在")
return nil, false
}
}
return a, true
}
func (h *AccountHandler) scopedAdminStatistics(c *gin.Context) bool {
path := strings.TrimPrefix(c.FullPath(), "/api/v1/admin/accounts")
action := ""
switch {
case c.Request.Method == "GET" && (path == "/:id/today-stats" || path == "/:id/stats"):
action = "accounts.stats.read"
case c.Request.Method == "GET" && path == "/:id/usage":
action = "accounts.usage.read"
case c.Request.Method == "POST" && path == "/today-stats/batch":
action = "accounts.stats.read"
case c.Request.Method == "POST" && path == "/usage/batch":
action = "accounts.usage.read"
default:
return false
}
if strings.HasSuffix(path, "/batch") {
var req BatchUsageRequest
if c.ShouldBindJSON(&req) != nil || len(req.AccountIDs) == 0 || len(req.AccountIDs) > 100 {
response.BadRequest(c, "请明确指定 1 至 100 个账户 ID")
return true
}
ids := make([]int64, 0, len(req.AccountIDs))
accounts := map[int64]*service.Account{}
for _, id := range req.AccountIDs {
if id <= 0 {
response.BadRequest(c, "账户 ID 无效")
return true
}
if slices.Contains(ids, id) {
continue
}
a, ok := scopedAuthorizedAccount(c, h.adminService, id, action, action == "accounts.usage.read")
if !ok {
return true
}
ids = append(ids, id)
accounts[id] = a
}
if h.accountUsageService == nil {
response.Error(c, 503, "账户额度服务不可用")
return true
}
// 不读取全权批量缓存,避免不同权限共享 ETag 或未裁剪结果。
if action == "accounts.stats.read" {
stats, err := h.accountUsageService.GetTodayStatsBatch(c.Request.Context(), ids)
if err != nil {
response.Error(c, 502, "账户统计查询失败")
return true
}
response.Success(c, gin.H{"stats": stats})
return true
}
usage, errs, err := h.accountUsageService.GetUsageBatch(c.Request.Context(), ids, req.Force)
if err != nil {
response.Error(c, 502, "账户额度查询失败")
return true
}
safe := map[int64]any{}
for id, u := range usage {
if a := accounts[id]; a != nil && u != nil {
safe[id] = scopedUsageDTO(u, adminaccess.RestrictedFromContext(c.Request.Context()).Policy, a)
}
}
safeErrors := map[int64]string{}
for id := range errs {
if accounts[id] != nil {
safeErrors[id] = "账户额度查询失败"
}
}
response.Success(c, gin.H{"usage": safe, "errors": safeErrors})
return true
}
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
a, ok := scopedAuthorizedAccount(c, h.adminService, id, action, action == "accounts.usage.read")
if !ok {
return true
}
if h.accountUsageService == nil {
response.Error(c, 503, "账户额度服务不可用")
return true
}
switch path {
case "/:id/today-stats":
stats, err := h.accountUsageService.GetTodayStats(c.Request.Context(), id)
if err != nil {
response.Error(c, 502, "账户统计查询失败")
} else {
response.Success(c, stats)
}
case "/:id/stats":
h.GetStats(c)
case "/:id/usage":
var u *service.UsageInfo
var err error
if c.Query("source") == "passive" {
u, err = h.accountUsageService.GetPassiveUsage(c.Request.Context(), id)
} else {
u, err = h.accountUsageService.GetUsage(c.Request.Context(), id, c.Query("force") == "true")
}
if err != nil || u == nil {
response.Error(c, 502, "账户额度查询失败")
} else {
response.Success(c, scopedUsageDTO(u, adminaccess.RestrictedFromContext(c.Request.Context()).Policy, a))
}
}
return true
}
func scopedUsageDTO(u *service.UsageInfo, p adminaccess.Policy, a *service.Account) gin.H {
stats := p.AllowsAccount("accounts.stats.read", scopedAccountResource(a))
window := func(w *service.UsageProgress) *service.UsageProgress {
if w == nil {
return nil
}
safe := *w
if !stats {
safe.WindowStats = nil
}
return &safe
}
out := gin.H{
"source": u.Source,
"updated_at": u.UpdatedAt,
"five_hour": window(u.FiveHour),
"seven_day": window(u.SevenDay),
"seven_day_sonnet": window(u.SevenDaySonnet),
"seven_day_fable": window(u.SevenDayFable),
"gemini_shared_daily": window(u.GeminiSharedDaily),
"gemini_pro_daily": window(u.GeminiProDaily),
"gemini_flash_daily": window(u.GeminiFlashDaily),
"gemini_shared_minute": window(u.GeminiSharedMinute),
"gemini_pro_minute": window(u.GeminiProMinute),
"gemini_flash_minute": window(u.GeminiFlashMinute),
"thirty_day": window(u.ThirtyDay),
"antigravity_quota": u.AntigravityQuota,
"antigravity_quota_details": u.AntigravityQuotaDetails,
"ai_credits": u.AICredits,
"grok_request_quota": u.GrokRequestQuota,
"grok_token_quota": u.GrokTokenQuota,
"grok_retry_after_seconds": u.GrokRetryAfterSeconds,
"grok_quota_snapshot_state": u.GrokQuotaSnapshotState,
"grok_free_token_limit": u.GrokFreeTokenLimit,
"needs_reauth": u.NeedsReauth,
"needs_verify": u.NeedsVerify,
"is_banned": u.IsBanned,
"is_forbidden": u.IsForbidden,
}
if p.AllowsAccount("accounts.identity.read", scopedAccountResource(a)) {
out["subscription_tier"] = u.SubscriptionTier
out["subscription_tier_raw"] = u.SubscriptionTierRaw
}
if u.GrokBilling != nil {
billing := *u.GrokBilling
if !p.AllowsAccount("accounts.identity.read", scopedAccountResource(a)) {
billing.Plan = ""
billing.TopUpMethod = ""
billing.IsUnifiedBillingUser = false
}
if !stats {
billing.UsedCents = nil
billing.IncludedUsedCents = nil
billing.MonthlyUsed = nil
billing.OnDemandUsed = nil
}
out["grok_billing"] = &billing
}
if stats {
out["grok_local_usage"] = u.GrokLocalUsage
out["grok_local_usage_24h"] = u.GrokLocalUsage24h
out["grok_local_usage_7d"] = u.GrokLocalUsage7d
out["grok_local_usage_monthly"] = u.GrokLocalUsageMonthly
}
if u.Error != "" {
out["error"] = "上游额度查询失败"
}
switch u.ErrorCode {
case "forbidden", "unauthenticated", "rate_limited", "network_error":
out["error_code"] = u.ErrorCode
}
return out
}
@@ -0,0 +1,239 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type scopedStatisticsAccounts struct {
service.AdminService
accounts map[int64]*service.Account
}
func (s *scopedStatisticsAccounts) GetAccount(_ context.Context, id int64) (*service.Account, error) {
return s.accounts[id], nil
}
func statisticsPolicy(permission string) adminaccess.Policy {
return adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{permission}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}
}
func statisticsContext(c *gin.Context, permission string) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: statisticsPolicy(permission)}))
}
func TestScopedAdminStatisticsRejectBeforeCacheOrService(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, 2: {ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}}
h := &AccountHandler{adminService: svc}
for _, path := range []string{"/api/v1/admin/accounts/1/today-stats", "/api/v1/admin/accounts/1/stats", "/api/v1/admin/accounts/today-stats/batch", "/api/v1/admin/accounts/usage/batch"} {
t.Run(path, func(t *testing.T) {
r := gin.New()
r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.read") })
r.Use(h.ScopedAdminKeyAccounts)
method := "GET"
if strings.Contains(path, "batch") {
method = "POST"
}
r.Handle(method, strings.Replace(path, "/1/", "/:id/", 1), func(c *gin.Context) { t.Fatal("不得调用原处理器") })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(`{"account_ids":[1,2]}`)))
require.Equal(t, 404, w.Code, w.Body.String())
})
}
}
func TestScopedAdminOpenAIRejectsBeforeUpstream(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}}
stub := &referralHandlerStub{}
h := &OpenAIOAuthHandler{adminService: svc, referralService: stub}
r := gin.New()
r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.read") })
r.POST("/:id/referrals/invite", h.SendReferralInvite)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/1/referrals/invite", strings.NewReader(`{"email":"friend@example.com","program_id":"codex_referral_consumer","confirmed":true}`)))
require.Equal(t, 404, w.Code, w.Body.String())
require.Zero(t, stub.sends)
}
func TestScopedAdminUsageProjectionKeepsPlatformQuotaAndHidesCosts(t *testing.T) {
a := &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}
u := &service.UsageInfo{FiveHour: &service.UsageProgress{Utilization: 25, WindowStats: &service.WindowStats{Cost: 123}}, SevenDaySonnet: &service.UsageProgress{Utilization: 30}, GeminiProDaily: &service.UsageProgress{Utilization: 40}, AntigravityQuota: map[string]*service.AntigravityModelQuota{"model": {Utilization: 50}}, Error: "TOKEN_SECRET", ValidationURL: "URL_SECRET", ForbiddenReason: "IDENTITY_SECRET"}
out := scopedUsageDTO(u, statisticsPolicy("accounts.usage.read"), a)
require.Nil(t, out["five_hour"].(*service.UsageProgress).WindowStats)
require.NotNil(t, out["seven_day_sonnet"])
require.NotNil(t, out["gemini_pro_daily"])
require.NotNil(t, out["antigravity_quota"])
raw, err := json.Marshal(out)
require.NoError(t, err)
require.NotContains(t, string(raw), "SECRET")
require.NotContains(t, string(raw), "123")
require.NotNil(t, u.FiveHour.WindowStats, "裁剪不能更改共享缓存")
}
func TestScopedAdminOpenAIQuotaActionsAndIdentity(t *testing.T) {
for _, tc := range []struct {
action, path, method string
allow bool
}{
{"openai.quota.read", "/1/quota", "GET", true}, {"openai.quota.read", "/1/quota/refresh", "POST", true},
{"accounts.usage.read", "/1/quota", "GET", false}, {"openai.quota.reset", "/1/quota", "GET", false},
} {
t.Run(tc.action+tc.path, func(t *testing.T) {
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}}
stub := &openAIQuotaWorkflowStub{queryResult: &service.OpenAIQuotaUsage{UserID: "IDENTITY_SECRET", Email: "IDENTITY_SECRET", AccountID: "IDENTITY_SECRET", PlanType: "IDENTITY_SECRET", RateLimit: &service.OpenAIRateLimit{PrimaryWindow: &service.OpenAIRateLimitWindow{UsedPercent: 23}}, RateLimitResetCredits: &service.OpenAIRateLimitResetCredits{AvailableCount: 3}}}
h := &OpenAIOAuthHandler{adminService: svc, quotaService: stub}
r := gin.New()
r.Use(func(c *gin.Context) { statisticsContext(c, tc.action) })
r.GET("/:id/quota", h.QueryQuota)
r.POST("/:id/quota/refresh", h.RefreshQuota)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil))
if tc.allow {
require.Equal(t, 200, w.Code, w.Body.String())
require.Equal(t, 1, stub.queryCalls)
require.Contains(t, w.Body.String(), `"available_count":3`)
require.Contains(t, w.Body.String(), `"used_percent":23`)
} else {
require.Equal(t, 404, w.Code)
require.Zero(t, stub.queryCalls)
require.Zero(t, stub.cacheCalls)
}
require.NotContains(t, w.Body.String(), "SECRET")
})
}
}
func TestScopedAdminAccountScopeAndShadowSource(t *testing.T) {
parent := int64(2)
for _, tc := range []struct {
name string
a, source *service.Account
rules []adminaccess.Rule
allowed bool
}{
{"同规则", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, nil, nil, true},
{"其他组", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}, nil, nil, false},
{"其他平台", &service.Account{ID: 1, Platform: "anthropic", Type: "oauth", GroupIDs: []int64{1}}, nil, nil, false},
{"其他类型", &service.Account{ID: 1, Platform: "openai", Type: "apikey", GroupIDs: []int64{1}}, nil, nil, false},
{"母账户越权", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}, ParentAccountID: &parent}, &service.Account{ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}, nil, false},
{"不能拼接规则", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, nil, []adminaccess.Rule{{Permissions: []string{"openai.quota.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"apikey"}}, {Permissions: []string{"openai.quota.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}, false},
} {
t.Run(tc.name, func(t *testing.T) {
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: tc.a, 2: tc.source}}
r := gin.New()
r.Use(func(c *gin.Context) {
statisticsContext(c, "openai.quota.read")
if tc.rules != nil {
p := adminaccess.FromContext(c.Request.Context())
p.Policy.Rules = tc.rules
}
})
r.GET("/:id/quota", func(c *gin.Context) {
_, ok := scopedAuthorizedAccount(c, svc, 1, "openai.quota.read", true)
if ok {
c.Status(204)
}
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/1/quota", nil))
want := 404
if tc.allowed {
want = 204
}
require.Equal(t, want, w.Code, w.Body.String())
})
}
}
func TestScopedAdminMutationResponseRequiresReadPermission(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, read := range []bool{false, true} {
for _, kind := range []string{"reset", "invite"} {
t.Run(fmt.Sprintf("%s/read=%v", kind, read), func(t *testing.T) {
count := 2
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}}
quota := &openAIQuotaWorkflowStub{resetResult: &service.OpenAIQuotaResetResult{Code: "success"}, queryResult: &service.OpenAIQuotaUsage{RateLimitResetCredits: &service.OpenAIRateLimitResetCredits{AvailableCount: 3}, Email: "IDENTITY_SECRET"}}
referral := &referralHandlerStub{eligibility: &service.OpenAIReferralEligibility{ShouldShow: true, AvailableInvites: &count}}
h := &OpenAIOAuthHandler{adminService: svc, quotaService: quota, referralService: referral, rateLimitService: &openAIAccountStateRecovererStub{}}
action, readAction, path := "openai.quota.reset", "openai.quota.read", "/1/reset"
if kind == "invite" {
action, readAction, path = "openai.referrals.invite", "openai.referrals.read", "/1/invite"
}
r := gin.New()
r.Use(func(c *gin.Context) {
statisticsContext(c, action)
if read {
p := adminaccess.FromContext(c.Request.Context())
p.Policy.Rules[0].Permissions = append(p.Policy.Rules[0].Permissions, readAction)
}
})
r.POST("/:id/reset", h.ResetQuota)
r.POST("/:id/invite", h.SendReferralInvite)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(`{"email":"friend@example.com","program_id":"codex_referral_consumer","confirmed":true}`)))
require.Equal(t, 200, w.Code, w.Body.String())
require.NotContains(t, w.Body.String(), "IDENTITY_SECRET")
if kind == "reset" {
require.Equal(t, 1, quota.resetCalls)
if read {
require.Contains(t, w.Body.String(), "available_count")
} else {
require.NotContains(t, w.Body.String(), "available_count")
}
} else {
require.Equal(t, 1, referral.sends)
if read {
require.Contains(t, w.Body.String(), "available_invites")
} else {
require.NotContains(t, w.Body.String(), "available_invites")
}
}
})
}
}
}
func TestScopedAdminUsageBillingPreservesQuotaWithoutCost(t *testing.T) {
limit, used, percent := 100.0, 123.0, 25.0
u := &service.UsageInfo{GrokBilling: &xai.BillingSummary{MonthlyLimit: &limit, MonthlyUsed: &used, UsedCents: &used, UsedPercent: &percent, Plan: "IDENTITY_SECRET"}}
a := &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}
out := scopedUsageDTO(u, statisticsPolicy("accounts.usage.read"), a)
billing, ok := out["grok_billing"].(*xai.BillingSummary)
require.True(t, ok, "须保留真实上游额度窗口")
require.Equal(t, &limit, billing.MonthlyLimit)
require.Equal(t, &percent, billing.UsedPercent)
require.Nil(t, billing.MonthlyUsed)
require.Nil(t, billing.UsedCents)
require.Empty(t, billing.Plan)
require.NotNil(t, u.GrokBilling.MonthlyUsed, "不能裁剪共享缓存")
}
func TestScopedAdminBatchAuthorizationPrecedesETag(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, 2: {ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}}
h := &AccountHandler{adminService: svc}
cached := accountTodayStatsBatchCache.Set(buildAccountTodayStatsBatchCacheKey([]int64{1, 2}), gin.H{"stats": "CACHE_SECRET"})
r := gin.New()
r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.stats.read") })
r.Use(h.ScopedAdminKeyAccounts)
r.POST("/api/v1/admin/accounts/today-stats/batch", h.GetBatchTodayStats)
request := httptest.NewRequest("POST", "/api/v1/admin/accounts/today-stats/batch", strings.NewReader(`{"account_ids":[1,2]}`))
request.Header.Set("If-None-Match", cached.ETag)
w := httptest.NewRecorder()
r.ServeHTTP(w, request)
require.Equal(t, 404, w.Code, w.Body.String())
require.Empty(t, w.Header().Get("ETag"))
require.NotContains(t, w.Body.String(), "CACHE_SECRET")
}
@@ -0,0 +1,47 @@
package admin
import (
"slices"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// adminUserResponse 对受限密钥使用字段白名单,避免完整管理员 DTO 新增字段时隐式扩大授权。
// 订阅及用量由各自的独立接口提供,用户资料接口不嵌入这些关联数据。
func adminUserResponse(c *gin.Context, user *service.User) any {
principal := adminaccess.RestrictedFromContext(c.Request.Context())
if principal == nil {
return dto.UserFromServiceAdmin(user)
}
if user == nil {
return nil
}
out := gin.H{"id": user.ID}
permissions := principal.Policy.GlobalPermissions
if slices.Contains(permissions, "users.read") {
out["email"] = user.Email
out["username"] = user.Username
out["role"] = user.Role
out["status"] = user.Status
out["concurrency"] = user.Concurrency
out["rpm_limit"] = user.RPMLimit
out["last_active_at"] = user.LastActiveAt
out["created_at"] = user.CreatedAt
out["updated_at"] = user.UpdatedAt
out["deleted_at"] = user.DeletedAt
}
if slices.Contains(permissions, "users.balance.read") {
out["balance"] = user.Balance
out["frozen_balance"] = user.FrozenBalance
out["total_recharged"] = user.TotalRecharged
}
if slices.Contains(permissions, "groups.read") {
out["allowed_groups"] = user.AllowedGroups
out["restrict_public_groups"] = user.RestrictPublicGroups
out["group_rates"] = user.GroupRates
}
return out
}
@@ -0,0 +1,122 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"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 scopedUserResponseService struct {
service.AdminService
filters service.UserListFilters
writes int
}
func (*scopedUserResponseService) user() *service.User {
return &service.User{ID: 7, Email: "user@example.com", Notes: "内部备注", Balance: 123,
APIKeys: []service.APIKey{{Key: "内部密钥"}}, Subscriptions: []service.UserSubscription{{ID: 8, DailyUsageUSD: 10}}}
}
func (s *scopedUserResponseService) ListUsers(_ context.Context, _, _ int, filters service.UserListFilters, _, _ string) ([]service.User, int64, error) {
s.filters = filters
return []service.User{*s.user()}, 1, nil
}
func (s *scopedUserResponseService) GetUser(context.Context, int64) (*service.User, error) {
return s.user(), nil
}
func (s *scopedUserResponseService) UpdateUserBalance(context.Context, int64, float64, string, string) (*service.User, error) {
s.writes++
return s.user(), nil
}
func TestScopedAdminUserResponsePreservesFullAdminResponses(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := &scopedUserResponseService{}
h := NewUserHandler(svc, nil, nil, nil, nil, nil, nil)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{KeyID: "full", Policy: adminaccess.Policy{FullAccess: true}}))
})
r.GET("/users", h.List)
r.GET("/users/:id", h.GetByID)
for _, path := range []string{"/users", "/users?include_subscriptions=true", "/users/7"} {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
require.Equal(t, 200, w.Code)
for _, field := range []string{`"notes":"内部备注"`, `"balance":123`, `"subscriptions":`, `"daily_usage_usd":10`, `"api_keys":`} {
require.Contains(t, w.Body.String(), field)
}
if path == "/users" {
require.Nil(t, svc.filters.IncludeSubscriptions)
}
if strings.Contains(path, "include_subscriptions") {
require.NotNil(t, svc.filters.IncludeSubscriptions)
require.True(t, *svc.filters.IncludeSubscriptions)
}
}
}
func TestScopedAdminUserBalanceReplayRejectsDifferentCredential(t *testing.T) {
gin.SetMode(gin.TestMode)
previous := service.DefaultIdempotencyCoordinator()
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) })
for _, scopedFirst := range []bool{false, true} {
t.Run(map[bool]string{false: "完整管理员先执行", true: "受限Key先执行"}[scopedFirst], func(t *testing.T) {
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig()))
svc := &scopedUserResponseService{}
h := NewUserHandler(svc, nil, nil, nil, nil, nil, nil)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9})
if c.GetHeader("X-Test-Scoped") == "true" {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{
KeyID: "test-key", Policy: adminaccess.Policy{GlobalPermissions: []string{"users.balance.write"}},
}))
}
c.Next()
})
r.POST("/users/:id/balance", h.UpdateBalance)
for i, scoped := range []bool{scopedFirst, !scopedFirst, true} {
req := httptest.NewRequest("POST", "/users/7/balance", strings.NewReader(`{"balance":1,"operation":"add"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "same-operation")
if scoped {
req.Header.Set("X-Test-Scoped", "true")
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if scoped != scopedFirst {
require.Equal(t, 409, w.Code, w.Body.String())
require.NotContains(t, w.Body.String(), "内部备注")
require.NotContains(t, w.Body.String(), "内部密钥")
continue
}
require.Equal(t, 200, w.Code, w.Body.String())
if i > 0 {
require.Equal(t, "true", w.Header().Get("X-Idempotency-Replayed"))
}
var result struct {
Data map[string]json.RawMessage `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
if scoped {
require.Len(t, result.Data, 1)
require.JSONEq(t, `7`, string(result.Data["id"]))
} else {
require.Contains(t, result.Data, "notes")
require.Contains(t, result.Data, "balance")
}
}
require.Equal(t, 1, svc.writes, "重放只改变当前响应的权限投影,不能重复修改余额")
})
}
}
@@ -0,0 +1,105 @@
package admin
import (
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
func requireAdminKeyJWT(c *gin.Context) bool {
if c.GetString("auth_method") != service.AuditAuthMethodJWT {
response.Error(c, 403, "仅管理员 JWT 会话可管理密钥")
return false
}
role, ok := middleware.GetUserRoleFromContext(c)
if !ok || role != "admin" {
response.Error(c, 403, "需要管理员权限")
return false
}
return true
}
func (h *SettingHandler) ListScopedAdminKeys(c *gin.Context) {
if !requireAdminKeyJWT(c) {
return
}
items, e := h.settingService.ListScopedAdminKeys(c.Request.Context())
if e != nil {
response.ErrorFrom(c, e)
return
}
response.Success(c, gin.H{"items": items, "permissions": adminaccess.PermissionCatalog()})
}
func (h *SettingHandler) CreateScopedAdminKey(c *gin.Context) {
if !requireAdminKeyJWT(c) {
return
}
var in service.ScopedAdminKeyInput
if e := c.ShouldBindJSON(&in); e != nil {
response.Error(c, 400, "请求格式无效")
return
}
subject, ok := middleware.GetAuthSubjectFromContext(c)
if !ok {
response.Error(c, 403, "需要管理员身份")
return
}
key, item, e := h.settingService.CreateScopedAdminKey(c.Request.Context(), in, subject.UserID)
if e != nil {
response.ErrorFrom(c, e)
return
}
middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access": item.Policy.FullAccess})
response.Success(c, gin.H{"key": key, "item": item})
}
func (h *SettingHandler) UpdateScopedAdminKey(c *gin.Context) {
if !requireAdminKeyJWT(c) {
return
}
var in service.ScopedAdminKeyInput
if e := c.ShouldBindJSON(&in); e != nil {
response.Error(c, 400, "请求格式无效")
return
}
item, e := h.settingService.UpdateScopedAdminKey(c.Request.Context(), c.Param("id"), in)
if e != nil {
response.ErrorFrom(c, e)
return
}
middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access_before": item.PreviousFullAccess, "full_access": item.Policy.FullAccess})
response.Success(c, item)
}
func (h *SettingHandler) RotateScopedAdminKey(c *gin.Context) {
if !requireAdminKeyJWT(c) {
return
}
key, item, e := h.settingService.RotateScopedAdminKey(c.Request.Context(), c.Param("id"))
if e != nil {
response.ErrorFrom(c, e)
return
}
middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access": item.Policy.FullAccess})
response.Success(c, gin.H{"key": key, "item": item})
}
func (h *SettingHandler) RevokeScopedAdminKey(c *gin.Context) {
if !requireAdminKeyJWT(c) {
return
}
if e := h.settingService.RevokeScopedAdminKey(c.Request.Context(), c.Param("id")); e != nil {
response.ErrorFrom(c, e)
return
}
response.Success(c, gin.H{"message": "管理密钥已永久撤销"})
}
func (h *SettingHandler) DeleteScopedAdminKeyRecord(c *gin.Context) {
if !requireAdminKeyJWT(c) {
return
}
if e := h.settingService.DeleteScopedAdminKeyRecord(c.Request.Context(), c.Param("id")); e != nil {
response.ErrorFrom(c, e)
return
}
response.Success(c, gin.H{"message": "密钥已从列表移除,历史操作记录仍会继续保留"})
}
@@ -0,0 +1,78 @@
//go:build unit
package admin
import (
"context"
"net/http/httptest"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestScopedAdminKeyHandlersRejectNonJWT(t *testing.T) {
h := &SettingHandler{}
for _, fn := range []gin.HandlerFunc{h.ListScopedAdminKeys, h.CreateScopedAdminKey, h.UpdateScopedAdminKey, h.RotateScopedAdminKey, h.RevokeScopedAdminKey, h.DeleteScopedAdminKeyRecord, h.GetAdminAPIKey, h.RegenerateAdminAPIKey, h.DeleteAdminAPIKey} {
for _, method := range []string{"", "admin_api_key"} {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set("auth_method", method)
fn(c)
if w.Code != 403 {
t.Fatalf("%s 应拒绝,返回 %d", method, w.Code)
}
}
}
}
type deleteScopedKeyRecordRepo struct {
service.ScopedAdminKeyRepository
err error
id string
}
func (r *deleteScopedKeyRecordRepo) DeleteScopedAdminKeyRecord(_ context.Context, id string, at time.Time) error {
r.id = id
if at.IsZero() {
panic("删除时间不能为空")
}
return r.err
}
func TestScopedAdminKeyDeleteRecordHandler(t *testing.T) {
for _, tc := range []struct {
name, role string
err error
status int
}{
{"仅列表移除", "admin", nil, 200},
{"未撤销或已移除", "admin", service.ErrScopedAdminKeyNotFound, 404},
{"普通用户拒绝", "user", nil, 403},
} {
t.Run(tc.name, func(t *testing.T) {
repo := &deleteScopedKeyRecordRepo{err: tc.err}
settings := service.NewSettingService(nil, nil)
settings.SetScopedAdminKeyRepository(repo)
h := &SettingHandler{settingService: settings}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("DELETE", "/api/v1/admin/settings/admin-api-keys/key-1/record", nil)
c.Params = gin.Params{{Key: "id", Value: "key-1"}}
c.Set("auth_method", service.AuditAuthMethodJWT)
c.Set("user_role", tc.role)
h.DeleteScopedAdminKeyRecord(c)
require.Equal(t, tc.status, w.Code)
if tc.role != "admin" {
require.Empty(t, repo.id)
} else {
require.Equal(t, "key-1", repo.id)
}
if tc.status == 200 {
require.Contains(t, w.Body.String(), "历史操作记录仍会继续保留")
}
})
}
}
@@ -0,0 +1,141 @@
//go:build unit
package admin
import (
"context"
"database/sql"
"fmt"
"net/http/httptest"
"os"
"sync"
"testing"
"time"
"entgo.io/ent/dialect"
entsql "entgo.io/ent/dialect/sql"
dbent "github.com/Wei-Shaw/sub2api/ent"
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
"github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
_ "github.com/lib/pq"
"github.com/stretchr/testify/require"
)
// 在轮换读取旧值后暂停,让删除在恢复轮换之前完整提交。
type legacyKeyReadBarrier struct {
service.SettingRepository
read chan struct{}
resume chan struct{}
once sync.Once
}
func (r *legacyKeyReadBarrier) GetValue(ctx context.Context, key string) (string, error) {
value, err := r.SettingRepository.GetValue(ctx, key)
if key == service.SettingKeyAdminAPIKey && err == nil {
r.once.Do(func() { close(r.read); <-r.resume })
}
return value, err
}
func (r *legacyKeyReadBarrier) ReplaceExistingAdminAPIKey(ctx context.Context, value string) (bool, error) {
return r.SettingRepository.(interface {
ReplaceExistingAdminAPIKey(context.Context, string) (bool, error)
}).ReplaceExistingAdminAPIKey(ctx, value)
}
func legacyKeyRequest(handler gin.HandlerFunc) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/api/v1/admin/settings/admin-api-key/regenerate", nil)
c.Set("auth_method", service.AuditAuthMethodJWT)
c.Set("user_role", "admin")
handler(c)
return w
}
func TestLegacyAdminKeyRotationPostgres(t *testing.T) {
dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN")
if dsn == "" {
t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN")
}
base, err := sql.Open("postgres", dsn)
require.NoError(t, err)
schema := fmt.Sprintf("legacy_key_test_%d", time.Now().UnixNano())
_, err = base.Exec(`CREATE SCHEMA ` + schema)
require.NoError(t, err)
db, err := sql.Open("postgres", dsn+" search_path="+schema)
require.NoError(t, err)
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
t.Cleanup(func() { _ = client.Close(); _, _ = base.Exec(`DROP SCHEMA ` + schema + ` CASCADE`); _ = base.Close() })
_, err = db.Exec(`CREATE TABLE settings(id BIGSERIAL PRIMARY KEY, key VARCHAR(100) UNIQUE NOT NULL, value TEXT NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`)
require.NoError(t, err)
repo := repository.NewSettingRepository(client)
settings := service.NewSettingService(repo, nil)
h := &SettingHandler{settingService: settings}
ctx := context.Background()
t.Run("删除先完成不得被轮换重建", func(t *testing.T) {
require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, "admin-test-old-key"))
barrier := &legacyKeyReadBarrier{SettingRepository: repo, read: make(chan struct{}), resume: make(chan struct{})}
var release sync.Once
unblock := func() { release.Do(func() { close(barrier.resume) }) }
defer unblock()
rotating := &SettingHandler{settingService: service.NewSettingService(barrier, nil)}
done := make(chan *httptest.ResponseRecorder, 1)
go func() { done <- legacyKeyRequest(rotating.RegenerateAdminAPIKey) }()
select {
case <-barrier.read:
case <-time.After(5 * time.Second):
t.Fatal("轮换未进入读取屏障")
}
require.Equal(t, 200, legacyKeyRequest(h.DeleteAdminAPIKey).Code)
var afterDelete int
require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM settings WHERE key=$1`, service.SettingKeyAdminAPIKey).Scan(&afterDelete))
require.Zero(t, afterDelete, "恢复轮换前删除必须已经落库")
unblock()
var response *httptest.ResponseRecorder
select {
case response = <-done:
case <-time.After(5 * time.Second):
t.Fatal("轮换未结束")
}
var count int
require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM settings WHERE key=$1`, service.SettingKeyAdminAPIKey).Scan(&count))
require.Zero(t, count, "已删除旧版密钥被轮换重新创建")
require.Equal(t, 403, response.Code)
require.NotContains(t, response.Body.String(), `"key":`)
})
t.Run("已有密钥可轮换且随后可删除", func(t *testing.T) {
require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, "admin-test-old-key"))
response := legacyKeyRequest(h.RegenerateAdminAPIKey)
require.Equal(t, 200, response.Code)
key, err := settings.GetAdminAPIKey(ctx)
require.NoError(t, err)
require.NotEqual(t, "admin-test-old-key", key)
require.NotEmpty(t, key)
require.Contains(t, response.Body.String(), key)
require.Equal(t, 200, legacyKeyRequest(h.DeleteAdminAPIKey).Code)
key, err = settings.GetAdminAPIKey(ctx)
require.NoError(t, err)
require.Empty(t, key)
})
t.Run("缺失与空值不能新建", func(t *testing.T) {
for _, emptyRow := range []bool{false, true} {
require.NoError(t, settings.DeleteAdminAPIKey(ctx))
if emptyRow {
require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, ""))
}
require.Equal(t, 403, legacyKeyRequest(h.RegenerateAdminAPIKey).Code)
key, err := settings.GenerateAdminAPIKey(ctx)
require.Error(t, err, "服务层也必须拒绝从无到有创建")
require.Empty(t, key)
stored, err := settings.GetAdminAPIKey(ctx)
require.NoError(t, err)
require.Empty(t, stored)
}
})
}
@@ -0,0 +1,179 @@
package admin
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"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"
)
type emailBlacklistSettingRepoStub struct {
*settingHandlerRepoStub
setCalls int
}
func (s *emailBlacklistSettingRepoStub) Set(_ context.Context, key, value string) error {
s.setCalls++
s.values[key] = value
return nil
}
type emailBlacklistAdminServiceStub struct {
*stubAdminService
findEmails []string
matched []service.User
disableIDs []int64
disableCalls int
}
func (s *emailBlacklistAdminServiceStub) FindActiveUsersByBlacklistedEmails(_ context.Context, emails []string) ([]service.User, error) {
s.findEmails = append([]string(nil), emails...)
return s.matched, nil
}
func (s *emailBlacklistAdminServiceStub) BatchDisableUsers(_ context.Context, userIDs []int64) (int, error) {
s.disableCalls++
s.disableIDs = append([]int64(nil), userIDs...)
return len(userIDs), nil
}
func serveEmailBlacklistJSON(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder {
t.Helper()
var reader *bytes.Reader
if raw, ok := body.(string); ok {
reader = bytes.NewReader([]byte(raw))
} else {
raw, err := json.Marshal(body)
require.NoError(t, err)
reader = bytes.NewReader(raw)
}
recorder := httptest.NewRecorder()
request := httptest.NewRequest(method, path, reader)
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
return recorder
}
func setupEmailBlacklistSettingRouter(repo *emailBlacklistSettingRepoStub) *gin.Engine {
gin.SetMode(gin.TestMode)
svc := service.NewSettingService(repo, &config.Config{})
handler := NewSettingHandler(svc, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.GET("/api/v1/admin/settings/registration-email-blacklist", handler.GetRegistrationEmailBlacklist)
router.PUT("/api/v1/admin/settings/registration-email-blacklist", handler.UpdateRegistrationEmailBlacklist)
return router
}
func TestUpdateRegistrationEmailBlacklist_RequiresEmailsField(t *testing.T) {
repo := &emailBlacklistSettingRepoStub{settingHandlerRepoStub: &settingHandlerRepoStub{values: map[string]string{
service.SettingKeyRegistrationEmailBlacklist: `["keep@gmail.com"]`,
}}}
router := setupEmailBlacklistSettingRouter(repo)
rec := serveEmailBlacklistJSON(t, router, http.MethodPut, "/api/v1/admin/settings/registration-email-blacklist", `{}`)
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Zero(t, repo.setCalls)
}
func TestUpdateRegistrationEmailBlacklist_ReturnsSavedAndAdded(t *testing.T) {
repo := &emailBlacklistSettingRepoStub{settingHandlerRepoStub: &settingHandlerRepoStub{values: map[string]string{
service.SettingKeyRegistrationEmailBlacklist: `["keep@gmail.com"]`,
}}}
router := setupEmailBlacklistSettingRouter(repo)
rec := serveEmailBlacklistJSON(t, router, http.MethodPut, "/api/v1/admin/settings/registration-email-blacklist",
map[string]any{"emails": []string{"keep@gmail.com", "NEW@gmail.com"}})
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
var resp struct {
Data UpdateRegistrationEmailBlacklistResponse `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Equal(t, []string{"keep@gmail.com", "new@gmail.com"}, resp.Data.Emails)
require.Equal(t, []string{"new@gmail.com"}, resp.Data.Added)
require.Equal(t, service.MaxRegistrationEmailBlacklistSize, resp.Data.Max)
rec = serveEmailBlacklistJSON(t, router, http.MethodGet, "/api/v1/admin/settings/registration-email-blacklist", `{}`)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), "new@gmail.com")
}
func TestUpdateRegistrationEmailBlacklist_InvalidEntryRejected(t *testing.T) {
repo := &emailBlacklistSettingRepoStub{settingHandlerRepoStub: &settingHandlerRepoStub{values: map[string]string{}}}
router := setupEmailBlacklistSettingRouter(repo)
rec := serveEmailBlacklistJSON(t, router, http.MethodPut, "/api/v1/admin/settings/registration-email-blacklist",
map[string]any{"emails": []string{"ok@gmail.com", "broken"}})
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Contains(t, rec.Body.String(), "EMAIL_BLACKLIST_INVALID_ENTRY")
require.Zero(t, repo.setCalls)
}
func setupEmailBlacklistUserRouter(stub service.AdminService) *gin.Engine {
gin.SetMode(gin.TestMode)
handler := NewUserHandler(stub, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.POST("/api/v1/admin/users/blacklist-matches", handler.FindBlacklistedEmailUsers)
router.POST("/api/v1/admin/users/batch-disable", handler.BatchDisable)
return router
}
func TestFindBlacklistedEmailUsers_ReturnsMatchedUsers(t *testing.T) {
stub := &emailBlacklistAdminServiceStub{
stubAdminService: newStubAdminService(),
matched: []service.User{{ID: 3, Email: "a.b@gmail.com", Username: "ab", PasswordHash: "secret"}},
}
router := setupEmailBlacklistUserRouter(stub)
rec := serveEmailBlacklistJSON(t, router, http.MethodPost, "/api/v1/admin/users/blacklist-matches",
map[string]any{"emails": []string{"ab@gmail.com"}})
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, []string{"ab@gmail.com"}, stub.findEmails)
var resp struct {
Data struct {
Items []map[string]any `json:"items"`
Total int `json:"total"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Equal(t, 1, resp.Data.Total)
require.Equal(t, map[string]any{"id": float64(3), "email": "a.b@gmail.com", "username": "ab"}, resp.Data.Items[0])
}
func TestFindBlacklistedEmailUsers_RejectsOversizedRequest(t *testing.T) {
stub := &emailBlacklistAdminServiceStub{stubAdminService: newStubAdminService()}
router := setupEmailBlacklistUserRouter(stub)
emails := make([]string, service.MaxRegistrationEmailBlacklistSize+1)
for i := range emails {
emails[i] = "x@gmail.com"
}
rec := serveEmailBlacklistJSON(t, router, http.MethodPost, "/api/v1/admin/users/blacklist-matches",
map[string]any{"emails": emails})
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Nil(t, stub.findEmails)
}
func TestBatchDisable_ValidatesAndForwards(t *testing.T) {
stub := &emailBlacklistAdminServiceStub{stubAdminService: newStubAdminService()}
router := setupEmailBlacklistUserRouter(stub)
rec := serveEmailBlacklistJSON(t, router, http.MethodPost, "/api/v1/admin/users/batch-disable",
map[string]any{"user_ids": []int64{}})
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Zero(t, stub.disableCalls)
rec = serveEmailBlacklistJSON(t, router, http.MethodPost, "/api/v1/admin/users/batch-disable",
map[string]any{"user_ids": []int64{4, 5}})
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, []int64{4, 5}, stub.disableIDs)
require.Contains(t, rec.Body.String(), `"affected":2`)
}
@@ -200,6 +200,7 @@ type CreateGroupRequest struct {
// 图片生成计费配置(antigravity 和 gemini 平台使用,负数表示清除配置)
AllowImageGeneration bool `json:"allow_image_generation"`
AllowBatchImageGeneration bool `json:"allow_batch_image_generation"`
ImageCountBilling bool `json:"image_count_billing"`
ImageRateIndependent bool `json:"image_rate_independent"`
ImageRateMultiplier *float64 `json:"image_rate_multiplier"`
BatchImageDiscountMultiplier *float64 `json:"batch_image_discount_multiplier"`
@@ -238,6 +239,7 @@ type CreateGroupRequest struct {
AllowMessagesDispatch bool `json:"allow_messages_dispatch"`
AllowLive bool `json:"allow_live"`
ForceOpenAIFast bool `json:"force_openai_fast"`
ForceOpenAIUltrafast bool `json:"force_openai_ultrafast"`
FreeOpenAIFast bool `json:"free_openai_fast"`
RequireOAuthOnly bool `json:"require_oauth_only"`
RequirePrivacySet bool `json:"require_privacy_set"`
@@ -276,6 +278,7 @@ type UpdateGroupRequest struct {
// 图片生成计费配置(antigravity 和 gemini 平台使用,负数表示清除配置)
AllowImageGeneration *bool `json:"allow_image_generation"`
AllowBatchImageGeneration *bool `json:"allow_batch_image_generation"`
ImageCountBilling *bool `json:"image_count_billing"`
ImageRateIndependent *bool `json:"image_rate_independent"`
ImageRateMultiplier *float64 `json:"image_rate_multiplier"`
BatchImageDiscountMultiplier *float64 `json:"batch_image_discount_multiplier"`
@@ -314,6 +317,7 @@ type UpdateGroupRequest struct {
AllowMessagesDispatch *bool `json:"allow_messages_dispatch"`
AllowLive *bool `json:"allow_live"`
ForceOpenAIFast *bool `json:"force_openai_fast"`
ForceOpenAIUltrafast *bool `json:"force_openai_ultrafast"`
FreeOpenAIFast *bool `json:"free_openai_fast"`
RequireOAuthOnly *bool `json:"require_oauth_only"`
RequirePrivacySet *bool `json:"require_privacy_set"`
@@ -681,6 +685,7 @@ func (h *GroupHandler) Create(c *gin.Context) {
ModelPricing: req.ModelPricing,
AllowImageGeneration: req.AllowImageGeneration,
AllowBatchImageGeneration: req.AllowBatchImageGeneration,
ImageCountBilling: req.ImageCountBilling,
ImageRateIndependent: req.ImageRateIndependent,
ImageRateMultiplier: req.ImageRateMultiplier,
BatchImageDiscountMultiplier: req.BatchImageDiscountMultiplier,
@@ -716,6 +721,7 @@ func (h *GroupHandler) Create(c *gin.Context) {
AllowMessagesDispatch: req.AllowMessagesDispatch,
AllowLive: req.AllowLive,
ForceOpenAIFast: req.ForceOpenAIFast,
ForceOpenAIUltrafast: req.ForceOpenAIUltrafast,
FreeOpenAIFast: req.FreeOpenAIFast,
RequireOAuthOnly: req.RequireOAuthOnly,
RequirePrivacySet: req.RequirePrivacySet,
@@ -828,6 +834,7 @@ func (h *GroupHandler) Update(c *gin.Context) {
ModelPricing: req.ModelPricing,
AllowImageGeneration: req.AllowImageGeneration,
AllowBatchImageGeneration: req.AllowBatchImageGeneration,
ImageCountBilling: req.ImageCountBilling,
ImageRateIndependent: req.ImageRateIndependent,
ImageRateMultiplier: req.ImageRateMultiplier,
BatchImageDiscountMultiplier: req.BatchImageDiscountMultiplier,
@@ -863,6 +870,7 @@ func (h *GroupHandler) Update(c *gin.Context) {
AllowMessagesDispatch: req.AllowMessagesDispatch,
AllowLive: req.AllowLive,
ForceOpenAIFast: req.ForceOpenAIFast,
ForceOpenAIUltrafast: req.ForceOpenAIUltrafast,
FreeOpenAIFast: req.FreeOpenAIFast,
RequireOAuthOnly: req.RequireOAuthOnly,
RequirePrivacySet: req.RequirePrivacySet,
@@ -25,3 +25,21 @@ func TestGroupRequestsDecodeForceOpenAIFast(t *testing.T) {
require.Nil(t, omitted.ForceOpenAIFast)
require.Nil(t, omitted.FreeOpenAIFast)
}
func TestGroupRequestsDecodeForceOpenAIUltrafast(t *testing.T) {
var createReq CreateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{"name":"ultrafast","force_openai_ultrafast":true}`), &createReq))
require.True(t, createReq.ForceOpenAIUltrafast)
require.False(t, createReq.ForceOpenAIFast)
var updateReq UpdateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{"force_openai_fast":false,"force_openai_ultrafast":true}`), &updateReq))
require.NotNil(t, updateReq.ForceOpenAIUltrafast)
require.True(t, *updateReq.ForceOpenAIUltrafast)
require.NotNil(t, updateReq.ForceOpenAIFast)
require.False(t, *updateReq.ForceOpenAIFast)
var omitted UpdateGroupRequest
require.NoError(t, json.Unmarshal([]byte(`{}`), &omitted))
require.Nil(t, omitted.ForceOpenAIUltrafast)
}
@@ -2,6 +2,10 @@ package admin
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"strconv"
"time"
@@ -68,6 +72,11 @@ func executeAdminIdempotentWithTimeout(
}
func adminActorScope(c *gin.Context) string {
if principal := adminaccess.FromContext(c.Request.Context()); principal != nil {
policy, _ := json.Marshal(principal.Policy)
digest := sha256.Sum256(policy)
return "admin-key:" + principal.KeyID + ":" + hex.EncodeToString(digest[:])
}
actorScope := "admin:0"
if subject, ok := middleware2.GetAuthSubjectFromContext(c); ok {
actorScope = "admin:" + strconv.FormatInt(subject.UserID, 10)
@@ -115,6 +124,18 @@ func executeAdminIdempotentJSONWithMode(
mode idempotencyStoreUnavailableMode,
execute func(context.Context) (any, error),
) {
executeAdminIdempotentJSONWithProjection(c, scope, payload, ttl, executionTimeout, mode, execute, nil)
}
// executeAdminIdempotentJSONWithResponse 在实际执行及缓存重放之后统一约束响应。
func executeAdminIdempotentJSONWithResponse(c *gin.Context, scope string, payload any, ttl time.Duration, execute func(context.Context) (any, error), present func(any) any) {
executeAdminIdempotentJSONWithProjection(c, scope, payload, ttl, 0, idempotencyStoreUnavailableFailClose, execute, present)
}
func executeAdminIdempotentJSONWithProjection(c *gin.Context, scope string, payload any, ttl time.Duration, executionTimeout time.Duration, mode idempotencyStoreUnavailableMode, execute func(context.Context) (any, error), present func(any) any) {
if present == nil {
present = func(data any) any { return data }
}
result, err := executeAdminIdempotentWithTimeout(c, scope, payload, ttl, executionTimeout, execute)
if err != nil {
if infraerrors.Code(err) == infraerrors.Code(service.ErrIdempotencyStoreUnavail) {
@@ -131,7 +152,7 @@ func executeAdminIdempotentJSONWithMode(
return
}
c.Header("X-Idempotency-Degraded", "store-unavailable")
response.Success(c, data)
response.Success(c, present(data))
return
}
}
@@ -144,5 +165,5 @@ func executeAdminIdempotentJSONWithMode(
if result != nil && result.Replayed {
c.Header("X-Idempotency-Replayed", "true")
}
response.Success(c, result.Data)
response.Success(c, present(result.Data))
}
@@ -9,6 +9,7 @@ import (
"time"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -194,6 +195,11 @@ type OpenAICodexPATCreateRequest struct {
// RefreshToken refreshes an OpenAI OAuth token
// POST /api/v1/admin/openai/refresh-token
func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) {
scoped := adminaccess.RestrictedFromContext(c.Request.Context()) != nil
if scoped && !adminaccess.RouteAllowed(adminaccess.RestrictedFromContext(c.Request.Context()).Policy, c.Request.Method, c.FullPath()) {
response.Error(c, 403, "调用方令牌刷新未授权")
return
}
var req OpenAIRefreshTokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
@@ -211,6 +217,10 @@ func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) {
var proxyURL string
if req.ProxyID != nil {
proxy, err := h.adminService.GetProxy(c.Request.Context(), *req.ProxyID)
if scoped && (err != nil || proxy == nil || !proxy.IsActive() || proxy.IsExpired(time.Now())) {
response.BadRequest(c, "代理不可用")
return
}
if err == nil && proxy != nil {
proxyURL = proxy.URL()
}
@@ -225,6 +235,10 @@ func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) {
tokenInfo, err := h.openaiOAuthService.RefreshTokenWithClientID(c.Request.Context(), refreshToken, proxyURL, clientID)
if err != nil {
if scoped {
response.Error(c, 502, "调用方令牌刷新失败")
return
}
response.ErrorFrom(c, err)
return
}
@@ -477,6 +491,10 @@ func buildOpenAICodexPATAccountName(name string, tokenInfo *service.OpenAITokenI
// QueryQuota queries the rate-limit / quota usage for an OpenAI account.
// GET /api/v1/admin/openai/accounts/:id/quota
func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
h.scopedOpenAIQuota(c, false)
return
}
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
@@ -504,6 +522,10 @@ func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) {
// state: the audit middleware only records mutating verbs, so a persisting GET
// would mutate the database without an audit trail.
func (h *OpenAIOAuthHandler) RefreshQuota(c *gin.Context) {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
h.scopedOpenAIQuota(c, true)
return
}
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
@@ -588,13 +610,19 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) {
response.BadRequest(c, "Invalid account ID")
return
}
if !h.scopedOpenAIAllowed(c, accountID, "openai.quota.reset", false) {
return
}
if h.quotaService == nil {
response.BadRequest(c, "openai quota service is not enabled")
return
}
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
c.Request = c.Request.WithContext(service.WithScopedAdminAccountOperation(c.Request.Context(), "openai.quota.reset"))
}
result, err := h.quotaService.ResetCredit(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
scopedOpenAIError(c, err)
return
}
if result == nil {
@@ -620,5 +648,13 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) {
if postResult.Account != nil {
resetResponse.Account = dto.AccountFromService(postResult.Account)
}
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
if h.scopedOpenAIHasPermission(c, accountID, "openai.quota.read", true) {
resetResponse.Quota = h.scopedQuotaDTO(c, accountID, resetResponse.Quota)
} else {
resetResponse.Quota = nil
}
resetResponse.Account = nil
}
response.Success(c, resetResponse)
}
@@ -47,15 +47,19 @@ func (h *OpenAIOAuthHandler) RefreshReferrals(c *gin.Context) {
if !ok {
return
}
if !h.scopedOpenAIAllowed(c, id, "openai.referrals.read", true) {
return
}
eligibility, err := h.referralService.QueryReferralEligibility(c.Request.Context(), id)
if err != nil {
response.ErrorFrom(c, err)
scopedOpenAIError(c, err)
return
}
if eligibility == nil {
response.Error(c, http.StatusBadGateway, "Empty invitation eligibility response")
return
}
eligibility = h.scopedReferralDTO(c, eligibility)
cacheErr := h.referralService.CacheReferralSnapshot(c.Request.Context(), id, eligibility)
response.Success(c, openAIReferralRefreshResponse{Eligibility: eligibility, CachePersisted: cacheErr == nil})
}
@@ -65,6 +69,9 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) {
if !ok {
return
}
if !h.scopedOpenAIAllowed(c, id, "openai.referrals.invite", false) {
return
}
var input service.OpenAIReferralSendRequest
if err := c.ShouldBindJSON(&input); err != nil {
response.BadRequest(c, "Invalid invitation request")
@@ -72,7 +79,7 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) {
}
result, err := h.referralService.SendReferralInvite(c.Request.Context(), id, input)
if err != nil {
response.ErrorFrom(c, err)
scopedOpenAIError(c, err)
return
}
if result == nil || !result.Sent {
@@ -81,7 +88,7 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) {
}
// The email is already sent. Refresh failure must not turn it into a failed
// submission and encourage a duplicate send, even if the browser disconnects.
baseCtx := context.WithoutCancel(c.Request.Context())
baseCtx := service.WithScopedAdminAccountOperation(context.WithoutCancel(c.Request.Context()), "openai.referrals.invite")
refreshCtx, cancelRefresh := context.WithTimeout(baseCtx, 8*time.Second)
eligibility, refreshErr := h.referralService.QueryReferralEligibility(refreshCtx, id)
cancelRefresh()
@@ -92,10 +99,15 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) {
// invalidating a stale snapshot) a fresh, independent deadline.
cacheCtx, cancelCache := context.WithTimeout(baseCtx, 3*time.Second)
defer cancelCache()
eligibility = h.scopedReferralDTO(c, eligibility)
cacheErr := h.referralService.CacheReferralSnapshot(cacheCtx, id, eligibility)
responseEligibility := eligibility
if !h.scopedOpenAIHasPermission(c, id, "openai.referrals.read", true) {
responseEligibility = nil
}
response.Success(c, openAIReferralSendResponse{
OpenAIReferralSendResult: *result,
openAIReferralRefreshResponse: openAIReferralRefreshResponse{Eligibility: eligibility, CachePersisted: cacheErr == nil},
openAIReferralRefreshResponse: openAIReferralRefreshResponse{Eligibility: responseEligibility, CachePersisted: cacheErr == nil},
RefreshFailed: eligibility == nil,
})
}
@@ -2,6 +2,7 @@ package admin
import (
"fmt"
"math"
"net/http"
"strconv"
"strings"
@@ -309,6 +310,9 @@ func parseOpsOpenAITokenStatsFilter(c *gin.Context) (*service.OpsOpenAITokenStat
}
filter.PageSize = pageSize
}
if filter.Page > math.MaxInt/filter.PageSize {
return nil, fmt.Errorf("invalid page")
}
return filter, nil
}
@@ -207,5 +207,5 @@ func (h *PromoHandler) GetUsages(c *gin.Context) {
for i := range usages {
out = append(out, *dto.PromoCodeUsageFromService(&usages[i]))
}
response.Paginated(c, out, paginationResult.Total, page, pageSize)
response.Paginated(c, adminPromoUsagesResponse(c, out), paginationResult.Total, page, pageSize)
}
@@ -57,6 +57,9 @@ type UpdateProxyRequest struct {
// List handles listing all proxies with pagination
// GET /api/v1/admin/proxies
func (h *ProxyHandler) List(c *gin.Context) {
if h.scopedAdminProxyRead(c) {
return
}
page, pageSize := response.ParsePagination(c)
protocol := c.Query("protocol")
status := c.Query("status")
@@ -86,6 +89,9 @@ func (h *ProxyHandler) List(c *gin.Context) {
// GET /api/v1/admin/proxies/all
// Optional query param: with_count=true to include account count per proxy
func (h *ProxyHandler) GetAll(c *gin.Context) {
if h.scopedAdminProxyRead(c) {
return
}
withCount := c.Query("with_count") == "true"
if withCount {
@@ -118,6 +124,9 @@ func (h *ProxyHandler) GetAll(c *gin.Context) {
// GetByID handles getting a proxy by ID
// GET /api/v1/admin/proxies/:id
func (h *ProxyHandler) GetByID(c *gin.Context) {
if h.scopedAdminProxyRead(c) {
return
}
proxyID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid proxy ID")
@@ -0,0 +1,47 @@
package admin
import (
"time"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// 受限密钥仅接收记录自身字段;不嵌入完整用户资料或实时财务数据。
type scopedPromoUsageResponse struct {
ID int64 `json:"id"`
PromoCodeID int64 `json:"promo_code_id"`
UserID int64 `json:"user_id"`
BonusAmount float64 `json:"bonus_amount"`
UsedAt time.Time `json:"used_at"`
}
func adminPromoUsagesResponse(c *gin.Context, items []dto.PromoCodeUsage) any {
if adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return items
}
out := make([]scopedPromoUsageResponse, 0, len(items))
for _, item := range items {
out = append(out, scopedPromoUsageResponse{ID: item.ID, PromoCodeID: item.PromoCodeID, UserID: item.UserID, BonusAmount: item.BonusAmount, UsedAt: item.UsedAt})
}
return out
}
type scopedAnnouncementReadResponse struct {
UserID int64 `json:"user_id"`
Eligible bool `json:"eligible"`
ReadAt *time.Time `json:"read_at,omitempty"`
}
func adminAnnouncementReadResponse(c *gin.Context, items []service.AnnouncementUserReadStatus) any {
if adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return items
}
out := make([]scopedAnnouncementReadResponse, 0, len(items))
for _, item := range items {
out = append(out, scopedAnnouncementReadResponse{UserID: item.UserID, Eligible: item.Eligible, ReadAt: item.ReadAt})
}
return out
}
@@ -0,0 +1,94 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"net/http/httptest"
"testing"
"time"
)
type scopedContentPromoRepo struct{ service.PromoCodeRepository }
func (scopedContentPromoRepo) ListUsagesByPromoCode(context.Context, int64, pagination.PaginationParams) ([]service.PromoCodeUsage, *pagination.PaginationResult, error) {
return []service.PromoCodeUsage{{ID: 1, PromoCodeID: 2, UserID: 3, BonusAmount: 4, User: &service.User{ID: 3, Email: "private@example.com", Balance: 999, FrozenBalance: 888, TotalRecharged: 777}}}, &pagination.PaginationResult{Total: 1}, nil
}
type scopedContentUsers struct{ service.UserRepository }
func (scopedContentUsers) ListWithFilters(context.Context, pagination.PaginationParams, service.UserListFilters) ([]service.User, *pagination.PaginationResult, error) {
return []service.User{{ID: 3, Email: "private@example.com", Balance: 999}}, &pagination.PaginationResult{Total: 1}, nil
}
type scopedContentSubs struct {
service.UserSubscriptionRepository
}
func (scopedContentSubs) ListActiveByUserID(context.Context, int64) ([]service.UserSubscription, error) {
return nil, nil
}
type scopedContentReads struct {
service.AnnouncementReadRepository
}
func (scopedContentReads) GetReadMapByUsers(context.Context, int64, []int64) (map[int64]time.Time, error) {
return map[int64]time.Time{3: time.Unix(100, 0).UTC()}, nil
}
func TestScopedAdminContentHandlersResponseBoundary(t *testing.T) {
gin.SetMode(gin.TestMode)
promo := NewPromoHandler(service.NewPromoService(scopedContentPromoRepo{}, nil, nil, nil, nil))
announcement := NewAnnouncementHandler(service.NewAnnouncementService(&announcementRepoCapture{}, scopedContentReads{}, scopedContentUsers{}, scopedContentSubs{}))
for _, endpoint := range []struct {
name, path, request string
handler gin.HandlerFunc
}{{"优惠码", "/promo-codes/:id/usages", "/promo-codes/2/usages", promo.GetUsages}, {"公告", "/announcements/:id/read-status", "/announcements/2/read-status", announcement.ListReadStatus}} {
for _, scoped := range []bool{false, true} {
t.Run(endpoint.name+map[bool]string{true: "受限", false: "普通"}[scoped], func(t *testing.T) {
r := gin.New()
r.Use(func(c *gin.Context) {
if scoped {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"promo.read", "announcements.read"}}}))
}
c.Next()
})
r.GET(endpoint.path, endpoint.handler)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", endpoint.request, nil))
require.Equal(t, 200, w.Code)
var body struct {
Data struct {
Items []map[string]json.RawMessage `json:"items"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Len(t, body.Data.Items, 1)
item := body.Data.Items[0]
if scoped {
require.NotContains(t, w.Body.String(), "private@example.com")
require.NotContains(t, w.Body.String(), "999")
require.NotContains(t, item, "user")
require.NotContains(t, item, "balance")
require.Contains(t, item, "user_id")
if endpoint.name == "优惠码" {
require.Contains(t, item, "bonus_amount")
require.Contains(t, item, "used_at")
} else {
require.Contains(t, item, "eligible")
require.Contains(t, item, "read_at")
}
} else {
require.Contains(t, w.Body.String(), "private@example.com")
require.Contains(t, w.Body.String(), "999")
}
})
}
}
}
@@ -0,0 +1,65 @@
package admin
import (
"encoding/json"
"slices"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/gin-gonic/gin"
)
func scopedAdminWriteOnly(c *gin.Context, readPermission string) bool {
p := adminaccess.RestrictedFromContext(c.Request.Context())
return p != nil && !slices.Contains(p.Policy.GlobalPermissions, readPermission)
}
// adminSubscriptionResponse 在缓存重放后也应用字段白名单,不嵌入用户、分配人或分组配置。
// 写权限只确认订阅 ID;订阅用量等字段必须另有读取权限。
func adminSubscriptionResponse(c *gin.Context, data any) any {
if adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return data
}
raw, err := json.Marshal(data)
if err != nil {
return nil
}
return projectSubscriptionJSON(raw, !scopedAdminWriteOnly(c, "subscriptions.read"))
}
func projectSubscriptionJSON(raw json.RawMessage, readable bool) any {
var list []json.RawMessage
if len(raw) > 0 && raw[0] == '[' && json.Unmarshal(raw, &list) == nil {
out := make([]any, 0, len(list))
for _, item := range list {
out = append(out, projectSubscriptionJSON(item, readable))
}
return out
}
var fields map[string]json.RawMessage
if json.Unmarshal(raw, &fields) != nil || fields == nil {
return nil
}
out := make(map[string]any)
if subscriptions, ok := fields["subscriptions"]; ok {
for _, key := range []string{"success_count", "created_count", "reused_count", "failed_count", "errors", "statuses"} {
if value, exists := fields[key]; exists {
out[key] = value
}
}
out["subscriptions"] = projectSubscriptionJSON(subscriptions, readable)
return out
}
keys := []string{"id"}
if readable {
keys = append(keys, "user_id", "group_id", "starts_at", "expires_at", "status",
"daily_window_start", "weekly_window_start", "monthly_window_start",
"daily_usage_usd", "weekly_usage_usd", "monthly_usage_usd",
"created_at", "updated_at", "revoked_at", "assigned_by", "assigned_at", "notes")
}
for _, key := range keys {
if value, exists := fields[key]; exists {
out[key] = value
}
}
return out
}
@@ -0,0 +1,166 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type scopedSubscriptionRepo struct {
service.UserSubscriptionRepository
writes int
}
func (*scopedSubscriptionRepo) GetByID(context.Context, int64) (*service.UserSubscription, error) {
return &service.UserSubscription{ID: 1, UserID: 2, GroupID: 3, DailyUsageUSD: 4, ExpiresAt: time.Now().Add(time.Hour),
User: &service.User{ID: 2, Email: "private-user@example.com", Balance: 987},
AssignedByUser: &service.User{ID: 8, Email: "private-admin@example.com", Balance: 654},
Group: &service.Group{ID: 3, Name: "group", RateMultiplier: 42}}, nil
}
func TestScopedAdminSubscriptionDoesNotExposeAssociatedUserAndPricing(t *testing.T) {
gin.SetMode(gin.TestMode)
s := service.NewSubscriptionService(nil, &scopedSubscriptionRepo{}, nil, nil, nil)
defer s.Stop()
h := NewSubscriptionHandler(s)
for _, scoped := range []bool{false, true} {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/subscriptions/1", nil)
c.Params = gin.Params{{Key: "id", Value: "1"}}
if scoped {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"subscriptions.read"}}}))
}
h.GetByID(c)
require.Equal(t, 200, w.Code)
require.Contains(t, w.Body.String(), `"daily_usage_usd":4`)
for _, field := range []string{"private-user@example.com", "private-admin@example.com", `"balance"`, `"rate_multiplier"`} {
if scoped {
require.NotContains(t, w.Body.String(), field)
} else {
require.Contains(t, w.Body.String(), field)
}
}
}
}
func TestScopedAdminQuotaWriteDoesNotGrantQuotaRead(t *testing.T) {
repo := &upsertCapturingQuotaRepo{listRecords: []service.UserPlatformQuotaRecord{{UserID: 42, Platform: "anthropic"}}}
h := buildTestHandler(repo, &billingCacheStub{})
c, w := putReq(t, `{"quotas":[{"platform":"anthropic","daily_limit_usd":10}]}`)
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"users.quotas.write"}}}))
h.UpdateUserPlatformQuotas(c)
require.Equal(t, 200, w.Code)
require.NotContains(t, w.Body.String(), "platform_quotas")
require.NotContains(t, w.Body.String(), "usage")
require.Len(t, repo.upsertCalls, 1)
}
func (r *scopedSubscriptionRepo) GetByIDForUpdate(ctx context.Context, id int64) (*service.UserSubscription, error) {
return r.GetByID(ctx, id)
}
func (r *scopedSubscriptionRepo) ExtendExpiry(context.Context, int64, time.Time) error {
r.writes++
return nil
}
func TestScopedAdminSubscriptionExtendReplayRejectsChangedAuthorization(t *testing.T) {
gin.SetMode(gin.TestMode)
previous := service.DefaultIdempotencyCoordinator()
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) })
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig()))
repo := &scopedSubscriptionRepo{}
svc := service.NewSubscriptionService(nil, repo, nil, nil, nil)
defer svc.Stop()
h := NewSubscriptionHandler(svc)
r := gin.New()
r.Use(func(c *gin.Context) {
if c.GetHeader("X-Test-Mode") != "admin" {
permissions := []string{"subscriptions.extend"}
if c.GetHeader("X-Test-Mode") == "read" {
permissions = append(permissions, "subscriptions.read")
}
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: permissions}}))
}
})
r.POST("/subscriptions/:id/extend", h.Extend)
for i, mode := range []string{"admin", "write", "read"} {
req := httptest.NewRequest("POST", "/subscriptions/1/extend", strings.NewReader(`{"days":1}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "same-extension")
req.Header.Set("X-Test-Mode", mode)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if i > 0 {
require.Equal(t, 409, w.Code, w.Body.String())
require.NotContains(t, w.Body.String(), "private-user")
continue
}
require.Equal(t, 200, w.Code, w.Body.String())
var result struct {
Data map[string]json.RawMessage `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
if mode == "admin" {
require.Contains(t, result.Data, "user")
} else {
require.NotContains(t, result.Data, "user")
require.NotContains(t, result.Data, "group")
require.NotContains(t, result.Data, "assigned_by_user")
if mode == "write" {
require.Len(t, result.Data, 1)
} else {
require.Contains(t, result.Data, "daily_usage_usd")
}
}
}
require.Equal(t, 1, repo.writes)
}
func TestScopedAdminSubscriptionBulkProjectionPreservesIDs(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("GET", "/", nil)
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{}))
sub, _ := (&scopedSubscriptionRepo{}).GetByID(context.Background(), 1)
sub.ID = 9007199254740993
data := &dto.BulkAssignResult{SuccessCount: 1, Subscriptions: []dto.AdminUserSubscription{*dto.UserSubscriptionFromServiceAdmin(sub)}}
raw, err := json.Marshal(adminSubscriptionResponse(c, data))
require.NoError(t, err)
require.Contains(t, string(raw), `"id":9007199254740993`)
require.Contains(t, string(raw), `"success_count":1`)
for _, field := range []string{"daily_usage_usd", "user_id", "balance", "group", "private-user"} {
require.NotContains(t, string(raw), field)
}
}
func TestScopedAdminQuotaResetRequiresReadToReturnUsage(t *testing.T) {
for _, readable := range []bool{false, true} {
repo := &upsertCapturingQuotaRepo{listRecords: []service.UserPlatformQuotaRecord{{UserID: 42, Platform: "anthropic"}}}
cache := &billingCacheStub{}
h := buildTestHandler(repo, cache)
c, w := postReq(t, `{"platform":"anthropic","window":"daily"}`)
permissions := []string{"users.quotas.write"}
if readable {
permissions = append(permissions, "users.quotas.read")
}
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: permissions}}))
h.ResetUserPlatformQuotaWindow(c)
require.Equal(t, 200, w.Code, w.Body.String())
require.Len(t, repo.resetCalls, 1)
require.Len(t, cache.deleteCalls, 1)
if readable {
require.Contains(t, w.Body.String(), "platform_quotas")
} else {
require.NotContains(t, w.Body.String(), "platform_quotas")
}
}
}
@@ -0,0 +1,97 @@
package admin
import (
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// scopedAdminUsageLogResponse 仅公开该次请求的用量、计费快照和请求元数据。
// 关联资源只返回 ID;新增通用 DTO 字段不会自动获得受限密钥的读取权限。
func scopedAdminUsageLogResponse(record *service.UsageLog) gin.H {
if record == nil {
return nil
}
// 在转换前移除关联,避免构造含原始密钥、用户余额等内容的嵌套 DTO。
flat := *record
flat.User, flat.APIKey, flat.Group, flat.Subscription, flat.Account = nil, nil, nil, nil, nil
usage := dto.UsageLogFromServiceAdmin(&flat)
return gin.H{
"id": usage.ID,
"user_id": usage.UserID,
"api_key_id": usage.APIKeyID,
"account_id": usage.AccountID,
"request_id": usage.RequestID,
"model": usage.Model,
"service_tier": usage.ServiceTier,
"reasoning_effort": usage.ReasoningEffort,
"inbound_endpoint": usage.InboundEndpoint,
"upstream_endpoint": usage.UpstreamEndpoint,
"group_id": usage.GroupID,
"subscription_id": usage.SubscriptionID,
"input_tokens": usage.InputTokens,
"output_tokens": usage.OutputTokens,
"cache_creation_tokens": usage.CacheCreationTokens,
"cache_read_tokens": usage.CacheReadTokens,
"cache_creation_5m_tokens": usage.CacheCreation5mTokens,
"cache_creation_1h_tokens": usage.CacheCreation1hTokens,
"input_cost": usage.InputCost,
"output_cost": usage.OutputCost,
"cache_creation_cost": usage.CacheCreationCost,
"cache_read_cost": usage.CacheReadCost,
"total_cost": usage.TotalCost,
"actual_cost": usage.ActualCost,
"rate_multiplier": usage.RateMultiplier,
"long_context_billing_applied": usage.LongContextBillingApplied,
"billing_type": usage.BillingType,
"request_type": usage.RequestType,
"stream": usage.Stream,
"openai_ws_mode": usage.OpenAIWSMode,
"native_compaction_v2": usage.NativeCompactionV2,
"duration_ms": usage.DurationMs,
"first_token_ms": usage.FirstTokenMs,
"image_count": usage.ImageCount,
"image_size": usage.ImageSize,
"image_input_size": usage.ImageInputSize,
"image_output_size": usage.ImageOutputSize,
"image_input_tokens": usage.ImageInputTokens,
"image_input_cost": usage.ImageInputCost,
"image_output_tokens": usage.ImageOutputTokens,
"image_output_cost": usage.ImageOutputCost,
"image_size_source": usage.ImageSizeSource,
"image_size_breakdown": usage.ImageSizeBreakdown,
"media_type": usage.MediaType,
"user_agent": usage.UserAgent,
"ip_address": usage.IPAddress,
"session_id": usage.SessionID,
"cache_ttl_overridden": usage.CacheTTLOverridden,
"billing_mode": usage.BillingMode,
"created_at": usage.CreatedAt,
"upstream_model": usage.UpstreamModel,
"upstream_reasoning_effort": usage.UpstreamReasoningEffort,
"upstream_response_model": usage.UpstreamResponseModel,
"upstream_model_mismatch": usage.UpstreamModelMismatch,
"channel_id": usage.ChannelID,
"model_mapping_chain": usage.ModelMappingChain,
"upstream_request_id": usage.UpstreamRequestID,
"billing_tier": usage.BillingTier,
"account_rate_multiplier": usage.AccountRateMultiplier,
"account_stats_cost": usage.AccountStatsCost,
}
}
func adminUsageLogResponses(c *gin.Context, records []service.UsageLog) any {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
out := make([]gin.H, 0, len(records))
for i := range records {
out = append(out, scopedAdminUsageLogResponse(&records[i]))
}
return out
}
out := make([]dto.AdminUsageLog, 0, len(records))
for i := range records {
out = append(out, *dto.UsageLogFromServiceAdmin(&records[i]))
}
return out
}
@@ -0,0 +1,92 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/Wei-Shaw/sub2api/internal/pkg/usagestats"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type scopedUsageResponseRepo struct {
service.UsageLogRepository
records []service.UsageLog
}
func (r *scopedUsageResponseRepo) ListWithFilters(context.Context, pagination.PaginationParams, usagestats.UsageLogFilters) ([]service.UsageLog, *pagination.PaginationResult, error) {
return r.records, &pagination.PaginationResult{Total: int64(len(r.records))}, nil
}
func TestScopedAdminUsageListDoesNotGrantNestedResourceRead(t *testing.T) {
gin.SetMode(gin.TestMode)
privateUser := &service.User{ID: 7, Email: "private-email@example.invalid", Balance: 97531, Notes: "private-user-notes"}
privateKey := &service.APIKey{ID: 8, Key: "private-api-key-secret", Name: "private-key-name", User: privateUser}
privateGroup := &service.Group{ID: 9, Name: "private-group-name", Description: "private-group-description", RateMultiplier: 7}
privateSub := &service.UserSubscription{ID: 10, User: privateUser, Group: privateGroup, DailyUsageUSD: 100}
privateAccount := &service.Account{ID: 11, Name: "private-account-name", Credentials: map[string]any{"access_token": "private-account-token"}}
for _, scoped := range []bool{true, false} {
t.Run(map[bool]string{true: "受限用量读取", false: "完整管理员保留响应"}[scoped], func(t *testing.T) {
repo := &scopedUsageResponseRepo{records: []service.UsageLog{{ID: 12, UserID: 7, APIKeyID: 8, AccountID: 11, RequestID: "request-public", RequestedModel: "requested-model", Model: "effective-model", InputTokens: 123, OutputTokens: 456, TotalCost: 1.25, ActualCost: 1, User: privateUser, APIKey: privateKey, Group: privateGroup, Subscription: privateSub, Account: privateAccount}}}
h := NewUsageHandler(service.NewUsageService(repo, nil, nil, nil), nil, nil, nil)
r := gin.New()
r.Use(func(c *gin.Context) {
if scoped {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"usage.read"}}}))
}
})
r.GET("/api/v1/admin/usage", h.List)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/usage", nil))
require.Equal(t, 200, w.Code, w.Body.String())
var result struct {
Data struct {
Items []map[string]json.RawMessage `json:"items"`
Total int64 `json:"total"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
require.Len(t, result.Data.Items, 1)
require.EqualValues(t, 1, result.Data.Total)
item := result.Data.Items[0]
require.JSONEq(t, `123`, string(item["input_tokens"]))
require.JSONEq(t, `456`, string(item["output_tokens"]))
require.JSONEq(t, `1.25`, string(item["total_cost"]))
require.JSONEq(t, `"requested-model"`, string(item["model"]))
require.JSONEq(t, `8`, string(item["api_key_id"]))
if scoped {
require.NotContains(t, w.Body.String(), "private-")
require.NotContains(t, w.Body.String(), "97531")
for _, field := range []string{"user", "api_key", "group", "subscription", "account", "balance", "credentials"} {
require.NotContains(t, item, field)
}
} else {
require.Contains(t, w.Body.String(), "private-api-key-secret")
require.Contains(t, w.Body.String(), "private-email@example.invalid")
require.Contains(t, item, "user")
require.Contains(t, item, "api_key")
require.Contains(t, item, "account")
}
require.Equal(t, "private-api-key-secret", repo.records[0].APIKey.Key, "输出投影不得修改服务返回对象")
})
}
}
func TestScopedAdminUsageListEmptyRemainsArray(t *testing.T) {
gin.SetMode(gin.TestMode)
h := NewUsageHandler(service.NewUsageService(&scopedUsageResponseRepo{}, nil, nil, nil), nil, nil, nil)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{}))
})
r.GET("/usage", h.List)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/usage", nil))
require.Equal(t, 200, w.Code)
require.Contains(t, w.Body.String(), `"items":[]`)
}
@@ -0,0 +1,65 @@
package admin
import (
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// RegistrationEmailBlacklistResponse 精确邮箱黑名单
type RegistrationEmailBlacklistResponse struct {
Emails []string `json:"emails"`
Max int `json:"max"`
}
// UpdateRegistrationEmailBlacklistRequest 整体替换精确邮箱黑名单;emails 必须显式提交,
// 传空数组表示清空。
type UpdateRegistrationEmailBlacklistRequest struct {
Emails *[]string `json:"emails"`
}
// UpdateRegistrationEmailBlacklistResponse 保存后的名单,added 为相对旧名单新增的项。
type UpdateRegistrationEmailBlacklistResponse struct {
Emails []string `json:"emails"`
Added []string `json:"added"`
Max int `json:"max"`
}
// GetRegistrationEmailBlacklist 获取精确邮箱黑名单
// GET /api/v1/admin/settings/registration-email-blacklist
func (h *SettingHandler) GetRegistrationEmailBlacklist(c *gin.Context) {
emails, err := h.settingService.GetRegistrationEmailBlacklist(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, RegistrationEmailBlacklistResponse{
Emails: emails,
Max: service.MaxRegistrationEmailBlacklistSize,
})
}
// UpdateRegistrationEmailBlacklist 整体替换精确邮箱黑名单
// PUT /api/v1/admin/settings/registration-email-blacklist
func (h *SettingHandler) UpdateRegistrationEmailBlacklist(c *gin.Context) {
var req UpdateRegistrationEmailBlacklistRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if req.Emails == nil {
response.BadRequest(c, "emails is required")
return
}
saved, added, err := h.settingService.SetRegistrationEmailBlacklist(c.Request.Context(), *req.Emails)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, UpdateRegistrationEmailBlacklistResponse{
Emails: saved,
Added: added,
Max: service.MaxRegistrationEmailBlacklistSize,
})
}
Loaded 100 of 1395 files, more files were not shown because too many files have changed in this diff. Show more