Compare commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs: GHSA-p3r4-jcm3-2hph

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Changes:

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

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

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

Existing benchmarks:

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

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

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

Three avoidable copies showed up in that path:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

All three are required:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

同步升级 8 处版本点:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

修复:

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

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

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

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

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

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

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

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

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

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

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

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

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

同步升级 8 处版本点:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Code Assist(OAuth + project_id)包装改为原字节嵌入 request,避免 Unmarshal→Marshal
重排 schema 属性顺序、截断大整数。
2026-11-11 10:17:12 +08:00
xy3 d70a23f84b feat(gemini): add Gemini 4 Carbon support 2026-11-11 10:01:42 +08:00
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
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
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 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
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
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
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
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
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
shaw ac1b8f1271 chore: update sponsors 2026-10-23 15:24:04 +08:00
shaw 8286268047 fix(deps): bump dompurify to 3.4.17 for GHSA-cg2g-xh64-v4q7 / GHSA-mrv2-3pqr-j5jr
DOMPurify <=3.4.16 is affected by two advisories published 2026-10-22:
- GHSA-cg2g-xh64-v4q7 (critical): SAFE_FOR_TEMPLATES bypass via split
  template expressions in attached shadow root content on DOM output modes
- GHSA-mrv2-3pqr-j5jr (high): IN_PLACE hook removing a parent/sibling leaves
  detached subtree event handlers armed

Bump the direct dependency and the pnpm override floor to 3.4.17 so the
mermaid-transitive copy dedupes to the same patched version. Lockfile-only
regen via pnpm 9 (matches CI); no other package changes.
2026-10-23 14:07:16 +08:00
Wesley Liddick c5b811284a Merge pull request #8305 from apple050620312/fix/openai-overload-recovery-20261023
fix(openai): 缓解 Codex overload 并恢复空流事件后的安全重试
2026-10-23 13:49:37 +08:00
apple050620312 c591412c42 fix(openai): 合并 Codex overload 身份与空流安全重试修复 2026-10-23 01:51:48 +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
Wesley Liddick dba770d56a Merge pull request #8170 from StarryKira/fix/issue-8119-grok-fast-pricing
fix(billing): Grok 4.7 Fast 按官方 Fast 价卡计费 (#8119)
2026-10-22 10:33:03 +08:00
Wesley Liddick 21cc926933 Merge pull request #8275 from apple050620312/fix/docker-go-1.27.3
fix(build): 对齐 Docker 默认 Go 镜像至 1.27.3
2026-10-22 08:44:45 +08:00
apple050620312 59100d324e fix(build): 对齐上游 Go 1.27.3 镜像版本 2026-10-21 22:53:30 +08:00
shaw 7da09cab4e chore: update sponsors 2026-10-21 20:19:37 +08:00
Wesley Liddick aa48a8bbd8 Merge pull request #8255 from wucm667/fix/issue-8248-cloudflare-json-403
fix(ratelimit): avoid penalizing Cloudflare 1010 blocks
2026-10-21 20:09:19 +08:00
Wesley Liddick 888c605733 Merge pull request #8188 from wucm667/fix/issue-8187-tool-schema-constants
fix(tools): normalize parameter constants and annotations
2026-10-21 20:09:06 +08:00
Wesley Liddick 5e45fa482b Merge pull request #8224 from wucm667/fix/issue-8222-deepseek-image-size
fix(deepseek): avoid duplicate image payloads
2026-10-21 20:08:52 +08:00
Wesley Liddick 624874b313 Merge pull request #8269 from feeeei/perf/account-quota-increment-variants
perf(billing): 账号配额累加按已设置的周期维度选择语句
2026-10-21 18:54:28 +08:00
feeeei 67dca9687e perf(billing): 账号配额累加按已设置的周期维度选择语句
计费事务中账号配额累加位于余额(或订阅用量)扣减之后、提交之前,与同一用户
共享的余额行锁处在同一持有区间。累加语句约 9.4KB,无论账号设置了哪些上限,
都要解析、规划并求值总额度、日、周三个维度的全部分支;lib/pq 每次执行都重新
规划,同一用户的并发计费在这段上串行。

- 预先拼好 4 条语句:只累加总额度、加日维度、加周维度、日周都累加(与原语句
  去空白后逐字相同)。按账号设置的日/周上限选择,只设总额度的账号使用约 1KB
  的语句。
- 选择依据来自构造计费命令时的账号配置:UsageBillingCommand 新增
  AccountQuotaHasDailyLimit / AccountQuotaHasWeeklyLimit,不参与幂等指纹。
  省略维度的语句在 WHERE 中要求 extra 为对象、被省略维度未设上限(键不存在、
  JSON null 或不大于 0 的数字);库中配置不符时命中 0 行,再执行日周都累加的
  语句,结果与原语句一致。条件只用 ->、jsonb_typeof 与 jsonb 比较,对任何行
  求值都不报错。
- 事务内语句顺序、加锁顺序、越线入队 scheduler_outbox 与返回的额度状态不变。
  集成测试对 15 种 extra 配置 × 4 种选择组合,与原语句比对 extra、updated_at、
  返回值与报错码,并断言各语句是否命中。

单条语句耗时(PostgreSQL 18,BEGIN/ROLLBACK 内,扣除空事务):
  只设总额度 0.77ms → 0.24ms
  设日上限   0.79ms → 0.50ms
  设周上限   0.79ms → 0.57ms
  日周都设   不变

压测(PostgreSQL 18、NVMe、lib/pq;1 个用户经 41 个只设总额度的账号计费,
同时运行 usage_logs 批量写入;TPS):
  并发 32:488 → 1209
  并发 64:424 → 874
  并发 128:357 → 575
2026-10-21 18:14:30 +08:00
Wesley Liddick a34f373973 Merge pull request #8251 from feeeei/perf/scheduler-snapshot-memo
perf(scheduler): 调度快照解码结果常驻进程内存,选号不再每次全量读取并解码分组
2026-10-21 17:44:14 +08:00
Wesley Liddick b3e66f79a8 Merge pull request #8250 from feeeei/perf/model-mapping-signature
perf(account): 模型映射签名改为与遍历顺序无关、零分配
2026-10-21 17:44:03 +08:00
Wesley Liddick b6c366380b Merge pull request #8249 from feeeei/perf/lazy-single-antigravity-probe
perf(gateway): 单 antigravity 账号分组判定改为按需求值,纯 Gemini/Anthropic 分组不再每请求回源数据库
2026-10-21 17:43:49 +08:00
Wesley Liddick b751230512 Merge pull request #8210 from feeeei/fix/anthropic-compat-stream-disconnect-billing
fix(gateway): Anthropic 账号 chat/responses 兼容流式客户端断开后读完上游再计费
2026-10-21 17:43:37 +08:00
Wesley Liddick 98f83b7263 Merge pull request #8167 from feeeei/fix/gemini-group-image-generation-gate
fix(gemini): 分组「允许当前分组生图」开关对 Gemini 系入口生效
2026-10-21 17:43:01 +08:00
Wesley Liddick 4c7e9b5b6b Merge pull request #8166 from feeeei/feat/vertex-account-quota
feat(account): Vertex 账号支持配额上限
2026-10-21 17:42:28 +08:00
Wesley Liddick 9a1680042a Merge pull request #8267 from wucm667/fix/issue-8266-security-scan
fix(security): clear dependency security scan failures
2026-10-21 16:54:56 +08:00
Wesley Liddick d744c22016 Merge pull request #8142 from qhmhyp/fix/account-filter-persistence
fix(accounts): persist platform and status filters
2026-10-21 16:54:21 +08:00
Wesley Liddick 4942b2afc7 Merge pull request #8139 from zenggang/contribute/openai-preoutput-metadata-20261016
fix(openai): preserve overload retries after queued and metadata events
2026-10-21 16:33:49 +08:00
wucm667 4c940c3cb7 fix(ci): synchronize Go patch version checks 2026-10-21 15:35:03 +08:00
wucm667 cacc80b862 fix(security): clear dependency security scan failures 2026-10-21 15:27:29 +08:00
wucm667 e0fa4b94f9 fix(ratelimit): avoid penalizing Cloudflare 1010 blocks 2026-10-21 02:34:30 +08:00
feeeei 53002f677c perf(scheduler): 调度快照解码结果常驻进程内存
GetSnapshot 每次选号都 ZRANGE 全组账号 ID、分块 MGET 全组 sched:meta
并逐条 JSON 解码,Redis 出口、CPU 与 GC 都随分组号数线性增长。

- 每个 bucket 的解码结果常驻进程内存。每次读取用一次 MGET 取 ready、
  active、全局修订号与 bucket 平台修订号(mixed 另加 antigravity),全部与
  条目一致且条目未超过 10 秒才复用,否则重新加载。last_used 仍每次读取,
  套用在本次调用独占的副本上,LRU 语义不变。
- 修订号是随机串:精简记录改写后写入所涉平台的修订号,与最后一批写入同一
  pipeline 发出;删除记录、账号平台变化(SET ... GET 取回旧值比对)、
  写入出错时写入全局修订号,出错路径在后台合并写入。
- 母本发布前预解析模型映射;副本在指针、长度与运行时版本都匹配时直接复用,
  不计算签名。
- 未命中、空快照、记录缺失、解码失败、Redis 出错的返回与原实现一致;选中后
  的整账号读取仍每次重新解码,转发路径对账号的原地修改不触及常驻对象。

真实 Redis 端到端(SelectAccountWithLoadAwareness,本机):
  100 号:3.83ms → 0.73ms,Redis 出口 251KB → 7.0KB,分配 2.03MB → 0.23MB
  1000 号:27.8ms → 1.92ms,Redis 出口 2.47MB → 25KB,分配 20.2MB → 1.97MB
  每次都未命中:100 号 3.83ms → 3.10ms,1000 号 27.6ms → 21.9ms
常驻内存约为每号 7KB × 活跃 bucket 数;闲置超过 100 秒的条目在写入新
条目时清除。
2026-10-21 00:38:20 +08:00
feeeei d5dbb5c36b perf(gateway): 单 antigravity 账号分组判定改为按需求值
三个入口(Gemini 原生、/v1/messages 的 Gemini 分支与 Claude 路径)
每个请求都会查询分组的 antigravity:forced 快照桶。纯 Gemini/Anthropic
分组的该桶恒为空,空快照按未命中处理,于是每个请求都回源 PG 并重新
发布快照,而判定结果只被 antigravity 账号的 503 原地重试与模型限流
预检查读取。

入口改为挂载延迟判定:antigravity 账号首次需要时才查询快照,同一请求
内只查一次;显式设置的 SingleAccountRetry 标记仍优先。其他平台的请求
不再触发该查询。
2026-10-20 23:49:34 +08:00
feeeei 38b72d734e fix(ratelimit): 模型限流快照写入改为写时复制
setAccountModelRateLimitSnapshot 原地写 account.Extra 以及其中的
model_rate_limits map。选号阶段的 Anthropic Fable 阈值过滤
(filterAccountsBySchedulingThreshold → ApplyAccountSchedulingThreshold)
会对候选账号调用它;候选账号的 Extra 一旦与其它请求共享,原地写就会造成
并发 map 读写并污染共享对象。

改为复制旧的 limits 与 Extra 顶层、写入新条目后替换 account.Extra,
不修改任何已有 map,本请求后续读取到的结果不变。其余调用方
(ratelimit_cline、cline_usage、openai_images_balance)都通过同一个
*Account 读取结果,不依赖原地修改可见。
2026-10-20 23:32:42 +08:00
feeeei 89654873ff perf(account): 模型映射签名改为与遍历顺序无关、零分配
GetModelMapping 命中缓存前要计算 model_mapping 的签名:收集全部 key、
排序、再逐个写入 fnv64a。签名只存放在 Account 的未导出字段里,不持久化、
不序列化、不跨进程比较,排序的唯一作用是消除 Go map 的随机遍历顺序。

改为逐条目计算 FNV-1a(key、分隔字节、value 或非字符串标记)并经 fmix64
收尾后求和:内容相同签名相同,单条改值、改键、两个 key 互换 value 都能检出,
且不分配内存。30 条映射单次计算约 2.3µs/1 次分配降到约 0.8µs/0 次分配;
选号时每个候选账号每次调用 3 次。
2026-10-20 23:32:41 +08:00
feeeei 4355236e00 fix(gateway): 兼容流上游未正常结束时报错并对齐原生收尾
客户端在线时,Anthropic 账号的 chat/responses 兼容流在上游未发出结束事件
(message_stop、带 stop_reason 的 message_delta 或 [DONE])就中断,不再补发
finish_reason / [DONE] / response.completed 报成功:
- 读间隔超时、读错误、message_start 之后直接 EOF:service 写出协议内终止
  事件(CC 为 error 帧,Responses 为沿用流内 id 与 sequence_number 的
  response.failed),返回错误并带上已观测到的 usage;读间隔超时调用
  HandleStreamTimeout。
- 流内 event: error:立即结束读取,与 /v1/messages 共用
  sseStreamErrorEventFailover 转为 UpstreamFailoverError,未输出前换号重试,
  客户端在线时不计费。
- 两个 handler 的错误分支对带结果的错误照常入账。

客户端断开后的读取:stream_data_interval_timeout 未启用时按 180s 启用读间隔
上限;请求 ctx 取消也视为断开。复用 anthropicNativeStreamInterval。行泵在
计时器到期且已有缓冲行时优先交付数据,下游写入慢不再被判为上游空闲。
2026-10-20 01:25:19 +08:00
feeeei 47cb84b8b0 fix(gemini): 分组「允许当前分组生图」开关对 Gemini 系入口生效
- 门禁作用于展示该开关的 Gemini 系分组(gemini/antigravity/composite);无分组 Key、
  anthropic 等其他平台分组不受影响,OpenAI/Grok 仍走各自门禁
- 生图判定:复用图片接口的 gemini-*-image 判定(isGeminiCompatibleImageModel),或请求体
  generationConfig.responseModalities 含 IMAGE(camelCase/snake_case、字符串/整数枚举、
  重复键逐个检查);countTokens 不拦
- 两道检查:/v1/messages、/v1/chat/completions、/v1/responses、/v1beta/models 入口在
  选号前按客户端请求名与渠道映射名预检;Gemini 兼容与 Antigravity 的 6 个转发函数在
  账号模型映射后再按上游模型名检查,覆盖账号级别名
- 拒绝统一返回 400(Gemini 原生 INVALID_ARGUMENT,其余 invalid_request_error),
  不触发换号与账号处罚,下游 sub2api 把本实例当上游时不会因此停用账号;
  请求标记为本地功能门禁
- 升级兼容:迁移 246 把存量 gemini/antigravity 分组的生图开关置为开启;新建分组与简易
  模式默认分组对 gemini/antigravity 默认开启(与 grok 同为 OR 语义,创建时传 false 不生效),
  前端创建表单同步默认值;composite 不回填(同一开关还控制 OpenAI 生图),未开启的
  composite 分组升级后 Gemini 生图返回 400
- 未覆盖:最终模型名不符合 gemini-*-image 形态(如上游中转自定义的 nano-banana 别名)
  且请求体未声明 IMAGE 模态;门禁按 Key 所属分组判断,Claude Code 专用分组降级到
  其他分组时仍按原分组
2026-10-19 23:53:29 +08:00
feeeei d6120b5d8e feat(account): Vertex 账号支持配额上限
- 新增 AccountTypeSupportsQuota / SupportsAccountQuota(apikey/bedrock/service_account)
  作为配额账号类型的唯一判定,累加、超限停调度、额度通知、接口输出与计费仓储统一改用;
  池模式等其它特性仍只看 IsAPIKeyOrBedrock
- service_account 配额语义与 apikey 一致:配置了任一上限才累加,用满停调度,跨阈值发额度通知
- 计费事务中账号已删除时跳过账号配额计数,与 API Key 对称,用户扣费不再整笔回滚
- 账号额度通知只对配置了上限的账号做检查
- 前端创建/编辑弹窗对 Vertex 开放配额设置,设上限后用量列显示配额进度条;
  账号类型判断收敛到 supportsAccountQuota
2026-10-19 23:31:46 +08:00
Wesley Liddick 8f2cbb53d9 Merge pull request #8177 from feeeei/fix/gemini-negative-input-tokens
fix(gemini): prompt 被拦截只报缓存命中时 input_tokens 不再为负
2026-10-19 20:45:15 +08:00
Wesley Liddick 0fa02816af Merge pull request #8168 from feeeei/fix/gemini-stream-client-disconnect-billing
fix(gemini): 流式中途客户端断开时按已收集用量计费
2026-10-19 20:45:02 +08:00
wucm667 afbef7c8cc fix(deepseek): avoid duplicate image payloads 2026-10-19 20:15:37 +08:00
Wesley Liddick 378984d87f Merge pull request #8223 from Wei-Shaw/fix/async-image-download-policy
fix(images): 异步生图转存的图片下载与同步回填策略对齐
2026-10-19 18:33:04 +08:00
shaw ab71e12ec4 fix(images): 异步生图转存的图片下载与同步回填策略对齐
异步生图任务把上游返回的图片 url 下载后转存对象存储,此前沿用默认 http.Client,
与同步 Images 端点 url 回填(c227863d)的下载策略不一致。

- 下载目的地为 localhost、回环、私网、链路本地、CGNAT 等非公网地址时不下载,
  重定向的每一跳同样校验;直连时在 socket 层按实际连接 IP 判断
- 继续支持环境变量代理:经代理时先校验目标主机的解析结果
- 响应声明类型与字节嗅探都不是图片时任务失败,不再按 png 落盘
- 下载客户端进程内共享,复用连接池;超时与大小上限不变
2026-10-19 17:51:18 +08:00
feeeei 94c7d6b025 fix(gateway): Anthropic 账号 chat/responses 兼容流式客户端断开后读完上游再计费
handleCCStreamingFromAnthropic 与 handleResponsesStreamingResponse 写客户端失败时
立即返回,message_delta 的 output_tokens 未合并,usage 记为 0。改为断开后停止向
下游写入、继续读完上游合并 usage,与原生 /v1/messages 路径一致;ForwardResult
标记 ClientDisconnect。

两条路径改用 anthropicNativeLinePump 读上游,按 gateway.stream_data_interval_timeout
限制逐行读间隔,上游挂住时关闭 body 并按已累计 usage 收尾。
2026-10-19 13:37:54 +08:00
Yuan Liu 3f4e13aaba Merge upstream main and resolve pricing comment conflict 2026-10-19 11:55:47 +08:00
wucm667 c7bfcd93aa fix(tools): normalize parameter constants and annotations 2026-10-18 04:40:42 +08:00
feeeei 9c41b32695 fix(gemini): prompt 被拦截只报缓存命中时 input_tokens 不再为负
- Vertex 拦截 prompt(promptFeedback.blockReason,如 PROHIBITED_CONTENT)时 usageMetadata
  可能只带 cachedContentTokenCount、缺 promptTokenCount,promptTokenCount − cachedContentTokenCount
  得到负的 input_tokens 与负费用
- extractGeminiUsage 与 antigravity 非流式 / 流式(累计用量、message_start)四处换算改为差值下限 0,
  缓存命中仍照上游所报计入 cache_read_input_tokens
- 补充表测试、原生流式拦截用例与 antigravity 两条路径用例
2026-10-17 19:09:23 +08:00
wucm667 7f6673ead5 fix(apicompat): preserve Anthropic cache creation TTL details 2026-10-17 13:43:55 +08:00
harukaandClaude Opus 5.5 1cdecf4a88 fix(billing): Grok 4.7 Fast 按官方 Fast 价卡计费 (#8119)
grok-4.7-fast 没有专属价格,落入「未知 Grok 文本模型」兜底按 grok-4.6
价卡计费,与普通 grok-4.7 同价($2 / $0.50 / $6),少收一半。

- 内置兜底价新增 grok-4.7-fast:<200k 为 $4 输入 / $1 缓存读取 / $12 输出
  (每百万 token,标准价 2 倍);>=200k 整次请求为 $6 / $1.50 / $18,
  即 Fast 基础价 1.5 倍,阈值口径与其它 xAI 价卡一致(达到即进高档)
- grok-4.7-build-fast(Grok Build 侧的 Fast ID,见 #7502)同样命中该价卡
- 本地价格快照新增 grok-4.7-fast 条目,带 xai/ 前缀的写法也能识别

价格来源:https://docs.x.ai/developers/pricing(Grok 4.7 Fast,仅 Cursor
与 Grok Build 提供)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:13:58 -04:00
feeeei 2b1f129385 fix(gemini): 流式中途客户端断开时按已收集用量计费
- 原生 /v1beta、Claude 兼容 /v1/messages、Chat 兼容三条流式路径:读取中断由客户端
  断开引起(context.Canceled 或请求 context 已取消),且已观测到 token 用量或已回吐
  图片时,以已收集结果收尾并返回成功,handler 照常提交 usage;ForwardResult 标记
  ClientDisconnect
- 读到结束分片后断开按完整用量计费;中途断开按断开前最后一份 usageMetadata 计费,
  断开前无任何用量时仍不计费
- 图片数:收到 finishReason 前断开只计已送达的图片(原生按已观测 inlineData,Claude/
  Chat 兼容流不转发图片计 0);收到 finishReason 后断开与正常完成同口径
- Chat 兼容流写失败断开的既有返回同样带上断开标记与结束状态
- 原生路径读错误时不处理未以换行结尾的残行,避免截断的 usageMetadata 覆盖已收集用量
- 上游 context 不解绑:Gemini 兼容链路没有流空闲超时,解绑后上游挂起会让读取无限期阻塞
- 客户端未断开时的上游读错误、非流式客户端断开、Antigravity 非流式转换的读错误
  行为不变
2026-10-17 01:00:51 +08:00
wucm667 eb4ccd173e fix(openai): apply reasoning mappings to synthesized effort 2026-10-16 20:32:00 +08:00
github-actions[bot] b0a02a3304 chore: sync VERSION to 0.2.17 [skip ci] 2026-10-16 04:42:02 +00:00
Wesley Liddick 060d016041 Merge pull request #8140 from Wei-Shaw/fix/issue-8118-responses-created-at
fix(responses): 网关送出的 Responses 对象一律带 created_at,修复 grok-build 反序列化失败
2026-10-16 12:28:11 +08:00
Wesley Liddick b14f316ca2 Merge pull request #8080 from SipengXie2024/fix/openai-messages-web-search-emulation
fix(openai): emulate web_search on /v1/messages for OpenAI API key accounts
2026-10-16 12:27:52 +08:00
Wesley Liddick 43157c478e Merge pull request #8121 from Larry-Labs/fix/gpt55-subscription-retirement
fix(openai): respect GPT-5.5 retirement on ChatGPT upstreams
2026-10-16 12:27:39 +08:00
ahe 7fcaa32db4 fix(accounts): persist platform and status filters 2026-10-16 11:54:50 +08:00
shaw 71e6b6a971 test(responses): 模型改写转发测试夹具补齐上游 created_at
网关现会为缺 created_at 的 Response 对象补齐该字段(#8118),该测试以
"输出包含上游原始字节"断言模型改写,夹具缺 created_at 时输出多出补齐字段
而失配。夹具改为真实上游必带 created_at 的形态,测试意图(仅改写 model)不变。
2026-10-16 11:38:13 +08:00
shaw f2e5b55f3e test(responses): 模型改写转发测试夹具补齐上游 created_at
网关现会为缺 created_at 的 Response 对象补齐该字段(#8118),该测试以
"输出包含上游原始字节"断言模型改写,夹具缺 created_at 时输出多出补齐字段
而失配。夹具改为真实上游必带 created_at 的形态,测试意图(仅改写 model)不变。
2026-10-16 11:37:24 +08:00
shaw bdfe215cbb fix(responses): 网关送出的 Responses 对象一律带 created_at,修复 grok-build 反序列化失败
grok-build / Codex 等 Rust serde 客户端把 Response.created_at 与事件的
sequence_number 当必填字段,缺失即 `missing field 'created_at'` 整轮读不出响应。
#5601 只补了 apicompat 两座桥的合成路径,以下出口仍会送出缺字段的对象:

- 合成的 response.failed:buildOpenAIResponseFailedSSE(主流 + 透传)与
  buildOpenAIWSHTTPBridgeFailedEvent 在流以裸 error 结束时补发终止帧,
  缺 created_at,前者还缺 sequence_number。现统一写出:created_at 取本流
  上游值(无则当前时间),sequence_number 沿用被替换的裸 error 帧序号(无则 0)。
- 上游原样透出:Grok 账号挂第三方中转时,上游 Response 对象可能不带
  created_at,网关逐字节转发后客户端同样失败。现于 Responses 流式出口、
  WS HTTP 桥(Grok WS 恒走此路)与非流式 JSON 出口,对缺失/null 的
  created_at 补一个整条流固定的时间戳;上游已带时输出逐字节不变。

透传路径保持不改写上游事件,只观察 created_at 供合成终止帧对齐。

Fixes #8118
2026-10-16 11:22:48 +08:00
zeng gang e068c3d02f fix(openai): preserve overload retries after queued and metadata events 2026-10-16 11:17:44 +08:00
Wesley Liddick 455d317d6a Merge pull request #8114 from feeeei/feat/gemini-compat-thinking
feat(gemini): 兼容入口转发思考档位并流式返回思考摘要
2026-10-16 10:53:56 +08:00
shaw a431e53f9e Merge remote-tracking branch 'origin/main' into pr-8114
# Conflicts:
#	backend/internal/service/gemini_chat_completions_compat_service.go
2026-10-16 10:09:46 +08:00
Wesley Liddick b8cfb78840 Merge pull request #8133 from Wei-Shaw/fix/easypay-query-confirm
fix(payment): fix EasyPay order queries and confirm notifications before crediting
2026-10-16 10:06:43 +08:00
shaw 1b92038eaf fix(payment): fix EasyPay order queries and confirm notifications before crediting
Order query:
- 彩虹易支付 and ZPay read act=order parameters from the URL query only;
  a body-only request is answered with "No Act!", so order status queries
  (reconcile, payment status checks) never reached the order. Parameters
  are now sent in the URL query and mirrored in the form body for forks
  that read the body.
- Decode status/money/trade_no leniently: PHP deployments commonly return
  integers as strings ("status":"1"), which previously failed the whole
  response decode. JSON null falls back to the nested data object.
- Treat a non-success code as a query error instead of an unpaid order,
  and require an echoed out_trade_no to match the queried order.
- Strip the request URL (which carries the merchant key) from transport
  errors before they are returned.

Notifications:
- Add payment.NotificationConfirmer. After a notification is verified, the
  webhook asks the same provider instance to confirm it; EasyPay queries
  the upstream order and requires it to be paid with a matching amount and
  trade_no (a missing notify trade_no is filled from the query). Failures
  are recorded as PAYMENT_UPSTREAM_UNCONFIRMED and answered with 502 so the
  gateway retries; the order stays pending and reconcile still applies.
- EasyPay notifications must carry the instance's configured pid, and
  field values other than name must be plain tokens.
- Return URLs must use a plain hostname or IP literal without userinfo.
2026-10-16 09:39:55 +08:00
Wesley Liddick 52b3ca9609 Merge pull request #8122 from Wei-Shaw/fix/payment-order-type-refund-hold
fix(payment): validate order types, keep refund deductions while pending, load Stripe secret from local snapshot
2026-10-16 08:32:48 +08:00
xugao 86f8443045 fix(openai): evaluate retirement after public alias projection 2026-10-15 22:42:45 +08:00
shaw f37b69b779 fix(payment): treat Alipay refund query errors as pending and delay not-found failure
- The SDK returns signed business-failure responses (for example
  ACQ.SYSTEM_ERROR) with a nil error and empty fields. QueryRefund now
  checks the response code and returns an error, so the order stays
  REFUND_PENDING instead of being read as "no refund record" and failed.
- A missing refund record is treated as failed only after a 10 minute
  grace period from when the refund became pending. Alipay notes that a
  query sent too soon can miss a refund that later succeeds. The pending
  time comes from the REFUND_PENDING audit entry.
2026-10-15 22:26:53 +08:00
shaw 83337a0c65 fix(payment): query Alipay refund status and close unsupported order types
- Alipay: record the generated out_request_no as the refund ID and
  implement QueryRefund (alipay.trade.fastpay.refund.query), so refunds
  that return fund_change=N can be finalized from the admin refund query.
  Refunds recorded before this change return REFUND_QUERY_UNSUPPORTED.
- Fulfillment: mark paid orders with an unsupported order type as FAILED
  with an audit entry instead of erroring, so payment callbacks are
  acknowledged; RetryFulfillment rejects them with INVALID_ORDER_TYPE.
2026-10-15 22:03:15 +08:00
shaw 44e35fbf84 fix(payment): finalize failed pending refunds atomically
- Claim REFUND_PENDING -> REFUND_FAILED, return the held deduction and
  write the audit in one transaction. If the deduction cannot be
  returned, the order is still marked failed together with a
  REFUND_ROLLBACK_FAILED audit so a retried refund skips the deduction.
- Return an error when the REFUND_PENDING audit cannot be loaded or
  parsed instead of falling back to the legacy finalization path.
2026-10-15 21:38:57 +08:00
harukaandClaude Opus 5.5 f996b0bfaa fix(payment): load Stripe client secret from the local order snapshot
The /payment/stripe route no longer carries client_secret in its query.
The page reads it from the recovery snapshot written when the order was
created and requires the snapshot order to match order_id, consistent
with AirwallexPaymentView.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:38:52 +08:00
harukaandClaude Opus 5.5 7c6f70680d fix(payment): validate order types and keep refund deductions while pending
- Validate order_type (balance/subscription) at order creation and in
  fulfillment; other values are rejected with INVALID_ORDER_TYPE.
- Keep the balance/subscription deduction while a gateway refund is
  pending. The deduction is recorded in the REFUND_PENDING audit (written
  in the same transaction as the status change), not applied again on
  successful finalization, and returned once if the gateway reports
  failure. Legacy pending audits keep the previous behaviour.
- REFUND_PENDING orders are finalized via refund query only;
  PrepareRefund/ExecuteRefund no longer accept them.
- Invalidate the billing balance cache after refund deductions/returns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:38:48 +08:00
Wesley Liddick 1b2243a4f5 Merge pull request #8120 from Wei-Shaw/revert/inline-account-filters
revert(accounts): restore inline account filters (#7853)
2026-10-15 21:01:40 +08:00
xugao 26aab6dc07 fix(openai): respect GPT-5.5 retirement on ChatGPT upstreams 2026-10-15 20:53:15 +08:00
shaw c2cca510f2 revert(accounts): restore inline account filters (#7853)
Revert 679a7186f ("feat(accounts): compact account search and filters"),
which moved the type / privacy / group filters behind a collapsed
"More filters" panel on /admin/accounts.

Polish on top of the revert:
- Widen the privacy select (w-48) so "全部Privacy状态" / "All Privacy States"
  no longer truncates.
- Narrow the search input to w-52 so all six controls fit on one row at 1440px.
- Below sm, lay the filters out as a two-column grid that fills the width
  instead of fixed-width selects with a ragged edge.
2026-10-15 20:44:29 +08:00
Wesley Liddick 698d142468 Merge pull request #8088 from wucm667/fix/issue-8077-workspace-aware-import
fix(openai): isolate Codex imports by workspace
2026-10-15 16:40:38 +08:00
Wesley Liddick ddef05527e Merge pull request #8079 from wucm667/fix/issue-8074-anthropic-base-url
fix(gateway): honor Anthropic protocol base URLs.
2026-10-15 16:40:19 +08:00
Wesley Liddick 58b5e858c8 Merge pull request #8094 from wucm667/feat/issue-8092-configurable-min-output
feat(apicompat): configure minimum output token floor
2026-10-15 16:40:06 +08:00
feeeei 64211de8de feat(gemini): 兼容入口转发思考档位并流式返回思考摘要
- chat/messages 兼容入口把 reasoning_effort、thinking、output_config.effort
  映射为 Gemini thinkingConfig:2.5 用 thinkingBudget,3 及以上用 thinkingLevel;
  minimal 只发给 flash 系列,medium 只发给 flash 系列与 3.1 Pro,其余升为 high;
  图像/语音/向量与无法识别版本的型号、带档位后缀的型号不写档位
- 流式请求开启 includeThoughts(messages 需客户端开启 thinking),thought part
  转为 Anthropic thinking 块,chat 侧输出为 reasoning_content
- 历史中的 thinking 块与 chat 回传的推理内容不再发给 Gemini;签名降级重试先删
  历史思考块再降级,思考参数沿用客户端原始请求
- messages 兼容路径记录实际转发的思考档位,与 chat 兼容路径一致
2026-10-15 16:26:46 +08:00
Wesley Liddick 857a76d4a0 Merge pull request #8093 from baryon/contrib/gemini-4-argon-support
feat(antigravity): support Gemini 4 Argon and accurate upstream model catalogs
2026-10-15 16:13:07 +08:00
shaw 9d3cc4507f fix(antigravity): keep legacy default passthroughs and bill Claude 5.5 tier IDs at base rates
- Restore runtime default passthroughs and Gemini 3.1 Pro aliases for
  explicit Antigravity model_mapping. Mappings saved before the Gemini
  3.x Flash / 3.1 Pro releases still depend on them; dropping them would
  silently remove those models from existing accounts on upgrade.
- Capability sync now skips injected-only passthrough targets, so models
  the upstream catalog omits no longer mark the sync as partial.
- Price Antigravity claude-{opus,sonnet}-5-5-{high,medium,low} at the base
  Opus/Sonnet 5.5 card instead of substring-matching claude-opus-5 /
  claude-sonnet-4-5 (1.25x-3x overbilling).
2026-10-15 15:47:42 +08:00
shaw 8afd2abd97 Merge remote-tracking branch 'origin/main' into contrib/gemini-4-argon-support
Resolve Gemini 4 Argon pricing conflicts in favor of main (#8078), which
already provides the base and Cyber Permissive price cards, thinking-tier
pricing aliases, and the local pricing snapshot.
2026-10-15 15:37:14 +08:00
Wesley Liddick dcde68aa58 Merge pull request #8078 from feeeei/feat/gemini-4-argon-pricing
feat(gemini): 补齐 Gemini 4 Argon 计费
2026-10-15 15:27:15 +08:00
Wesley Liddick abdc82725f Merge pull request #8076 from feeeei/fix/gemini-vertex-sa-and-error-policy
fix(gemini): Vertex SA 已删除时停用账号并换号,401 临时不可调度规则首次命中不再永久停用
2026-10-15 15:27:01 +08:00
Wesley Liddick 3b83e045ed Merge pull request #8060 from feeeei/fix/gemini-vertex-shared-capacity-429
fix(gemini): Vertex 共享容量不足的 429 不冷却账号,改为同号退避重试
2026-10-15 15:26:51 +08:00
Wesley Liddick fdc7f1fa01 Merge pull request #8087 from coder-zhw/fix/zhipu-credit-limit-window-classification
fix(zhipu): 修正 GLM Coding Plan 5h/weekly 用量窗口标反 / fix swapped GLM coding plan usage windows
2026-10-15 15:26:38 +08:00
Wesley Liddick 3856a02856 Merge pull request #8106 from Wei-Shaw/fix/composite-oauth-ambiguous-misroute
fix(gateway): 拒绝含 OpenAI 网关 OAuth 的 composite 歧义路由,防止凭据误入 Anthropic 管线
2026-10-15 15:08:47 +08:00
shaw d19265ddb2 fix(gateway): 拒绝含 OpenAI 网关 OAuth 的 composite 歧义路由,防止凭据误入 Anthropic 管线
composite 分组中 openai OAuth 账号与 deepseek API Key 账号同时显式映射同一
gpt 模型时,模型归属判为歧义、路由层不解析平台,请求落到默认 Anthropic
GatewayHandler;handler 再按模型名前缀猜回 openai 并选中 OpenAI OAuth 账号,
ChatGPT token 被发往 api.anthropic.com,上游 401 "Invalid bearer token"
经 failover 逐号打成临时不可调度,单请求即可扫空号池。

- 归属记录声明方是否含 OpenAI 网关族 OAuth / setup-token;当模型名兜底也
  落在 OpenAI 网关族时判为配置错误,路由中间件与 WS 入口直接 400 拒绝并
  提示配置显式路由。纯 API Key 歧义及 Anthropic/Antigravity/Gemini OAuth
  歧义保持原行为。
- 模型归属改按配置计算(ListModelAvailabilityCandidates),不再随限流 /
  临时不可调度在「唯一归属」与「歧义」之间翻转。
- Anthropic 请求构建前校验凭据:非 Anthropic 网关族的 OAuth 凭据不出站,
  返回仅换号、不处罚账号的 failover;count_tokens 返回 404 不支持。
  API Key 不受限(上游可能兼容多种协议格式)。
2026-10-15 14:57:03 +08:00
coder-zhw 1774b79dcb fix(zhipu): 修正 GLM Coding Plan 5h/weekly 用量窗口标反
parseZhipuTokenTiers 只在 limitType == "TOKENS_LIMIT" 分支里按 unit 显式分类,
而智谱当前把 5h / weekly 两条窗口都标成 CREDIT_LIMIT(level=lite)。这些条目被放进
creditFallback,entry 结构体又不带 unit,信息在此永久丢失,降级路径退化为
「按 nextResetTime 升序填空位」。当周窗口先于 5h 重置时(每个周期临尾的几小时),
周窗口会被先填进 5h 槽,两档必然标反 —— 函数文档注释第 1 条已警告过该场景,
只是防线建在了错误的 type 分支上。

因为只在「CREDIT_LIMIT 且周窗口更早重置」这一种组合下出错,症状是间歇性的,
容易被误判为随机抽风。该函数自 v0.2.0 到 v0.2.16 逐字节未变,不属于版本回归。

改动:
- entry 增加 unit 字段;classify 改为直接接收 unit,不再依赖 item。
- 仅在降级路径(无任何 TOKENS_LIMIT 条目)上,对 creditFallback 中 unit 可识别的
  条目先按 unit 分类;unit 仍不可识别的才落入原有的 reset 时间启发式。
- TOKENS_LIMIT 优先占槽的既有语义保持不变:两种 type 同时返回时 CREDIT_LIMIT
  依旧不参与槽位竞争。
- 更新 cnZhipuWindow 与 parseZhipuTokenTiers 的文档注释。
- cn_providers_test.go 补充 3 个回归用例。

验证:
- 反向验证:仅回退源文件保留测试,CreditLimitUnitClassification 失败于
  14 vs 90(两档被对调);另两个钉住原语义的用例修复前后均通过。
- go build ./... 通过;gofmt -l 无输出;golangci-lint v2.14.0 0 issues。
- go test -tags=unit ./internal/service/ 全量通过。

影响范围:backend/internal/service 两个文件(service + unit test)。
2026-10-15 14:56:00 +08:00
shaw 92c9433d40 chore: update sponsors 2026-10-15 08:53:20 +08:00
Long Li feab6d80dc fix(antigravity): preserve tool_result images, native Gemini functionCall/thoughtSignature, and composite /v1beta routing 2026-10-15 06:55:32 +09:00
wucm667 2a8cb088af feat(apicompat): configure minimum output token floor 2026-10-15 01:56:00 +08:00
Long Li 373d43533a feat(antigravity): support Gemini 4 Argon and accurate upstream model catalogs 2026-10-15 02:06:23 +09:00
wucm667 16611a8ee0 fix(openai): isolate Codex imports by workspace 2026-10-14 18:34:52 +08:00
SipengXie2024 7de15113c7 fix(openai): exclude OAuth accounts from web search emulation
Keep OpenAI non-API-key accounts on native search before channel inheritance. Cover 72 combinations of account types, modes, channel flags and global enablement in the shared interception gate.

Validation: the regression test fails in six OAuth/setup-token channel-enabled cases on the original code and passes with this guard. Related WebSearch unit tests pass. The broad service/handler test run was blocked by automatic approval review due to an unrelated daily-cloudcode-pa.googleapis.com request with unverified payload/credential use.
2026-10-14 16:44:53 +08:00
Shumin c01b2cb817 ci: retrigger CI (previous run hit Docker Hub rate limit) 2026-10-14 03:12:15 -04:00
SipengXie2024 26e55cf332 fix(openai): emulate web_search on /v1/messages for OpenAI API Key accounts
Chat Completions conversion drops Anthropic web_search tools, so Claude
Code's WebSearch on OpenAI-platform groups (e.g. DeepSeek upstreams)
got no web_search_tool_result and reported 0 results. Run the existing
search emulation in ForwardAsAnthropic and let OpenAI API Key accounts
opt in via extra.web_search_emulation.
2026-10-14 07:02:52 +00:00
wucm667 867563ae76 fix(gateway): honor Anthropic protocol base URLs 2026-10-14 14:58:26 +08:00
feeeei c6c9935ae3 feat(gemini): 补齐 Gemini 4 Argon 计费
- 内置兜底价:gemini-4-argon 为 $2 输入 / $10 输出 / $0.10 缓存读取(每百万
  token,优惠价有效期至 2026-11-30,2026-12-01 起为 $4 / $20 / $0.20);
  Cyber 变体(gemini-4-argon-cyber-permissive)不参与优惠,为 $4 / $20 / $0.20,
  匹配时先于基础型号判断
- Antigravity 的 -low / -medium / -high 档位名归一到基础价
- 本地价格快照新增两个不带前缀的条目,含 Priority 档价格;所有提示词长度同价,
  不带长上下文阶梯;只支持隐式缓存,不带存储价
2026-10-14 14:22:17 +08:00
feeeei 14cd587175 fix(gemini): 每个上游错误响应只检查一次错误策略
- 三条 Gemini 转发路径在重试循环内和循环外各对最终上游错误响应检查一次错误策略。
  配了账号级 401 临时不可调度规则的 API Key / Vertex 账号首次收到 401 时,第一次
  检查写入 401 暂停记录,第二次检查读回该记录判定为重复 401,同一请求内即升级为
  error 永久停用
- 循环内的检查结果带到循环外复用;循环内未检查的最终响应(Claude 兼容层的签名 400
  分支、原生路径的 cachedContent 透传分支)仍在循环外检查
2026-10-14 12:00:44 +08:00
feeeei 20c4bf5ae5 fix(gemini): Vertex SA 已不存在时账号置为 error 并换号
- 换取 SA access token 时 token 端点返回 400
  {"error":"invalid_grant","error_description":"Invalid grant: account not found"}
  表示服务账号已被删除,凭据再也换不到 token;此前三条 Gemini 转发路径把它当作
  本地构造请求失败直接回 502,不换号也不改账号状态,账号持续被调度
- 识别该错误后账号置为 error 并停止调度(Service account token rejected (400): …),
  记录凭据获取阶段(stage=account_auth)的 Ops 事件,请求交给 handler 换号
- 只匹配 400 + invalid_grant + account not found:invalid_grant 还涵盖时钟偏差、
  签名无效等情况,其他换 token 失败保持原行为
- token 端点地址改为包级变量,测试中替换为本地服务
2026-10-14 11:58:37 +08:00
shaw 9c2cca9e62 chore: update sponsors 2026-10-14 11:30:36 +08:00
feeeei 89ad4c2caa fix(gemini): Vertex 共享容量不足的 429 不冷却账号,改为同号退避重试
- Vertex 按量付费返回的 "Resource exhausted ... try again later"
  (RESOURCE_EXHAUSTED、无错误明细)表示共享资源池当时没有容量,与账号额度
  无关;此前一律冷却账号 1 分钟,冷却期间账号被调度快照剔除,绑定显式缓存
  的请求因无法换号直接 503
- 这类 429 只记日志、账号保持可调度,由请求内同号 1/2/4/8s 退避重试消化,
  重试用尽后未绑定缓存的请求照常换号
- 带 retryDelay、文案重试时长、配额/预留吞吐字样或其他形态的 429 仍按账号
  自身限速冷却;非 Vertex 账号行为不变
2026-10-13 23:51:43 +08:00
github-actions[bot] 4d9ac3e482 chore: sync VERSION to 0.2.16 [skip ci] 2026-10-13 07:20:40 +00:00
Wesley Liddick 01842576b3 Merge pull request #7810 from wucm667/fix/issue-6247-responses-chat-fallback
fix(gateway): retry rejected structured input through chat endpoint
2026-10-13 15:01:20 +08:00
Wesley Liddick 49b2122dc6 Merge pull request #7991 from wucm667/fix/issue-7988-international-quota
fix(quota): recognize international coding endpoints
2026-10-13 15:00:31 +08:00
Wesley Liddick 8d7d3185e9 Merge pull request #8038 from wucm667/fix/issue-8035-gemini-tool-result-images
Preserve images from tool results
2026-10-13 15:00:04 +08:00
Wesley Liddick bba85923b9 Merge pull request #8046 from wucm667/fix/issue-8040-antigravity-image-rate-limit
Isolate Antigravity image model rate limits
2026-10-13 14:59:39 +08:00
Wesley Liddick 49dc6e2363 Merge pull request #7828 from feeeei/feat/temp-unsched-rule-scope
feat(account): 临时不可调度规则新增作用范围 scope 选项
2026-10-13 14:59:27 +08:00
shaw 9d5e63a598 合并 main 并解决 PR #7828 的测试文件冲突
完整保留临时不可调度规则作用范围测试与 Gemini 显式缓存测试;保留双方生产代码改动。
2026-10-13 14:59:02 +08:00
Wesley Liddick 53c21fed25 Merge pull request #8006 from feeeei/feat/gemini-explicit-cache
feat(gemini): 支持显式上下文缓存,并完善 Vertex 与第三方 API Key 账号
2026-10-13 14:51:11 +08:00
Wesley Liddick 7c5afa4c36 Merge pull request #7957 from xcrong/feat/haiku-5-5-support-7919
feat(gateway): adapt Claude Haiku 5.5
2026-10-13 14:50:40 +08:00
shaw b669dc6daf test(frontend): 将模型白名单回归用例纳入 CI 2026-10-13 14:42:29 +08:00
shaw c4bdc48475 fix(haiku): 修正采样边界、默认模型配置与 lint 2026-10-13 14:38:16 +08:00
xcrong 26f70c6a87 fix(gateway): wire Claude Haiku 5.5 into Responses bridge
ResponsesToAnthropicRequest only recognized opus/sonnet 5.5, so Haiku
requests fell into the generic enabled+budget_tokens path (upstream 400)
and lost signed thinking history (preserveThinking=false). Mirror the
Messages-side rules: adaptive+medium default, none->disabled+low,
temp/top_p/combo guards, forced tool_choice allowed.

Also preserve Haiku55 thinking signatures in AnthropicToResponsesResponse
and streaming state, and name the model correctly in the between_tools
rejection.
2026-10-13 10:45:13 +08:00
wucm667 cfbbfd6b3b fix(antigravity): isolate image model rate limits 2026-10-13 09:24:38 +08:00
feeeei 43a3c197cb fix(gemini): 显式缓存恢复流程区分账号已删除与暂不支持缓存,上游必已过期后作废意图
后台回滚在持有账号返回 nil 时把修改意图当作已回滚清除:账号临时关闭显式缓存能力后
意图丢失,重新开启也无法补偿。

- boundAccount 区分两种情形:账号已删除返回 nil,账号存在但不支持显式缓存返回
  errGeminiCachedContentAccountUnsupported;BoundAccount 对外行为不变
- 账号暂不支持缓存时不改动上游、保留意图,租约过期后重试(期间同一缓存的修改返回 409);
  账号已删除时没有凭据可回滚上游,软删本地记录
- 修改前到期时间加上单次最长有效期与 1 小时容忍都已过去时上游缓存必已自行过期:
  账号不支持缓存或上游回滚持续失败的意图不再重试,直接作废本地记录
- 测试夹具 GetForOwner 过滤已软删记录
2026-10-13 00:54:27 +08:00
feeeei 2023c290e1 fix(account): 计数、Bedrock 与重试耗尽入口把上游模型交给错误处理
OpenAI 与 Anthropic 的 count_tokens / input_tokens 入口、Bedrock 故障转移入口
以及 OAuth 403 重试耗尽入口调 HandleUpstreamError 时没有传入实际发往上游的模型,
显式 scope=model 的 401 规则在这些入口看到空模型,仍落到 handleAuthError 整号置 error。

- 四处计数入口传入映射后的上游模型;Anthropic 透传计数函数新增 upstreamModel 参数
- handleRetryExhaustedSideEffects / handleRetryExhaustedError 增加模型变参,
  Forward、Anthropic 透传与 Bedrock 三处调用方传入实际模型
- Bedrock 入口传调度器的模型键(account.GetMappedModel),不是发往上游的
  Bedrock 模型 ID,模型级冷却才会被调度器读取
- 这些入口的 404 模型未找到与缺省 scope 的非 401 规则随之按主转发路径语义处理
  (模型已知走模型级)
2026-10-13 00:53:39 +08:00
Wesley Liddick ab80abc6d1 Merge pull request #7960 from feeeei/feat/group-i18n
feat(groups): 分组名称与描述支持多语言
2026-10-12 22:16:51 +08:00
wucm667 492c630599 fix(gemini): satisfy test lint 2026-10-12 19:13:17 +08:00
wucm667 ba2a717332 fix(gemini): preserve images from tool results 2026-10-12 18:52:00 +08:00
feeeei 8b74741efe fix(groups): 广场 Vary 保留 Origin,分组译文语言代码统一大小写
- 模型广场以追加方式写入 Vary: Accept-Language,保留 CORS 中间件为具体来源
  写入的 Vary: Origin
- 管理端写入分组译文时语言代码统一为 BCP 47 惯用大小写(en、zh-TW),
  统一后重复的语言代码(如 en 与 EN)返回 400 INVALID_GROUP_I18N
- 用户侧按语言取译文时规范写法的键优先,仅大小写不同的多个键按字节序取最小者,
  同一请求语言的结果固定
2026-10-12 18:09:03 +08:00
feeeei fc82e83102 fix(account): 显式模型级 401 规则在网关故障转移入口生效
OpenAI 转发 fastpath、HandleUpstreamError 及两处池模式分支对 401 一律跳过
临时不可调度规则,显式 scope=model 的 401 规则在 API Key 账号上仍落到
handleAuthError 整号置 error。

- 新增 tempUnschedRulesApply:401 仅在首条命中规则按模型级生效时交给规则,
  其余保持认证错误处理
- 凭据级 401(OAuth 账号与 Spark 影子、OpenAI token_invalidated/token_revoked、
  {"detail":"Unauthorized"})不受规则作用范围影响,各入口沿用原有处理
- 模型级命中不参与重复 401 升级;fastpath 不再因模型级命中封整号
2026-10-12 17:39:26 +08:00
Wesley Liddick 9591136d45 Merge pull request #8033 from Larry-Labs/fix/gpt61-sol-500k-context
fix(codex): raise GPT-6.1 Sol generated context default to 500k
2026-10-12 17:18:51 +08:00
feeeei 26b31a83e4 fix(gemini): 显式缓存修改串行化、失败回滚,确定金额费用按 Key / 订阅预留
同一缓存的并发 PATCH 可能以与上游提交不同的顺序写回本地到期时间;
确定金额的存储费只预留用户余额,并发续期可越过 API Key 总额度与订阅额度;
上游已修改而本地写回失败时没有可恢复的状态。

- 新增迁移 245:缓存记录增加修改意图(mutation_token / mutation_lease_until)。
  PATCH 在调用上游前登记意图并取得 2 分钟租约,条件为没有进行中的修改且到期时间
  未变;上游修改、本地写回与计费均由持有者完成,并发的修改返回 409 ABORTED
- 上游结果未知、本地写回失败或进程退出时修改意图保留且不计费;租约过期后由下一次
  修改或后台每分钟的恢复流程把上游有效期回滚到修改前的到期时间(已到期则删除上游
  缓存与本地记录)。上游明确拒绝或请求未发出时直接清除意图
- 修改 / 删除上游缓存的单次调用超时改为 30 秒;请求发出前的失败包装为
  ErrGeminiCachedContentRequestNotSent
- CheckChargeAffordable 与 ReserveInflightCharge 合并为 ReserveFixedCharge:在途预留
  新增订阅、API Key 两个维度(Redis billing:inflight_scope:*),先登记本笔预留再读取
  库中权威用量(Key quota_used 与限速窗口、订阅日 / 周 / 月用量)叠加同维度在途合计
  校验;预留随计费任务交接,落库后释放
- GetRateLimitData 一并读取 quota_used
2026-10-12 17:14:56 +08:00
Wesley Liddick 7b03b1f75a Merge pull request #8036 from Wei-Shaw/fix/gpt61-sol-subscription-long-context
fix(billing): 取消 GPT-6.1 Sol 订阅长上下文附加费
2026-10-12 17:04:09 +08:00
shaw 43768680d3 fix(billing): 取消 GPT-6.1 Sol 订阅长上下文附加费 2026-10-12 16:47:22 +08:00
xugao 0718581265 fix(codex): raise GPT-6.1 Sol generated context default to 500k 2026-10-12 15:16:44 +08:00
Wesley Liddick e468262294 Merge pull request #8002 from obst4cle/fix/group-rpm-override-stale-load
fix(groups): ignore stale RPM override loads
2026-10-12 14:38:14 +08:00
Wesley Liddick 5dbb8f7085 Merge pull request #7649 from Yukinoshita-Yukino/fix/codex-image-bridge-openai-only
fix(openai): only inject the Codex image generation bridge for OpenAI accounts
2026-10-12 14:38:00 +08:00
Wesley Liddick 6d509c632d Merge pull request #7711 from wucm667/fix/issue-7709-risk-control-groups
fix(risk-control): remove deleted groups from moderation scope
2026-10-12 14:37:44 +08:00
Wesley Liddick 6a6d4728a0 Merge pull request #7696 from a408665321/codex/issue-7687-timer-only
fix(ui): refresh usage countdown when tab becomes visible
2026-10-12 14:37:26 +08:00
Wesley Liddick 832677a5e6 Merge pull request #7717 from ouchihao/codex/bug-payment-countdown-drift
fix(payment): calculate QR countdowns from elapsed time
2026-10-12 14:37:11 +08:00
Wesley Liddick c2885c430f Merge pull request #7738 from r266-tech/codex/monitor-add-platform
fix(monitor): allow adding missing platforms in v2 settings
2026-10-12 14:36:41 +08:00
Wesley Liddick 59fb22791e Merge pull request #7933 from yan9651688/feat/issue-7926-ops-details-account-column
feat(ops): show account names in request details table
2026-10-12 14:36:28 +08:00
Wesley Liddick 20b0be5b05 Merge pull request #7969 from ouchihao/codex/bug-ops-custom-timezone
fix(ops): initialize custom time ranges in local time
2026-10-12 14:36:12 +08:00
Wesley Liddick d70265306b Merge pull request #7970 from ouchihao/codex/bug-select-ime-navigation
fix(select): preserve keyboard input during IME composition
2026-10-12 14:35:53 +08:00
Wesley Liddick f2b1556bd4 Merge pull request #7972 from ouchihao/codex/bug-group-rate-edit-validation
fix(groups): reject nonpositive rate multiplier edits
2026-10-12 14:35:37 +08:00
Wesley Liddick 0ae1b371fa Merge pull request #7973 from ouchihao/codex/bug-monitor-auto-detail-refresh
fix(monitor): refresh cached availability on automatic reload
2026-10-12 14:35:24 +08:00
Wesley Liddick da9799542d Merge pull request #7974 from ouchihao/codex/bug-gemini-auth-url-error
fix(gemini): preserve authorization URL error messages
2026-10-12 14:35:12 +08:00
Wesley Liddick 6977bb63bb Merge pull request #7983 from hutututtt/fix/account-group-names
fix(frontend): show full account group names
2026-10-12 14:34:58 +08:00
Wesley Liddick b63dafa426 Merge pull request #7982 from wucm667/fix/issue-7981-embedded-static-asset
test(web): use shipped SVG asset in embedded frontend tests
2026-10-12 14:34:38 +08:00
feeeei daebb7a80c fix(gemini): 模型列表与模型详情接口支持 Agent Platform (Vertex) 账号
Gemini 分组对外提供 AI Studio 兼容协议,分组内账号不一定是 AI Studio。
分组只剩 Vertex 服务账号时,GET /v1beta/models 与 /v1beta/models/{model}
选中服务账号后报 502 unsupported account type: service_account。

- SelectAccountForAIStudioEndpoints 改名 SelectAccountForModelsEndpoints,
  Vertex 账号排在所有 AI Studio 兼容账号之后参与选号
- ForwardAIStudioGET 拆为 ForwardListModels / ForwardGetModel,按账号类型分流:
  AI Studio 兼容账号原样转发;Vertex 服务账号读取 Google 发布方模型列表并
  转换为 AI Studio 格式,模型详情在该模型所用区域的列表中查找;Vertex API Key
  账号返回内置列表
- Vertex 发布方模型分页读取抽成 listVertexGeminiPublisherModels,与后台
  同步上游模型共用
- 模型接口响应体上限改用 gateway.models_list_read_max_bytes,超出时报错
2026-10-11 22:03:36 +08:00
feeeei 4426593e9d fix(gemini): 3.6 Flash 兜底价改为官方优惠价
- 内置兜底价与本地价格表快照的 gemini-3.6-flash 改为 $0.75 输入 / $3.75 输出 /
  $0.075 缓存读取(Priority 档 $1.35 / $6.75 / $0.135),有效期至 2026-12-31,
  2027-01-01 起恢复 $1.50 / $7.50 / $0.15,与 3.7 / 3.8 Flash 及远程价格目录一致
2026-10-11 11:22:48 +08:00
feeeei f0ee427f0a feat(gemini): 显式缓存存储价内置官方价并按 Pro / Flash 系列兜底
- 新增 Gemini 显式缓存存储单价表(Standard 档,USD / token / 小时):
  Pro 全系 $4.50、Flash 与 Flash-Lite 全系 $1.00;3.6 / 3.7 / 3.8 Flash
  为优惠价 $0.50(有效期至 2026-12-31,2027-01-01 起恢复 $1.00),
  AI Studio 与 Vertex 统一按优惠价计
- 型号表未命中的 Gemini 模型按系列兜底:Pro 取 $4.50,Flash / Flash-Lite
  取标准价 $1.00;Flash-Lite 变体不落到同版本 Flash 的优惠价
- 取值优先级:价格表(override_file 等)配置值 > 内置型号价 > 内置系列价;
  两者都没有的模型仍拒绝创建缓存
2026-10-11 11:22:43 +08:00
feeeei 05d7946af8 fix(gemini): 显式缓存错误透传收窄到上游网关账号,延长沿用创建时计费口径
- 绑定缓存的请求与缓存管理接口收到 429 / 5xx 时,只有上游网关账号的响应原样回写
  (UpstreamFailoverError.BoundUpstreamPassthrough / GeminiCachedContentUpstreamError.UpstreamGateway),
  官方账号仍走错误透传规则与通用映射,不向客户端暴露配额明细
- 记录新增 channel_usage(迁移 244)保存创建时的渠道计费口径,PATCH 延长按同一口径预检、报价与记账
- 创建 / 延长费用行的 request_id 改为固定前缀 gcache:{create|patch}:{id},不被客户端或网关请求 id 覆盖,
  按缓存 ID 即可检索一个缓存的全部费用行
- 调度快照凭据投影补齐 base_url / auth_mode / 上游显式缓存声明,显式缓存候选过滤一次算全,
  不再逐个选号后剔除
2026-10-11 01:37:04 +08:00
feeeei c9e4b267b6 fix(account): 同步上游模型失败时显示后端返回的错误原因
- apiClient 拒绝的是普通对象而非 Error,原写法 instanceof Error 恒为假,
  错误提示被替换成通用文案"同步上游模型失败:同步上游模型失败"
- 白名单选择器与 Antigravity 同步按钮改用 extractApiErrorMessage 取消息
2026-10-10 23:37:48 +08:00
feeeei 6f9b02f12c feat(gemini): Vertex 服务账号支持同步上游模型列表
- Gemini 平台 Service Account 账号改用 v1beta1 publishers/google/models
  分页拉取模型(pageSize 300,最多 20 页),按账号默认区域选端点;
  只保留 publishers/google/models/gemini-* 条目,排除区域端点里的
  Gemma、Veo、AutoML 等模型花园条目
- 凭据缺失或 location 非法返回配置错误(400),且不发起 token 交换;
  API Key 认证的 Vertex 账号返回不支持
- 翻页途中的 404/405 不再触发配置模型回退
- 模型列表的请求、读体与状态码检查抽成 readUpstreamModelsResponse
  供各平台共用
2026-10-10 23:37:48 +08:00
feeeei 1c68f9996d feat(gemini): 适配 AI Studio AQ. 格式 Key
- AI Studio 新建 Key 为 AQ.Ab 前缀的 auth key:logredact.RedactText 与
  渠道监控 sanitizeErrorMessage 增加 AQ.Ab 规则,长度按 40 位以上放宽以覆盖格式变体
- 创建 / 编辑账号的 Key 占位符改为 AQ.Ab...,提示文案说明新旧两种前缀
  与第三方上游 Key
2026-10-10 23:37:48 +08:00
feeeei 2588675ce7 fix(gemini): 第三方上游 API Key 与 Vertex 不再套用 AI Studio 等级和模拟配额
- 按 base_url 判定上游:非官方地址的 Gemini API Key 账号视为第三方上游
- 第三方上游与 Vertex 不返回本地模拟配额,隐藏等级与配额说明;
  账号列表中第三方上游按普通 Key 账号展示今日统计与额度进度条,
  Vertex 显示 vertex 徽章与今日统计
- 第三方上游的 429 只认显式重试时长,否则走全局 429 兜底冷却,
  不按每日配额冷却到 PST 午夜
- 创建账号:第三方 Base URL 不显示 AI Studio 等级选项,也不写入 tier_id;
  API 密钥卡片标题与说明不再限定 AI Studio,免费层说明只在官方 Base URL 下显示;
  OAuth 等级回退下拉只在 OAuth 表单显示
2026-10-10 23:37:48 +08:00
feeeei 81e6ec5346 feat(gemini): Vertex 账号支持 API Key 认证
- Gemini 平台的 Vertex 账号新增 API Key 认证(credentials.auth_mode=apikey),
  不填 Project ID 走全局端点,填写后走项目级端点,Key 通过 x-goog-api-key 传递;
  Anthropic 平台的 Vertex 账号仍只支持 Service Account JSON
- 转发(Claude 兼容 / 原生 / Chat Completions)与测试连接统一走
  buildVertexGeminiAccountURL / setVertexGeminiAuth
- API Key 账号不参与显式缓存(Vertex 缓存接口不接受 API Key)与批量生图
- 创建弹窗新增认证方式选择;编辑弹窗支持轮换 Key 与修改 Project ID,
  Key 留空表示保留
2026-10-10 23:37:48 +08:00
feeeei 64331a9792 ui(gemini): Vertex 显示名改为 Agent Platform (Vertex)
Google 已将 Vertex AI 更名为 Gemini Enterprise Agent Platform。
账号类型按钮、平台徽章、Vertex 相关提示、配额文档链接与批量生图报错文案
统一显示为 Agent Platform (Vertex);创建账号弹窗的 Vertex 按钮改用 i18n 文案。
2026-10-10 23:37:48 +08:00
feeeei 3abd646582 fix(ops): Gemini 原生路由的网关本地错误按错误类型归类
Google 格式错误体没有 type 字段,ops 一律记为 api_error,客户端参数错误、
引用不存在的缓存等都被归为平台内部错误。

- googleError 写出时按状态码向 ops 登记错误类型:400/413 invalid_request_error、
  401 authentication_error、403 permission_error、404 not_found_error,
  429 与 5xx 不登记
- 计费、并发与风控拦截沿用 Claude / OpenAI 格式错误的类型与错误码,归类口径一致
- 存储价未配置、显式缓存未启用改用 googlePlatformError,仍按平台错误统计;
  错误透传规则改写的上游错误不登记本地类型
- 上游返回的缓存不存在标记为请求级失败:按客户端请求错误分类,
  上游原始错误保留为明细但不参与上游归因
2026-10-10 23:37:48 +08:00
feeeei d5a802f84a feat(gemini): 支持显式上下文缓存(AI Studio / Vertex / 自建网关上游)
新增 /v1beta/cachedContents 的创建、列表、查询、更新有效期与删除接口。
参与账号:官方地址的 AI Studio API Key 账号、Vertex service account 账号,
以及开启"上游支持显式缓存"的自定义地址 API Key 账号。

- 网关自发缓存 ID,绑定上游资源名、持有账号与创建它的 API Key
  (迁移 243 gemini_cached_contents);list/get 只读本地记录
- 引用缓存的 generateContent / streamGenerateContent / countTokens
  改写为上游资源名,只发往持有缓存的账号,不参与会话粘性、不换号;
  拒绝重复键与 snake_case 写法;在持有账号上重试耗尽后,
  上游 429 / 5xx 原样透传,401 / 403 映射为 502
- 计费:创建时一次性收取缓存 token 输入费与整个有效期的存储费;
  延长按库中实际推进的时长收费,纯存储费不算一次请求;缩短与删除不退费
- 存储单价随计费模型取价,来自定价覆盖文件字段
  cache_storage_cost_per_token_per_hour,未配置的模型拒绝创建;
  存储费同时计入账号统计成本,渠道按 token 重算成本时叠加且不重复计入
- 扣费前校验:创建在上游建成后按确定金额校验余额 / 订阅额度 /
  API Key 额度并登记不封顶的在途预留,不足时删除上游缓存、只收输入费;
  延长在调用上游前按增量时长校验
- 有效期上限 gateway.gemini_cached_content_max_ttl_seconds,默认 86400,
  有效期向上取整到秒;创建请求保留数字原文、兼容 snake_case 元数据字段
- 上游调用与落库同客户端连接脱钩;2xx 不可用响应不换号并删除已建缓存
- 缓存不存在:AI Studio 的 403、Vertex 生成请求的 400 与缓存资源接口的
  404 统一识别;原生转发(含流式)不重试、不换号、不改账号状态,
  向客户端返回标准 403,不暴露上游缓存资源 ID,上游原始错误登记到 ops;
  PATCH 遇上游 404 移除本地记录并返回 403,DELETE 视为成功
- 自建网关上游:账号开关 explicit_cache_upstream,缓存接口发往账号自身
  base_url;可选 explicit_cache_upstream_max_ttl_seconds 对齐上游 TTL 上限,
  显式 TTL 超限时创建跳过该账号(全部超限返回 400),未显式时按上限创建,
  PATCH 取本站与账号上限的较小值;绑定缓存的请求在网关账号上收到
  429 / 5xx 时不重试、不限流该账号;前端创建 / 编辑账号弹窗新增开关与上限输入框
- 用量与 ops 端点统计:带缓存 ID 的路径归一化为 /v1beta/cachedContents,
  缓存操作的上游端点记为 /v1beta/cachedContents
2026-10-10 23:37:47 +08:00
feeeei 3bfd40f5af fix(gemini): 引用缓存不存在的 403 不再停用账号并换号
上游对不存在、已过期、已删除或不属于当前项目的 cachedContent 一律返回
403 "CachedContent not found (or permission denied)"。原生转发路径在错误
策略之前识别该响应,原样返回客户端,不标记账号错误、不临时停调度、
不重试、不换号;其余 403 处理不变。
2026-10-10 23:36:17 +08:00
Yuan Liu 5db2d6956b fix(billing): retain DeepSeek V4 Pro pricing after September 14 2026-10-10 20:01:39 +08:00
obstacle-Sweden-Avicii 0f189af8de fix(groups): ignore stale RPM override loads 2026-10-10 19:44:19 +08:00
wucm667 ce6242fca1 fix(quota): recognize international coding endpoints 2026-10-10 14:47:11 +08:00
hutututtt 66b7ce08e7 fix(frontend): show full account group names 2026-10-10 09:48:09 +08:00
wucm667 29b2d721f4 test(web): use shipped SVG asset in embedded frontend tests 2026-10-10 08:39:49 +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
chihao.ou 5753552b95 fix(gemini): preserve authorization URL error messages 2026-10-09 20:07:28 +08:00
chihao.ou 8e3d75b57b fix(monitor): refresh cached availability on automatic reload 2026-10-09 20:05:17 +08:00
chihao.ou bd2f53b855 fix(groups): reject nonpositive rate multiplier edits 2026-10-09 20:04:44 +08:00
chihao.ou d01628975d fix(select): preserve keyboard input during IME composition 2026-10-09 20:00:54 +08:00
chihao.ou 2bfc49477c fix(ops): initialize custom time ranges in local time 2026-10-09 20:00:02 +08:00
wucm667 b686842716 fix(gateway): sync main routing without widening responses retry 2026-10-09 13:36:36 +08:00
feeeei 9a51333101 feat(groups): 分组名称与描述支持多语言
- groups 新增 i18n JSONB 列(迁移 242):语言代码 -> {name, description},只存译文;
  name/description 原列语义不变,仍用于唯一性校验、搜索与各类日志
- 用户侧接口由后端按请求语言输出:取 Accept-Language 中权重最高的一项,先按完整
  语言代码、再按主语言匹配;该语言有译文的字段换成译文,否则保持原字段,且不再带出
  译文表。覆盖密钥、可用分组、订阅(含进度与汇总)、兑换、使用记录、可用渠道、
  模型广场、套餐列表
- 管理端接口一律返回原字段;分组管理接口额外带 i18n 供编辑
- 创建/编辑分组:名称、描述的标题行右侧新增语言下拉,同一个输入框在默认内容与各语言
  版本之间切换;语种跟随前端 availableLocales
- 管理端写入:创建/更新接受 i18n(更新时缺省不修改,传入则整体替换),校验语言代码
  形态与名称长度并丢弃空译文;简易模式同样放行;复制分组只带走描述译文
- 切换界面语言后整页刷新,让已加载的数据换成新语言;模型广场响应加
  Vary: Accept-Language
- 网关路径,以及只带 group_name 字符串的统计、错误记录出口不做本地化
2026-10-09 11:39:18 +08:00
github-actions[bot] 3a6fd1c9db chore: sync VERSION to 0.2.15 [skip ci] 2026-10-09 03:36:07 +00:00
Wesley Liddick f2669c8cf6 Merge pull request #7939 from IrisRainbowNeko/fix/issue-7927-web-search-history-tool
fix(openai): declare web_search when OAuth history replays web_search_call
2026-10-09 11:19:17 +08:00
shaw 85e3110953 fix(lint): check type assertions in web_search history helper and test 2026-10-09 11:10:11 +08:00
IrisRainbowNeko 64caa9af8b fix(openai): declare web_search via additional_tools for Responses Lite
Responses Lite rejects hosted tools at the top level ("responses Lite does
not support top-level tool type web_search"), so Lite requests now carry the
injected web_search tool in an input additional_tools item: extend the
caller's first additional_tools item, or insert one before a trailing
compaction_trigger so the v2 compaction wire keeps the trigger last.

The HTTP passthrough path also runs the shared compatibility normalizer on
/responses/compact; thread the compact flag through so that endpoint is
left untouched, and drop the now-redundant call from the passthrough OAuth
body normalizer.
2026-10-09 11:03:13 +08:00
IrisRainbowNeko dab3b87ea2 fix(openai): declare web_search when OAuth history replays web_search_call
ChatGPT's Codex endpoint now rejects requests whose input replays a hosted
web_search_call item unless tools declares web_search, failing the stream
with "response protection is unavailable". Codex local context compaction
sends the full history with tools:[], so every compaction after a web search
fails and the session gets stuck in a reconnect loop.

For OAuth transform, passthrough and WebSocket paths, append a cached-only
web_search tool when the history contains web_search_call and no web_search
tool is declared. When the caller offered no tools, pin tool_choice to
"none" so the injected tool cannot be invoked. The /responses/compact wire
shape is left untouched.

Fixes #7927
2026-10-09 11:03:13 +08:00
Wesley Liddick d0392edf06 Merge pull request #7618 from SavitarC/feat/provider-profile
feat(platform): 平台与多协议供应商改为数据驱动,并接入 Command Code 与 Cline
2026-10-09 11:01:09 +08:00
SavitarC d85cebecc4 fix(ci): 升级 schema 导入器支持 Go 1.27.2 导出格式 2026-10-09 10:40:59 +08:00
SavitarC 5f93bb3b3f fix(ci): 升级 lint 支持 Go 1.27.2 并保留 HTTP2 兼容检查 2026-10-09 10:38:48 +08:00
SavitarC c61f6ebaa8 fix(security): 升级 Go 1.27.2 与 x/net 修复安全扫描 2026-10-09 10:25:25 +08:00
SavitarC 387ee20ed1 test(platform): 补录制路由基准与平台约束迁移防护 2026-10-09 10:11:06 +08:00
SavitarC 7ca08d521f fix(frontend): 按平台能力展示模型同步入口并同步 Zen 规则 2026-10-09 10:11:06 +08:00
SavitarC 9264414612 fix(provider): 修复 Claude 计费与钱包冷却并隔离模型目录缓存 2026-10-09 10:11:06 +08:00
SavitarCandClaude Opus 5.5 874871a25a feat(platform): 接入 Cline 平台
Cline API(https://api.cline.bot/api/v1)是 OpenAI 兼容的多模型聚合端点,
只提供 Chat Completions(Cline 自己的客户端同样只走该端点),模型名带厂商
前缀。同一个 API Key 下有两个互不影响的额度来源,由模型名决定扣哪一边:
cline-pass/* 走 ClinePass 订阅(5 小时 / 7 天 / 30 天滚动上限),其余付费
模型扣账户积分;cline-free/* 免费模型只有逐模型的每日额度。

转发:
- 平台清单与 provider profile 新增 cline:按入站协议分流,只登记 Chat
  Completions 端点,Responses / Anthropic 入站由现有转换链转为 Chat
  Completions,无需新增转发代码。
- 只有一个接入模式,不需要选择账号类型。
- 连接测试未指定模型时使用 profile 默认模型(固定 Chat Completions 的账号
  此前落到不带厂商前缀的通用默认模型);订阅了 ClinePass 的账号改用订阅
  模型,不消耗积分,ClinePass 冷却中时仍用按量模型。

用量与余额:API Key 调 /api/v1/users/me/plan/usage-limits(三档窗口的已用
百分比与重置时间,未订阅时 404)与 /api/v1/users/me、/users/{id}/balance
(余额单位为百万分之一积分,1 积分 = 1 美元),兼容 {success, data} 信封,
只查官方主机。复用额度探测与周期检测:账号列表显示 ClinePass 窗口与积分
余额;窗口用满时 ClinePass 模型冷却到重置时间,未订阅时不调度 ClinePass
模型,积分低于阈值时冷却付费模型;数据显示恢复后自动解除,但只解除探测能
证明已恢复的原因(窗口用满、未订阅、积分不足),组织账户、所需订阅档位、推理
额度与花费上限的冷却到期后由请求重新确认。周期检测中走账号接口探测的平台
改为登记表(平台、支持判定、检测函数一一对应),按账号所属平台分派。

上游错误(依据 docs.cline.bot/api/errors 与 Cline 客户端的错误分类,按文案
识别):积分不足(含其他 402)、组织花费上限、推理额度上限、ClinePass 超限、
未订阅 ClinePass / 组织账户、免费模型每日额度。两边的超限只冷却请求模型所属
的一边(模型级冷却键 cline:pass / cline:credits,调度按请求模型检查),不停
整个账号;免费模型只限该模型,冷却到文案中的 "try again in …"。ClinePass
超限冷却到快照中对应窗口的重置时间,没有快照时 5 小时窗口 1 小时、7 天
6 小时、30 天 24 小时。普通频率限制走默认 429 逻辑。402 的冷却写入失败时
也不落入默认分支永久置 error(探测只覆盖激活账号,置 error 后无法自动恢复)。
余额类冷却时长抽为 cnBalanceCheckCooldown 共用。

上游计费探测的官方域名加入 cline.bot。

前端:官方标志(机器人头像)、violet 配色(品牌紫)、复用额度与余额单元格
(同样只对官方主机上的 API Key 账号显示);接入模式展示名抽为共用函数,编辑
弹窗不再显示原始模式值。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:11:06 +08:00
SavitarCandClaude Opus 5.5 e2939cd8fa feat(platform): 接入 Command Code 平台
转发:
- 平台清单与 provider profile 新增 command_code:按模型分流,Chat
  Completions / Responses 基址 https://api.commandcode.ai/provider/v1,
  Anthropic 基址 https://api.commandcode.ai/provider;内置规则 claude-* →
  Anthropic、gpt-* → Responses(也支持 Chat Completions)。
- 原生 Anthropic 端点的版本感知拼接改按分流方式判断,转发与连接测试共用
  (Anthropic 基址带 /v1 时连接测试不再误报为配置错误)。

按模型的协议集合(模型支持入站协议时直通,免去协议转换):
- 分流规则可带协议集合 protocols(首项为首选协议):入站协议在集合中时同
  协议直通,否则走首选协议;只有一个协议时与原规则相同,OpenCode 行为不变。
- profile 新增 model_catalog:Command Code 的 /models 为每个模型给出
  supported_endpoints。官方默认地址的目录按地址全进程共享,自定义上游按账号
  隔离;目录请求的 UA 收敛与账号请求头覆写与转发一致。目录缓存 30 分钟、后台
  刷新,失败退避 5 分钟;从未加载成功时首批请求最多等 2 秒,冷启动也按目录
  分流。账号规则未命中的模型按目录取协议集合;目录不可用时回落内置规则(账号
  未配置规则时)或 Chat Completions。
- 三个入站入口共用的 resolveUpstreamProtocol 增加目录参数。
- 前端分流规则编辑器可为每条规则勾选"也支持"的协议;提供模型目录的平台,
  兜底行改为说明按上游模型列表选协议。

连接测试:
- 按模型分流的平台共用一条测试路径(协议与网关同一判定,含模型目录;默认
  测试模型取自 profile),不再落入 Claude 测试路径。
- 首个分支由"国产厂商"改为"按入站协议分流";adaptive 测试跳过 profile 未
  提供的 Anthropic 端点。现有国产厂商行为不变。
- 连接测试是 OpenCode 专属分流入口的最后一个调用方,改走统一判定后删除
  ResolveOpenCodeGoUpstreamProtocol、openCodeGoNativeProtocol,以及此前就只剩
  测试使用的 OpenCodeGoModelProtocol;路由矩阵的旧行为基准改为测试内独立复述。

额度与余额(/alpha/whoami、billing/credits、billing/subscriptions、
usage/summary):
- 额度探测写入 5 小时 / 每周窗口(限额套餐)与还原出的月度窗口,同时写入
  积分余额;余额探测只取积分。仅对官方主机上的 API Key 账号生效。
- 订阅周期或本周期用量取数失败时保留上一次的月度快照,不当作没有月度窗口
  清掉;窗口尚未开始(没有重置时间)时清掉上一个窗口的重置时间。
- whoami 取不到时探测整体失败,不按个人账户继续(组织账号会查到成员的个人
  钱包,并据此按余额停调)。
- 阈值停调与定时检测纳入 Command Code;有充值积分时上游跳过窗口检查,窗口
  快照不参与停调与冷却;积分低于余额阈值时临时停调。
- 上游计费探测的官方域名加入 commandcode.ai,不把 Key 发往官方主机上并不
  存在的中转计费接口。

上游错误(依据 commandcode.ai/docs/troubleshooting/errors,按文案分类,
402 / 403 / 429 同样处理):
- 5 小时 / 每周窗口用满:带原因的临时停调,到文案中的 "Resets in …",解析
  不出时回落额度快照;充值积分不受窗口限制,额度 / 余额探测发现充值积分后
  只解除这一类停调。
- 积分耗尽(含 usage_exceeded):可恢复的临时停调,积分恢复后由周期检测
  解除,不再永久置为 error。
- 组织花费上限:文案指明模型("set for <模型>")且请求模型已知时只写模型级
  限流;成员总额度或作用域不明时整个账号冷却,最长一小时。
- 普通频率限制走默认 429 逻辑,不再冷却到窗口重置点。

前端:
- 账号列表显示额度窗口与积分余额,阈值设置增加 command_code。单元格可见性
  改为按账号判定,与后端一致:只对官方主机上的 API Key 账号显示,自定义中转
  显示占位符,不再每次打开列表都探测出一行报错。
- 使用官网的官方标志(圆角方块内镂空 ⌘);配色为中性灰(品牌黑色已由
  Grok 使用)。

测试基准中原先用作"仅服务端登记"示例的 command_code 改为虚构的 acme_router;
新增的前端测试加入 CI 前端关键测试列表。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:11:05 +08:00
SavitarCandClaude Opus 5.5 7ffa38a8ae feat(frontend): 平台列表与多协议账号表单改由平台清单驱动
后端新增 BuildPlatformCatalog:平台清单加上多协议供应商 profile(接入模式、
各协议默认基址、内置分流规则),由测试 TestFrontendBuiltinPlatformCatalogInSync
写成前端内置清单 constants/platformCatalog.builtin.json 并校验一致。前端随后端
一同构建发布,直接使用该清单,取代 credentialsBuilder.ts 中需要手工同步的默认
端点与 OpenCode 分流规则。

改为读取平台清单:
- 平台选项 CONCRETE_PLATFORM_OPTIONS / GROUP_PLATFORM_OPTIONS、平台展示名
  platformLabel 以及各处 i18n 平台名的默认值;
- 渠道定价平台与组合分组平台、用户平台额度、上游模型同步可用平台;
- 多协议供应商判断、原生协议能力、各接入模式的默认端点与内置分流规则、
  请求头覆写资格;
- 系统默认额度与各登录方式默认额度:此前前端只列出 5 个平台(新增国产厂商
  与 OpenCode 时漏改),后端一直支持全部平台,现在按清单列出全部平台。

没有专属界面的多协议供应商走通用表单:创建弹窗列出其按钮,接入模式、可选
协议、默认端点与分流规则都来自 profile(按模型分流的供应商显示分流规则编辑
器);编辑弹窗同样适用。未登记专属图标 / 配色的平台使用通用图标与中性配色。
平台按钮分三行:国际平台、国产厂商、多模型聚合平台(OpenCode 与平台清单中
登记的其他多协议供应商)。没有内置模型列表的供应商不预填模型白名单(此前
回落 Claude 模型列表,新账号只接受这些模型),API Key 输入框也不再显示
Claude 的占位符与说明。
AccountPlatform / GroupPlatform 类型放宽为"内置平台 | 任意字符串"。新登记
平台只需重新生成内置清单,无需修改前端代码。

另修正编辑弹窗两处遗漏 MiniMax 的默认端点回退(清空 Base URL 时曾回落到
Anthropic 默认地址)。

测试:credentialsBuilder 以改动前实现为基准,逐一比较全部平台 × 接入模式 ×
协议的默认端点与各判断;替换清单后平台选项、展示名、额度列表随之更新;创建 /
编辑弹窗对走通用表单的供应商(按模型 / 按入站两种分流)提交的凭证。更新了
两个固定旧列表写法的测试。平台清单与账号表单的测试加入 CI 前端关键测试列表
(FRONTEND_CRITICAL_VITEST)。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:10:33 +08:00
SavitarCandClaude Opus 5.5 c556aee8fd refactor(platform): 多协议供应商的转发与探测判断改查 profile
平台清单之外,后端还有几处用"国产厂商"或"国产厂商 ∪ OpenCode"表示
多协议供应商,新登记的供应商会被漏掉(例如上游模型同步直接报不支持)。

- 适用于全部多协议供应商的判断改用 IsMultiProtocolAPIKey:上游模型同步与
  模型目录基址、Anthropic count_tokens 本地估算、HTML 403 豁免与累计计数、Claude 型号
  计费候选过滤;
- 新增 RoutesProtocolByInbound(profile 分流方式为按入站协议),替换原来
  只针对国产厂商、实际描述"按入站协议分流"的判断:Responses 直转回退、
  Responses 能力标记(含创建 / 更新后的异步探测调度)、上游计费探测的
  adaptive 基址、Anthropic API Key 鉴权方式、OpenAI 输入 token 本地估算。
  按模型分流的供应商(OpenCode)仍走 routesByModel 分支。

依赖各家额度 / 余额接口的逻辑(Coding Plan 窗口、余额不足冷却等)仍按平台
显式判断。现有平台上两组判断与改动前逐一相同(测试覆盖全部平台与非法值);
另测试临时登记的新供应商按分流方式分别获得国产厂商与 OpenCode 的行为。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:10:33 +08:00
SavitarCandClaude Opus 5.5 eefa7dd9dc refactor(platform): 平台白名单由数据库约束改为应用层校验
新增迁移 242 删除 user_platform_quotas_platform_check 与
composite_model_routes_target_platform_check(DROP ... IF EXISTS,可重入)。
此后新增平台只需在平台清单中登记,不再需要改约束的迁移;此前 Grok、国产
厂商、MiniMax、OpenCode 共写过 5 次。

平台合法性改由应用层保证,与原约束的拒绝范围相同:
- user_platform_quotas 用原生 SQL 写入,不经过 ent Validate,repository 在
  BulkInsertInitial / UpsertForUser 写入前校验平台,非法值在发出任何 SQL 前
  返回错误(此前由数据库拒绝并回滚);
- ent schema 的 platform / target_platform 校验改查平台清单,组合路由新增
  target_platform 校验(service 层与 admin 接口的原有校验保留)。

渠道监控的 provider 约束表示已实现的探测能力,不属于平台清单,保留不动。

集成测试(真实 PostgreSQL):在还原旧约束的库上重复执行迁移、约束被移除、
渠道监控约束保留、数据库层可写入未来的新平台值;repository 拒绝未登记平台
且不产生副作用(去掉校验后该测试失败)。全部仓储集成测试通过。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:10:33 +08:00
SavitarCandClaude Opus 5.5 3b89cc08dd refactor(platform): 后端平台列表改由平台清单派生
新增 domain/platforms.go 作为具体平台的单一数据来源:每个平台一条登记,
写明展示名、所走网关(anthropic / openai / gemini / antigravity)、是否国产
单一厂商、定价目录 provider 名,顺序即展示顺序。

以下列表与判断改为查平台清单:
- "全部具体平台":用户平台额度白名单、错误透传规则平台列表、组合路由目标
  校验、上游计费探测资格、调度快照遍历、组合分组的定价 / 模型映射回退、
  组合分组默认模型列表;
- "OpenAI 网关族":IsOpenAICompatible、NormalizeOpenAICompatiblePlatform、
  Responses 兼容路由判断、count_tokens 分发、组合分组的 OpenAI 文本目标;
- 国产厂商判断、渠道定价同步的 provider 映射;
- 多协议 API Key 供应商相关的请求头覆盖资格、凭证测试、OpenAI 基址回退改用
  IsMultiProtocolAPIKeyProvider;
- 分组平台与组合路由目标的请求校验改为自定义校验标签 group_platform /
  concrete_platform,拒绝规则不变(大小写、首尾空格、别名一律拒绝)。

组合分组的逐平台回退是先命中者生效,CompositePrecedencePlatformIDs 保持
原有顺序 anthropic、gemini、openai,其余按登记顺序追加。依赖具体实现的
能力(OAuth、渠道监控、调度阈值、余额 / 用量窗口、Codex 模型目录等)仍在
各自代码中显式列出。

等价性测试把改动前的每个列表与 switch 原样保留为基准,逐一比较派生结果
(含顺序),谓词覆盖全部平台、composite 与非法值 × 全部账号类型。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:10:33 +08:00
SavitarCandClaude Opus 5.5 105c955c88 fix(gateway): /v1/responses 转 Anthropic 时统一以去空白的请求模型兜底映射
forwardResponsesViaNativeAnthropic 的 defaultMappedModel 是账号 model_mapping
未命中时的兜底模型。此前按模型分流的账号(OpenCode)传空串、其余账号传
reqModel,源自两处分支各自实现。映射未命中且请求模型带首尾空白时,前者的
计费模型名保留空白(上游模型名因 normalizeOpenAIModelForUpstream 已去空白,
两者不一致,定价查找可能落空),后者为去空白的名字。

统一传 reqModel,并移除入口里最后一处 routesByModel 分支。仅影响按模型
分流账号收到带首尾空白模型名的请求:计费模型名改为去空白后的名字;发往
上游的请求不变。新增测试覆盖 OpenCode 与 Kimi 两类账号。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:10:32 +08:00
SavitarCandClaude Opus 5.5 8ac2936a3d refactor(gateway): 三个入站入口的上游协议分流收敛为 resolveUpstreamProtocol
此前 /v1/responses、/v1/chat/completions、/v1/messages 各自用一串 if 决定
上游协议:OpenCode 按模型规则、国产 adaptive 按入站、显式 api_protocol、
Responses 探针四个来源的优先级靠语句先后隐式决定,且每个入口都有
IsOpenCodeGo 特判。

- provider profile 新增 Routing(by_inbound / by_model),OpenCode 登记为
  by_model;routesByModel 取代转发路径与 GetAPIProtocol 默认值中的
  IsOpenCodeGo 判断。
- 新增 upstream_protocol_routing.go:resolveUpstreamProtocol 以单一函数给出
  上游协议(按模型分流 → adaptive 按入站 → 显式 anthropic → CC 直转条件
  → Responses),resolveModelRoutedProtocol 以 profile 规则泛化 OpenCode
  的规则解析;三个入口改为 switch 该结果选择既有转换路径,Responses 形状
  请求体的转换合并为 convertResponsesShapedChatBody。

转换函数本身不变。新增分流矩阵测试经真实入口遍历 平台 × api_protocol ×
探针 × 账号类型 × 接入模式 × protocol_rules × 入站 × 模型(2045 组),
与改动前逐条 diff 仅 6 条不同:智谱 adaptive 的非 API Key 账号(UI 无法
创建)在 /v1/responses 入站时由 Responses 改为回落 CC,与
/v1/chat/completions 入口一致;这 6 组前后都在发出上游请求前报错。

协议规则与映射模型相关的类型、函数已被所有按模型分流的供应商共用,同时去掉
OpenCode 前缀(OpenCodeGoProtocolRule → ProtocolRule、matchOpenCodeGoProtocolRules
→ matchProtocolRules、NormalizeOpenCodeGoProtocolRulesCredentials →
NormalizeProtocolRulesCredentials、resolveOpenCodeGoMappedModel →
resolveMappedUpstreamModel 等),并删除收敛后已无调用方的
defaultOpenCodeProtocolRules。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:10:32 +08:00
xcrong d56f5e7879 feat(gateway): adapt Claude Haiku 5.5
Closes #7919. Wire claude-haiku-5-5 (released 2026-10-07) across model
registry, effort catalog, pricing, billing, validation and Codex
descriptors, following the opus-5-5/sonnet-5-5 template and the official
migration guide + overview specs.

- registry: DefaultModels entry (fixed ID, no date suffix per guide)
- effort: full low/medium/high/xhigh/max family + IsHaiku55 +
  claude-haiku-5.5 dotted normalization (official default: medium)
- pricing catalog: 1M/128k limits, base (<=100k) prices and
  *_above_100k_tokens absolute prices; the existing ladder derivation
  yields threshold=100000 with uniform 5x multipliers, matching the
  official two-tier table exactly (cache tiers follow input x5)
- billing/pricing fallbacks carry the same tier so a missing catalog
  entry can never silently bill >100k prompts at base rate
- validation: adaptive-only thinking (enabled always 400; disabled 400
  at xhigh/max), sonnet-style sampling locks, temp+top_p combo rejected,
  forced tool_choice explicitly allowed (differs from opus/sonnet)
- oauth mimicry: skip temperature:1 top-up when top_p is present on
  sampling-locked models (sonnet-5-5 included), otherwise the gateway
  manufactures the temp+top_p 400 itself
- toolset beta filter + Codex 1M context cover haiku-5-5
- Bedrock/Antigravity mappings intentionally left out (no 5.5 entries
  exist there at all, same as opus-5-5); Vertex passes the fixed ID
  through untouched
2026-10-09 10:07:36 +08:00
SavitarCandClaude Opus 5.5 3f8eea0807 refactor(provider): profile 端点改为按协议登记,Responses 路径约定并入 profile
ProviderEndpoints 由 ChatBaseURL + AnthropicBaseURL 改为以协议为键的
BaseURLs(chat_completions / responses / anthropic),与账号凭证
api_base_urls、前端 defaultCNAdaptiveBaseUrls 的结构一致:
- 某协议没有条目即表示不提供该原生端点,SupportsNativeCNResponses 改为
  由 responses 条目推导,去掉单独的 NativeResponses 布尔值;
- DeepSeek 的 Responses 路径例外(/responses,无 /v1)从
  buildOpenAIResponsesURLForPlatform 的平台硬编码移入 profile.ResponsesPath。

运行时行为不变。唯一的函数级差异:智谱 adaptive 账号的
GetCNProtocolBaseURL(responses) 默认值由 CC 基址变为空串;所有运行时调用方
均先经 UsesNativeCNResponses / SupportsNativeCNResponses 守卫,智谱不会走到,
TestAdaptiveProtocolBaseURLs 的对应期望随之更新。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:17:41 +08:00
SavitarCandClaude Opus 5.5 c063a4016e refactor(provider): 以 provider profile 收敛多协议供应商默认端点表
多协议 API Key 供应商(kimi/zhipu/deepseek/minimax/opencode_go)的默认端点
此前在 account.go 的 GetOpenAIBaseURL / defaultCNProtocolBaseURL /
GetAnthropicProtocolBaseURL / GetOpenAIFormatBaseURL 中按平台 switch 重复了
四遍,Responses 能力与 OpenCode 内置分流表也各自散落。

新增 provider_profile.go 作为单一数据来源:每个供应商登记各接入模式的
Chat/Anthropic 默认基址、内置 protocol_rules 与原生 Responses 能力;
上述函数、SupportsNativeCNResponses、IsMultiProtocolAPIKeyProvider 与
defaultOpenCodeProtocolRules 改为查表。纯重构,行为不变:新增测试以旧
switch 逻辑为基准,逐一核对平台 × account_mode × 协议的全部组合。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:17:41 +08:00
yan9651688 ba280b3d5e feat(ops): show account names in request details table 2026-10-08 01:10:22 -07:00
Wesley Liddick 5fc0e486c3 Merge pull request #7916 from wucm667/fix/issue-7914-monitor-request-sample
fix(channel-monitor): require request samples before health scoring
2026-10-08 13:52:34 +08:00
Wesley Liddick 3e69643392 Merge pull request #7721 from ouchihao/codex/bug-fractional-byte-rate
fix(ops): retain byte units for sub-byte throughput
2026-10-08 13:51:52 +08:00
Wesley Liddick 3a012ac0ce Merge pull request #7725 from ouchihao/codex/bug-select-disabled-open
fix(ui): close selectors when they become disabled
2026-10-08 13:51:40 +08:00
Wesley Liddick 80dd7288a6 Merge pull request #7728 from ouchihao/codex/bug-oauth-code-unmount
fix(auth): avoid starting OAuth code cooldowns after unmount
2026-10-08 13:51:30 +08:00
Wesley Liddick 5a6e826f83 Merge pull request #7716 from ouchihao/codex/bug-scaled-price-exponent
fix(pricing): preserve exponents when trimming scaled prices
2026-10-08 13:51:19 +08:00
Wesley Liddick d068b866f3 Merge pull request #7718 from ouchihao/codex/bug-bulk-user-error-message
fix(users): show normalized errors when bulk updating limits
2026-10-08 13:51:05 +08:00
Wesley Liddick a618338987 Merge pull request #7719 from ouchihao/codex/bug-notify-email-timers
fix(profile): ignore obsolete notification email code responses
2026-10-08 13:50:54 +08:00
Wesley Liddick b0c2c4d623 Merge pull request #7720 from ouchihao/codex/bug-usage-zero-rate
fix(usage): preserve zero user multipliers in cost details
2026-10-08 13:50:39 +08:00
Wesley Liddick 9663b5ccf0 Merge pull request #7722 from ouchihao/codex/bug-announcement-read-failure
fix(announcements): report failed read confirmations accurately
2026-10-08 13:50:19 +08:00
Wesley Liddick 6cfa0f4ef8 Merge pull request #7723 from ouchihao/codex/bug-batch-image-access-retry
fix(batch-image): allow access lookup retries after request failures
2026-10-08 13:50:08 +08:00
Wesley Liddick 3149d62851 Merge pull request #7724 from ouchihao/codex/bug-cleanup-task-race
fix(usage): ignore obsolete cleanup task list responses
2026-10-08 13:49:58 +08:00
Wesley Liddick 0b51cbe15d Merge pull request #7729 from ouchihao/codex/bug-backup-polling-unmount
fix(backup): prevent polling from restarting after navigation
2026-10-08 13:49:48 +08:00
Wesley Liddick 3dc2a9c371 Merge pull request #7731 from ouchihao/codex/bug-dialog-escape-stack
fix(ui): limit Escape to the most recently opened dialog
2026-10-08 13:49:34 +08:00
Wesley Liddick 2c13fb595e Merge pull request #7764 from ouchihao/codex/bug-plugin-config-session-race
fix(plugins): ignore obsolete configuration UI sessions
2026-10-08 13:49:23 +08:00
Wesley Liddick 068239305e Merge pull request #7765 from ouchihao/codex/bug-compliance-reset-race
fix(auth): keep cleared compliance state isolated from pending requests
2026-10-08 13:49:13 +08:00
Wesley Liddick 9e46f2d77e Merge pull request #7732 from ouchihao/codex/bug-step-up-concurrent-prompts
fix(auth): share pending step-up verification prompts
2026-10-08 13:48:52 +08:00
Wesley Liddick 2eb7ccb6d2 Merge pull request #7703 from wucm667/fix/issue-7700-thinking-signature
fix(openai): recover rejected encrypted reasoning signatures
2026-10-08 13:48:33 +08:00
Wesley Liddick 745ff1d3ca Merge pull request #7911 from lyy0709/codex/usage-output-tps
feat(usage): add output TPS to usage logs and ops dashboard
2026-10-08 11:40:15 +08:00
Wesley Liddick 8e2c4fad32 Merge pull request #7793 from wucm667/fix/issue-7784-composite-route-model-list
fix(models): list composite exact route aliases
2026-10-08 11:39:51 +08:00
Wesley Liddick 0ac774e378 Merge pull request #7853 from wucm667/feat/issue-7847-compact-account-filters
feat(accounts): compact account search and filters
2026-10-08 11:39:40 +08:00
Wesley Liddick ba3af61251 Merge pull request #7897 from wucm667/fix/issue-7894-long-context-marker
fix(usage): replace misleading long-context multiplier badge
2026-10-08 11:37:40 +08:00
Wesley Liddick 48c647b5d2 Merge pull request #7833 from ShanYi-Hui/fix/preserve-email-binding-draft
fix(profile): preserve email binding draft during user refresh
2026-10-08 11:37:25 +08:00
Wesley Liddick b94974467b Merge pull request #7818 from ouchihao/codex/bug-custom-page-request-race
fix(custom-pages): ignore obsolete Markdown responses
2026-10-08 11:37:11 +08:00
Wesley Liddick 4747827e35 Merge pull request #7819 from ouchihao/codex/bug-stripe-payment-unmount
fix(payment): stop late Stripe callbacks after leaving the page
2026-10-08 11:36:59 +08:00
Wesley Liddick f3bcad3c33 Merge pull request #7839 from ouchihao/codex/bug-scheduled-results-race
fix(admin): keep scheduled test results scoped to the expanded plan
2026-10-08 11:36:33 +08:00
Wesley Liddick 2c6bd63de9 Merge pull request #7840 from ouchihao/codex/bug-monitor-template-list-race
fix(monitor): ignore obsolete template manager list responses
2026-10-08 11:36:19 +08:00
Wesley Liddick 02aad478f3 Merge pull request #7841 from ouchihao/codex/bug-alert-events-pagination-race
fix(ops): discard stale alert event pages after filter changes
2026-10-08 11:36:07 +08:00
Wesley Liddick 486b226b69 Merge pull request #7842 from ouchihao/codex/bug-ops-settings-load-guard
fix(ops): require loaded settings before saving
2026-10-08 11:35:56 +08:00
Wesley Liddick d1202bea5f Merge pull request #7843 from ouchihao/codex/bug-alert-rule-integer-duration
fix(ops): validate alert rule durations as whole minutes
2026-10-08 11:35:42 +08:00
Wesley Liddick 1865f28469 Merge pull request #7900 from ouchihao/codex/bug-rpm-edit-number
fix(groups): preserve numeric values when editing RPM overrides
2026-10-08 11:35:27 +08:00
Wesley Liddick c2f0edc137 Merge pull request #7901 from ouchihao/codex/bug-airwallex-navigation
fix(payment): stop Airwallex checkout after leaving the page
2026-10-08 11:35:15 +08:00
Wesley Liddick cdbf1d6f4d Merge pull request #7902 from ouchihao/codex/bug-passthrough-toggle-state
fix(admin): use the saved passthrough rule enabled state
2026-10-08 11:35:01 +08:00
Wesley Liddick b126b94525 Merge pull request #7903 from ouchihao/codex/bug-profile-username-draft
fix(profile): preserve username edits made during save
2026-10-08 11:34:49 +08:00
Wesley Liddick 7fc5332b45 Merge pull request #7904 from ouchihao/codex/bug-group-rate-load-race
fix(groups): ignore stale rate multiplier loads
2026-10-08 11:34:38 +08:00
Wesley Liddick 4bcad0657b Merge pull request #7800 from duckducktw/fix/pricing-entry-autofill-append
fix(channels): 追加模型时不再改写条目已留空的价格
2026-10-08 11:34:17 +08:00
Wesley Liddick 7ff5cff1bb Merge pull request #7822 from neotan/fix/issue-7670-bare-api-alias-bypass
fix(web): bypass bare API aliases from embedded frontend fallback
2026-10-08 11:33:58 +08:00
Wesley Liddick bc63bd2874 Merge pull request #7782 from lyy0709/codex/fix-remote-model-catalog
fix(models): enforce account mappings for remote Codex discovery
2026-10-08 11:33:27 +08:00
Wesley Liddick 458865ed1b Merge pull request #7878 from Achordchan/fix/account-test-log-context
fix(accounts): attribute connectivity test failure logs
2026-10-08 11:33:14 +08:00
Wesley Liddick 3a7fd4ae78 Merge pull request #7837 from yJader/fix/antigravity-account-test-models
fix: use account mapping keys for Antigravity connectivity tests
2026-10-08 11:32:59 +08:00
Wesley Liddick 4b8c557705 Merge pull request #7877 from hezhaoqian1/fix/upstream-channel-monitor-zhipu-path
fix(channel-monitor): build zhipu probe URL from the configured endpoint
2026-10-08 11:32:38 +08:00
Wesley Liddick bb0d4a53c9 Merge pull request #7887 from whhphd/fix/grok-sso-consent
fix(grok): include consent token and origin in SSO device approval
2026-10-08 11:32:25 +08:00
Wesley Liddick 3c274768c1 Merge pull request #7889 from aishangwuji/fix/opencode-zen-routing-and-unsupported-models
fix(opencode): correct Zen qwen3.8-max endpoint and reject unsupported models
2026-10-08 11:32:11 +08:00
Wesley Liddick bbf1d37783 Merge pull request #7891 from aishangwuji/fix/opencode-go-usage-retry-after-and-403
fix(opencode): cap Retry-After backoff at 24h and report neutral 403
2026-10-08 11:31:40 +08:00
Wesley Liddick 90afaf120e Merge pull request #7854 from wucm667/fix/issue-7852-chat-stream-heartbeats
fix(streaming): preserve chat stream heartbeat comments
2026-10-08 11:28:38 +08:00
Wesley Liddick 6cacccc767 Merge pull request #7775 from YahooYuan666/fix/grok-empty-completed-silent-refusal
fix(grok): fail over silent-refusal empty response.completed on Grok Responses streams
2026-10-08 11:28:22 +08:00
Wesley Liddick 2afe7d4577 Merge pull request #7910 from liuyh06/codex/fix-responses-namespace-noop
perf(openai): lazily rebuild input when stripping namespaces
2026-10-08 11:28:02 +08:00
Wesley Liddick 129369204e Merge pull request #7827 from Achordchan/fix/anthropic-tool-change-betas
fix(anthropic): preserve requested tool change beta headers
2026-10-08 11:27:45 +08:00
Wesley Liddick f19cd4fdea Merge pull request #7844 from cyhhao/fix/anthropic-cache-ttl-order
fix(anthropic): keep cache TTL order valid on the mimic path
2026-10-08 11:27:27 +08:00
Wesley Liddick e473fba99c Merge pull request #7869 from 3219378872/fix/thinking-signature-key
fix(apicompat): always include `signature` on Anthropic thinking blocks
2026-10-08 11:27:14 +08:00
Wesley Liddick cc4a1e3f61 Merge pull request #7789 from SPHINX998/fix/anthropic-buffered-negative-block-index
fix(gateway): ignore negative content block index in buffered Anthropic paths
2026-10-08 11:26:47 +08:00
Wesley Liddick 9d49d275f3 Merge pull request #7788 from SPHINX998/fix/apicompat-responses-refusal-to-chat
fix(apicompat): preserve refusals when converting Responses to Chat
2026-10-08 11:26:28 +08:00
Wesley Liddick 8d50466809 Merge pull request #7787 from SPHINX998/fix/apicompat-chat-legacy-function-call
fix(apicompat): pair legacy chat function calls with their results
2026-10-08 11:26:15 +08:00
Wesley Liddick f9bd97cc15 Merge pull request #7786 from SPHINX998/fix/apicompat-chat-developer-role
fix(apicompat): keep chat developer messages as developer role
2026-10-08 11:26:03 +08:00
Wesley Liddick f087fdb205 Merge pull request #7785 from SPHINX998/fix/apicompat-chat-named-tool-choice
fix(apicompat): flatten named chat tool_choice for Responses
2026-10-08 11:25:46 +08:00
Wesley Liddick ef16f8a3d1 Merge pull request #7792 from SPHINX998/fix/ws-passthrough-image-usage
fix(openai): account image input usage on WS passthrough
2026-10-08 11:25:31 +08:00
Wesley Liddick 6db4171cfb Merge pull request #7779 from SPHINX998/fix/ws-turn-group-pricing
fix(openai-ws): bill each later turn with the current group pricing
2026-10-08 11:25:10 +08:00
Wesley Liddick db29b3a773 Merge pull request #7811 from kingsleydon/fix/codex-service-tiers-null-fallback
fix(codex): never advertise null service_tiers in models manifest
2026-10-08 11:23:47 +08:00
wucm667 7cd3dc85c3 fix(channel-monitor): require request samples before health scoring 2026-10-08 10:41:20 +08:00
wucm667 df3c38e10f chore: align branch with current upstream main 2026-10-08 08:46:25 +08:00
wucm667 07d51a6aef chore: sync upstream security updates 2026-10-08 08:46:24 +08:00
lyy0709 18182f1127 style(ops): align output TPS tooltip indentation 2026-10-07 13:06:35 -07:00
lyy0709 1817a8428a feat(ops): show per-request output TPS percentiles 2026-10-07 13:06:19 -07:00
lyy0709 38dd23f834 chore: remove PR screenshots 2026-10-07 12:07:52 -07:00
lyy0709 6f6a27f9c6 feat(usage): show per-request output TPS by default 2026-10-07 11:35:03 -07:00
liuyh06 61e1afdd49 perf(openai): lazily rebuild input when stripping namespaces 2026-10-08 01:11:23 +08:00
chihao.ou 8811c125ec fix(groups): ignore stale rate multiplier loads 2026-10-07 14:57:52 +08:00
chihao.ou 3f2f66f328 fix(profile): preserve username edits made during save 2026-10-07 14:54:14 +08:00
chihao.ou f022a04573 fix(admin): use the saved passthrough rule enabled state 2026-10-07 14:53:09 +08:00
chihao.ou 795a7e2783 fix(payment): stop Airwallex checkout after leaving the page 2026-10-07 14:51:46 +08:00
chihao.ou 7b1aa93148 fix(groups): preserve numeric values when editing RPM overrides 2026-10-07 14:50:53 +08:00
wucm667 d5f490e106 fix(usage): replace misleading long-context multiplier badge 2026-10-07 10:48:38 +08:00
github-actions[bot] 3f1a2ea0a7 chore: sync VERSION to 0.2.14 [skip ci] 2026-10-07 02:03:01 +00:00
Wesley Liddick 0363b8cdba Merge pull request #7893 from Wei-Shaw/fix/issue-7850-admin-bootstrap-hardening
fix(setup): stop shipping guessable admin credentials on fresh installs (fixes #7850)
2026-10-07 09:50:45 +08:00
shaw 0f9d460dc6 fix(deps): resolve frontend audit failures (vue, source-map-js, xlsx exceptions)
- Bump vue to ^3.5.43 so @vue/server-renderer is >= 3.5.42
  (GHSA-g2v6-rqmx-r4w6).
- Override source-map-js to >= 1.2.2 (GHSA-68fv-2mgg-jv7q).
- Renew the expired xlsx exceptions until 2027-01-06: xlsx has no patched
  release on npm and is only used for XLSX.write export in the admin usage
  view; both advisories require parsing a crafted file and no read path exists.

Lockfile regenerated with pnpm 9 to match CI.
2026-10-07 09:44:01 +08:00
shaw 6e315616ed fix(setup): stop shipping guessable admin credentials on fresh installs (fixes #7850)
Fresh Docker installs created the admin as admin@sub2api.local and accepted
any ADMIN_PASSWORD (e.g. "123456"), making them easy brute-force targets.

- Generate a random admin-<12 hex>@sub2api.local login email when
  ADMIN_EMAIL is empty; drop the fixed default from .env.example and the
  compose files, and have docker-deploy.sh write a random ADMIN_EMAIL.
- Validate user-supplied ADMIN_PASSWORD (8-72 bytes) and ADMIN_EMAIL on the
  auto-setup path, only when an admin is actually about to be created, so
  existing deployments are never blocked at startup.
- Align validateEmail with the login endpoint's email binding so setup can no
  longer create an admin that can never log in (e.g. "a@b", "Name <a@b.com>").
- Cap validatePassword at bcrypt's 72-byte limit; the CLI reuses it and now
  defaults to a random admin email instead of admin@example.com.
- Update READMEs/deploy docs to stop suggesting guessable credentials.
2026-10-07 09:27:36 +08:00
wucm667 daa7915749 fix(deps): update SheetJS past expired security exceptions 2026-10-07 08:50:14 +08:00
wucm667 63800c50d4 fix(gateway): guard structured-input fallback against unsafe retries 2026-10-07 08:50:13 +08:00
Wesley Liddick d97ccc952f Merge pull request #7888 from honestTai/fix/easypay-callback-forgery
fix(payment): 修复易支付回调签名复用伪造入账漏洞 (fixes #7881)
2026-10-07 08:33:53 +08:00
Wesley Liddick 33d9e72f90 Merge pull request #7851 from ZeroClover/fix/remote-model-catalog-discovery
fix: enable API-key discovery for remote Codex catalogs
2026-10-07 08:27:17 +08:00
ASWJ df89228c2d fix(opencode): report 403 as neutral forbidden in usage snapshot 2026-10-06 23:57:15 +08:00
ASWJ 480f668ba9 fix(opencode): cap Retry-After hint for billing probe schedule 2026-10-06 23:56:27 +08:00
ASWJ aa3b049000 fix(opencode): cap Retry-After hint at 24h for usage refresh backoff 2026-10-06 23:55:46 +08:00
ASWJ 0dccd7b6f5 fix(opencode): correct Zen qwen3.8-max endpoint and reject unsupported models
- Route qwen3.8-max to Chat Completions on OpenCode Zen mode instead of Messages
- Fast-reject unsupported model families (gemini-*, jev-*) with HTTP 400 on OpenCode gateway to avoid upstream 404 failovers and strike accumulation
- Sync frontend DEFAULT_OPENCODE_ZEN_PROTOCOL_RULES with backend
2026-10-06 23:18:57 +08:00
honest.tai d1aac6b989 fix(payment): close EasyPay forged-callback sign reuse (fixes #7881)
An order-creation signature (visible to the payer in popup submit.php
URLs) could be replayed as a payment-success notification, with no
merchant key required. Two compounding defects:

- CanonicalizeReturnURL kept client-supplied query parameters, so a
  return_url ending in '&trade_status=TRADE_SUCCESS' entered the signed
  order string verbatim;
- the sign base string concatenates values unescaped, so a callback that
  decodes return_url only up to the smuggled pair re-sorts to a
  byte-identical sign base and passes verification.

Fixes:

- CanonicalizeReturnURL now drops client query parameters entirely; the
  server builds its own signed set and the client query has no
  legitimate use;
- VerifyNotification rejects any parameter outside the genuine async
  notify set (pid/trade_no/out_trade_no/type/name/money/trade_status/
  param/sign/sign_type), failing closed against the whole smuggling
  class regardless of the injection point.

Regression tests cover the PoC payload, full order-URL replay, genuine
callback acceptance, unknown-parameter rejection (including empty
values), and the return_url smuggling strip. Genuinely paid orders that
an exotic upstream variant might reject are still recovered through the
existing upstream QueryOrder reconcile path.
2026-10-06 23:14:56 +08:00
whhphd 54810f8c82 fix(grok): include consent token and origin in SSO device approval 2026-10-06 22:53:10 +08:00
Achord Chan 5ef517d0fc fix(accounts): attribute connectivity test failure logs 2026-10-06 13:59:37 +08:00
hezhaoqianandClaude Opus 5.5 0173861a5a fix(channel-monitor): build zhipu probe URL from the configured endpoint
The zhipu adapter always appended the official /api/paas/v4/chat/completions
path, so probes broke whenever the endpoint was not the official root:

- OpenAI-compatible relay (e.g. https://relay.example.com): requested
  /api/paas/v4/chat/completions, which relays do not serve -> 404
- Coding Plan base (https://open.bigmodel.cn/api/coding/paas/v4): produced
  .../coding/paas/v4/api/paas/v4/chat/completions -> 404

Resolve the path from the endpoint instead: append /chat/completions when it
already carries /paas/v4, keep the official path for bigmodel.cn / z.ai
roots, and fall back to /v1/chat/completions (same as kimi/deepseek/minimax)
for everything else.

Fixes #7067

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:09:51 +08:00
wucm667 f7f1112cda fix(deps): update Vue and source map security patches 2026-10-06 10:49:15 +08:00
wucm667 c15d858eca fix(gateway): preserve Responses semantics in chat fallback 2026-10-06 10:49:15 +08:00
风起andClaude Opus 5.5 412718edf5 fix(apicompat): always include signature on Anthropic thinking blocks
AnthropicContentBlock / antigravity ClaudeContentItem serialized `signature`
with omitempty, so thinking blocks without an upstream signature (Chat
Completions reasoning_content, Responses reasoning without encrypted_content,
every streamed thinking content_block_start) went out with no `signature` key.

Anthropic always sends the key (`""` on content_block_start). Strict clients
such as Grok Build deserialize it as a required field and abort the response
or SSE stream with "missing field `signature`".

- apicompat: thinking MarshalJSON always emits `thinking` and `signature`
- antigravity: ClaudeContentItem MarshalJSON does the same; streamed thinking
  content_block_start carries `signature: ""`
- tests: wire-shape regression tests; update TestStreamingReasoning expectation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:41:15 +00:00
wucm667 9f84204c21 fix(streaming): preserve chat stream heartbeat comments 2026-10-04 09:13:04 +08:00
wucm667 679a7186fb feat(accounts): compact account search and filters 2026-10-04 08:43:47 +08:00
Zero Clover bbba01dae9 fix: enable API-key discovery for remote Codex catalogs 2026-10-04 05:12:40 +08:00
cyh da4419e626 fix(anthropic): keep cache TTL order valid on the mimic path
Anthropic processes cache breakpoints in tools, system, messages order and
rejects a ttl=1h breakpoint after a 5m one. The OAuth mimic path adds 5m
breakpoints to the injected system block and the last tool, so a third-party
client that marks a single message block with ttl=1h received a 400.

After the block limit, raise ephemeral breakpoints that precede the last 1h
breakpoint to 1h. Valid requests are unchanged.
2026-10-03 22:38:26 +08:00
chihao.ou b07b1fb5d9 fix(ops): validate alert rule durations as whole minutes 2026-10-03 22:29:25 +08:00
chihao.ou 81bd85ec55 fix(ops): require loaded settings before saving 2026-10-03 22:27:23 +08:00
chihao.ou b472042513 fix(ops): discard stale alert event pages after filter changes 2026-10-03 22:26:52 +08:00
chihao.ou 4551fb0d86 fix(monitor): ignore obsolete template manager list responses 2026-10-03 22:25:12 +08:00
chihao.ou 8f636513f7 fix(admin): keep scheduled test results scoped to the expanded plan 2026-10-03 22:24:52 +08:00
yJader f385bba928 docs: keep connectivity test fix out of README 2026-10-03 21:31:46 +08:00
yJader 856d7ea905 fix: expose mapped antigravity test models 2026-10-03 20:56:49 +08:00
ShanYi-Hui abbe42ac44 fix(profile): preserve email binding draft during user refresh 2026-10-03 17:09:38 +08:00
feeeei a46249aac5 test(account): 补充临时不可调度作用范围单元测试
- 后端:scope 解析归一化、缺省/显式账号级/显式模型级/模型未知兜底的分流判定,
  以及显式账号级、显式模型级 401、模型未知三种命中的落库位置与状态 JSON
- 前端:未设置 scope 的存量规则按 401 账号级、其余模型级回显并原样保存,
  显式 scope 回显与切换后提交,新增规则默认模型级
2026-10-03 12:08:05 +08:00
feeeei 5a25507dcb feat(account): 临时不可调度规则新增作用范围 scope 选项
- 规则新增 scope 字段:account 命中后暂停整个账号,model 只冷却本次请求的模型;
  字段缺省时保持现有语义(模型已知且非 401 走模型级,否则账号级),显式取值由运营人员决定,401 也不例外
- 模型未知的路径按账号级兜底;状态 JSON 记录 scope/model 便于排查
- 创建/编辑账号弹窗的规则编辑器新增作用范围单选卡片,新规则默认模型级;
  未设置 scope 的存量规则按后端缺省语义回显(401 账号级、其余模型级),打开再保存不改变行为
2026-10-03 12:08:05 +08:00
Achord Chan 852f0f824f fix(anthropic): preserve requested tool change beta headers 2026-10-03 10:34:06 +08:00
wucm667 5800abf1cb fix(models): preserve composite catalog isolation after base update 2026-10-03 09:11:53 +08:00
Neo Tan abdfbb704c fix(web): bypass bare API aliases from embedded frontend fallback
The embedded frontend middleware runs before the gateway routes and only
let a few root aliases through. Bare aliases such as /chat/completions,
/embeddings, /messages/count_tokens and /models/:model were answered with
index.html and HTTP 200 instead of reaching the API handlers.

Add every root alias registered in routes/gateway.go to the bypass list.
This also covers POST /videos, which the /videos/ prefix did not match.

Fixes #7670
2026-10-02 11:40:14 -04:00
chihao.ou 1c996fe301 fix(payment): stop late Stripe callbacks after leaving the page 2026-10-02 22:21:02 +08:00
chihao.ou 4b6ed15a8b fix(custom-pages): ignore obsolete Markdown responses 2026-10-02 22:20:41 +08:00
github-actions[bot] b8dece9000 chore: sync VERSION to 0.2.13 [skip ci] 2026-10-02 12:16:57 +00:00
Wesley Liddick 3040209f20 Merge pull request #7813 from kingsleydon/fix/typesafe-upstream-billing-probe
fix(billing): allow upstream billing probe for TypeSafe API-key accounts
2026-10-02 20:02:28 +08:00
Wesley Liddick f5aca74623 Merge pull request #7816 from Wei-Shaw/fix/usage-billing-deleted-key
fix(billing): settle usage when the API key is deleted before billing completes
2026-10-02 20:01:45 +08:00
shaw 432a6a461f chore(billing): simplify comment 2026-10-02 19:52:00 +08:00
shaw c2d5bbd93e fix(billing): settle usage when the API key is deleted before billing completes
When an API key with quota or rate limits was deleted while a request was
still in flight, the key counter update matched no rows and returned
ErrAPIKeyNotFound, rolling back the whole billing transaction including the
balance/subscription charge. Skip the key-scoped counters in that case and
keep settling the user and account side as usual.
2026-10-02 19:51:06 +08:00
Wesley Liddick ae501cc220 Merge pull request #7814 from Wei-Shaw/docs/security-policy
docs: add security policy with private vulnerability reporting
2026-10-02 19:06:07 +08:00
shaw 99efaa477f docs(security): add dev@sub2api.org as fallback reporting email 2026-10-02 19:04:36 +08:00
shaw d9d4333795 docs: add security policy with private vulnerability reporting
Closes #7812
2026-10-02 18:59:29 +08:00
KingsleyandClaude Opus 5.5 18380398d5 chore(codex): drop added comments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:48:40 +00:00
KingsleyandClaude Opus 5.5 8b9788eeb4 test(billing): drop added comments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:48:37 +00:00
KingsleyandClaude Opus 5.5 66a9e2e6bb fix(billing): allow upstream billing probe for TypeSafe API-key accounts
The create form shows the upstream billing auto-probe toggle for every
API-key platform and enables it by default. TypeSafe was added as an
API-key platform but not to IsUpstreamBillingProbeIdentity, so creating a
TypeSafe account with the default form state fails with
400 UPSTREAM_BILLING_PROBE_ACCOUNT_INVALID ("account is not an API key
account").

TypeSafe accounts store credentials.api_key/base_url like every other
API-key platform, which is all the probe reads. Add TypeSafe to the probe
identity set, and add typesafe.ai to the official API domains so accounts
on the default https://api.typesafe.ai base URL record "unsupported"
without sending the key to a path that cannot exist, matching the other
official providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:45:53 +00:00
KingsleyandClaude Opus 5.5 dd7ee21703 style(codex): use tagged switch for capability conflict fallback
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 09:47:26 +00:00
KingsleyandClaude Opus 5.5 c0e5a4670e fix(codex): never advertise null service_tiers in models manifest
intersectUpstreamModelMetadata falls back to null for every Codex tool
capability field whose value differs across peer accounts. Since
e6d191a83 added service_tiers to codexToolCapabilityFields, a model served
by accounts with different (or partially declared) tier lists ends up with
"service_tiers": null in the generated Codex manifest. Codex decodes
service_tiers as a required array and rejects the whole manifest, so the
client loses model metadata for every model.

Fall back to [] for conflicting service_tiers (do not advertise any tier
that is not shared by all peers), and normalize an explicit null to []
when applying capabilities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 09:38:08 +00:00
wucm667 983cf297da fix(gateway): retry rejected structured input through chat endpoint 2026-10-02 17:16:37 +08:00
github-actions[bot] 458b92abd4 chore: sync VERSION to 0.2.12 [skip ci] 2026-10-02 06:45:18 +00:00
Wesley Liddick 5106065716 Merge pull request #7630 from william-drakemond/feat/account-priority-quick-adjust
feat(admin): inline quick-adjust stepper for account priority
2026-10-02 14:33:29 +08:00
Wesley Liddick 46f5f5e8ba Merge pull request #7773 from william-drakemond/fix/custom-error-codes-warning-text
fix(frontend): correct custom error code warning and upgrade Axios
2026-10-02 14:33:03 +08:00
Wesley Liddick 2529371bab Merge pull request #7676 from william-drakemond/fix/email-code-token-atomic
fix(email): 验证码尝试次数原子化 + 重置密码 token 哈希存储且原子单次消费
2026-10-02 14:32:42 +08:00
Wesley Liddick 43c4c882fd Merge pull request #7674 from william-drakemond/fix/antigravity-sanitize-upstream-error
fix(antigravity): 返回客户端前脱敏上游错误体,避免泄露账号池身份
2026-10-02 14:32:12 +08:00
Wesley Liddick 719013053a Merge pull request #7803 from william-drakemond/feat/api-key-group-sort
feat(keys): 支持按分组名称排序 API 密钥
2026-10-02 14:31:49 +08:00
Wesley Liddick f3dc0835df Merge pull request #7673 from william-drakemond/fix/public-order-verify-hardening
fix(payment): 为匿名订单查询接口 /payment/public/orders/verify 增加 IP 限流
2026-10-02 14:31:17 +08:00
Wesley Liddick 5637f469fa Merge pull request #7802 from feeeei/feat/recharge-promotion-tiers
feat(payment): 充值优惠阶梯,支持赠金与折扣两种模式
2026-10-02 14:30:29 +08:00
Wesley Liddick 34fe845f5a Merge pull request #7425 from aofee/codex/jev-system-one
feat: add native TypeSafe Jev System One support
2026-10-02 14:16:08 +08:00
shaw fa49647c6d test(model): 错误透传平台列表守卫纳入 typesafe 2026-10-02 14:00:12 +08:00
shaw 9eb394e3e9 fix(typesafe): 堵住校验解析差异与审计盲区,收紧模型列表口径
- System One 校验拒绝重复键与大小写/Unicode 折叠变体键(请求顶层、
  questions、问题对象):encoding/json 大小写不敏感且取最后一个重复键,
  而原始 body 原样转发,此前 {"model":"x","MODEL":"jev-latest"} 可绕过
  jev-latest 限制、模型白名单与流式限制。
- Prompt 审计与旧审核同时收集对象键名、问题 ID 与未知扩展字段(不含规范
  字段名与已校验的 type),此前把内容放进键名即可完全绕过审计。
- 上游成功响应的 usage/model 宽松解码(浮点、数字字符串),避免上游已
  计费而网关整体 502 不记账;解码失败记录 response_error ops 事件。
- 上游 413 与 400/422 同视为请求错误:透传状态码、不切换、不改账号状态。
- TypeSafe base_url 末尾的 /v1 自动剥离,避免拼出 /v1/v1/systemone;
  /v1/systemone 改挂文本请求体上限。
- Composite 静态兜底模型列表、管理端候选列表恢复为不含 jev-latest;
  Codex 清单永不列出 TypeSafe 模型;TypeSafe 分组候选默认 jev-latest。
- 创建账号从 Grok 切到 TypeSafe 时重置为白名单模式;错误透传平台列表补 typesafe。
2026-10-02 13:51:58 +08:00
shaw 2d8a386811 fix(typesafe): 补齐平台迁移、审计覆盖、端点隔离与错误策略
- 新增 241 迁移:user_platform_quotas / composite_model_routes 的 CHECK 约束
  加入 typesafe。此前设置 typesafe 默认配额会让注册时的多行配额快照整体
  违约(fail-open 后新用户所有平台配额丢失),单用户配额与 Composite 路由保存 500。
- Prompt 审计新增 typesafe_systemone 协议提取(state + 各问题 instructions/
  criteria/选项标签,键排序保证哈希稳定);此前提取为空,阻断与异步审计均被放行。
  旧内容审核同样覆盖问题文本,且不再丢弃含 <system-reminder> 的 System One 文本。
- TypeSafe 分组及路由到 TypeSafe 的 Composite 请求访问 Messages / count_tokens /
  Chat Completions / Responses 时返回 404,避免以 x-api-key 打到错误上游路径并
  污染账号状态;TypeSafe 账号 base_url 为空时不再回退 api.anthropic.com。
- SystemOne 补在途余额预留、利润控制准入终检、wrapReleaseOnDone,失败切换改用
  共享 FailoverState(同账号重试 / 池模式 / 临时封禁)。
- 上游错误沿用共享账号错误策略:402/403、自定义错误码、临时不可调度规则生效,
  记录 ops 上游错误;400/422 仍不切换且永不改变账号状态。
- 账号测试改走原生 System One 探测,可用模型只返回 jev-latest;
  响应超限显式报错,响应 Content-Type 仅透传 JSON 类型。
2026-10-02 13:08:40 +08:00
aofee bb97ab364a fix(typesafe): align System One validation with upstream schema 2026-10-02 09:44:50 +08:00
aofee 7225538358 merge: sync Jev support with latest upstream main 2026-10-02 09:37:30 +08:00
William 0cecf3c367 feat(keys): support sorting API keys by group name 2026-10-01 13:01:01 -04:00
feeeei 1aa34d478d feat(payment): 充值优惠阶梯支持折扣模式,快捷金额角标改为促销价签
- 新增全局模式开关 RECHARGE_BONUS_MODE(bonus / discount),接入支付配置、后台设置接口与 checkout-info
- 折扣模式:到账不变,实付基数按百分比打折(按币种精度取整),手续费 / 每日限额 / 渠道选实例沿用折后基数;
  百分比须 < 100,运行时 ≥ 100 按无优惠处理
- 充值页角标改为单行红色价签(赠金「+20%」/ 折扣「20% OFF」),第二行按模式显示到账或折后实付;
  摘要卡折扣模式显示优惠行,渠道限额校验改用折后实付
- 后台「充值优惠阶梯」拆为独立卡片:赠金 / 折扣切换、紧凑档位表格、区间预览、活动文案
- 补前后端单测与 zh/en 文案
2026-10-02 00:25:41 +08:00
feeeei 1b1039f4fd feat(payment): 充值赠送阶梯(按金额档位额外赠送到账额度)
- 后台支付设置新增「充值赠送阶梯」(满 X 送 Y%,RECHARGE_BONUS_TIERS)与 Markdown 活动文案
  (RECHARGE_BONUS_NOTICE):阈值按用户输入的支付金额命中(取不超过金额的最大档),
  赠送按到账基数(输入 × 充值倍率)计算;严格校验写入、宽松解析读取,订阅订单不参与
- 下单时按当时配置计算赠送并落库:payment_orders 新增 bonus_amount 列(迁移 241),
  amount 仍为到账总额,到账/兑换码/退款逻辑不变;推广返利基数改为 amount - bonus_amount
- checkout-info 下发 recharge_bonus_tiers / recharge_bonus_notice;创建订单与订单查询响应带 bonus_amount
- 充值页:快捷金额按钮右上角「+N%」角标 + 第二行到账金额,金额卡顶部渲染活动文案,
  订单摘要新增赠送额度行并在有赠送时始终显示到账余额;订单列表/详情/支付结果/成功面板显示含赠送
- 后台新增 RechargeBonusTierEditor(行内校验重复/非法阈值,自动排序并显示区间预览)
- 补后端单测、契约测试与前端 vitest,zh/en 文案
2026-10-02 00:25:41 +08:00
duckducktw 4407849142 fix(channels): 追加模型时不再改写已留空的价格条目
渠道定价条目价格留空时按各模型官方默认价回退计费,但向这类条目追加
模型时,前端会用「第一个新增模型」的默认价回填整条价格字段,保存后
条目内所有模型被静默统一成同一个价格,造成少计费或多计费。

自动填充现在只作用于「空条目首次加入单个模型」:条目已有模型时追加、
或一次加入多个模型时都不再改写价格,留空条目继续按各模型默认价回退。

- 新增 PricingEntryCard.modelDefaultPrice.spec.ts 覆盖 4 种场景
- 把该 spec 加入 Makefile 的 FRONTEND_CRITICAL_VITEST,使 CI 覆盖该回归

Closes #7796
2026-10-01 23:59:58 +08:00
wucm667 1888de135d fix(models): list composite exact route aliases 2026-10-01 22:54:05 +08:00
SPHINX998andClaude Opus 5.5 b6a157c19c fix(openai): account image input usage on WS passthrough
The WS v2 passthrough relay only read output_tokens_details.image_tokens,
so image generation over WebSocket billed image input tokens at the text
input rate and ignored the hosted response.tool_usage.image_gen breakdown
that the HTTP Responses path already merges (extractOpenAIUsageFromJSONBytes
+ mergeHostedImageGenToolUsage).

The relay now reads image input tokens from input_tokens_details or
prompt_tokens_details, fills missing image input/output counters from
response.tool_usage.image_gen (usage values keep precedence), and carries
ImageInputTokens per turn and in the session aggregate into the
OpenAIForwardResult used for billing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 22:31:39 +08:00
SPHINX998andClaude Opus 5.5 775c1a3c1d fix(apicompat): preserve refusals when converting Responses to Chat
A Responses refusal arrives as a {"type":"refusal","refusal":...} content
part (streamed as response.refusal.delta), not as output_text. The
Responses → Chat Completions converters only read output_text, and
ResponsesContentPart had no refusal field, so Chat clients received an
empty assistant message when the model refused.

Map refusal parts to choices[0].message.refusal, response.refusal.delta
to delta.refusal, and let BufferedResponseAccumulator keep refusal deltas
so non-streaming replies rebuilt from deltas keep them too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 22:03:51 +08:00
SPHINX998andClaude Opus 5.5 15f469c86b fix(gateway): ignore negative content block index in buffered Anthropic paths
The buffered Anthropic aggregators index finalResp.Content with the
upstream content_block_delta index after checking only idx < len. A
malformed or third-party Anthropic-compatible upstream that sends a
negative index makes the request goroutine panic, so the client gets no
response and the forward never returns a result to record usage.

Add the lower bound in all four buffered aggregators (Chat Completions
and Responses, on both the Anthropic gateway and the OpenAI native
Anthropic paths); the out-of-range delta is skipped like an index past
the end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 22:00:22 +08:00
SPHINX998andClaude Opus 5.5 7a767d5ce8 fix(apicompat): pair legacy chat function calls with their results
Legacy Chat function calling has no call IDs: the assistant turn carries
function_call and the role=function result refers to it only by name.
ChatCompletionsToResponses ignored the assistant function_call and used
the function name as the result's call_id, so the Responses upstream got
a function_call_output with no matching function_call and rejected the
replayed history.

Emit a function_call item for each legacy assistant call and give the
following same-name result the same call_id. IDs follow message order
(call_legacy_N), so the same history converts to the same input across
turns, and skip IDs already used by tool_calls. A result with no
preceding call keeps the previous name-based call_id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:55:31 +08:00
SPHINX998andClaude Opus 5.5 9a8ab4f88e fix(apicompat): keep chat developer messages as developer role
chatMessageToResponsesItems only mapped "system" explicitly and sent every
other unknown role through the user converter, so Chat Completions
developer messages reached the Responses upstream as user turns and lost
their instruction priority.

The Responses API accepts role "developer" in input messages; convert it
like a system message and keep the original role. Downstream converters
already understand it (ResponsesToAnthropicRequest folds developer into
the system prompt, the Codex transform forwards it unchanged).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:53:30 +08:00
SPHINX998andClaude Opus 5.5 f3d752693f fix(apicompat): flatten named chat tool_choice for Responses
Chat Completions names a forced function as
{"type":"function","function":{"name":"X"}}, while the Responses API
expects {"type":"function","name":"X"}. ChatCompletionsToResponses passed
the Chat shape through unchanged, so OpenAI API-key accounts on
/v1/chat/completions forwarded the nested shape to /v1/responses and the
upstream rejected the request.

Flatten the named Chat choice; strings and objects already in the
Responses shape are kept as-is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:51:37 +08:00
lyy0709 71e97d1353 fix(models): enforce account mappings for remote Codex discovery 2026-10-01 03:30:56 -07:00
Wesley Liddick d6adebd22d Merge pull request #7780 from lyen1688/fix/grok-cli-identity-1-0-46
修复 Grok 426 并对齐交互式 CLI 身份头
2026-10-01 17:48:26 +08:00
lyen1688 53158587a6 升级 Axios 至 1.20.0 修复前端安全审计 2026-10-01 12:17:29 +08:00
lyen1688 ad05eda157 依据正常交互式 CLI 抓包修正 Grok 身份头 2026-10-01 12:17:27 +08:00
lyen1688 fdce5b8d01 修复 Grok CLI 版本门槛并对齐官方无界面请求头 2026-10-01 12:04:39 +08:00
SPHINX998andClaude Opus 5.5 73381fc9c7 fix(openai-ws): bill each later turn with the current group pricing
The Responses WebSocket handler reads the API key auth snapshot once at
connect and reuses it for every turn: RecordUsage takes the group pricing
from that snapshot, and the profit gate reinstalled in BeforeTurn takes
its selling price from the connect-time ctxkey.Group. A group price
change therefore never reaches an open connection until the client
reconnects, while HTTP requests pick it up once the auth cache entry is
invalidated.

Each later turn now re-reads the key through APIKeyService.GetByKey (the
auth cache the middleware uses) in BeforeTurn. When the key ID, group ID,
group platform and subscription type are unchanged, the fresh group is
swapped into ctxkey.Group for the turn's profit gate and passed to that
turn's RecordUsage. A failed lookup or a key moved to another group keeps
the connection snapshot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:27:35 +08:00
YahooYuan666 27f4a1780f test(grok): cover empty response.completed failover for PlatformGrok
Adds two regression cases mirroring the #5009 OpenAI ones for Grok
platform accounts (issue #7774):

- TestOpenAIResponsesEmptyCompletedFailsOverGrok: an empty
  response.completed on the forwardGrokResponses streaming path must
  produce UpstreamFailoverError with an empty client body. Verified to
  FAIL on main without the guard extension and PASS with it.
- TestOpenAIResponsesEmptyCompletedWithOutputSucceedsGrok: normal Grok
  streams with semantic output and usage are untouched.

Fixes #7774
2026-10-01 03:01:43 +08:00
YahooYuan666 3613174cf6 fix(grok): fail over silent-refusal empty response.completed on Grok Responses streams
Issue #5009 added a failover guard for OpenAI Responses streams that
terminate with an empty response.completed (no output, no usage, no
error), but the guard is gated on PlatformOpenAI. Grok platform
accounts reach the same handler (forwardGrokResponses ->
handleStreamingResponseWithReasoning) and exhibit the same upstream
silent-refusal shape, so their empty completions are relayed to the
client as successful empty turns: Responses SDK clients map the empty
completed to finishReason stop and accept the turn with no retry.

Extend the guard to PlatformGrok, matching the unconditional guard on
the passthrough path (openai_gateway_passthrough.go).

Fixes #7774
2026-10-01 02:16:22 +08:00
William Drake 00940743d2 fix(deps): upgrade axios to 1.20.0 to pass security audit 2026-09-30 14:02:28 -04:00
William DrakeandClaude Sonnet 5.5 2e3c2cf592 fix(i18n): correct the custom error codes warning text
The warning said "Other errors will return 500", but custom error codes
only gate normal account-error handling (stop scheduling, rate-limit
marking). Request retry and account failover decide independently: on the
OpenAI-compatible gateway, unselected 403/5xx still fail over to another
account and only exhaust to 502; only some non-failover paths (for example
an ordinary 400) are rewritten to a generic 500. Reword zh/en to describe
what the setting actually does, including that an empty list applies no
filtering.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-09-30 13:54:33 -04:00
chihao.ou 21d90fb5e5 fix(auth): keep cleared compliance state isolated from pending requests 2026-09-30 19:11:19 +08:00
chihao.ou 75420462a6 fix(plugins): ignore obsolete configuration UI sessions 2026-09-30 19:10:51 +08:00
github-actions[bot] 42bc7f6cff chore: sync VERSION to 0.2.11 [skip ci] 2026-09-30 07:07:11 +00:00
Wesley Liddick 96f4c115c9 Merge pull request #7726 from william-drakemond/feat/claude-reset-redeem
feat(claude): 手动兑换 Claude 重置次数 / Manually redeem Claude limit resets
2026-09-30 14:33:23 +08:00
Wesley Liddick 327c322184 Merge pull request #7730 from lyy0709/codex/gpt61-sol-codex-plans
feat(openai): support GPT-6.1 Sol, Codex plans and Astra Ultrafast
2026-09-30 14:32:59 +08:00
Wesley Liddick 48b7109588 Merge pull request #7736 from lyy0709/codex/remote-codex-model-catalog
feat(codex): 支持 model_catalog_url 远程模型目录配置
2026-09-30 14:32:34 +08:00
Wesley Liddick 4f0c079e27 Merge pull request #7681 from william-drakemond/fix/balance-inflight-reservation
fix(billing): Redis 在途预留,防止余额模式并发透支
2026-09-30 14:31:04 +08:00
Wesley Liddick b0cfff9826 Merge pull request #7752 from Wei-Shaw/fix/api-key-create-limits
feat(api-key): 增加 API Key 创建数量与频率限制
2026-09-30 14:20:00 +08:00
shaw 017bbcb901 chore(api-key): 创建频率默认值调整为每小时 60 次 2026-09-30 13:55:37 +08:00
shaw 9ecb340822 feat(api-key): 增加 API Key 创建数量与频率限制
- 新增 api_key_create.max_active_per_user(默认 200)与
  api_key_create.max_per_user_per_hour(默认 20),0 表示不限制
- 创建频率按固定一小时窗口统计,自定义与自动生成的 Key 统一计入
- 创建计数独立于 Key 生命周期,删除或修改 Key 不再重置计数
- 移除不再使用的 DeleteCreateAttemptCount 缓存方法
2026-09-30 13:44:02 +08:00
Wesley Liddick a0f41f95a0 Merge pull request #7579 from feeeei/fix/claude-code-only-fallback-openai-compat
fix(gateway): Claude Code 限制分组的 OpenAI 兼容入口改走降级分组,不再直接 403
2026-09-30 10:47:08 +08:00
r266-tech 69d6d106fd fix(monitor): allow adding missing platforms in v2 settings 2026-09-30 06:56:15 +08:00
lyy0709 b5efbe3f4c feat(codex): support remote model catalogs in client config 2026-09-29 13:26:44 -07:00
chihao.ou c641453123 fix(auth): share pending step-up verification prompts 2026-09-30 02:52:50 +08:00
chihao.ou e0019da463 fix(ui): limit Escape to the most recently opened dialog 2026-09-30 02:51:49 +08:00
chihao.ou 00a922c429 fix(backup): prevent polling from restarting after navigation 2026-09-30 02:50:29 +08:00
lyy0709 e6d191a83f fix(openai): support Astra Ultrafast capabilities and pricing 2026-09-29 11:50:08 -07:00
lyy0709 c91bb6124a feat(codex): recognize current subscription plans 2026-09-29 11:50:08 -07:00
lyy0709 9688571a83 feat(models): support GPT-6.1 Sol 2026-09-29 11:49:26 -07:00
chihao.ou 2e2b8f6d59 fix(auth): avoid starting OAuth code cooldowns after unmount 2026-09-30 02:49:07 +08:00
chihao.ou 8167d85b32 fix(ui): close selectors when they become disabled 2026-09-30 02:46:31 +08:00
chihao.ou 8a495b0a54 fix(usage): ignore obsolete cleanup task list responses 2026-09-30 02:45:47 +08:00
chihao.ou 8bc375b592 fix(batch-image): allow access lookup retries after request failures 2026-09-30 02:45:26 +08:00
chihao.ou cee76030be fix(announcements): report failed read confirmations accurately 2026-09-30 02:45:09 +08:00
chihao.ou 3a1a37b7b9 fix(ops): retain byte units for sub-byte throughput 2026-09-30 02:42:28 +08:00
chihao.ou 7d0bf9c87f fix(usage): preserve zero user multipliers in cost details 2026-09-30 02:24:37 +08:00
William DrakeandClaude Opus 5.5 514ad0aa8e fix(accounts): readable window labels in Claude reset confirm (review R1-4)
- Map five_hour/seven_day/seven_day_overage_included to 5h/7d/7d overage
  (raw key fallback) in the confirm message, credit tooltip and success message.
- Align zh/en confirm copy with the Codex dialog; {count} is the count
  remaining after this use.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 14:24:19 -04:00
William DrakeandClaude Opus 5.5 dc2efc6b9a fix(claude): tighten reset redeem outcome handling (review R1)
- R1-1: an explicit upstream "unavailable" answer now fences the organization
  for 15 minutes (CLAUDE_RESET_UPSTREAM_UNAVAILABLE) instead of 24h; ambiguous
  outcomes keep the 24h fence. Frontend tells the operator to retry later.
- R1-2: rotate the idempotency key after definite pre-claim refusals (busy,
  not available, unresolved, upstream unavailable); map IDEMPOTENCY_IN_PROGRESS
  and IDEMPOTENCY_RETRY_BACKOFF to clear zh/en messages.
- R1-3: redeem reason and cleared windows pass only through explicit
  allowlists, so upstream values can never echo a grant ID to clients.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 14:21:10 -04:00
chihao.ou 636faa695b fix(profile): ignore obsolete notification email code responses 2026-09-30 02:20:42 +08:00
chihao.ou e180a939ac fix(users): show normalized errors when bulk updating limits 2026-09-30 02:20:13 +08:00
chihao.ou c4224045dc fix(payment): calculate QR countdowns from elapsed time 2026-09-30 02:17:47 +08:00
chihao.ou 5ace0699b2 fix(pricing): preserve exponents when trimming scaled prices 2026-09-30 02:17:23 +08:00
1872d44b58 feat(accounts): add confirmed Claude reset button next to reset count
Orange 「重置」 button mirrors the Codex cell: enabled only after a query
shows a redeemable credit, danger confirm, one idempotency key per
confirmation reused on retry, outcome-specific messages, then refreshes
credits and the usage row. Ported from upstream PR #7591.

Co-authored-by: korkin25 <eugeny.kuzakov@gmail.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 11:41:33 -04:00
196b47757a feat(claude): redeem native limit resets with server-selected grant
POST /admin/accounts/:id/claude/reset-credits/redeem (Idempotency-Key
required, same middleware chain as the Codex reset-quota route). The server
re-queries eligibility and claims only the upstream next_grant_id when it is
redeemable; grant/org IDs never reach the client. Claims are serialized by
account and organization Redis leases, and a durable per-organization fence
in the idempotency table blocks further redemption after an unconfirmed
outcome (settles after 24h). Ported from upstream PR #7591.

Co-authored-by: korkin25 <eugeny.kuzakov@gmail.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 11:41:33 -04:00
wucm667 27de27ac64 fix(risk-control): remove deleted groups from moderation scope 2026-09-29 23:24:45 +08:00
wucm667 a4ea8059b7 fix(openai): recover rejected encrypted reasoning signatures 2026-09-29 16:42:02 +08:00
github-actions[bot] a60a29549f chore: sync VERSION to 0.2.10 [skip ci] 2026-09-29 08:28:45 +00:00
Wesley Liddick 2f3fed2fdb Merge pull request #7678 from PMExtra/feat/claude-code-only-client-tabs
feat: Claude Code 专用分组仅展示受支持的客户端入口
2026-09-29 15:53:58 +08:00
Wesley Liddick fe9dadfc7d Merge pull request #7679 from PMExtra/feat/risk-control-allowlist
feat: 新增可信用户风控白名单,保留审计并免除本地自动处罚
2026-09-29 15:53:18 +08:00
Wesley Liddick 41dcfec489 Merge pull request #7680 from PMExtra/fix/openai-model-catalog
fix: 移除 OpenAI 分组 Codex 配置中的模型目录依赖
2026-09-29 15:52:51 +08:00
Wesley Liddick 052e08e764 Merge pull request #7684 from william-drakemond/feat/claude-reset-credits-ui
feat(claude): 查询 Claude 重置次数(只读),UI 复用 Codex 次数按钮 / Read-only Claude reset credit count, reusing Codex count UI
2026-09-29 15:50:53 +08:00
Wesley Liddick 1f955af353 Merge pull request #7380 from wucm667/fix/issue-7377-forward-stream-usage
fix(gateway): forward received chat stream usage
2026-09-29 15:44:10 +08:00
Wesley Liddick ccb027b515 Merge pull request #7378 from wucm667/fix/issue-7368-composite-ws-routing
fix(gateway): resolve composite routes for websocket aliases
2026-09-29 15:43:52 +08:00
Wesley Liddick f50b99b66c Merge pull request #7542 from wucm667/fix/model-whitelist-mapping-conflict
fix(accounts): warn when whitelist model conflicts with mapping
2026-09-29 15:43:33 +08:00
Wesley Liddick 883a53fea0 Merge pull request #7643 from wucm667/fix/issue-7637-antigravity-compat-keepalive
fix(antigravity): keep compat streams alive before first content
2026-09-29 15:43:19 +08:00
Wesley Liddick b35a611538 Merge pull request #7646 from wucm667/feat/issue-7642-dashboard-spending-trend
feat(dashboard): toggle recent usage between tokens and spending
2026-09-29 15:43:07 +08:00
Wesley Liddick 1dca86f287 Merge pull request #7701 from wucm667/fix/issue-7699-tool-rewrite
fix(anthropic): rewrite tool names in one body pass
2026-09-29 15:42:45 +08:00
Wesley Liddick dd6cb410e6 Merge pull request #7683 from StarryKira/codex/sonnet-5-5-upstream
feat: support Claude Sonnet 5.5
2026-09-29 15:42:21 +08:00
wucm667 27a9421e6a fix(anthropic): rewrite tool names in one body pass 2026-09-29 15:00:16 +08:00
a408665321 a56720855c fix(ui): refresh countdown when tab becomes visible 2026-09-29 11:51:09 +08:00
William DrakeandClaude Opus 5.5 860782e6fb fix(claude): harden reset credit projection and cell state (review R2)
- Drop selection_token (unsalted hash of a short grant ID, reversible) and
  claudeGrantSelection from the read-only DTO; assert it never serializes.
- query() returns only the projected result; no raw upstream block escapes.
- Clear a cooldown_until that is already past, using the same `now` as the
  redeemable check; the cell also shows the cooldown only when in the future.
- Invalidate in-flight queries when account id, platform or type changes.
- Sort the earliest-expiry fallback by parsed timestamp, invalid/missing last.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 20:59:39 -04:00
William DrakeandClaude Opus 5.5 35232c3949 fix(accounts): address review of Claude reset credit count
- Show resets held (sum of resets_left) on the count button, matching the
  Codex count; flag "not usable now" when none is redeemable yet, instead
  of showing 0 while a grant exists.
- Pick the redeemable (next) grant for the expiry chip, falling back to
  the earliest expiry, rather than assuming credits[0] is next.
- Render a single ClaudeResetCreditsCell across usage states so a query
  started while usage loads is not lost on remount.
- Drop an unrelated google/subcommands go.sum entry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 19:03:47 -04:00
William DrakeandClaude Opus 5.5 421da3f0d4 feat(accounts): align Claude reset credit query with Codex reset count button
The Claude reset credit query rendered as a bare "Claude 重置额度" link,
which reads like a redeem action, and dumped raw ISO timestamps and
window keys. Render it like OpenAIQuotaResetCell instead: a read-only
"次数 N" button sharing one row with the local query button via a
#pre-actions slot, plus an expiry chip whose tooltip carries the grant
label, cleared windows and limit requirement.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 18:06:23 -04:00
korkin25 48970f61b4 fix(claude): explicitly close status HTTP response 2026-09-28 18:04:14 -04:00
korkin25 f8984b8a93 feat(accounts): show Claude reset credit status on demand 2026-09-28 18:04:13 -04:00
korkin25 6a8f921650 feat(claude): expose sanitized native reset credit status 2026-09-28 18:04:13 -04:00
haruka 2cc459e24f style: satisfy Sonnet 5.5 lint checks 2026-09-29 05:20:04 +08:00
William DrakeandClaude Opus 5.5 475c0839c6 style: gofmt
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 17:08:27 -04:00
William DrakeandClaude Opus 5.5 b886fb8edb fix(billing): read account-level mappings from scheduler snapshot only when unpriced
- only consult account mappings after primary/channel candidates fail to price (or composite)
- source mappings from the scheduler snapshot (same pool as account selection), no direct DB query and no per-model cache
- ungrouped API keys use the scheduler's ungrouped pool
- no negative caching: new mappings take effect on the next request

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 17:08:13 -04:00
haruka 8490a81867 feat: support Claude Sonnet 5.5 2026-09-29 04:55:07 +08:00
William DrakeandClaude Opus 5.5 652a7d74f9 fix(billing): estimate unpriced aliases via billing fallback models; don't renew expired reservations
- Inflight estimate now mirrors billableModelWithFallback: when the primary
  billing model has no price, fall back to the channel-mapped model (also for
  billing_model_source=requested) and to account-level mapped models (max over
  schedulable accounts in the group, cached 30s).
- Composite groups also consider concrete account-mapped models (max) so the
  alias' family fuzzy price cannot underestimate.
- Renew Lua refuses (and purges) members whose score <= now.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 16:49:29 -04:00
William DrakeandClaude Opus 5.5 52c123e6f4 fix(billing): hold inflight reservation until billing lands; price estimate like billing; wire remaining endpoints
Address gaps found in adversarial verification of the in-flight balance
reservation:

- Early release: the reservation is now a ref-counted handle carried on the
  request context. Billing tasks submitted via submit*UsageRecordTask take a
  ref and return it only after RecordUsage has run; with reservation enabled
  the balance cache is deducted synchronously inside the billing task, so the
  reservation is released only after admission can see the deduction. Dropped
  tasks return their ref immediately. The reservation is renewed every ttl/3
  while the handler runs; after the handler returns it is no longer renewed,
  so the post-handler hold is bounded by one TTL.
- Estimate: use the same billing model (channel mapping + BillingModelSource,
  max over requested/mapped when ambiguous) and ModelPricingResolver (group
  ModelPricing incl. wildcards, channel per_request/image/video/token
  overrides), default/group/user rate + peak multiplier, plus image, video,
  audio and search surcharge kinds. Unpriced requests fail open with a
  throttled log; new billing.inflight_reservation.fail_closed_on_unpriced
  (default false) rejects them instead.
- Wire images, embeddings, web/x search, alpha search, grok media generation,
  grok realtime/voice, OpenAI-platform /v1/messages and ResponsesWebSocket
  (session-level reservation with renewal).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 16:14:43 -04:00
William DrakeandClaude Opus 5.5 43f88c99aa fix(billing): reserve in-flight balance to prevent concurrent overdraft
Balance-mode admission only checked cached balance > threshold, so N
concurrent expensive requests could all pass and overdraw the user.
Add a Redis in-flight reservation: at admission estimate a conservative
per-request cost (input estimate + output price x max_tokens, times rate
multiplier) and atomically require cached_balance - inflight >= estimate
(first in-flight request always admitted). Reservations are released via
defer on every path and expire by TTL. Fails open on estimation / Redis
errors. Configurable via billing.inflight_reservation (enabled by default).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 14:20:49 -04:00
PMExtra 6073704fd7 fix: omit Codex model catalog for OpenAI groups 2026-09-29 01:50:43 +08:00
PMExtra 6a69dd051a feat: add risk control user allowlist 2026-09-29 01:50:21 +08:00
PMExtra 2840cdeced feat(frontend): hide unsupported clients for Claude Code-only groups 2026-09-29 01:48:23 +08:00
William DrakeandClaude Opus 5.5 b1ce3c6d59 fix(email): atomic verify-code attempts and hashed single-use reset tokens
- Verification code attempts (register + notify email) are now reserved via
  an atomic Redis INCR (Lua) before comparing, so concurrent wrong guesses
  cannot exceed the 5-attempt cap.
- Password reset tokens are stored as SHA-256 hashes and consumed with an
  atomic Lua compare-and-delete, so a token can only be used once even under
  concurrent requests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 12:26:28 -04:00
William DrakeandClaude Opus 5.5 d359196adc fix(antigravity): sanitize upstream error body before returning to client
The antigravity Gemini forward path returned the raw upstream Google error
body to end users, which can contain consumer project numbers, GCP project
IDs and service account emails. Return a Gemini-style error body with only
code/status and a scrubbed message; raw body stays in ops logging.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 12:23:13 -04:00
William DrakeandClaude Opus 5.5 cf19f30d26 fix(payment): rate-limit anonymous public order verify endpoint
POST /api/v1/payment/public/orders/verify is unauthenticated and still used
by PaymentResultView as a fallback, so keep it but cap it at 20 req/min per
client IP (fail-open on Redis errors) to make out_trade_no enumeration
impractical without affecting users mid-payment.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 12:03:17 -04:00
Yuan LiuandClaude Opus 5.5 f48866958b fix(openai): only inject the Codex image generation bridge for OpenAI accounts
The hosted image_generation tool is OpenAI-only. With the global switch or
a channel's openai bridge flag enabled, isCodexImageGenerationBridgeEnabled
also returned true for Kimi / DeepSeek / MiniMax accounts that forward
natively over Responses, so their upstream requests carried the tool,
tool_choice and the bridge instructions and were rejected with 400.

Return false for nil and non-OpenAI accounts before evaluating the
account / channel / global settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 14:59:35 +08:00
wucm667 aa3a3ea787 feat(dashboard): toggle recent usage between tokens and spending 2026-09-28 14:48:42 +08:00
wucm667 bd48b2b2d2 fix(antigravity): keep compat streams alive before first content 2026-09-28 12:15:27 +08:00
github-actions[bot] 9a62841fd1 chore: sync VERSION to 0.2.9 [skip ci] 2026-09-28 03:09:17 +00:00
Wesley Liddick 4c00df2e01 Merge pull request #7638 from Achordchan/fix/anthropic-structured-output-beta
fix(anthropic): preserve requested structured outputs beta
2026-09-28 10:52:52 +08:00
Wesley Liddick b5298fdde8 Merge pull request #7538 from TouHouQing/fix/claude-thinking-disabled-openai
fix(openai): honor disabled thinking in Claude Messages bridge
2026-09-28 10:51:30 +08:00
Wesley Liddick 5a350108c4 Merge pull request #7607 from ResidualBlood/fix/antigravity-malformed-function-call-retry
fix(antigravity): trigger failover retry on empty stream caused by MALFORMED_FUNCTION_CALL
2026-09-28 10:50:53 +08:00
Wesley Liddick 1df5c39311 Merge pull request #7562 from william-drakemond/fix/opencode-zen-deepseek-reasoning-placeholder
fix(openai): inject DeepSeek reasoning placeholder for OpenCode Zen upstream
2026-09-28 10:50:02 +08:00
Wesley Liddick b3c7038cf4 Merge pull request #7526 from HuntercodeT/fix/passthrough-model-discovery-merge
fix(gateway): let OpenAI passthrough accounts supplement model discovery instead of hiding mapped models
2026-09-28 10:49:01 +08:00
Wesley Liddick 8616d4e036 Merge pull request #7617 from korkin25/fix/responses-beta-upstream
fix(openai): preserve caller beta headers for HTTP Responses
2026-09-28 10:48:48 +08:00
Wesley Liddick 93c3da03eb Merge pull request #7555 from Yukinoshita-Yukino/fix/openai-auto-reset-credit-sched-projection
fix(scheduler): keep auto reset-credit fields in the scheduler projection
2026-09-28 10:27:00 +08:00
Achord Chan 68c2f5ae6d fix(anthropic): preserve requested structured outputs beta 2026-09-28 10:10:47 +08:00
Wesley Liddick ff6b85e30b Merge pull request #7615 from UnlastingR/fix/codex-ws-context-rollover-upstream
fix(openai): break websocket chain on context rollover
2026-09-28 10:05:05 +08:00
Wesley Liddick 79c18ec836 Merge pull request #7609 from feeeei/fix/client-disconnect-499
fix(gateway): 客户端断开统一标记 499,不再被记成 502/200 上游错误
2026-09-28 10:04:07 +08:00
Wesley Liddick 790723e040 Merge pull request #7610 from nhirsama/fix/redis-command-exec-form
fix(deploy): redis 启动命令改用 exec 列表,修复密码含 shell 特殊字符时失效
2026-09-28 10:01:15 +08:00
Wesley Liddick 1ff2bd6d95 Merge pull request #7573 from Yukinoshita-Yukino/fix/channel-image-price-inherit-when-unset
fix(billing): keep catalog image prices when channel pricing leaves them unset
2026-09-28 09:57:02 +08:00
Wesley Liddick f592b336a3 Merge pull request #7595 from wucm667/feat/issue-7587-allowlist-glob
feat(groups): support wildcards anywhere in model allowlists
2026-09-28 09:55:55 +08:00
Wesley Liddick 37f35b12ea Merge pull request #7524 from Achordchan/fix/plaza-video-rate
fix(model-plaza): apply independent video billing multipliers
2026-09-28 09:55:34 +08:00
Wesley Liddick e4b34446af Merge pull request #7619 from SavitarC/fix/account-stats-long-context-billing
fix(billing): 账号统计成本按 OpenAI 账号开关计入长上下文价
2026-09-28 09:55:19 +08:00
Wesley Liddick 90ae81e9f8 Merge pull request #7624 from wucm667/fix/issue-7620-future-quota-reset
fix(openai): retain quota pause until known future reset
2026-09-28 09:54:52 +08:00
Wesley Liddick 9375e288ba Merge pull request #7571 from SPHINX998/fix/openai-probe-model-unavailable-inconclusive
fix(openai): keep Responses support unknown when the probe model is missing
2026-09-28 09:54:31 +08:00
Wesley Liddick 06f70a6232 Merge pull request #7572 from SPHINX998/fix/openai-alpha-search-require-completion
fix(openai): require a successful completion before billing an alpha search fallback
2026-09-28 09:54:12 +08:00
Wesley Liddick 6906062187 Merge pull request #7597 from far5man/codex/opus55-openrouter-alias-main
fix: recognize OpenRouter Claude Opus 5.5 alias for billing
2026-09-28 09:53:49 +08:00
Wesley Liddick dc4874a2f1 Merge pull request #7613 from yujunkim/fix/openai-free-fast-missing-pricing
fix(billing): keep zero-cost usage log when Free Fast has no pricing
2026-09-28 09:53:26 +08:00
Wesley Liddick 11608c51f0 Merge pull request #7568 from SPHINX998/fix/apicompat-gpt6-reasoning-models
fix(apicompat): treat every GPT generation from 5 on as a reasoning model
2026-09-28 09:53:05 +08:00
Wesley Liddick 8aa7fb8c2d Merge pull request #7569 from SPHINX998/fix/apicompat-recover-empty-final-text
fix(apicompat): recover streamed text when the final output message is empty
2026-09-28 09:52:48 +08:00
Wesley Liddick 00ae7c38e2 Merge pull request #7570 from SPHINX998/fix/apicompat-tool-input-on-block-start
fix(apicompat): keep tool arguments sent on content_block_start
2026-09-28 09:52:13 +08:00
Wesley Liddick 51a10e42f7 Merge pull request #7585 from ResidualBlood/fix/antigravity-pdf-inline-data
fix(antigravity): forward chat PDF file parts as Gemini inlineData
2026-09-28 09:51:28 +08:00
Wesley Liddick 6655f4ec0e Merge pull request #7393 from Achordchan/fix/antigravity-string-const
fix(antigravity): intersect string const with existing enums
2026-09-28 09:51:04 +08:00
Wesley Liddick be64b553f9 Merge pull request #7635 from wucm667/fix/issue-7629-responses-message-type
fix(apicompat): mark converted Chat role items as Responses messages
2026-09-28 09:50:34 +08:00
Wesley Liddick 66f07efd26 Merge pull request #7549 from helianthus1/fix/ccswitch-usage-v1-path
fix(ccswitch): stop usage query from requesting /v1/v1/usage
2026-09-28 09:49:47 +08:00
Wesley Liddick 89e9976950 Merge pull request #7497 from ouchihao/codex/bug-group-modal-cleanup
fix(groups): clean up modal listeners and pending searches
2026-09-28 09:42:09 +08:00
Wesley Liddick 99d86e41ac Merge pull request #7611 from ZeroClover/fix/usage-bar-idle-reset-time
fix(ui): show reset countdown for idle usage windows with known reset time
2026-09-28 09:41:52 +08:00
Wesley Liddick ec334fda2c Merge pull request #7628 from Sterbennicht/fix/codex-windows-catalog-path
fix(keys): use ~/ for the Codex model catalog path on Windows
2026-09-28 09:41:35 +08:00
Wesley Liddick 35d2ef0cbd Merge pull request #7636 from wucm667/fix/issue-7631-remove-unused-rate-limit
fix(setup): omit unused rate limit fields from generated config
2026-09-28 09:41:16 +08:00
wucm667 512aa8bc93 fix(setup): omit obsolete rate limit defaults 2026-09-28 08:50:36 +08:00
Wesley Liddick f45126c8ec Merge pull request #7622 from Anti2077/fix/ccswitch-codex-root-endpoint
fix(ccswitch): preserve Codex provider root endpoint
2026-09-28 08:48:37 +08:00
wucm667 82d2552360 fix(apicompat): mark converted role items as messages 2026-09-28 08:40:41 +08:00
William DrakeandClaude Opus 5.5 58d605083e fix(admin): keep disabled priority stepper hidden until hover
disabled:opacity-30 overrode opacity-0, so the decrement button stayed
faintly visible on every row already at the minimum. Style disabled
buttons via text colour instead, and raise idle icon contrast.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 12:12:39 -04:00
William DrakeandClaude Opus 5.5 0da18e4a5e feat(admin): inline quick-adjust stepper for account priority
Replace the static priority number in the accounts table with a compact
stepper: hover reveals -/+ buttons, clicking the value allows typing
(Enter to save, Esc to cancel, arrow keys to nudge). Rapid clicks are
debounced into a single priority-only PUT, failures revert the value and
surface a toast, and the row is patched in place without a full reload.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 11:49:25 -04:00
Sterbennicht f652d0ed38 fix(keys): use ~/ for the Codex model catalog path on Windows
Codex expands a leading ~/ in config.toml paths on every platform but
does not expand %userprofile%. The Windows config generated by the Use
Key dialog wrote model_catalog_json = "%userprofile%\.codex\codex-models.json",
which Codex resolves relative to the config directory
(C:\Users\<user>\.codex\%userprofile%\.codex\codex-models.json), so it
fails to load the config with "The system cannot find the path
specified (os error 3)".

Always write ~/.codex/codex-models.json into config.toml. The download
hint still shows the Windows location to save the file.
2026-09-27 22:58:44 +08:00
ResidualBlood 6b40449c3f fix(antigravity): exclude Signature-only events from meaningful data check
MALFORMED_FUNCTION_CALL responses from upstream contain only
thoughtSignature without any text, thinking, or tool calls.
The previous fix still treated delta.Signature and block.Signature
as meaningful data, so the empty-stream failover was never triggered.

- Remove Signature from isMeaningfulAntigravityCompatEvent checks
- Let hasMeaningfulData() also consult processor.HasContent() as
  a secondary guard for edge cases
2026-09-27 13:15:56 +00:00
wucm667 02088be2d1 fix(openai): retain quota pause until known future reset 2026-09-27 14:56:38 +08:00
anti 14483c9254 fix(ccswitch): preserve Codex provider root endpoint 2026-09-27 13:48:39 +08:00
SavitarC fd7af1d462 fix(billing): honor long-context gate in account stats pricing 2026-09-27 12:12:25 +08:00
korkin25 8b95dc94f8 fix(openai): preserve Responses multi-agent beta 2026-09-27 09:57:51 +08:00
UnlastingR 7626110d0b fix(openai): break websocket chain on context rollover 2026-09-26 07:45:10 -04:00
Yujun KimandClaude Opus 5.5 3c5ea297ff fix(billing): keep zero-cost usage log when Free Fast has no pricing
RecordUsage treats a missing price as zero cost on the first pass, but
the Free Fast Standard re-evaluation returned the same pricing error.
Requests in a free_openai_fast group sent at priority/fast tier to a
model without pricing therefore lost their usage log entirely.

Ignore pricing-unavailable errors on the Standard pass and keep the
zero-cost entry, matching the first pass.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 20:11:03 +09:00
Zero Clover 994048e6a4 fix(ui): show reset countdown for idle usage windows with known reset time
UsageProgressBar returned 'now' whenever showNowWhenIdle was set and
utilization was 0%, ignoring resetsAt. OpenAI Codex 7d windows at 0%
usage still carry a future reset time, so the admin account list hid it.
Only fall back to 'now' when no reset time is known.
2026-09-26 18:49:51 +08:00
ling c802c45e37 fix(deploy): 用 exec 列表形式重写 redis command
参数逐项传递,不再经 sh 拼接,避免密码含 shell 特殊字符时被展开或截断;
空密码时按 redis 语义不设密码。
2026-09-26 17:56:19 +08:00
feeeei f4f8ff04db fix(gateway): 客户端断开统一标记 499,不再被记成 502/200 上游错误
客户端在响应提交前断开时,只有排队/换号阶段和 OpenAI 的兜底写入会标 499。
Claude 非流式与 Gemini 的 Chat Completions / Messages / Responses 兼容入口
在等待上游时断开,由 GatewayHandler.ensureForwardErrorResponse 补写 502;
Gemini 原生入口什么都不写,落成 200 并被 ops 记成一条 provider 的
"Recovered upstream error";Antigravity 回写 502。这些行都按上游失败计入
SLA 与上游错误数。

- GatewayHandler.ensureForwardErrorResponse 补客户端断开检查,与 OpenAI 版一致
- GatewayHandler 的 Messages / ChatCompletions / Responses 与 Gemini 原生入口:
  首次选号失败时先判断客户端断开;ChatCompletions / Responses 循环开头改用
  failoverClientGone,不再直接 return 落成 200
- Gemini 原生入口:forward 失败时补 499 标记;并发槽错误改走
  concurrencyErrorResponse 统一映射(断开 499、排队满/超时 429、其余 503)
- Antigravity 上游响应前断开回写 499;googleapi 与 Antigravity 的 Google 错误
  格式把 499 映射为 CANCELLED
- OpenAI alpha search 非 failover 错误分支补断开检查
- Claude / Gemini / OpenAI 传输层错误:请求 context 已取消时不记 ops 上游事件
- ops:IgnoreContextCanceled 开启时跳过没有上游错误上下文的 499;带上游错误的
  499(上游失败后客户端没等到换号结果就离开)仍按上游失败落库

计费不变:Gemini 流式中途断开的用量处理不在本次范围。新增 handler/service
单测覆盖各入口的断开场景与 ops 过滤规则。
2026-09-26 17:13:10 +08:00
Achord Chan 510b680fca Merge upstream main and retain upstream scheduler test fix 2026-09-26 15:47:52 +08:00
Achord Chan afbe51abf8 Merge upstream main and retain string const enum intersection 2026-09-26 15:42:47 +08:00
ResidualBlood 52c2f4cb10 fix(antigravity): trigger failover retry on empty stream caused by MALFORMED_FUNCTION_CALL 2026-09-26 05:29:18 +00:00
far5man 630639f747 test: preserve Opus 5.5 thinking for OpenRouter alias 2026-09-25 07:01:27 +02:00
far5man 11ffee5543 fix: recognize OpenRouter Claude Opus 5.5 alias for billing 2026-09-25 06:56:40 +02:00
Yuan LiuandClaude Opus 5.5 85810365a6 fix(auto-reset): stop re-querying confirmed no-credit accounts and back off after query failures
With the credit config now visible to the scheduler, every scheduling pass
notifies the auto-reset worker for paused credit-enabled accounts.
evaluateAccount forced an upstream query whenever the reset threshold was
reached, regardless of the last result. Accounts with no credits left and
7d >= 95% were therefore polled on /wham/usage every ~15-20s across
instances (previously once a minute by the scanner), and during upstream
outages the failed state caused the same storm.

- At the reset threshold, skip the forced query while a no_credit result is
  still within the state TTL (10 min); re-query once it expires so newly
  granted credits are still picked up.
- After a query-stage failure (RESET_CREDIT_QUERY_FAILED,
  USAGE_SNAPSHOT_WRITE_FAILED, RESET_CREDIT_DETAILS_UNAVAILABLE), wait one
  minute before querying again, including snapshot-staleness triggers.
- Redemption-stage failures are unaffected and still retry immediately with
  the same idempotency key; accounts with available credits still query and
  redeem immediately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 12:17:11 +08:00
wucm667 f0ebc183e1 feat(groups): allow wildcard positions in model allowlist 2026-09-25 09:12:09 +08:00
ResidualBlood ca2746f3bb fix(antigravity): forward chat PDF file parts as Gemini inlineData
Chat Completions file parts already become Responses input_file, but the
Antigravity path dropped them when converting to Anthropic and then to
Gemini. Map data-URI input_file to a document block and emit it as
inlineData so Gemini receives the PDF.

Fixes #7583
2026-09-24 15:17:25 +00:00
feeeei b31b435091 fix(gateway): Claude Code 限制分组的 OpenAI 兼容入口改走降级分组,不再直接 403
分组开启 claude_code_only 并配置降级分组时,/v1/messages 会在选号入口的
checkClaudeCodeRestriction 中把非 Claude Code 请求解析到降级分组;但
GatewayHandler.ChatCompletions / Responses 在 handler 层只要分组开了
claude_code_only 就直接返回 403,不看降级分组,请求到不了调度层:只会发
Chat Completions / Responses 的第三方客户端拿这类分组的 Key 一律 403。

- handler 层提前拒绝只在未配置降级分组时生效,拒绝的状态码与文案不变
- 配置了降级分组时请求继续,由 SelectAccountWithLoadAwareness 解析到降级分组
  选号,再经已有的 Chat Completions / Responses ⇄ Anthropic Messages 转换转发;
  service 层无改动
- 与 /v1/messages 的降级语义一致:选号与渠道限制预检按降级分组,计费与用量
  记录仍按 API Key 所属分组

新增 handler 单测覆盖两个入口在有/无降级分组时的行为。
2026-09-24 16:20:28 +08:00
SPHINX998andClaude Opus 5.5 1d126c833b fix(openai): require a successful completion before billing an alpha search fallback
The personal-access-token /v1/alpha/search fallback turned any upstream
Responses SSE body into a 200 search result and billed one web search call.
Error, response.failed and response.incomplete events, a response.completed
with a non-success status or without its response, a truncated stream and a
bare [DONE] were all accepted, returning partial text as a successful and
billable search.

Parse the stream strictly: those shapes now return an error, so nothing is
written to the client and no WebSearchCalls result is produced. A successful
response.completed keeps the existing output and citation handling. The
existing PAT metadata test now feeds a Responses SSE stream, which is what
that upstream path returns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:54:15 +08:00
SPHINX998andClaude Opus 5.5 9461196864 fix(openai): keep Responses support unknown when the probe model is missing
The API-key Responses capability probe treated every 404 as conclusive and
stored responses_supported=false. The probe model is the first mapped
upstream model in lexical order, so on third-party accounts it is often an
auxiliary entry such as codex-auto-review; a model_not_found answer then
permanently routed the account away from /v1/responses although the
endpoint works.

A 400/404 whose error code/type or message says the probe model does not
exist or is unavailable is now inconclusive, so the stored capability is not
overwritten. Plain 404/405 still mean the endpoint is missing. The probe
also prefers a general gpt-* text model (not an image model) among the
mapped models before falling back to the first one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:50:00 +08:00
Yuan LiuandClaude Opus 5.5 a2007db707 fix(billing): keep catalog image prices when channel pricing leaves them unset
When a channel pricing entry left image_output_price empty,
GetModelPricingWithChannel and the pricing resolver zeroed the image
output price and marked it explicit, so image output tokens were billed
at $0. image_input_price followed the same "unset means zero" rule and
fell back to the text input price instead of the catalog image input
price. A channel that lists an image model such as gpt-image-2 in token
mode without filling in prices therefore generated images without
charging for image output tokens, while the available-channels view
(#2475) displayed the catalog image price for the same entry.

#2930 wanted an explicit 0 on the channel to stop falling back to the
catalog; the change applied the same treatment to unset values as well.

Treat the two image fields like every other token price field:
- Set on the channel (including 0): override the catalog. An explicit
  image_output_price keeps ImageOutputPriceExplicit, so 0 stays free.
- Left empty: keep the catalog price (LiteLLM or built-in fallback). If
  the catalog has none, computeTokenBreakdown still falls back to the
  text input/output price.

The admin UI saves an empty field as null and only an entered 0 as 0,
so the two cases stay distinguishable. The flat, interval and
GetModelPricingWithChannel paths now share applyChannelImagePriceOverrides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:46:14 +08:00
SPHINX998andClaude Opus 5.5 97bdde3135 fix(apicompat): keep tool arguments sent on content_block_start
The canonical Anthropic stream leaves tool_use input empty on
content_block_start and streams the arguments as input_json_delta.
Anthropic-compatible relays may instead put the complete arguments on
content_block_start and send no delta. The Anthropic-to-Responses stream
converter ignored that input, so function_call_arguments.done carried ""
and the closed item "{}", and clients executed the tool with no arguments.

Keep the inline input as a seed. A real input_json_delta supersedes it, so
canonical streams keep their exact event sequence and two JSON documents are
never concatenated. When no delta arrived by content_block_stop, emit the
seed as a single arguments delta before the done event, which still repeats
exactly what the deltas streamed. Empty, "{}" and null inputs keep the
existing "{}" fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:45:14 +08:00
SPHINX998andClaude Opus 5.5 090b2cc000 fix(apicompat): recover streamed text when the final output message is empty
BufferedResponseAccumulator.SupplementResponseOutput rebuilt the output only
when the terminal response had an empty output array. Upstreams can also end
with a non-empty output whose message carries no (or only blank) output_text.
The buffered Chat Completions and Anthropic Messages paths then returned an
empty reply although the text had streamed, while usage still billed the
terminal output_tokens.

When the terminal output has no usable message text, fill the first empty
output_text part (or append one, or append a message item) from the
accumulated deltas. Non-empty terminal text stays authoritative, and nothing
is synthesized when no text streamed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:44:05 +08:00
SPHINX998andClaude Opus 5.5 82b092ffc2 fix(apicompat): treat every GPT generation from 5 on as a reasoning model
isReasoningModel matched the literal "gpt-5" prefix plus the GPT-6 Sol/Luna
spellings, so gpt-6 and gpt-6-astra (both already in the model catalog and
price list) fell into the sampling branch. Anthropic Messages and Chat
Completions requests converted to the Responses API then forwarded
temperature/top_p, which the Responses API rejects for these models with
"Unsupported parameter".

Key the check on the parsed GPT generation number instead, keeping the
existing Sol/Luna spelling match, so later families are covered without
another edit. Non-generation GPT families (gpt-image-1, gpt-audio) and
gpt-4.x are unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 15:37:16 +08:00
William DrakeandClaude Opus 5 5979521309 fix(openai): inject DeepSeek reasoning placeholder for OpenCode Zen upstream
- OpenCode Zen / Go 把 deepseek-* 模型转发给 DeepSeek,thinking mode 的
  reasoning_content 约束原样生效,上游 400 原文一字不差地回吐
- 原判定只认 platform=deepseek 与 base_url 指向 api.deepseek.com,
  opencode_go 账号漏出,Responses→CC 回退在缓存未命中时必踩 400
- 按「官方 OpenCode 上游 + deepseek-* 模型」补一条判定,不放宽成任意上游的
  deepseek-* 模型名,避免对无此约束的上游无谓改写请求体

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 18:32:49 -04:00
Yuan LiuandClaude Opus 5.5 1ca7b2a519 fix(scheduler): keep auto reset-credit fields in the scheduler projection
OpenAI candidate filtering reads the Redis metadata projection, but
filterSchedulerExtra dropped auto_reset_credit_enabled, the 5h/7d
reset-credit thresholds and codex_auto_reset_credit_state. The scheduler
therefore always saw automatic reset credits as disabled, so accounts
were paused at the ops quota auto-pause threshold even when a fresh
state showed an available reset credit. The "keep scheduling until the
reset-credit threshold" branch never took effect, and accounts with
credits stayed idle until their window reset naturally.

- Keep the four keys in the scheduler projection; the test round-trips
  the real JSON payload and resolves the credit config from it.
- Once visible, every scheduling pass notifies the auto-reset worker for
  paused credit-enabled accounts, and each notification reloads the
  account. Add a 30s per-account cooldown for the scheduler hot path
  only; other event-driven notifications are unchanged and the
  per-minute scan remains the fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 20:02:50 +08:00
helianthus1 00f6f4e4a8 fix(ccswitch): stop usage query from requesting /v1/v1/usage
#7395 made Codex (and Grok) imports store a base URL ending in /v1, but the
usage script still appends a hard-coded /v1/usage, so CC Switch requests
/v1/v1/usage, gets a 404 and shows "query failed" for every newly imported
Codex/Grok provider. Move the script into ccswitchImport.ts and strip an
existing trailing /v1 from {{baseUrl}} before appending /v1/usage, which
covers both the imported value and base URLs users edit either way later.
2026-09-23 04:24:52 -07:00
wucm667 e2c35cf394 fix(account): prevent whitelist model mapping conflicts 2026-09-23 17:47:47 +08:00
github-actions[bot] a3eb7ef302 chore: sync VERSION to 0.2.8 [skip ci] 2026-09-23 09:18:46 +00:00
touhouqing 2fc91663d2 fix(apicompat): honor disabled thinking in OpenAI bridges 2026-09-23 16:48:15 +08:00
Wesley Liddick fd80b08c90 Merge pull request #5616 from alfadb/feature/opencode-go-usage-window
feat(opencode): 支持 OpenCode Go 用量窗口(opencode_go 平台账号 + 多厂商挂载复用)
2026-09-23 15:39:28 +08:00
wucm667 453b796df0 fix(gateway): enforce composite model ownership in legacy scheduling 2026-09-23 15:29:11 +08:00
wucm667 e878ab710f fix(gateway): constrain account model route ownership 2026-09-23 15:29:11 +08:00
wucm667 13fcfc0f3b fix(gateway): resolve composite routes for websocket aliases 2026-09-23 15:29:11 +08:00
wucm667 0416c9ede4 fix(gateway): avoid ambiguous late-cache input subtraction 2026-09-23 15:27:53 +08:00
alfadb dc9216512d fix(opencode): normalize the quota endpoint for the /zen/go base variant
OpenCode Go 有两个都合法的 base_url:https://opencode.ai/zen/go/v1(OpenAI
协议档,DefaultOpenCodeGoBaseURL)与 https://opencode.ai/zen/go(Anthropic
协议档,前端 defaultCNBaseUrl 会写入)。旧拼接只做 strings.TrimRight(base,
"/") + "/usage",Anthropic 档账号的额度探测必然打到 /zen/go/usage。

实测证据(curl 无鉴权,401=端点存在,404=不存在):
  401 https://opencode.ai/zen/go/v1/usage
  404 https://opencode.ai/zen/go/usage

修法沿用同包 kimiQuotaURL(coding/v1 与 coding 两种 base)的既有惯例:
TrimSuffix(base, "/v1") 后统一拼回 /v1/usage,两个变体与尾斜杠写法都归一到
https://opencode.ai/zen/go/v1/usage;自定义 base 保持同一语义。
2026-09-23 15:26:44 +08:00
alfadb d0731be2f0 fix(opencode): lite 列表 DTO 补 opencode_go_usage,修复列表页显示余额 2026-09-23 15:26:44 +08:00
alfadb a2e1618700 fix(opencode): 纠正 CASE 求值顺序注释并补齐 mode 语义护栏 2026-09-23 15:26:44 +08:00
alfadb 31635849e0 fix(opencode): 用量单元格与 CN 子单元格互斥,避免重复渲染 2026-09-23 15:26:44 +08:00
alfadb d03274ad5f feat(opencode): 用量窗口资格支持 OpenCode 平台并扩展到其它厂商挂载 2026-09-23 15:26:44 +08:00
alfadb 0c860e81e1 fix(i18n): merge duplicate opencodeGo locale blocks after upstream rebase 2026-09-23 15:26:44 +08:00
alfadb daf6cbb5d9 feat(opencode): 用量单元格支持主动查询并将周/月徽章改为 7d/1m 2026-09-23 15:26:44 +08:00
alfadb 912e1c414c fix(opencode): remove stray conflict-marker text from usage cell imports 2026-09-23 15:26:35 +08:00
alfadb 0a43efb9a4 fix(opencode): preserve managed usage state on account updates 2026-09-23 15:26:35 +08:00
alfadb f7f0a56f35 fix(opencode): preserve auto-refresh on usage refresh 2026-09-23 15:26:35 +08:00
alfadb ae2735cdb6 feat(opencode): 用量窗口支持同 Key 组共享、活动防抖与超窗强刷
与 Ollama Cloud usage 对齐:OpenCode Go 作为同 Key 聚合订阅,
多个 openai/apikey/base_url=opencode.ai/zen/go/v1 账号共享同一份
用量状态与刷新节奏:

- 组共享:组指纹 sha256("opencode.ai\0"+api_key);auto_refresh 开关
  与 snapshot 按组写(事务 + FOR NO KEY UPDATE + 锚点 CAS + 纯合并,
  写 snapshot 不会抹掉开关);列表/详情经 ResolveAccounts 组内共享;
  账号换 Key → IdentityChanged → 组级关闭 auto_refresh 并清快照
- 活动防抖 + 超窗强刷:settings 新增 debounce_minutes(默认 1,
  1-60,必须小于 interval_minutes);模型请求活动经网关 5 处调用点
  驱动刷新,due = min(lastUsed+debounce, fetchedAt+maxWait),
  成功路径有 5 分钟最小抓取间隔,失败路径退避优先
- 手动刷新限频 10s→30s 且按组;singleflight/RunDue 按组去重;
  ListDue 在 SQL 内按组算 due(CTE 分组取组内 MAX(last_used_at))

验证:go build + 五包回归 OK;新增组共享/三态 due/组单飞/
IdentityChanged/debounce 校验单测全绿;vitest 11 例全绿;
vue-tsc 零错误。
2026-09-23 15:26:35 +08:00
alfadb 6624947b62 feat(opencode): 支持 OpenCode Go 官方用量窗口查询与自动刷新
OpenCode Go 上游(https://opencode.ai/zen/go/v1)官方提供用量端点
GET /zen/go/v1/usage(Bearer 复用消费 key),返回 rolling(5h)/weekly/monthly
三窗口的 percent 与 resetsAt。本提交为 openai apikey 账号(base_url 为
opencode.ai/zen/go/v1)接入该用量窗口:

- 后端:OpenCodeGoUsageService——手动刷新(每账号 10s 节流)、
  周期自动刷新(全局开关 + 账号开关双开启,interval 5-1440 分钟,
  leader lock + 每轮 20 账号 + 并发 4)、失败指数退避(上限 24h)、
  Retry-After 尊重;401→unauthorized、403→failed;snapshot 持久化于
  accounts.extra(单账号写入,无分组 CAS、无会话加密)
- admin API:settings GET/PUT、/:id/opencode-go-usage GET、
  auto-refresh PUT、refresh POST(与 Ollama Cloud usage 同构)
- 前端:账号列表行内三窗口进度条(复用 UsageProgressBar)、
  编辑弹窗内配置面板(详情+手动刷新+auto-refresh)、全局设置卡片、
  en/zh i18n

验证:
- 上游端点已用生产真实 Go key 实测 200,响应
  {"usage":{"rolling":{"status":"ok","percent":6,...},...}}(2026-08-13)
- go build ./... OK;service/handler/repo/dto/cmd 全量回归 OK
- 新增单测 20 例(解析 401/403/畸形 JSON、退避、节流等)全绿
- frontend vitest 新增 7 例 + Ollama 回归 4 例全绿;vue-tsc 零错误
2026-09-23 15:26:35 +08:00
Wesley Liddick afd069b169 Merge pull request #7532 from alfadb/feature/claude-cli-version-sync
feat(claude): 自动同步 Claude Code 客户端版本号,无需改代码跟随官方版本
2026-09-23 14:54:36 +08:00
shaw 6452aeffa1 fix(claude): 修复版本同步契约测试和缓存刷新 2026-09-23 14:39:29 +08:00
Wesley Liddick 4318a63bd8 Merge pull request #7509 from lyy0709/codex/gpt6-sol-luna-opus55
feat(models): support GPT-6 Sol, Luna and Claude Opus 5.5
2026-09-23 14:23:38 +08:00
alfadb ca08825935 feat(claude): 自动同步 Claude Code 客户端版本号
出站伪装用的 Claude Code 版本号此前硬编码在 claude.CLICurrentVersion,
只能靠环境变量 SUB2API_CLAUDE_CLI_VERSION 覆盖且需重启;Anthropic 抬高
版本下限时(如 Opus 5.5 要求 >= 2.1.280)必须改代码发版才能跟上。

改为每小时从官方 GitHub Releases 同步最新稳定版,无需重启也无需发版。

- 新增 ClaudeCodeVersionSyncService:1 小时间隔,数据源 anthropics/claude-code
  的 releases/latest,失败回退最近 30 条列表;过滤 draft/prerelease;
  只向前推进,拉取失败保留上次值不降级;面板可关闭
- 新增三个设置项:claude_code_client_version(管理员手动固定)、
  claude_code_client_version_synced(同步服务独占写)、
  claude_code_version_auto_sync_enabled(开关,默认开)
- 取值优先级:面板手动值 -> 同步值 -> SUB2API_CLAUDE_CLI_VERSION -> 内置基线,
  每层经 IsSupportedCLIVersion 校验,含 60s 缓存与 singleflight
- 版本号运行期化:claude.DefaultHeaders 由包级 var 改为函数,新增
  EffectiveCLIVersion/DefaultUserAgent 与 SetCLIVersionResolver(未注入时
  与 CLIVersion() 等价);identity 的 defaultFingerprint 不再在包 init 固化,
  指纹下限与主版本超前校验改用运行期值
- 守住一致性铁律:buildUpstreamRequest 与 count_tokens 各取一次 UA 字符串,
  同时喂给出站 User-Agent 头与请求体 billing 的 cc_version,避免缓存翻转
  瞬间头体版本不一致被判非正版客户端
- 管理后台设置页新增配置区块,含中英文案与「当前同步到」只读展示
2026-09-23 13:35:44 +08:00
lyy0709 c060aa0031 fix(models): repair tests after rebasing onto upstream main
Close the existing catalog identity test before the new capability test and
assert that an explicit null capability remains present. Update the quota
snapshot fixture to the pointer parameter already used by the current base.

Verified six full backend unit packages, scoped lint and CGO-disabled build.
2026-09-23 12:01:40 +08:00
HuntercodeT ecba49f711 fix(gateway): let OpenAI passthrough accounts supplement model discovery instead of hiding mapped models
A single passthrough account made GetAvailableModels return nil for the whole
group, so every other account's model_mapping was dropped from /v1/models and
the Codex catalog. Treat passthrough accounts like unmapped ones: skip their
(possibly stale) mapping and let supplementUnmappedOpenAIModels add the
default set, while ordinary accounts' mappings still reach the list.

Refs #6647, #7517
2026-09-23 11:51:06 +08:00
Achord Chan 17ce21c038 test(scheduler): pass explicit multiplier pointer to snapshot 2026-09-23 11:38:23 +08:00
shaw 5e244e7382 fix(test): 修复调度倍率参数变更后的 CI 编译失败 2026-09-23 11:36:08 +08:00
Achord Chan b5b5f1f94b fix(model-plaza): apply independent video billing multipliers 2026-09-23 11:28:41 +08:00
lyy0709 5b5f315b87 chore: remove model selector review screenshot 2026-09-23 11:27:49 +08:00
lyy0709 c4c2e66070 feat(models): support GPT-6 Sol, Luna and Claude Opus 5.5 2026-09-23 11:27:49 +08:00
Wesley Liddick d8d5e1dd35 Merge pull request #7282 from feeeei/feat/affiliate-offline-withdrawal
feat(affiliate): 提取记录支持登记线下提现
2026-09-23 11:20:32 +08:00
Wesley Liddick 59a00631ed Merge pull request #7478 from superzcj/codex/simple-mode-key-window-limits
feat: optionally enforce API-key spending windows in simple mode
2026-09-23 11:19:17 +08:00
Wesley Liddick b2d6b954a1 Merge pull request #7090 from Brisbanehuang/codex/scheduling-rate-account-fallback
fix(scheduler): 无有效探测时回退账号倍率,支持 OAuth 参考倍率留空
2026-09-23 11:18:37 +08:00
Wesley Liddick 1947add842 Merge pull request #7288 from feeeei/feat/backup-monthly-archive
feat(backup): 支持月度归档与独立保留策略
2026-09-23 11:18:08 +08:00
Wesley Liddick 6b71d75bde Merge pull request #4867 from coo1white/fix-backup-s3-secret-reencrypt
fix(backup): keep the S3 secret encrypted when a save inherits it
2026-09-23 11:17:55 +08:00
Wesley Liddick f53252e292 Merge pull request #6844 from ouchihao/codex/issue-6837-groups-manifest-test-pinia
test(groups): initialize Pinia in Codex manifest regression
2026-09-23 11:17:41 +08:00
Wesley Liddick 61e7d31605 Merge pull request #7513 from Achordchan/fix/channel-video-pricing-preview
fix(channels): display video pricing per second
2026-09-23 11:17:27 +08:00
shaw 033047b7d4 chore(docs): 移除已删除文档的忽略例外 2026-09-23 10:36:16 +08:00
shaw d68a68fd0d chore(docs): 清理 PR 误入的文档和截图 2026-09-23 10:35:34 +08:00
Wesley Liddick 31a6e74770 Merge pull request #7491 from Thinker-Joe/fix/openai-picker-model-mapping
fix(openai): scope the account test picker to the account model mapping
2026-09-23 10:31:36 +08:00
Wesley Liddick 7c0a2a556c Merge pull request #7160 from StarryKira/codex/log-retention-upstream
feat: 支持运维与请求日志的滚动保留设置
2026-09-23 10:07:25 +08:00
Wesley Liddick 0dd71286f2 Merge pull request #7060 from heathermhuang/fix/composite-image-models-6076
fix(images): allow compatible Gemini models on API-key upstreams
2026-09-23 10:07:02 +08:00
Wesley Liddick b350e079f8 Merge pull request #7139 from HP-network/fix/api-key-model-401-failover
fix: keep API-key accounts available for unknown models
2026-09-23 10:05:42 +08:00
Wesley Liddick 24872fda7c Merge pull request #7493 from ouchihao/codex/bug-temp-unsched-race
fix(accounts): keep temporary unschedulable status scoped to the current account
2026-09-23 10:03:22 +08:00
Wesley Liddick 5ad7cf4fb9 Merge pull request #7300 from lizhaoxinlizhaoxin2-lab/fix/responses-stream-error-schema
fix(responses): emit protocol-correct stream errors once
2026-09-23 10:03:00 +08:00
Wesley Liddick 60b9bf7558 Merge pull request #7308 from HuntercodeT/fix/codex-manifest-non-gpt-identity
fix(codex-models): 非 GPT 模型的 Codex 提示词模板去掉 GPT 身份声明,避免 Antigravity 429
2026-09-23 10:01:45 +08:00
Wesley Liddick d6e8b44bcb Merge pull request #7411 from HuntercodeT/fix/antigravity-vendor-identity-429
fix(antigravity): neutralize Claude Agent SDK identity in system prompts
2026-09-23 10:01:18 +08:00
Wesley Liddick fa3f526785 Merge pull request #7489 from doublepi123/fix/tool-schema-null-required
fix(tools): 清洗工具 Schema 里非法的 null required,修复 xAI / Moonshot 400
2026-09-23 10:01:03 +08:00
Wesley Liddick 7d5615998c Merge pull request #7492 from ouchihao/codex/bug-monitor-detail-race
fix(channel-monitor): ignore stale detail requests
2026-09-23 10:00:49 +08:00
Wesley Liddick d7e4bba0e7 Merge pull request #7494 from ouchihao/codex/bug-balance-error-message
fix(users): show normalized API errors in the balance dialog
2026-09-23 10:00:30 +08:00
Wesley Liddick d3d0f653e5 Merge pull request #7495 from ouchihao/codex/bug-subscription-expiry-label
fix(subscriptions): use calendar dates for expiry labels
2026-09-23 09:59:49 +08:00
Wesley Liddick 9e0e146984 Merge pull request #7496 from ouchihao/codex/bug-totp-late-timer
fix(profile): avoid starting TOTP cooldowns after unmount
2026-09-23 09:59:22 +08:00
Wesley Liddick fc4465f78b Merge pull request #7498 from ouchihao/codex/bug-model-tag-ime
fix(channels): preserve model tags during IME composition
2026-09-23 09:58:50 +08:00
Wesley Liddick 0eaa7c3c84 Merge pull request #7499 from ouchihao/codex/bug-date-picker-midnight
fix(date-picker): refresh relative dates after midnight
2026-09-23 09:58:36 +08:00
Wesley Liddick 5e4968492f Merge pull request #7500 from ouchihao/codex/bug-user-attribute-race
fix(users): discard stale user attribute responses
2026-09-23 09:57:53 +08:00
Wesley Liddick a81547f244 Merge pull request #7501 from ouchihao/codex/bug-profile-dingtalk-source
fix(profile): recognize DingTalk profile sources
2026-09-23 09:57:39 +08:00
Achord Chan bdb9a91db0 fix(channels): display video pricing per second 2026-09-23 09:09:37 +08:00
zhangcj 3b336b2eca feat: optionally enforce API-key spending windows in simple mode 2026-09-23 08:17:48 +08:00
Thinker-Joe 9d7c636db9 fix(openai): respect passthrough in picker image choices
Validate mapped targets for default image models as well as aliases. Preserve native image choices in passthrough and cover mapping changes over the shared catalog cache.
2026-09-23 01:43:06 +08:00
feeeei c19204289d fix(affiliate): 线下提现登记按 Idempotency-Key 幂等
登记请求只有金额,提交成功但响应丢失时,管理员重试会把同一笔站外打款再扣
一次返利额度。现在一次登记由 Idempotency-Key 标识,数据库在同一事务内以唯一
约束去重:

- user_affiliate_ledger 新增 operation_id(幂等键派生的 SHA-256)与部分唯一
  索引(迁移 240);接口要求 Idempotency-Key,缺失或非法返回 400
- 事务内先以 operation_id 写入占位流水,再解冻、扣减并补写额度快照;同键
  重试返回首笔流水的结果并带 X-Idempotency-Replayed,不重复扣减;同键换了
  用户或金额返回 409 IDEMPOTENCY_KEY_CONFLICT;额度不足时占位随事务回滚
- 并发的同键请求在唯一索引上等待先到者:先到者提交则返回同一条流水,回滚
  则自行登记
- 弹窗在网络错误、超时、5xx、408/409 时锁定用户与金额,重试沿用同一请求与
  幂等键;幂等键按管理员、用户、金额暂存于 sessionStorage,登记有确定结果后
  释放
2026-09-23 01:24:59 +08:00
feeeei 8f8358cc67 fix(backup): 关闭月度归档后不再改写旧归档的保留份数 2026-09-23 00:44:29 +08:00
Wesley Liddick 20a94fbb56 Merge pull request #6920 from aofee/codex/grok-quota-cooldown
fix(grok): allow quota queries during account cooldowns
2026-09-22 22:01:24 +08:00
Wesley Liddick da25b18db7 Merge pull request #7077 from ggllzz04/fix/antigravity-tuple-array-schema
fix(antigravity): handle prefixItems and ensure array schema has valid items fallback
2026-09-22 22:01:09 +08:00
Wesley Liddick 02d9901b49 Merge pull request #7038 from zenggang/contribute/gpt55-lite-compat
fix(openai): remove Responses Lite markers after OAuth mapping to GPT-5.5
2026-09-22 22:00:51 +08:00
Wesley Liddick 13be6ca27c Merge pull request #7276 from cyhhao/fix/openai-keepalive-semantic-output
fix(openai): keep transport heartbeats outside semantic output
2026-09-22 22:00:08 +08:00
Wesley Liddick e26abaef7d Merge pull request #6473 from cxx-cod/pr/openai-stream-terminal-eof
fix(openai): end streaming at terminal event instead of waiting for u…
2026-09-22 21:57:45 +08:00
Wesley Liddick 583398d186 Merge pull request #7303 from little-greenbean/fix/upstream-response-close-lifecycle
fix(upstream): prevent EOF stalls when closing response bodies
2026-09-22 21:57:24 +08:00
Wesley Liddick 5cc6ca6f5b Merge pull request #7311 from YogaSakti/fix/scheduler-cache-rpm-fields
fix(scheduler): keep account RPM config in the scheduler projection
2026-09-22 21:57:05 +08:00
Wesley Liddick b12a187d4f Merge pull request #7097 from MHJoy99/contrib/upstream-5203-ping-filter
fix(streaming): drop Anthropic ping keepalives before OpenAI conversion
2026-09-22 21:56:46 +08:00
Wesley Liddick 974a819ba1 Merge pull request #7108 from ouchihao/codex/bug-select-keyboard-focus
fix(ui): focus non-searchable select dropdowns
2026-09-22 21:56:34 +08:00
Wesley Liddick d27fbb3b7d Merge pull request #7109 from ouchihao/codex/bug-date-range-dismiss
fix(ui): discard unapplied date ranges on dismissal
2026-09-22 21:56:24 +08:00
Wesley Liddick ea34a2356c Merge pull request #7142 from ouchihao/codex/bug-select-search-highlight
fix(ui): reset select highlight when search results change
2026-09-22 21:56:14 +08:00
Wesley Liddick fa9f104a93 Merge pull request #7169 from HuntercodeT/fix/gemini-mixed-model-listing
fix(gateway): list mixed Antigravity models for Gemini groups
2026-09-22 21:56:04 +08:00
Wesley Liddick 51f73840a1 Merge pull request #7272 from zoutao212/fix/responses-function-call-arguments-done
fix(apicompat): 修复 Anthropic 转 Responses 流中 function_call_arguments.done 缺少 arguments 参数的问题
2026-09-22 21:55:48 +08:00
Wesley Liddick 2b12de14ee Merge pull request #7319 from ouchihao/codex/bug-dialog-scroll-lock
fix(dialog): keep body locked while another dialog is open
2026-09-22 21:55:30 +08:00
Wesley Liddick 7865051fdf Merge pull request #7320 from ouchihao/codex/bug-image-upload-read-order
fix(upload): cancel superseded image reads
2026-09-22 21:55:18 +08:00
Wesley Liddick 4b0adb6863 Merge pull request #7321 from ouchihao/codex/bug-proxy-expiry-boundary
fix(proxies): label newly expired proxies correctly
2026-09-22 21:55:07 +08:00
Wesley Liddick ba5737fe14 Merge pull request #7322 from ouchihao/codex/bug-ccswitch-antigravity-slash
fix(ccswitch): trim trailing slashes before Antigravity path
2026-09-22 21:54:51 +08:00
Wesley Liddick 7b13cb410d Merge pull request #7323 from ouchihao/codex/bug-announcement-stale-fetch
fix(announcements): ignore superseded fetch results
2026-09-22 21:54:38 +08:00
Wesley Liddick bb1f40e35f Merge pull request #7487 from wucm667/fix/issue-7482-anthropic-moderation
Handle trailing system messages in moderation input
2026-09-22 21:54:26 +08:00
Wesley Liddick 7be1628a74 Merge pull request #7488 from wucm667/fix/issue-7484-responses-item-id
Strip oversized input item IDs
2026-09-22 21:54:02 +08:00
chihao.ou 3eb4bae9ab fix(profile): recognize DingTalk profile sources 2026-09-22 21:49:27 +08:00
chihao.ou 1f5cfe8973 fix(users): discard stale user attribute responses 2026-09-22 21:49:11 +08:00
chihao.ou 5fc4a06af6 fix(date-picker): refresh relative dates after midnight 2026-09-22 21:46:06 +08:00
chihao.ou a1eaad6033 fix(channels): preserve model tags during IME composition 2026-09-22 21:45:48 +08:00
chihao.ou 1af3269adb fix(groups): clean up modal listeners and pending searches 2026-09-22 21:43:13 +08:00
chihao.ou 1ca54bcc25 fix(profile): avoid starting TOTP cooldowns after unmount 2026-09-22 21:42:54 +08:00
chihao.ou 7ba6efe805 fix(subscriptions): use calendar dates for expiry labels 2026-09-22 21:40:14 +08:00
chihao.ou 4d667f1b08 fix(users): show normalized API errors in the balance dialog 2026-09-22 21:39:54 +08:00
chihao.ou 5c38d372c1 fix(accounts): keep temporary unschedulable status scoped to the current account 2026-09-22 21:37:01 +08:00
chihao.ou 9e4010695b fix(channel-monitor): ignore stale detail requests 2026-09-22 21:36:42 +08:00
Thinker-Joe 4daea093f9 fix(openai): keep OAuth image aliases in the test picker
Image choices were resolved from DefaultModels IDs and from mapping keys, so an
alias whose target is a local image model (paint -> gpt-image-2.5-flare) never
reached the picker: IsModelSupported only matches keys, and a public name is not
an image model. Resolve the public name to its target before deciding, and only
synthesize an entry when the target is an image model.

Update the fixture of
TestFetchOpenAIAccountModelsOAuthLabelsLocalImageModelsLikeUpstream: it asserted
on an upstream slug the account did not configure, which conflicts with the
account-scoped projection. Coverage is preserved by configuring that slug and by
a new test asserting unconfigured text models stay out.
2026-09-22 21:15:20 +08:00
lcy 1d640c40e5 fix(tools): 清洗工具 Schema 里非法的 null required,修复上游 400
JSON Schema 规定 required 必须是属性名数组,但部分客户端会发成 null,
严格校验的上游直接拒绝整个请求:

  xAI       400 /required: null is not of type "array"
  Moonshot  400 At path 'required': required must be an array

同样的模型发纯文本请求一切正常,只有带 tools 时才失败,因此表现得像模型
或渠道故障。

三处改动:

1. 清洗 required:null 时整键删除,而不是替换成 []。JSON Schema 里缺省
   required 等价于无必填项,删除保留了客户端原意,置 [] 反而凭空造出一条
   客户端从未声明的约束。

2. 把 input_schema 也识别为 schema 根。此前只认 OpenAI Responses 的
   parameters 拼法,Anthropic Messages 的工具定义因此绕过整套清洗。

3. 在 ForwardAsAnthropic 入口调用清洗。/v1/messages 此前不做任何工具
   Schema 处理;该函数会分流到原生 Anthropic 直通、Chat Completions 与
   Responses 三条路径,每条都原样透传 tools,所以必须在分流之前处理。

另外把 contentSchema 补进子 schema 关键字:它承载嵌套 schema,其中的
null required 此前会漏网。

配套测试同时锁定反向保证:default / examples / const / enum 里装的是实例
数据,字面量 {"required": null} 属于客户端 payload,不能被改写。现有的
关键字白名单下降本就如此,测试用于防止它退化成无差别遍历。
2026-09-22 20:49:24 +08:00
Wesley Liddick b0e32fe5be Merge pull request #7427 from xlplbo/fix/openai-legacy-scheduler-decision
fix(openai): 非高级调度补齐选号决策并按 previous_response 路由
2026-09-22 20:34:59 +08:00
Wesley Liddick 65f086d2d0 Merge pull request #7479 from lzfxxx/fix/opencode-commandcode-cf1010
fix(gateway): prevent Cloudflare 1010 from disabling OpenCode and Command Code accounts
2026-09-22 20:32:42 +08:00
Wesley Liddick de6388aeca Merge pull request #5443 from llissery/fix/vertex-429-cooldown
fix(gemini): honor RetryInfo on 429 and stop cooling Vertex service accounts until PST midnight
2026-09-22 20:30:37 +08:00
Wesley Liddick 55108ee877 Merge pull request #7394 from Achordchan/fix/baseten-reasoning-budget
fix(gateway): recognize Baseten reasoning budget errors
2026-09-22 20:30:21 +08:00
Wesley Liddick 231e72fdde Merge pull request #7339 from superman2003/fix/openai-stream-error-status-field
fix(openai): honor error.status when classifying in-stream failures
2026-09-22 20:30:08 +08:00
Wesley Liddick a079a6596a Merge pull request #7342 from Pluviobyte/codex/fix-inactive-proxy-backup
fix(proxies): exclude inactive fallback targets
2026-09-22 20:29:52 +08:00
Wesley Liddick ed2360d7ea Merge pull request #7341 from Pluviobyte/codex/fix-proxy-expiry-renewal
fix(proxies): preserve renewals during expiry sweeps
2026-09-22 20:29:39 +08:00
Wesley Liddick b717ac7f0b Merge pull request #7289 from wucm667/fix/issue-7281-platform-quota-options
fix(admin): align platform quota editor with supported platforms
2026-09-22 20:29:26 +08:00
Wesley Liddick c619ff8474 Merge pull request #7404 from a408665321/codex/fix-oauth-credentials-merge
fix(account): preserve model mapping on OAuth reauth
2026-09-22 20:29:01 +08:00
Wesley Liddick 2448a38b55 Merge pull request #7395 from zhuzhihaocool-bit/fix/codex-base-url-v1
fix(frontend): ensure Codex base URLs include /v1
2026-09-22 20:28:39 +08:00
Wesley Liddick 5fd3461142 Merge pull request #7418 from ouchihao/codex/bug-pricing-exponent
fix(pricing): parse scientific notation in token bounds
2026-09-22 20:28:12 +08:00
Wesley Liddick c1319917cf Merge pull request #7417 from ouchihao/codex/bug-payment-callback-slash
fix(payment): trim callback base URL trailing slashes
2026-09-22 20:28:03 +08:00
Wesley Liddick a5015e1fc4 Merge pull request #7354 from baryon/contrib/codex-deepseek-input-image-url
fix(openai): alias DeepSeek Responses input_image with url
2026-09-22 20:27:35 +08:00
Wesley Liddick 738ef1c73c Merge pull request #7442 from wucm667/fix/issue-7436-image-balance-error
fix(images): preserve insufficient balance failures
2026-09-22 20:27:23 +08:00
Wesley Liddick 5af29a3b93 Merge pull request #7422 from ouchihao/codex/bug-user-api-keys-stale
fix(users): keep API key results scoped to the selected user
2026-09-22 20:27:07 +08:00
Wesley Liddick 62a8919a1c Merge pull request #7365 from ouchihao/codex/bug-monitor-template-stale-list
fix(monitor): ignore stale template picker responses
2026-09-22 20:26:58 +08:00
Wesley Liddick 1ea00258d0 Merge pull request #7375 from ouchihao/codex/bug-balance-history-stale
fix(users): ignore superseded balance history requests
2026-09-22 20:26:33 +08:00
Wesley Liddick 023b38354f Merge pull request #7373 from ouchihao/codex/bug-user-groups-load-guard
fix(users): wait for group configuration before enabling save
2026-09-22 20:26:23 +08:00
Wesley Liddick a765b3c176 Merge pull request #7367 from ouchihao/codex/bug-rpm-override-empty
fix(groups): require integer RPM overrides before adding
2026-09-22 20:26:11 +08:00
Wesley Liddick ca47fa352c Merge pull request #7376 from ouchihao/codex/bug-group-rate-positive
fix(groups): reject negative custom rates before adding
2026-09-22 20:26:00 +08:00
Wesley Liddick 680a992fc9 Merge pull request #7426 from xlplbo/fix/openai-codex-turn-metadata-ascii
fix(openai): 改写 Codex turn metadata 时保留非 ASCII 转义
2026-09-22 20:25:47 +08:00
Wesley Liddick f2e55bf4d7 Merge pull request #7420 from ouchihao/codex/bug-error-detail-stale
fix(usage): ignore superseded error detail requests
2026-09-22 20:25:26 +08:00
Wesley Liddick c96d36ec95 Merge pull request #7374 from ouchihao/codex/bug-search-ime
fix(search): wait for committed IME input before searching
2026-09-22 20:25:15 +08:00
Wesley Liddick e4f97a53ec Merge pull request #7366 from ouchihao/codex/bug-user-attribute-clear-metadata
fix(users): persist cleared custom attribute hints
2026-09-22 20:24:59 +08:00
Wesley Liddick 9e175bd491 Merge pull request #7364 from ouchihao/codex/bug-group-replace-errors
fix(users): show errors when group replacement fails
2026-09-22 20:24:47 +08:00
Wesley Liddick e7d348868c Merge pull request #7264 from ouchihao/codex/bug-antigravity-mapping-retry
fix(accounts): retry default mappings after a failed fetch
2026-09-22 20:24:32 +08:00
Wesley Liddick c0b23ff791 Merge pull request #7372 from ouchihao/codex/bug-admin-settings-retry
fix(settings): allow retrying failed initial admin settings loads
2026-09-22 20:24:21 +08:00
Wesley Liddick 322cc5e5f1 Merge pull request #7363 from ouchihao/codex/bug-user-attribute-number
fix(users): keep numeric custom attribute values as strings
2026-09-22 20:24:12 +08:00
Wesley Liddick 23dc073e65 Merge pull request #7419 from ouchihao/codex/bug-monitor-refresh-preference
fix(monitor): preserve the saved auto-refresh preference
2026-09-22 20:24:00 +08:00
wucm667 a5d8db2445 fix(responses): strip oversized input item IDs 2026-09-22 19:47:12 +08:00
GongTengXY de28eea11f fix(openai): filter account test models by model mapping 2026-09-22 19:34:15 +08:00
wucm667 66843cc95c fix(moderation): handle trailing Anthropic system messages 2026-09-22 19:07:04 +08:00
Achord Chan f867e3e2ec test(antigravity): check schema properties type assertion 2026-09-22 18:34:36 +08:00
Wesley Liddick 1716e99151 Merge pull request #7466 from nagi330/add_grok4-7_support-0922
feat(grok):add grok 4.7 support
2026-09-22 18:13:37 +08:00
Wesley Liddick 483cd56924 Merge pull request #7361 from wucm667/feat/issue-7357-optional-default-groups
feat(simple): make startup default group creation optional
2026-09-22 18:13:18 +08:00
Wesley Liddick b6c6f1add5 Merge pull request #7473 from lzfxxx/fix/codex-manifest-opencode-go
fix(codex): include OpenCode Go in model capability resolution
2026-09-22 18:13:00 +08:00
Wesley Liddick 3442a6a53e Merge pull request #7432 from doublepi123/fix/antigravity-compat-bare-gemini-model
fix(antigravity): 裸 Gemini 模型名在所有转发入口解析到思考变体,修复 404/502
2026-09-22 18:12:34 +08:00
Wesley Liddick 9d9e90960e Merge pull request #7448 from feeeei/fix/gemini-transport-error-failover
fix(gemini): 传输层错误转 failover,不再同账号退避重试
2026-09-22 18:12:19 +08:00
Wesley Liddick fcd07ba0af Merge pull request #7475 from Pluviobyte/codex/fix-proxy-restore-probe
fix(proxies): invalidate billing probe on fallback restore
2026-09-22 18:12:04 +08:00
Wesley Liddick 405727805a Merge pull request #7477 from Pluviobyte/codex/fix-subscription-reduction-remainder
fix(subscriptions): preserve partial days during redemption deductions
2026-09-22 18:11:46 +08:00
Wesley Liddick a46493724b Merge pull request #7476 from Pluviobyte/codex/fix-subscription-reduction-lock
fix(subscriptions): lock negative redemption updates
2026-09-22 18:11:11 +08:00
Wesley Liddick d8eeb0989b Merge pull request #7481 from spongehah/fix/selection-skip-account-count
perf: 选号读取分组时不再聚合账号数
2026-09-22 18:11:00 +08:00
Wesley Liddick a266e50e8e Merge pull request #7369 from feeeei/feat/admin-users-toggle-status-in-place
ui(users): 禁用/启用用户后原地更新该行
2026-09-22 18:10:45 +08:00
Wesley Liddick 5295bd8227 Merge pull request #7446 from wucm667/fix/issue-7441-csv-reasoning-effort
fix(usage): export missing reasoning effort cleanly
2026-09-22 18:10:35 +08:00
spongehah 7fbc59eb69 fix: 选号读取分组时不再聚合账号数
- 推理选号只需要隐私开关和分组名,改为 GetByIDLite
- 避免 GetByID 附带的账号计数聚合打满主库
- 管理列表的实时账号数统计保持不变
2026-09-22 16:54:36 +08:00
Zhaofeng Li fa79b1ebc3 fix(gateway): prevent Cloudflare 1010 from disabling OpenCode and Command Code accounts 2026-09-22 15:51:51 +08:00
Rain 0c0df031c5 fix(subscriptions): preserve partial days during redemption deductions 2026-09-22 15:03:06 +08:00
Rain 85ed17b313 fix(subscriptions): lock negative redemption updates 2026-09-22 15:03:05 +08:00
Rain b754ff6f1b fix(proxies): invalidate billing probe on fallback restore 2026-09-22 14:51:44 +08:00
Zhaofeng Li e35123b8ac fix(codex): include OpenCode Go in model capability resolution 2026-09-22 14:50:29 +08:00
Erik 7f1f85cb76 fix(gemini): stop cooling Vertex 429s until PST midnight, honor RetryInfo
Vertex AI reports 429s with a standard google.rpc.RetryInfo detail
(retryDelay like "39s"), but ParseGeminiRateLimitResetTime only knew the
AI Studio quotaResetDelay metadata, so parsing always failed for Vertex
bodies. The fallback then lumped service_account accounts in with
API-key/AI-Studio ones and rate limited them until the next PST
midnight, so a transient per-minute throttle could take a pay-as-you-go
account (and with it the whole group) offline for up to a day.

- Parse google.rpc.RetryInfo retryDelay from 429 bodies, capped at 15
  minutes to guard against absurd upstream values.
- When no reset time can be parsed, cool service_account (Vertex)
  accounts down for 60s instead of until PST midnight: pay-as-you-go
  quotas are short-window RPM/TPM with no daily reset.

Fallback behavior for Code Assist, Google One and API-key accounts is
unchanged, covered by new regression tests.
2026-09-22 11:31:31 +08:00
nagi330 935db68517 feat(grok):add grok 4.7 support 2026-09-22 10:30:01 +08:00
Wesley Liddick 1c0a69c0ce Merge pull request #7412 from StarryKira/codex/custom-reasoning-effort-billing
feat: 支持自定义思考等级倍率计费
2026-09-21 22:55:17 +08:00
lcy 27f4398b50 fix(antigravity): 裸 Gemini 模型名在所有转发入口解析到思考变体
#7258 引入的 resolveGeminiThinkingVariant 只接到了 ForwardGemini,
因此仅覆盖 /v1beta 原生 Gemini 路径。经 /v1/chat/completions 与
/v1/messages 进来的请求直接调用 getMappedModel,裸名被原样透传;
Antigravity 目录只登记 -low/-medium/-high/-tiered 变体,这些请求
仍然以 404 "Requested entity was not found." 失败。

把解析下沉到 getMappedModel(新增 getMappedModelForThinkingLevel),
一次覆盖四个调用点:/v1beta 原生、/v1/chat/completions、/v1/messages
以及后台账号连接测试。各转发入口按自身协议推导档位——原生读
generationConfig.thinkingConfig,Claude 侧读 thinking.budget_tokens,
两者阈值一致;默认入口按 high 兜底。

mapAntigravityModel 保持不变,调度侧的模型支持判定语义不受影响。
2026-09-21 20:13:44 +08:00
haruka e47255715d fix(billing): preserve final reasoning effort across forwarding paths 2026-09-21 19:58:02 +08:00
feeeei d0ed0eacac fix(gemini): 传输层错误转 failover,不再同账号退避重试
上游 Do 返回非 HTTP 错误(代理/DNS/TCP/TLS/响应头超时)时,Gemini 三条转发路径
(ForwardNative / Forward / ForwardAsChatCompletions)原先在同一账号上重试 5 次,
退避 1+2+4+8≈15s(time.Sleep 不感知 ctx),耗尽后直接向客户端写 502 且不换号:
单账号链路故障期间 TTFT 被整段拖高,同组健康账号闲置。

对齐 Anthropic/Bedrock 侧 handleUpstreamTransportError 的既有语义:
- 传输层错误单次尝试后即返回 *UpstreamFailoverError(502),由 handler failover
  循环换号,耗尽后才按端点格式渲染错误;service 不再写响应
- 持久性故障(connection refused/no route/DNS not found/代理认证失败)额外临时
  摘除账号 10 分钟;瞬时故障(EOF/reset/超时)只换号不摘号
- context.Canceled 保持原样返回:不换号也不摘账号
- countTokens 传输失败时立即本地估算兜底,不换号
- 摘号实现抽为 tempUnscheduleAccountForTransportError 供两侧共用,日志事件名不变

HTTP 状态码(429/5xx)的服务内重试环未改动。
2026-09-21 14:13:57 +08:00
wucm667 ece1ecccca fix(gateway): normalize streamed Anthropic usage 2026-09-21 12:58:56 +08:00
wucm667 b13200d7a1 fix(gateway): forward received chat stream usage 2026-09-21 12:58:56 +08:00
wucm667 386f321d3c fix(usage): export missing reasoning effort cleanly 2026-09-21 12:41:01 +08:00
wucm667 60a64568bf ci: run simple mode compose environment test 2026-09-21 11:06:25 +08:00
wucm667 de98bdff1e fix(images): preserve insufficient balance failures 2026-09-21 10:23:10 +08:00
wucm667 992c4f4b89 test(frontend): run platform quota modal spec in CI 2026-09-21 08:16:18 +08:00
aofee d1ba57977d feat: add native TypeSafe Jev System One support 2026-09-20 20:20:16 +08:00
shaw 7c700729c2 chore: update gitignore 2026-09-20 20:05:09 +08:00
Wesley Liddick 87957a608b Merge pull request #7413 from ranxi2001/ci/release-build-matrix
ci: parallelize release builds across platform runners
2026-09-20 20:02:48 +08:00
xlplbo 0d02000592 fix(openai): 非高级调度按 previous_response 路由到持有响应的账号 2026-09-20 19:28:13 +08:00
xlplbo 8d88b66668 fix(openai): 补齐非高级调度选号决策标签 2026-09-20 19:27:53 +08:00
xlplbo 763443abf2 fix(openai): 改写 Codex turn metadata 时保留非 ASCII 转义 2026-09-20 19:27:47 +08:00
chihao.ou 7f18f3e9af fix(users): keep API key results scoped to the selected user 2026-09-20 18:09:50 +08:00
chihao.ou b86849e442 fix(usage): ignore superseded error detail requests 2026-09-20 18:07:52 +08:00
chihao.ou 319299519b fix(monitor): preserve the saved auto-refresh preference 2026-09-20 18:07:39 +08:00
chihao.ou 23a1d38187 fix(pricing): parse scientific notation in token bounds 2026-09-20 18:05:23 +08:00
chihao.ou 1582347204 fix(payment): trim callback base URL trailing slashes 2026-09-20 18:05:09 +08:00
ranxi2001 d1556a7a96 ci: point release helper tests at their final directory 2026-09-20 17:01:27 +08:00
ranxi2001 d2416a9b68 ci: keep release tooling and cache keys stable across jobs 2026-09-20 16:54:06 +08:00
HuntercodeT fb58dfbd93 test(antigravity): cover the identity rewrite end-to-end through the transformer
Adds a case with the real block layout (attribution block, identity sentence,
task instructions) and asserts that user content mentioning Claude Code and
claude-sonnet-4-6 is forwarded unchanged.
2026-09-20 16:48:04 +08:00
haruka b8d52fad34 feat(billing): support configurable reasoning effort multipliers 2026-09-20 16:41:49 +08:00
shaw d2e319b2a1 test: 修复 WebSocket 同线程抢占测试的关闭时序竞态 2026-09-20 16:37:07 +08:00
ranxi2001 0892ef3a9a ci: build release targets on independent matrix runners 2026-09-20 16:36:24 +08:00
HuntercodeT dd292e3b00 fix(antigravity): neutralize Claude Agent SDK identity in system prompts
Stripping the x-anthropic-billing-header line is not enough. Claude Code's
Agent SDK prompts (session title generation, and other SDK-driven calls) open
a separate system block with

    You are a Claude agent, built on Anthropic's Claude Agent SDK.

and the Google upstream still rejects those requests with 429 RESOURCE_EXHAUSTED.

Measured on Sub2API 0.2.7, which already contains the attribution fix, using an isolated single-account group, waiting for the per-model cooldown
to expire before every request so that a previous failure could not turn later
results into 503:

  original request replayed                      429 (8/8)
  same request, generic system prompt            200 (8/8)
  attribution also removed client-side           429 (3/3)
  attribution removed + identity neutralized     200 (3/3)
  only 'Claude' replaced in system               200 (2/2)
  only 'Anthropic' removed from system           200 (2/2)
  output_config / max_tokens / non-stream        no effect

The rewrite is anchored at the start of a system block, so user instructions that
merely mention Claude or Anthropic, and model ids such as claude-sonnet-4-6, are
left untouched. Scoped to the Antigravity transformer, as with the existing
attribution handling.
2026-09-20 16:34:26 +08:00
shaw 95134201b2 docs: 删除误合入的 Codex 积分文档和截图 2026-09-20 16:12:11 +08:00
Wesley Liddick acdf3c54da Merge pull request #7401 from StarryKira/codex/codex-credits-referrals-upstream
feat(openai): display Codex credits and support referral invitations
2026-09-20 16:00:28 +08:00
haruka fc96132e72 fix(openai): harden referral outcomes and isolate HTTP transport 2026-09-20 15:47:53 +08:00
haruka 8f6bbb59c7 test: stabilize Gemini keepalive test 2026-09-20 15:04:15 +08:00
Wesley Liddick fbb9006ade Merge pull request #7402 from Wei-Shaw/fix/7268-openai-http2-keepalive
fix(upstream): 恢复 OpenAI HTTP/2 保活容错期限
2026-09-20 14:57:35 +08:00
shaw e009ea3036 fix(upstream): 恢复 OpenAI HTTP/2 保活容错期限 2026-09-20 14:46:25 +08:00
a408665321 63c079d873 fix(account): preserve settings on OAuth reauth 2026-09-20 14:39:36 +08:00
haruka e509937382 docs: add Codex referral UI validation screenshots 2026-09-20 14:38:30 +08:00
haruka 5090ffe05e feat(openai): show Codex credits and manage referral invitations 2026-09-20 14:38:29 +08:00
Wesley Liddick bbdcfbac0a Merge pull request #7304 from wucm667/fix/issue-7298-response-model-alias
fix(gateway): restore public response model aliases
2026-09-20 14:07:16 +08:00
Wesley Liddick 7403a01177 Merge pull request #7314 from wucm667/fix/issue-7306-keyword-reminder-bypass
fix(moderation): prevent reminder tags from bypassing keyword checks
2026-09-20 14:07:04 +08:00
Wesley Liddick 53b4bbe736 Merge pull request #7349 from wucm667/fix/issue-7348-preserve-client-version
fix(settings): preserve client version on invalid user agent
2026-09-20 14:06:48 +08:00
Wesley Liddick 8bb48622a3 Merge pull request #7362 from wucm667/fix/issue-7358-preserve-account-errors
fix(accounts): preserve refresh errors during usage queries
2026-09-20 14:06:36 +08:00
Wesley Liddick f28adb6ddb Merge pull request #7387 from Brisbanehuang/codex/upstream-content-audit-typesafe
feat: 内容审计接入 TypeSafe AI,支持双引擎切换与独立配置
2026-09-20 13:47:14 +08:00
Wesley Liddick 19794bc46a Merge pull request #7397 from Wei-Shaw/feat/hostservice-account-metadata
feat(pluginapi): HostService 账号目录返回结构化只读元数据
2026-09-20 11:39:15 +08:00
shaw 29eead917f feat(pluginapi): HostService 账号目录返回结构化只读元数据
纯宿主侧改动,向后兼容。

- 契约(pkg/pluginapi/v1/plugin.proto,已重新生成):ListAccounts 增补
  repeated AccountInfo accounts(保留 account_ids 向后兼容),新增 metadata_json
  只读快照字段。HostServiceAPIVersion 1→2(InitHostServices 运行时协商,加法式,
  旧调用方忽略新字段即可)。
- 权限边界:可见范围由清单能力经 pluginCapabilityAccountScopeGrants 推导,
  ListAccounts 与 ResolveOutboundIdentity 均以该范围为权威边界。
- metadata_json 采用 denylist:剥离 Credentials 与含反向引用的关联对象
  Groups/AccountGroups(避免 encoding/json 循环引用),其余字段自动透传,
  数据模型新增非机密字段无需改宿主。

测试:范围/元数据/无凭据泄漏用例、denylist 反射护栏 + 循环引用安全断言、纵深过滤用例;
build/vet/gofmt、-tags unit 与 -race 全绿。
2026-09-20 11:26:19 +08:00
zhuzhihaocool-bit fabdfb8a5b fix(frontend): ensure Codex base URLs include /v1 2026-09-20 11:07:29 +08:00
Achord Chan 1411b7eb7e fix(gateway): recognize Baseten reasoning budget errors 2026-09-20 11:02:06 +08:00
Achord Chan ef51690b5a fix(antigravity): preserve string const constraints in tool schemas 2026-09-20 10:46:09 +08:00
Brisbanehuang 1bfe0d3728 fix: sync draft audit key status and threshold defaults 2026-09-19 20:52:31 -04:00
Brisbanehuang 783a0a9830 feat(content-audit): add independent TypeSafe engine profiles 2026-09-19 20:52:31 -04:00
chihao.ou cd2a4357c2 fix(groups): reject negative custom rates before adding 2026-09-19 19:43:39 +08:00
chihao.ou f3a2dcabba fix(users): ignore superseded balance history requests 2026-09-19 19:43:23 +08:00
chihao.ou 7bf3d0b585 fix(search): wait for committed IME input before searching 2026-09-19 19:43:08 +08:00
chihao.ou cb2bb6084c fix(users): wait for group configuration before enabling save 2026-09-19 19:42:12 +08:00
chihao.ou 00591cbe9a fix(settings): allow retrying failed initial admin settings loads 2026-09-19 19:41:56 +08:00
chihao.ou ba26e543f9 fix(accounts): retry default mappings after a failed fetch 2026-09-19 19:26:59 +08:00
feeeei f6eeed3d5a ui(users): 禁用/启用用户后原地更新该行
管理端用户列表点「禁用/启用」后会重新拉取整个列表:表格先换成骨架屏,
再重新请求用户列表与用量、属性、平台限额三份附属数据,滚动位置随之丢失,
连续处理多个用户时每点一次都像整页刷新。

- 请求成功后按 id 找到当前列表中的那一行,只回写 status 与 updated_at;
  更新接口的响应不含 current_concurrency、subscriptions 等列表专属字段,
  不能整行替换
- 更新返回时若有列表请求在途,该请求可能读到更新前的状态,此时重新拉取列表
- 按状态筛选时,被切换的行留在原地并显示新状态,可当场撤回误操作;
  总数在下次刷新前不变
- 新增三条用例:原地更新且不重载列表、请求失败时该行不变、并发列表请求时回退为重载
2026-09-19 18:14:27 +08:00
chihao.ou 3b0bb60ea3 fix(groups): require integer RPM overrides before adding 2026-09-19 17:56:42 +08:00
chihao.ou 26c09b7de6 fix(users): persist cleared custom attribute hints 2026-09-19 17:56:21 +08:00
chihao.ou 4d5a4ab0e5 fix(monitor): ignore stale template picker responses 2026-09-19 17:56:04 +08:00
chihao.ou 50f79e11fc fix(users): show errors when group replacement fails 2026-09-19 17:54:43 +08:00
chihao.ou 6b09c74e35 fix(users): keep numeric custom attribute values as strings 2026-09-19 17:54:19 +08:00
wucm667 b252821c59 fix(accounts): preserve refresh errors during usage queries 2026-09-19 17:22:39 +08:00
wucm667 68aa26477f feat(simple): make startup default group creation optional 2026-09-19 16:47:17 +08:00
Long LiandCursor 7e530c9d4e fix(openai): alias DeepSeek Responses input_image with url
Codex sends images as input_image.image_url. DeepSeek's live /responses
decoder requires a url field and returns 422 missing field url, including
on openai-platform accounts whose base_url host is api.deepseek.com.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-19 14:55:02 +09:00
github-actions[bot] 1a9d49e16f chore: sync VERSION to 0.2.7 [skip ci] 2026-09-19 04:29:03 +00:00
Wesley Liddick aea725f2ea Merge pull request #7247 from Qiaogun/codex/seedance-native-api
feat: 支持 Seedance / Ark 原生视频任务 API
2026-09-19 12:11:17 +08:00
Wesley Liddick 74431ffad8 Merge pull request #7258 from HuntercodeT/fix/antigravity-gemini-bare-model-thinking-variant
fix(antigravity): Gemini 原生请求的裸模型名按 thinkingConfig 解析到 -low/-medium/-high 变体
2026-09-19 12:01:22 +08:00
Wesley Liddick 0c9e83b59c Merge pull request #7278 from HuntercodeT/fix/antigravity-gemini-sse-comment-keepalive
fix(antigravity): Gemini 原生流对 go-genai / python-genai 客户端不发 SSE 注释心跳
2026-09-19 12:00:18 +08:00
Wesley Liddick 09f88865e0 Merge pull request #7294 from feeeei/feat/model-plaza-icon
ui(header): 手机竖屏顶栏保留模型广场图标入口
2026-09-19 11:59:46 +08:00
Wesley Liddick 1b45d21328 Merge pull request #7340 from ye4241/fix/kimi-cn-quota-403-rate-limit-pause
fix(ratelimit): CN coding-plan 账号配额耗尽的 403 按限流暂停调度,而非永久禁用
2026-09-19 11:59:21 +08:00
Wesley Liddick d5cea617a5 Merge pull request #7345 from laoxiechuzheng/fix/anthropic-root-union-schema
fix(apicompat): 摊平 Responses→Anthropic 工具 schema 顶层联合,修复 Codex 内置工具导致的 400
2026-09-19 11:59:00 +08:00
Wesley Liddick 4275047d16 Merge pull request #7313 from baryon/contrib/deepseek-chat-reasoning-content
fix(openai): pass DeepSeek thinking-mode reasoning_content on chat fallback
2026-09-19 11:57:55 +08:00
Wesley Liddick 4dbcdce43c Merge pull request #7351 from Wei-Shaw/feat/plugin-host-services-status-bridge
feat(plugin): generic host services + read-only status bridge channel
2026-09-19 11:57:41 +08:00
shaw 6477143533 test(plugin): check type assertions to satisfy errcheck lint 2026-09-19 11:47:14 +08:00
shaw c63bd14a02 feat(plugin): generic host services + read-only status bridge channel
Extend the local plugin system's host<->plugin contract with generic,
capability-neutral facilities, so transport plugins can be built on top
without embedding plugin-specific logic in the host.

Host services (plugin dials a broker-provided HostService gRPC):
- per-plugin namespaced KV store (key/value size and TTL bounded)
- account directory: ListAccounts + ResolveOutboundIdentity, restricted to
  the accounts a plugin's declared capability already covers
- InitHostServices lifecycle hook; plugins that don't implement it run
  unchanged and are simply offered no host services

Read-only runtime status channel:
- HealthResponse gains an opaque, plugin-defined status_json produced
  passively (no config apply, no upstream call, no side effects)
- GET /admin/plugins/:id/status (ungated) and the plugin.status UI-bridge
  verb map to Health, so a status UI can poll live state without a step-up
  prompt or a "test" side effect
- config.test no longer force-shows a host success toast; the plugin UI owns
  result presentation, so plugins that read status do not spam toasts

Document the UI-bridge verb taxonomy (read vs mutate/test gating) and the
status contract under pkg/pluginapi.
2026-09-19 11:25:56 +08:00
wucm667 2d37088bd9 fix(settings): preserve client version on invalid user agent 2026-09-19 10:36:51 +08:00
laoxiechuzheng a8a1a3a958 fix(apicompat): flatten root union tool schemas for Anthropic
Codex 会把 codex_app 等内置工具的 parameters 根节点声明成对象分支的 oneOf/anyOf,Anthropic 拒绝工具 input_schema 顶层的 oneOf/anyOf/allOf,导致 /v1/responses -> /v1/messages 直接 400。

Responses->Anthropic 转换时摊平顶层联合:属性取各分支并集,同名属性用嵌套联合保留两侧约束,required 在 oneOf/anyOf 下取分支交集、allOf 下取并集;嵌套联合保持不变。
2026-09-19 07:34:21 +08:00
Rain 4ccdead2a2 fix(proxies): skip inactive fallback targets 2026-09-19 00:51:01 +08:00
Rain f7280213f7 fix(proxies): skip expiry writes from stale snapshots 2026-09-19 00:51:01 +08:00
ye4241andClaude Opus 4.8 db8692d679 fix(ratelimit): pause CN coding-plan accounts on quota-exhausted 403
Kimi reports Coding Plan window exhaustion (5h/weekly) as a 403 with
error.type=access_terminated_error instead of 429. It fell into the
generic handleOpenAI403 escalation, so three 403s within 180 minutes
permanently disabled accounts that recover by themselves at the window
reset.

Detect the quota-exhausted 403 for CN coding-plan accounts and cool it
down exactly like the 429 path: SetRateLimited until the earliest future
window reset from the quota snapshot, falling back to a short
temp-unschedulable window when the snapshot is missing. Non-coding-plan
accounts keep the generic 403 escalation since the rolling-window
recovery mechanism does not apply to them.

Also extract cooldownCNProviderToQuotaSnapshotReset and
setCNProviderTempUnschedulable so the 429 (OpenCodeGo / Coding Plan)
and 403 branches stop carrying three copies of the same sequence.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-19 00:00:57 +08:00
superman2003 37238c0985 fix(openai): honor error.status when classifying in-stream failures
OpenAI 兼容上游(含二级中转)常把流内 error / response.failed 事件的状态码写在
error.status 上,而不是 OpenAI 使用的 error.status_code。SSE 路径只读
status_code,于是这些上游的 401/403/429/529 全部被降级成通用 502:认证失败不
再判定为凭据故障、429 不再标记限流与配额窗口、error 帧丢掉 401/429/529 的
failover 快路径,运维日志也记成 502。WS 路径的 openAIWSPayloadTransientStatus
早已同时读这两种拼写,SSE 路径一直没跟上。

把状态码路径集合抽成共享常量,让 SSE 路径与 WS 路径对齐。5xx 仍按通用上游故障
处理,不改动既有的账号状态语义。
2026-09-18 23:51:08 +08:00
chihao.ou 7b282c4f1d fix(announcements): ignore superseded fetch results 2026-09-18 16:39:25 +08:00
chihao.ou d054ee9af3 fix(ccswitch): trim trailing slashes before Antigravity path 2026-09-18 16:38:58 +08:00
chihao.ou 9612a70c77 fix(proxies): label newly expired proxies correctly 2026-09-18 16:38:29 +08:00
chihao.ou 24f4736f64 fix(upload): cancel superseded image reads 2026-09-18 16:37:56 +08:00
chihao.ou 9d5c8d961c fix(dialog): keep body locked while another dialog is open 2026-09-18 16:37:03 +08:00
wucm667 7b4de8b6ae fix(moderation): prevent reminder tags from bypassing keyword checks 2026-09-18 14:54:18 +08:00
Long LiandCursor bcc73f8d40 fix(openai): pass DeepSeek thinking-mode reasoning_content on chat fallback
Codex histories often replay encrypted-only reasoning items. After a
Responses→Chat Completions fallback, a cache miss left assistant
messages without reasoning_content and DeepSeek rejected the turn
with 400. Fill empty assistant fields with a single-space placeholder
for DeepSeek hosts, including openai-platform accounts whose base_url
points at api.deepseek.com. Existing plaintext and cache hits are
left unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 15:42:22 +09:00
Yoga Sakti 4805f069e4 fix(scheduler): keep account RPM config in the scheduler projection
`filterSchedulerExtra` 的白名单没有 `base_rpm` / `rpm_strategy` /
`rpm_sticky_buffer`,写进 `sched:meta:<id>` 的精简投影因此丢掉整套 RPM 配置。
候选过滤走 `ListSchedulableAccounts`,缓存命中时读的正是这份投影:
`isAccountSchedulableForRPM` 拿到的账号上 `GetBaseRPM()` 返回 0,`baseRPM <= 0`
直接放行,已配置限流的账号在选号阶段被当作未开启 RPM,单个自然分钟内被超额调度。
缓存未命中时回退数据库读到完整 extra,所以现象是间歇性的。

选中的账号随后由 `hydrateSelectedAccount` 从 `sched:acc:<id>` 重新水合,
RPM 计数与用户消息队列限速读的是完整账号,不受影响;缺的只是选号阶段这道门。

修法沿用投影里既有的处理方式(见 `openai_passthrough` 一组注释):把判定依赖的
键补进白名单,而不是在判定侧另开一条读取完整账号的路径。

回归测试覆盖序列化往返后的三个键:`tiered` 子用例证明缓冲被裁掉时红区会被误判成
黄区,`sticky_exempt` 子用例证明策略被裁掉时会退回三区判定。

Refs #7225
2026-09-18 13:37:58 +07:00
HuntercodeT cfd2fc779b fix(codex-models): 非 GPT 模型的 Codex 提示词模板去掉 GPT 身份声明,避免 Antigravity 429
模型目录对所有模型都用 openai.CodexBaseInstructionsForModel 填 instructions_template,
gemini / claude 等因此下发 "You are Codex, a coding agent based on GPT-5."。Codex 把它作为
instructions 发出,Antigravity 对「Codex 提示词 + GPT-5 身份」返回 429 RESOURCE_EXHAUSTED,
并让账号进入限流冷却。

OpenAI GPT 模型保持原模板;其他模型族(含 gpt-oss)去掉 "based on GPT-N" /
"You are GPT-N" 身份声明,提示词其余部分不变。

Refs #7307
2026-09-18 14:21:21 +08:00
wucm667 0920e06a42 fix(gateway): restore public response model aliases 2026-09-18 13:31:58 +08:00
little-greenbean 3fdd54ca12 fix(upstream): cancel response attempt before closing body 2026-09-18 13:30:35 +08:00
lizhaoxinlizhaoxin2-lab cf10d6d01d fix(responses): emit protocol-correct stream errors once 2026-09-18 12:38:05 +08:00
feeeei a9c7c6e8bf ui(header): 手机竖屏顶栏保留模型广场图标入口
模型广场入口所有宽度都渲染,<640px 只保留图标,补 title/aria-label
2026-09-18 09:52:40 +08:00
HuntercodeT c12d0131cb fix(gateway): list mixed antigravity models for gemini groups 2026-09-18 09:03:41 +08:00
HuntercodeT 0f4d8acaa8 fix(antigravity): Gemini 原生请求的裸模型名按 thinkingConfig 解析到 -low/-medium/-high 变体
Antigravity CLI / go-genai 发裸 Gemini 模型名(gemini-3.8-flash)并用
generationConfig.thinkingConfig 表达思考深度,而 Antigravity 上游目录只有
-low/-medium/-high/-tiered 变体。v0.2.5 起 resolveModelMapping 会给 antigravity
账号运行时补 gemini-3.x-flash 裸名自映射,裸名因此被当成显式透传直发上游,
上游回 404 "Requested entity was not found."。

在 ForwardGemini 取映射之前加 resolveGeminiThinkingVariant:
- 仅对 gemini- 前缀且不带后缀的裸名生效;
- 用户在 credentials.model_mapping 亲写的裸名条目一律不介入,运行时注入的
  默认自映射不算用户意图;
- thinkingLevel 优先;否则 thinkingBudget <0→high,≤1024→low,≤8192→medium,
  其余 high;未携带 thinkingConfig→high;所选变体不存在时按
  high→medium→low→tiered 降级;一个变体都没有则回退原逻辑;
- thinkingConfig 仍原样透传,上游按 budget 决定实际思考量。
2026-09-18 09:03:40 +08:00
wucm667 94225b5ed3 fix(admin): align platform quota editor with supported platforms 2026-09-18 08:42:21 +08:00
feeeei a9ff663387 feat(backup): 支持月度归档与独立保留策略 2026-09-18 06:56:27 +08:00
feeeei 57b7dbdc85 feat(affiliate): 提取记录支持登记线下提现
管理员在站外给邀请人打款后,系统里原本无法扣减对应的返利额度,用户仍可把
这部分额度转入余额。现在可在「邀请返利 → 提取记录」点「登记线下提现」,
从该用户的可提取返利额度中扣除已打款金额:

- POST /api/v1/admin/affiliates/users/:user_id/withdraw,请求体只含 amount,
  金额按 8 位小数舍入后校验
- 先解冻已到期的冻结额度,再以 aff_quota >= amount 为条件原子扣减,写入
  action=withdraw 的流水并带额度快照;额度不足返回 AFFILIATE_QUOTA_INSUFFICIENT
- 不新增字段与迁移:线下提现复用已有 action 列区分,操作人由管理端审计日志记录
- 提取记录同时列出转入余额与线下提现,新增「类型」列
- 弹窗选择用户后展示可提取额度,支持一键填入全部;从未产生返利的用户按 0 处理

返利记录改为 LEFT JOIN 订单与被邀请人,兑换码、管理员充值来源的返利也会出现
在明细中,接口里订单相关字段与被邀请人 ID 可为 null。
2026-09-17 23:42:02 +08:00
HuntercodeT f79b8bf96c fix(antigravity): Gemini 原生流对 go-genai / python-genai 客户端不发 SSE 注释心跳
Antigravity 账号的 Gemini 原生流式路径在上游空闲超过 gateway.stream_keepalive_interval
(默认 10s)时会向下游写 ":\n\n" 作为心跳。SSE 规范允许注释行,但 Google 官方 SDK 里
go-genai 与 python-genai 都不会忽略它:

- go-genai(Antigravity CLI 在用)api_client.go iterateResponseStream 对任何非 data: 前缀的
  事件直接返回 "iterateResponseStream: invalid stream chunk: :",整个流中断;
- python-genai _api_client.py 把非 data: 行当作错误 JSON 拼接后 json.loads,同样抛错。

Google 官方 API 从不下发注释行,这两个 SDK 从未处理过这种输入。js-genai 用规范的
event-stream 解析器,不受影响。

现在按下游 User-Agent / X-Goog-Api-Client 识别这两类 SDK(形如
google-genai-sdk/1.71.0 gl-go/go1.28 …、google-genai-sdk/x gl-python/3.12),命中时该路径
不再发注释心跳;其他客户端(curl、js-genai、Gemini CLI)行为不变。

生产复现:Antigravity CLI 1.2.5 经网关(sub2api 0.2.5)跑长思考请求,上游首个 chunk 超过 10s
时客户端报 "agent executor error: … iterateResponseStream: invalid stream chunk: :"。
2026-09-17 19:41:55 +08:00
cyh e74c690ac4 fix(openai): keep transport heartbeats outside semantic output 2026-09-17 19:15:09 +08:00
Wesley Liddick efe9aab1e4 Merge pull request #7246 from laoxiechuzheng/fix/deepseek-native-responses-tool-output-media
fix(deepseek): lift Responses tool output images
2026-09-17 17:02:43 +08:00
zoutao 0952ce3410 fix(apicompat): include streamed arguments in function_call_arguments.done
Gemini/Antigravity delivers tool arguments as one complete object, so this
converter synthesizes the Responses tool-call stream itself and therefore owns
its self-consistency. The done event was built without Arguments, leaving it ""
while the preceding delta carried the entire JSON. Clients that reconcile the
done payload against the accumulated deltas (OpenAI Responses SDK); Qoder's
reconcileToolCall) reject that mismatch as inconsistent_tool_call and abort the
turn non-retryably, so every tool call through the gateway failed.

Emit state.CurrentArgs, which closeCurrentResponsesItem already uses for the
item, restoring sum(deltas) == done.arguments == item.arguments.

Regression test asserts the delta sum equals the done payload and fails closed
when Arguments is dropped.
2026-09-17 16:54:44 +08:00
Cai d099c06945 fix: resolve Seedance lint and gRPC security checks 2026-09-17 17:51:03 +09:00
Wesley Liddick aeab57b9b2 Merge pull request #7256 from zhudaguaneren/fix/antigravity-attribution-429
fix(antigravity): 过滤 Claude attribution 元数据,修复特定请求的 429
2026-09-17 16:44:09 +08:00
Wesley Liddick 18328aed05 Merge pull request #7212 from wucm667/feat/issue-7203-redemption-pagination
feat(redeem): paginate user redemption history
2026-09-17 16:43:06 +08:00
Wesley Liddick 48a86ec926 Merge pull request #7224 from HypoxanthineOvO/codex/upstream-chat-role-compat
fix(gateway): normalize developer roles for strict native Chat upstreams
2026-09-17 16:42:31 +08:00
Wesley Liddick b4e560824a Merge pull request #7177 from xO-ox-ai/codex/fix-openai-response-binding-context
fix(openai): 客户端断开后仍持久化 Responses 续聊绑定
2026-09-17 16:42:12 +08:00
Wesley Liddick 9efc167482 Merge pull request #7195 from bitnom/fix/refresh-paused-oauth-accounts
fix(account): keep refreshing OAuth tokens for paused accounts
2026-09-17 16:41:54 +08:00
Wesley Liddick 5050471822 Merge pull request #7239 from Liu8Can/fix/register-promo-code-flicker
fix: prevent promo code field flash on registration
2026-09-17 16:41:35 +08:00
Wesley Liddick c84a3d50a3 Merge pull request #7215 from xz-dev/fix/manifest-double-parse
fix(openai): parse Codex models manifest envelope once
2026-09-17 16:41:12 +08:00
Wesley Liddick cd1834e0a9 Merge pull request #7262 from ouchihao/codex/bug-refund-balance-warning
fix(payment): base refund balance warnings on the requested amount
2026-09-17 16:41:00 +08:00
Wesley Liddick 0932e8ce0a Merge pull request #7266 from ouchihao/codex/bug-subscription-loading-reset
fix(subscriptions): reset loading when clearing state
2026-09-17 16:40:44 +08:00
Wesley Liddick ffa43607e5 Merge pull request #7236 from ouchihao/codex/bug-payment-amount-input
fix(payment): restore accepted text after invalid amount input
2026-09-17 16:40:33 +08:00
Wesley Liddick 57e9f6a4b8 Merge pull request #7238 from ouchihao/codex/bug-model-tag-tab-navigation
fix(channels): allow tabbing out of an empty model input
2026-09-17 16:40:23 +08:00
Wesley Liddick 71c0eb5126 Merge pull request #7184 from ouchihao/codex/bug-totp-error-messages
fix(totp): display normalized API error messages
2026-09-17 16:40:07 +08:00
Wesley Liddick 10fd1ada28 Merge pull request #7182 from ouchihao/codex/bug-orders-filter-page
fix(payment): reset the order page when changing status
2026-09-17 16:39:53 +08:00
Wesley Liddick 53fd5f8351 Merge pull request #7183 from ouchihao/codex/bug-proxy-test-dedup
fix(proxies): reuse in-flight test guards during batch testing
2026-09-17 16:39:34 +08:00
Wesley Liddick 55bde0857f Merge pull request #7185 from ouchihao/codex/bug-announcement-read-results
fix(announcements): preserve successful bulk read results
2026-09-17 16:39:16 +08:00
Wesley Liddick 5f75e0d2a7 Merge pull request #7186 from ouchihao/codex/bug-clipboard-fallback-error
fix(clipboard): report errors thrown by the copy fallback
2026-09-17 16:38:55 +08:00
Wesley Liddick efd86c63e6 Merge pull request #7235 from ouchihao/codex/bug-totp-setup-input-sync
fix(auth): keep TOTP setup digits in sync with state
2026-09-17 16:38:37 +08:00
Wesley Liddick ea68c0e82c Merge pull request #7263 from ouchihao/codex/bug-dialog-title-ids
fix(ui): keep dialog title IDs unique across instances
2026-09-17 16:38:16 +08:00
Wesley Liddick 40e7ce7fbf Merge pull request #7265 from ouchihao/codex/bug-payment-config-await
fix(payment): await in-flight configuration requests
2026-09-17 16:37:54 +08:00
Wesley Liddick d52ab27def Merge pull request #7173 from HuntercodeT/fix/gemini-native-mixed-model-listing
fix(gemini): discover Antigravity mappings in native model lists
2026-09-17 16:37:38 +08:00
Wesley Liddick 7e4164c1cf Merge pull request #7207 from HuntercodeT/fix/group-usage-summary-seq-scan
fix: 分组用量汇总不再全表扫 usage_logs(48.7s → 34ms)
2026-09-17 16:37:21 +08:00
Wesley Liddick 44831bb854 Merge pull request #7261 from HuntercodeT/chore/bump-grpc-1.83.2
chore(deps): 升级 google.golang.org/grpc 到 v1.83.2,修复 govulncheck 报告的 GO-2026-6443 / GO-2026-6348
2026-09-17 16:36:57 +08:00
Wesley Liddick 131893e449 Merge pull request #7237 from ouchihao/codex/bug-platform-quota-negative
fix(admin): reject negative platform quota limits before saving
2026-09-17 16:36:34 +08:00
Wesley Liddick 4daabc3d84 Merge pull request #7234 from ouchihao/codex/bug-pagination-jump-number
fix(pagination): handle numeric jump input
2026-09-17 16:36:23 +08:00
laoxiechuzheng acc05620cb fix(deepseek): keep parallel Responses tool outputs contiguous 2026-09-17 15:45:56 +08:00
chihao.ou 406be7c518 fix(subscriptions): reset loading when clearing state 2026-09-17 14:59:43 +08:00
chihao.ou b51f0759d4 fix(payment): await in-flight configuration requests 2026-09-17 14:58:46 +08:00
chihao.ou be313735dc fix(ui): keep dialog title IDs unique across instances 2026-09-17 14:56:58 +08:00
chihao.ou 017e9e98d1 fix(payment): base refund balance warnings on the requested amount 2026-09-17 14:56:33 +08:00
HuntercodeT 611c30f04f chore(deps): 升级 google.golang.org/grpc 到 v1.83.2 修复 govulncheck 报告的两条公告
Security Scan / backend-security 自 2026-09-16 起在所有 PR 上失败,govulncheck 对
google.golang.org/grpc v1.82.1 报:
- GO-2026-6443 Server panic via missing authority or Host headers(修复于 v1.83.2)
- GO-2026-6348 Heap Memory Exhaustion via HTTP/2 DATA Frame Fragmentation(修复于 v1.83.1)
调用链在 pkg/pluginapi/v1/runtime.go 与 internal/service/plugin_runtime.go。

go get google.golang.org/grpc@v1.83.2 && go mod tidy。最小版本选择连带抬升了
golang.org/x/{crypto,mod,net,sync,term,sys,text,tools}、genproto/googleapis/rpc 与
go.opentelemetry.io/otel* 的间接依赖,均为补丁级别。
2026-09-17 14:33:48 +08:00
zhudaguaneren be4a4990ff fix(antigravity): strip Claude attribution metadata from system prompts 2026-09-17 11:57:53 +08:00
Cai aba34524f1 feat: support native Seedance Ark video task API 2026-09-17 04:14:14 +09:00
laoxiechuzheng 881ab1b0c6 fix(deepseek): lift Responses tool output images
DeepSeek native Responses rejects Codex view_image results when function_call_output.output contains input_image parts. Move media into a following user message and keep the tool output as a string so call_id pairing remains valid.
2026-09-17 01:22:22 +08:00
DanielSong fe36f4a914 fix: prevent promo code field flash on registration 2026-09-16 18:34:52 +08:00
chihao.ou f8e5a0d94f fix(channels): allow tabbing out of an empty model input 2026-09-16 18:19:41 +08:00
chihao.ou 0838e0e610 fix(admin): reject negative platform quota limits before saving 2026-09-16 18:17:29 +08:00
chihao.ou 98321a054e fix(payment): restore accepted text after invalid amount input 2026-09-16 18:17:14 +08:00
chihao.ou ee9ac3e45f fix(auth): keep TOTP setup digits in sync with state 2026-09-16 18:15:28 +08:00
chihao.ou 1a32b91eb2 fix(pagination): handle numeric jump input 2026-09-16 18:15:12 +08:00
HypoxanthineOvO 18bfa4bf20 fix(gateway): normalize developer roles for strict Chat upstreams 2026-09-16 16:11:43 +08:00
Xiangzhe 31f3003ff5 fix(openai): preserve manifest key validation 2026-09-16 06:15:31 +00:00
Xiangzhe 2f16e0984e fix(openai): avoid duplicate manifest parsing 2026-09-16 06:15:25 +00:00
wucm667 a9ed218989 feat(redeem): paginate user redemption history 2026-09-16 13:19:15 +08:00
HuntercodeT 18d483c2a1 fix: 分组用量汇总不再全表扫 usage_logs
GET /api/v1/admin/groups/usage-summary 在有一定数据量的库上会退化成
usage_logs 全表扫。根因是 getAllGroupUsageSummaryFromRollups 里,tail CTE
的 created_at 下界 state.tail_start 由同一条 SQL 的 state CTE 算出、再用
CROSS JOIN 交给 tail:这个值对 planner 来说要到运行期才知道,既进不了
index cond,也估不准选择性,于是只能顺序扫全表再逐行过滤。

生产实测(1721 万行 usage_logs / PostgreSQL 17):

    Nested Loop  (actual time=28161..48334 rows=34788)
      Join Filter: (ul.created_at >= state_1.tail_start)
      Rows Removed by Join Filter: 17178082
      ->  Seq Scan on usage_logs  (actual time=0.030..47567 rows=17212870)
          Buffers: shared hit=12863 read=951875
    Execution Time: 48720 ms

改成先读一次水位行、在 Go 侧算出 tail_start / closed_before / retained
日期,再把它们当查询参数传进来。同一套数据上:

    Index Scan using idx_usage_logs_created_at on usage_logs
      Index Cond: (created_at >= $7)
    Execution Time: 34 ms

水位有效性的判定(恰好一行、时区名与配置一致、水位不在未来)和无效时
退化成从 epoch 全量重算的行为,与原先 SQL 里 state_values / CASE WHEN
valid 的分支逐条对应,结果口径不变。

另外读取水位的语句不加锁,不参与 #6976 那条 FOR UPDATE / FOR KEY SHARE
的阻塞链。
2026-09-16 10:11:18 +08:00
bitnom 8e34ca5e31 fix(account): keep refreshing OAuth tokens for paused accounts
Paused (schedulable=false) active accounts were excluded from the
background token refresh candidates, so their stored access_token
silently expired. The admin usage-window quota probe uses the stored
token verbatim (no token provider / no refresh), so the probe then gets
HTTP 401 UNAUTHENTICATED and the dashboard reports a false "needs
re-auth" for a perfectly healthy account, while Test Connection and live
traffic (which refresh on demand via the token provider) keep working.

Pause is not permanent rejection: error accounts are already excluded by
the status = 'active' filter, and accounts whose refresh genuinely fails
are rate-limited by the retry-cooldown exclusion (10-minute retry-
exhausted cooldown). Refresh success only persists credentials and never
touches schedulable, so a paused account cannot be silently un-paused.

Drop the schedulable filter and update the SQL-filter test, the
integration pagination test, and the service-level candidate fake.
2026-09-15 10:00:26 -04:00
chihao.ou 130ba634ad fix(clipboard): report errors thrown by the copy fallback 2026-09-15 20:08:45 +08:00
chihao.ou 6a4938bdfb fix(announcements): preserve successful bulk read results 2026-09-15 20:06:33 +08:00
chihao.ou 14636d2f0e fix(totp): display normalized API error messages 2026-09-15 20:06:18 +08:00
chihao.ou 0ed735d3ba fix(proxies): reuse in-flight test guards during batch testing 2026-09-15 20:04:49 +08:00
chihao.ou 21532add46 fix(payment): reset the order page when changing status 2026-09-15 20:04:35 +08:00
xO-ox-ai d7ee1ab6be fix(openai): persist response affinity after client cancel 2026-09-15 18:44:50 +08:00
github-actions[bot] 881f320269 chore: sync VERSION to 0.2.5 [skip ci] 2026-09-15 09:02:51 +00:00
HuntercodeT da74bf13a4 fix(gemini): discover antigravity mappings in native model lists 2026-09-15 16:50:46 +08:00
Wesley Liddick 86f93c28ee Merge pull request #6977 from alfadb/fix/deepseek-model-name-validation
fix(deepseek): 未配置 model_mapping 时按官方模型名单校验,不再透传未知模型名
2026-09-15 16:20:31 +08:00
Wesley Liddick 30ed40a56a Merge pull request #7074 from Brisbanehuang/codex/fix-codex-quota-windows
fix(scheduler): 按规范 5h/7d 窗口读取 Codex 配额与重置时间
2026-09-15 16:17:37 +08:00
Wesley Liddick b8275209e8 Merge pull request #7162 from HuntercodeT/fix/antigravity-gemini-sse-separator
fix(antigravity): gemini 透传 SSE 事件之间不再多写一个空行(Antigravity CLI invalid stream chunk)
2026-09-15 16:17:25 +08:00
郭兰鑫andClaude Code 1e231ee2ae fix(antigravity): resolve golangci-lint errors in schema cleaner tests
- Replace unchecked single-value type assertions with comma-ok form
  guarded by require.True (errcheck check-type-assertions)
- Remove trailing blank line flagged by gofmt

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-15 16:01:30 +08:00
Wesley Liddick 25c21aedda Merge pull request #7129 from kk-418/fix/grok-build-responses-sequence-number
fix(responses): 始终在 Responses SSE 中写出 sequence_number 避免反序列化失败
2026-09-15 15:28:33 +08:00
Wesley Liddick 2d9af8592f Merge pull request #7153 from hezhaoqian1/codex/upstream-api-key-provider-filter
feat: filter API key groups by provider
2026-09-15 15:26:29 +08:00
HuntercodeT 8447bdd368 fix(antigravity): gemini 透传 SSE 事件之间不再多写一个空行
handleGeminiStreamingResponse 把上游每条 data 行改写成 "data: ...\n\n",
紧接着又把上游的空分隔行原样透传成第三个 "\n",下游看到的事件之间是
"\n\n\n"。google-genai 的 Go SDK(Antigravity CLI 在用)按 "\n\n" 切事件,
多出的 "\n" 粘到下一个事件开头,前缀变成 "\ndata" 而报
"iterateResponseStream: invalid stream chunk",每条流都在第二个事件中断。

空分隔行不再透传(data 分支已经写过 "\n\n"),附回归测试:两个事件
(LF 与 CRLF 各一)经过后输出必须恰好是一个空行分隔,并按 "\n\n" 切帧
逐个校验前缀。

Fixes #7161
2026-09-15 15:10:45 +08:00
haruka 4f6f206458 docs: add rolling log retention settings screenshot 2026-09-15 14:23:27 +08:00
haruka 6582260bc8 feat: add configurable rolling log retention 2026-09-15 14:21:15 +08:00
shaw 32682a4f84 chore: update sponsors 2026-09-15 14:01:28 +08:00
hezhaoqian1 55a95d4c67 feat: filter API key groups by provider 2026-09-15 11:16:17 +08:00
alfadb a939553c87 fix(deepseek): 模型名校验不再默认兜底,未配置映射时按官方名单校验
- 未配置 model_mapping 的 DeepSeek 账号不再放行任意模型名,改为官方名单精确匹配
  (deepseek-flash / deepseek-v4-pro / deepseek-v4-flash /
   deepseek-v4-flash-vision-exp / deepseek-v4-pro-0813)
- 校验前先归一化:剥离 Claude Code 客户端上下文后缀 [1m](含重复形式)并统一小写,
  使官方 Claude Code 接入写法 deepseek-flash[1m] 继续可用
- 未知模型名在调度阶段即拒绝,返回 404 model_not_found,避免透传上游后触发
  per-(账号,模型) 冷却、并避免上游把不认识的模型名静默兜底成 deepseek-flash
- 出站前剥离泄漏的 [1m] 后缀,仅作用于 DeepSeek 平台
- 配置了 model_mapping 的账号语义不变(映射优先)
2026-09-15 10:42:29 +08:00
Wesley Liddick badfad8b72 Merge pull request #6257 from 88766lawrence/fix/oauth-promo-code-6216
fix(auth): preserve promo codes through OAuth registration
2026-09-15 09:01:39 +08:00
Wesley Liddick 1be482c313 Merge pull request #7148 from Wei-Shaw/revert-7110-codex/bug-batch-image-access-session
Revert "fix(batch-image): scope access cache to the current user"
2026-09-15 09:00:23 +08:00
Wesley Liddick 325213ae66 Revert "fix(batch-image): scope access cache to the current user" 2026-09-15 08:59:52 +08:00
Wesley Liddick 0a215c9318 Merge pull request #7110 from ouchihao/codex/bug-batch-image-access-session
fix(batch-image): scope access cache to the current user
2026-09-15 08:59:23 +08:00
Wesley Liddick 2061508ad8 Merge pull request #7072 from Brisbanehuang/codex/fix-scheduler-metrics
fix(scheduler): 修复选号耗时返回值和粘性命中率重复计数
2026-09-15 08:58:58 +08:00
Wesley Liddick fb90414c05 Merge pull request #7126 from xO-ox-ai/codex/fix-responses-lite-namespace
fix(openai): 保留 Responses Lite namespace 工具调用
2026-09-15 08:58:25 +08:00
Wesley Liddick 9fade3e8c2 Merge pull request #6769 from alfadb/feature/ollama-rate-limit-reset
feat(ollama): 根据用量窗口异步更新限流恢复时间
2026-09-15 08:57:43 +08:00
Wesley Liddick 1920a7d687 Merge pull request #7091 from SavitarC/feat/subscription-bulk-actions
feat: 支持订阅管理批量操作
2026-09-15 08:57:27 +08:00
Wesley Liddick a444551a6d Merge pull request #6654 from ouchihao/codex/issue-2229-register-confirm-password
feat(auth): require password confirmation during registration
2026-09-15 08:56:56 +08:00
Wesley Liddick 0bba06d64a Merge pull request #6691 from yan9651688/feat/api-key-bulk-edit
feat(keys): add bulk editing to API key management
2026-09-15 08:56:07 +08:00
Wesley Liddick 150c52b8de Merge pull request #6689 from tunsuy/fix/antigravity-codex-web-search-mixed-tools
fix(antigravity): drop mixed web_search when client tools present
2026-09-15 08:54:40 +08:00
Wesley Liddick 3e4b6a09b2 Merge pull request #6925 from reed-yang/fix/recover-responses-text
fix(apicompat): recover Responses text from done and terminal events
2026-09-15 08:54:21 +08:00
Wesley Liddick dd2e6b3680 Merge pull request #7076 from Shen-An/fix/antigravity-refresh-warning
fix(admin): surface partial Antigravity refresh warnings
2026-09-15 08:54:06 +08:00
Wesley Liddick d4439129a7 Merge pull request #7094 from liuyuzhou666/fix/responses-chat-developer-role-mapping
fix(apicompat): 修复 Responses 降级 Chat Completions 时的 system 消息顺序问题
2026-09-15 08:53:50 +08:00
Wesley Liddick 1e1d15cca5 Merge pull request #7082 from ggllzz04/fix/antigravity-token-cache-isolation
fix(antigravity): isolate OAuth token cache key by account ID to prevent 429 collision
2026-09-15 08:53:32 +08:00
Wesley Liddick f7e959ae5f Merge pull request #7111 from ouchihao/codex/bug-proxy-clear-credentials
fix(proxy): allow explicitly clearing stored credentials
2026-09-15 08:52:58 +08:00
Wesley Liddick 008391f699 Merge pull request #7085 from r266-tech/codex/sub2api-f352188cb784
fix(openai): strip internal metadata from OAuth input items
2026-09-15 08:52:30 +08:00
Wesley Liddick a4c517917b Merge pull request #7073 from Brisbanehuang/codex/fix-batch-image-priority
fix(batch-image): 修正批量生图账号优先级排序方向
2026-09-15 08:52:19 +08:00
Wesley Liddick e9169901d2 Merge pull request #7112 from ouchihao/codex/bug-monitor-refresh-interval
fix(monitor): honor the selected auto-refresh interval
2026-09-15 08:52:00 +08:00
chihao.ou 0e1329b520 fix(ui): reset select highlight when search results change 2026-09-14 21:28:59 +08:00
HPnetwork 29bce46a2a fix: keep API key accounts available for unknown models 2026-09-14 05:56:59 -04:00
xO-ox-ai 13c1d4cde2 test(openai): 覆盖 Lite 命名空间工具回传 2026-09-14 11:46:41 +08:00
cikenerdandCursor 087987070b fix(responses): 为 grok-build 始终写出 sequence_number
网关合成/重编的 Responses SSE 因 omitempty 或缺字段丢掉 sequence_number,
grok-build 会整轮反序列化失败。合成失败帧、compact 桥接和转换 wire JSON
一律写出该字段,0 也保留。

Fixes #7128

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:45:53 +08:00
xO-ox-ai 4bd7132ba9 fix(openai): 保留 Responses Lite namespace 调用 2026-09-14 11:35:03 +08:00
chihao.ou 28a4ea914d fix(proxy): allow explicitly clearing stored credentials 2026-09-13 17:23:24 +08:00
chihao.ou 5ecfaa4837 fix(batch-image): scope access cache to the current user 2026-09-13 17:22:56 +08:00
chihao.ou 06af9f871c fix(monitor): honor the selected auto-refresh interval 2026-09-13 17:20:56 +08:00
chihao.ou 7dace2fecb fix(ui): discard unapplied date ranges on dismissal 2026-09-13 17:18:15 +08:00
chihao.ou a985de062c fix(ui): focus non-searchable select dropdowns 2026-09-13 17:16:26 +08:00
MHJoy99 7511e4de59 fix(streaming): drop Anthropic ping keepalives before OpenAI conversion
Upstream Anthropic keepalive frames (event: ping) leaked into OpenAI
Chat Completions SSE streams, crashing strict clients (Cursor, Hermes,
OpenAI SDKs) on unexpected event types. Error events still forward.

Fixes #5203
2026-09-13 13:30:50 +06:00
liuyuzhou666 52558381c6 fix(apicompat): merge leading system messages and downgrade mid-conversation system from Responses bridge
The Responses to Chat Completions bridge mapped both the instructions field and role developer items to system messages. Codex always sends both, and also injects developer notices mid-conversation when switching models, so the forwarded request contained consecutive leading system messages and mid-conversation system messages. Strict Qwen-family upstreams reject this with HTTP 400 "System message must be at the beginning."

Leading system/developer messages are now merged into a single leading system message, and later system/developer messages are downgraded to user so the content is preserved without violating upstream role ordering.
2026-09-13 14:08:57 +08:00
SavitarC e3cce574d7 fix: serialize subscription extensions 2026-09-13 12:33:35 +08:00
Brisbanehuang b18e4ce455 fix(scheduler): 为调度倍率补充账号倍率回退 2026-09-13 00:14:16 -04:00
SavitarC 3d6c207723 feat: 支持订阅管理批量操作 2026-09-13 11:49:03 +08:00
alfadb a1d5968b24 feat(ollama): async rate-limit reset for Ollama Cloud usage windows
Real Ollama Cloud 429s are driven by ollama.com usage windows, not by
response headers that OpenAI/Anthropic/CN rate-limit parsing understands.
Handle them separately: apply a never-shortening temporary cooldown first,
then schedule an async probe that learns the true usage-window reset point
with a controlled, coalesced per-api_key refresh.

- ratelimit_service: route real Ollama Cloud usage accounts to a dedicated
  429 path before the CN-provider branch.
- ollama_cloud_usage: add a background probe coordinator (started in Start,
  waited by Stop) that fans out model-429 probes to one controlled refresh
  per api_key group, reusing the recent group snapshot for coalesced members.
- repository/account_repo: add SetRateLimitedIfUnchanged, a write-back CAS
  counterpart to ClearRateLimitIfObserved, so an async reset never overwrites
  a newer 429, an admin clear, a re-armed generation, or a key/state change
  observed by another writer between read and write.
- wire: inject OllamaCloudUsageService into RateLimitService.

Tests: unit tests for service and repository pass; targeted race tests pass;
build and vet clean; git diff --check clean. The CAS integration test compiles
but is not run (no Docker available).
2026-09-13 10:41:47 +08:00
r266-tech e5272c130c test(openai): check input type before metadata assertion 2026-09-13 07:13:31 +08:00
r266-tech 196c15b5cd fix(openai): strip internal metadata from OAuth input items 2026-09-13 07:00:50 +08:00
郭兰鑫 69d49744cf fix(antigravity): address code review feedback on schema cleaner
- Fix test assertion target location for whereItems prefixItems
- Support const keyword normalization to enum and infer scalar type
- Infer scalar type for enum-only schema to prevent object reason injection
- Recursively clean properties and items after anyOf/oneOf merge
- Ensure empty prefixItems is safely deleted
2026-09-13 03:57:18 +08:00
郭兰鑫 62635532a6 fix(antigravity): explicitly invalidate legacy project-based token cache 2026-09-13 03:45:12 +08:00
郭兰鑫 bc8da78150 fix(antigravity): isolate OAuth token cache key by account ID to prevent collision 2026-09-13 03:40:47 +08:00
郭兰鑫 5d781ee6b7 fix(antigravity): handle prefixItems and ensure array schema has valid items fallback
- Handle JSON Schema Draft 2020-12 prefixItems (tuple arrays) by converting to a best-match items schema
- Ensure array schema always defines a valid items schema to prevent Gemini 400 'missing field: items.items' error
- Fix recursive traversal when a schema defines both properties and items
- Add comprehensive unit test cases for tuple and array schemas
2026-09-12 23:25:57 +08:00
Brisbanehuang db76cc4e4e fix(scheduler): 按规范窗口读取 Codex 配额与重置时间
优先读取 codex_5h/codex_7d 规范字段,旧快照复用 Normalize 的窗口分类;用量与重置时间按同源窗口配对。重置评分与管理端快照复用规范 5h 重置时间,保留会话列回退,不改变权重与暂停阈值。
2026-09-12 09:06:33 -04:00
Brisbanehuang d2c2b46c9e fix(batch-image): 修正批量生图账号优先级排序方向
按较小 priority 优先选择账号,保留同优先级 ID 排序及现有资格过滤。补充选择回归,并将定价夹具对齐实际选中的账号,不改变计费公式。
2026-09-12 09:06:33 -04:00
Brisbanehuang 7e152e4279 fix(scheduler): 修复选号耗时返回值和粘性命中率重复计数
使用命名返回值传回 defer 中记录的选号耗时;按每次选号累计任意粘性命中,保留两类独立计数。增加成功、失败及双粘性回归,不改变调度策略。
2026-09-12 09:03:52 -04:00
Wesley Liddick bdb42e22f8 Merge pull request #7064 from xlplbo/codex/openai-ws-v2-pool-capacity
fix(openai-ws): 对齐新版 ctx_pool 连接容量计算
2026-09-12 20:13:03 +08:00
Wesley Liddick 9383e0b154 Merge pull request #7057 from Sjeary/codex/issue-7042-max-context-window
fix(codex): 保留本地模型目录的最大上下文窗口
2026-09-12 20:11:40 +08:00
Wesley Liddick c7ed614240 Merge pull request #7001 from SavitarC/feat/ops-token-stats-all-platforms
feat(ops): 扩展 Token 请求统计至所有平台
2026-09-12 19:34:45 +08:00
Wesley Liddick a59f0c7fac Merge pull request #5833 from xuhaihan/fix/openai-fast-missing-tier
fix(openai): force priority when fast tier is omitted
2026-09-12 19:31:21 +08:00
Wesley Liddick 0a378f3432 Merge pull request #7026 from ouchihao/codex/bug-key-quota-reset-state
fix(keys): sync status after resetting quota
2026-09-12 19:30:40 +08:00
Wesley Liddick f2b51e3b24 Merge pull request #7023 from ouchihao/codex/bug-profile-api-errors
fix(profile): show normalized API error messages
2026-09-12 19:30:29 +08:00
Wesley Liddick 329641a86f Merge pull request #7025 from ouchihao/codex/bug-proxy-partial-import-refresh
fix(proxies): refresh the list after partial imports
2026-09-12 19:30:09 +08:00
Wesley Liddick f0dd497780 Merge pull request #7054 from ouchihao/codex/bug-usage-export-filter-snapshot
fix(usage): keep export filters consistent across pages
2026-09-12 19:29:57 +08:00
Wesley Liddick 99b93b2985 Merge pull request #7053 from ouchihao/codex/bug-proxy-filter-pagination
fix(proxies): reset pagination when changing filters
2026-09-12 19:29:41 +08:00
Wesley Liddick 67845665d6 Merge pull request #7050 from ouchihao/codex/bug-balance-email-verification-race
fix(profile): remove verified notification emails by identity
2026-09-12 19:29:24 +08:00
Wesley Liddick 3a070ec1bf Merge pull request #7010 from xpflying/fix/openai-privacy-client-cf-challenge
fix(openai): 隐私/账号检查客户端改用 Firefox 指纹,规避 chatgpt.com Cloudflare 质询
2026-09-12 19:28:09 +08:00
Wesley Liddick 749cd7c354 Merge pull request #7062 from wc4440222/fix/channel-monitor-minimax-provider
fix(channel-monitor): add missing minimax to provider allowlists
2026-09-12 19:27:46 +08:00
Wesley Liddick eaa4083e23 Merge pull request #6995 from alfadb/fix/claude-mid-conversation-output-config
fix(claude): 修复对话中 output_config 的 beta 兼容问题
2026-09-12 19:27:21 +08:00
Wesley Liddick 3873215908 Merge pull request #7049 from xlplbo/perf/openai-ws-pool-queue-wake
perf(openai): WS 连接池排队等待者按账号池变更重选连接
2026-09-12 19:26:56 +08:00
Wesley Liddick 2a4f3d1a71 Merge pull request #7043 from xlplbo/fix/openai-ws-max-conns-factor-default
fix(openai-ws): ctx_pool 每账号连接上限系数默认值改为 5.0
2026-09-12 19:26:26 +08:00
Wesley Liddick 4ff3e6dfb9 Merge pull request #7055 from ouchihao/codex/bug-redeem-profile-refresh
fix(redeem): preserve success when account refresh fails
2026-09-12 19:26:02 +08:00
Wesley Liddick f78c4b241e Merge pull request #7011 from ouchihao/codex/issue-7003-compact-default-model
fix(config): use GPT-5.5 as the default compact model
2026-09-12 19:25:43 +08:00
Wesley Liddick e67ffda7ae Merge pull request #7012 from ouchihao/codex/issue-6982-easypay-upstream-type-dots
fix(payment): allow periods in EasyPay upstream types
2026-09-12 19:24:48 +08:00
Wesley Liddick d2067668d3 Merge pull request #7024 from ouchihao/codex/fix-subscription-assignment-selection
fix(subscriptions): clear assignment user before search debounce
2026-09-12 19:24:00 +08:00
Wesley Liddick ba57ea914b Merge pull request #7052 from ouchihao/codex/issue-2912-transient-auth-failures
fix(auth): preserve sessions during temporary service failures
2026-09-12 19:23:12 +08:00
Wesley Liddick 5948988aae Merge pull request #7022 from ouchihao/codex/issue-3623-accept-encoding-header
fix(gateway): avoid duplicate Accept-Encoding headers
2026-09-12 19:22:44 +08:00
xlplbo 76b3f3c7cf docs(ui): 精简 OpenAI WS 模式提示 2026-09-12 17:38:55 +08:00
xlplbo db15ddf07f docs(ui): 区分 OpenAI WS 开关与连接模式说明 2026-09-12 16:54:22 +08:00
xlplbo 5d5b395d00 docs(ui): 完善 OpenAI WS 模式说明 2026-09-12 16:32:17 +08:00
xlplbo cf3aca6e3b fix(ui): 按 OpenAI WS 模式显示链路提示 2026-09-12 16:28:04 +08:00
xlplbo 956f4672e4 fix(openai-ws): 对齐 OpenAI 新版上下文池容量计算 2026-09-12 16:13:16 +08:00
Wesley Liddick 6206ce940e Merge pull request #6929 from feeeei/fix/gemini-inband-response-signals
fix(gemini): 原生路径登记 2xx 响应里的带内错误信号
2026-09-12 16:08:26 +08:00
Zichen Wang 5968fd0ed9 fix(channel-monitor): add missing minimax to provider allowlists
Fixes #7061

monitorProviders and probeCapableProviders were missing
MonitorProviderMiniMax even though the constant, adapter, ent schema and
error message all already included minimax, so provider=minimax was
rejected by validateProvider.
2026-09-12 15:30:43 +08:00
Shen-AnandClaude Sonnet 5 c6727ed4c9 fix(admin): surface partial Antigravity refresh warnings
Return the updated account alongside partial refresh warnings so the admin UI can keep its state current and tell operators when project ID retrieval must retry.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 15:19:19 +08:00
Heatherm Huang c24da29f6b test(images): require explicit incompatible-account rejection 2026-09-12 14:46:50 +08:00
Heatherm Huang baa39f39e8 test(images): assert the recorded requested model field 2026-09-12 14:44:47 +08:00
Heatherm Huang 9fedf899e2 fix(images): route compatible Gemini image models through API keys 2026-09-12 14:34:31 +08:00
Heatherm Huang 8e23e13158 test(images): reproduce compatible Gemini image rejection 2026-09-12 14:29:47 +08:00
chihao.ou bb0b50d8bc fix(redeem): preserve success when account refresh fails 2026-09-12 13:50:12 +08:00
chihao.ou 429d6f0480 fix(usage): keep export filters consistent across pages 2026-09-12 13:44:33 +08:00
chihao.ou 5bafffed51 fix(proxies): reset pagination when changing filters 2026-09-12 13:44:05 +08:00
chihao.ou 781a02aea7 fix(auth): preserve sessions during temporary service failures 2026-09-12 13:41:16 +08:00
chihao.ou 3645ce5f43 fix(profile): remove verified notification emails by identity 2026-09-12 13:38:11 +08:00
xlplbo 7cf90c79d6 perf(openai): WS 连接池排队等待者按账号池变更重选连接 2026-09-12 13:01:43 +08:00
Sjeary 195a331322 fix(codex): preserve maximum context window in model catalogs 2026-09-11 21:56:25 -07:00
xlplbo 29371b0819 fix(openai-ws): ctx_pool 每账号连接上限系数默认值改为 5.0 2026-09-12 11:39:05 +08:00
zeng gang f744375a4c fix(openai): preserve GPT-5.5 requests carrying Responses Lite markers 2026-09-12 08:08:59 +08:00
xuhaihan (cc) 8e7954438d fix(openai): force priority when service tier is omitted 2026-09-11 21:16:12 +08:00
chihao.ou a65d476f25 fix(keys): sync status after resetting quota 2026-09-11 19:32:20 +08:00
chihao.ou 961d9e94f3 fix(proxies): refresh the list after partial imports 2026-09-11 19:29:36 +08:00
chihao.ou 51c5d03888 fix(subscriptions): clear assignment user before search debounce 2026-09-11 19:29:07 +08:00
chihao.ou 9b6a49b8e7 fix(profile): show normalized API error messages 2026-09-11 19:27:47 +08:00
chihao.ou 213de0797e fix(gateway): avoid duplicate Accept-Encoding headers 2026-09-11 19:19:40 +08:00
alfadb d8326fccfc fix(claude): preserve mid-conversation output config beta 2026-09-11 18:44:41 +08:00
xpflyingandClaude Fable 5.1 9eb120dd40 fix(openai): 隐私/账号检查客户端改用 Firefox 指纹,规避 chatgpt.com Cloudflare 质询
chatgpt.com 的 Cloudflare 会对 req 内置的 ImpersonateChrome(TLS/HTTP2 指纹与 UA 均为
Chrome/120)返回 403 cf-mitigated=challenge,导致 accounts/check、subscriptions、
account_user_setting 三个 backend-api 调用长期失败:订阅到期时间不再更新、隐私开关显示 Fail。
仅改 UA 版本号无效(指纹仍是 120),Firefox 伪装在同一出口下稳定通过,故切换。

同时:
- 用 cf-mitigated 响应头识别质询页,隐私设置失败时正确标记为 training_set_cf_blocked
- accounts/check / subscriptions 失败日志由 Debug 提升为 Warn 并附 cf_challenge 字段,不再静默

Closes #4825

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 18:10:15 +08:00
Wesley Liddick 4726bdd08b Merge pull request #6890 from slovx2/feat/openai-images-75be
feat(openai): route OAuth image requests through native Codex Images
2026-09-11 17:29:54 +08:00
feeeei 8ea4dc56f0 fix(gemini): 模型侧 finishReason 不再按上游失败登记
MALFORMED_FUNCTION_CALL / UNEXPECTED_TOOL_CALL 是模型生成结果,此前按生成异常
登记为上游 502:写带账号归因的上游错误事件、计入 SLA、严重度 P1,并落进渠道
监控的 upstream_5xx 桶。

- detectGeminiResponseSignal 的 finishReason 只登记内容过滤类枚举,其余一律不登记
- geminiSignalAbnormalStop 仅承载 EMPTY_STREAM / EMPTY_RESPONSE
- 新增原生流式 MALFORMED_FUNCTION_CALL 不留 ops 标记的回归用例
2026-09-11 17:06:01 +08:00
song 23eef9ecc3 test(openai): restore image model regression coverage 2026-09-11 16:44:56 +08:00
Wesley Liddick cdb5cfaf6c Merge pull request #6747 from DuskLin/feat/opencode-go-platform
feat(opencode): 增加 OpenCode 平台支持(Zen / GO)
2026-09-11 16:42:05 +08:00
Wesley Liddick dfa83fbe93 Merge pull request #6986 from feeeei/feat/site-billing-mode
feat(settings): 新增「站点类型」开关(充值 & 订阅 / 仅充值 / 仅订阅)
2026-09-11 16:34:46 +08:00
Wesley Liddick 2dff7af0f9 Merge pull request #6954 from feeeei/fix/quota
fix(quota): 修复仪表盘默认会给所有人分配显示所有平台卡片的问题
2026-09-11 16:34:18 +08:00
song 1067e89fab fix(openai): address image route review findings 2026-09-11 16:30:32 +08:00
song 04c45e9dc2 test: remove incompatible upstream image model assertions 2026-09-11 15:57:49 +08:00
song 5ee436d8a2 fix(pricing): set image cache fallback rate 2026-09-11 15:57:49 +08:00
song e5e04de137 fix: sync upstream config and model tests 2026-09-11 15:57:49 +08:00
song fa565eafb1 fix(pricing): add image cache pricing field 2026-09-11 15:57:38 +08:00
song eacff0a629 fix: retain upstream config and image pricing updates 2026-09-11 15:57:38 +08:00
song c0d5119375 feat(openai): route OAuth image requests through native Codex Images
Use shared model routing for image forwarding and account tests, retain Luna orchestration for legacy models, and add Image 2.5 pricing and usage accounting.
2026-09-11 15:57:09 +08:00
刘佳林 22dffa1bb9 fix(opencode): apply De Morgan for staticcheck QF1001
golangci-lint failed on the CN/OpenCode billing-candidate guard.
2026-09-11 15:47:23 +08:00
刘佳林 efcc2252e5 fix(opencode): address review on dispatch, billing, session, and 402
Skip OpenAI messages-dispatch gpt-5.x defaults for OpenCode groups and
composite OpenCode targets. Filter unpriced claude-* billing candidates,
estimate count_tokens locally, sanitize body session IDs before setting
X-OpenCode-Session, and treat Zen 402 as recoverable payg cooldown.

Stop rewriting the inbound body before protocol routing so account
model_mapping applies once and usage_logs.model stays the client name.
2026-09-11 15:39:13 +08:00
刘佳林 981279c996 fix(opencode): rewrite mapped model onto all three upstream protocols
Apply account model_mapping to the request body before OpenCode
protocol routing so /v1/responses, /v1/chat/completions, and
/v1/messages all send the mapped ID as the real upstream model.
2026-09-11 15:07:43 +08:00
chihao.ou c3b3072a6f fix(payment): allow periods in EasyPay upstream types 2026-09-11 14:51:34 +08:00
chihao.ou 489968fd7a fix(config): use GPT-5.5 as the default compact model 2026-09-11 14:50:39 +08:00
刘佳林 7c008bd8c1 fix(opencode): apply account model mapping in connection tests
Responses probes used the requested model as-is, so aliases like
opencode/muse-spark-* were sent upstream instead of the mapped ID.
2026-09-11 14:19:23 +08:00
Wesley Liddick 9c30951e4a Merge pull request #6973 from ouchihao/codex/issue-4210-renewal-modal-scroll
fix(payment): allow scrolling through renewal plans
2026-09-11 14:01:48 +08:00
Wesley Liddick 40cf3f50a6 Merge pull request #6968 from ouchihao/codex/issue-6903-deepseek-vision-modality
fix(codex): advertise DeepSeek vision image input
2026-09-11 14:01:36 +08:00
Wesley Liddick 75b7dd1e0b Merge pull request #6969 from ouchihao/codex/issue-5882-peak-rate-validation
fix(groups): return bad request for invalid peak-rate settings
2026-09-11 14:01:14 +08:00
Wesley Liddick 642d20b8ac Merge pull request #6988 from ZeroClover/fix/codex-manifest-display-name
fix(openai): keep Codex manifest display names in account model lists
2026-09-11 14:00:42 +08:00
Wesley Liddick 623c32e391 Merge pull request #6989 from ZeroClover/fix/openai-plan-type-labels
fix(openai): map new ChatGPT plan tiers to friendly labels
2026-09-11 14:00:07 +08:00
Wesley Liddick 310f8b7fa2 Merge pull request #6964 from xlplbo/fix/apicompat-agent-message-chat-bridge
fix(apicompat): chat 桥保留 Codex agent_message 任务正文
2026-09-11 13:59:41 +08:00
Wesley Liddick 6254aba5e9 Merge pull request #6575 from doublepi123/feat/antigravity-gemini-3.8-flash
feat(antigravity): support Gemini 3.7 and 3.8 Flash models
2026-09-11 13:58:54 +08:00
Wesley Liddick 7145484fde Merge pull request #6971 from ouchihao/codex/issue-1890-ttft-request-details
fix(ops): show first-token latency in TTFT request details
2026-09-11 13:58:37 +08:00
Wesley Liddick fd300ab6f3 Merge pull request #6974 from alfadb/fix/deepseek-v41-flash-pricing
fix(billing): 适配 DeepSeek V4.1-Flash 新价与 pro→Flash 计费切换
2026-09-11 13:58:23 +08:00
Wesley Liddick 88011a6a2e Merge pull request #6783 from asmoyou/fix/large-image-request-memory
perf(gateway): reduce memory amplification for large Responses image requests
2026-09-11 13:58:11 +08:00
Wesley Liddick 14029e50aa Merge pull request #6661 from whhphd/fix/grok-media-slot-release
fix(grok): release abandoned media slots and preserve video ownership
2026-09-11 13:57:07 +08:00
Wesley Liddick 3fb03cdac1 Merge pull request #6960 from xlplbo/fix/openai-ws-exec-scope-preemption
fix(openai-ws): ctx_pool 会话抢占与会话状态按 codex 线程隔离
2026-09-11 13:56:52 +08:00
Wesley Liddick 8f9a9a255b Merge pull request #6965 from xlplbo/fix/openai-ws-pool-reader-loop
fix(openai-ws): 连接池常驻读循环应答上游 ping,根治空闲连接 1011 keepalive ping timeout
2026-09-11 13:56:23 +08:00
Wesley Liddick bae37a00fb Merge pull request #7006 from Wei-Shaw/fix/setup-test-errcheck-close
fix(ci): 修复 main 分支 golangci-lint 红灯(setup_test.go errcheck)
2026-09-11 13:46:15 +08:00
xlplbo 4543ddc5c1 fix(openai): WS 执行作用域按 request_kind 分道 2026-09-11 13:37:59 +08:00
matt 5af7e7438a fix(ci): check deferred sql.DB.Close errors in setup tests
PR #6499 merged without CI ever running on its head commit (fork run stayed
action_required), landing three bare `defer db.Close()` calls in
internal/setup/setup_test.go. The repo's errcheck config sets
disable-default-exclusions: true, so those are reported and golangci-lint has
been red on main ever since, failing every subsequent PR run.

Switch them to the codebase's existing convention
`defer func() { _ = db.Close() }()`.
2026-09-11 11:45:59 +08:00
xlplbo 613722eee4 fix(openai): HTTP 转发的执行作用域改从原始请求计算 2026-09-11 11:36:29 +08:00
SavitarC 66a10d4939 fix(setup): handle mock database cleanup errors in tests 2026-09-11 10:31:03 +08:00
xlplbo d0ca057ca4 fix(openai): WS 会话被抢占时先发关闭帧再取消 2026-09-11 10:25:50 +08:00
xlplbo e4c369bd56 fix(openai): HTTP 经 WS 池转发按执行作用域取会话状态键 2026-09-11 10:25:50 +08:00
SavitarC 1035a4daf0 feat(ops): support token request stats across all platforms 2026-09-11 10:16:32 +08:00
刘佳林 242907854d feat(opencode): add OpenCode platform with Zen and GO account types
Keep the internal platform ID opencode_go. Product surface is OpenCode
with account_mode zen|go, model-aware routing across Chat Completions,
Responses, and Anthropic Messages, and X-OpenCode-Session derived from
prompt_cache_key / metadata.user_id so prompt cache can hit.

Unmatched models fall back to /v1/chat/completions. Related to #6742.
2026-09-11 10:05:24 +08:00
Wesley Liddick 0116c5a1e1 Merge pull request #6915 from ouchihao/codex/issue-2734-async-processed-label
fix(risk-control): clarify the async processed counter label
2026-09-11 09:35:50 +08:00
Wesley Liddick 67d3a896bd Merge pull request #6912 from ouchihao/codex/issue-2106-redeem-subscription-duration
fix(redeem): align subscription duration limit with the backend
2026-09-11 09:35:29 +08:00
Wesley Liddick 501cc19d0e Merge pull request #6902 from anguobao123/codex/apple-container-self-update
fix(deploy): support Web UI updates with Apple container
2026-09-11 09:35:11 +08:00
Wesley Liddick 8efe2fd8cf Merge pull request #6843 from ouchihao/codex/issue-6841-usage-cost-precision
fix(usage): show eight decimal places in cost details
2026-09-11 09:34:36 +08:00
Wesley Liddick 0aac71c6ee Merge pull request #6845 from ouchihao/codex/issue-6808-ops-error-summary-columns
fix(ops): prioritize time and response in error details
2026-09-11 09:34:23 +08:00
Wesley Liddick f4dd88b001 Merge pull request #6847 from ouchihao/codex/issue-4064-custom-page-button-visibility
feat(settings): allow hiding the custom page open button
2026-09-11 09:34:11 +08:00
Wesley Liddick 0be30886a5 Merge pull request #6916 from ouchihao/codex/issue-3640-subscription-user-search
fix(subscriptions): exclude deleted users from assignment search
2026-09-11 09:33:57 +08:00
Wesley Liddick 324a47e2b7 Merge pull request #6913 from ouchihao/codex/issue-6732-bulk-delete-users
feat(admin): support deleting selected users
2026-09-11 09:33:45 +08:00
Wesley Liddick 2493b0dc31 Merge pull request #6924 from smyyyyy2025/fix/codex-user-agent-validation
fix: validate Codex User-Agent before identity parsing
2026-09-11 09:33:19 +08:00
Wesley Liddick 264cbbec26 Merge pull request #6499 from soulxyz/fix/setup-database-bootstrap
fix(setup): avoid hardcoded postgres connection
2026-09-11 09:32:01 +08:00
Wesley Liddick 87e01596b7 Merge pull request #6850 from reallyfeishi/fix/channel-monitor-utc-buckets
fix: anchor channel monitor date_bin buckets to UTC
2026-09-11 09:31:22 +08:00
Wesley Liddick 43f9383d40 Merge pull request #6869 from Garfielk/codex/fix-heartbeat-envelope-fields
fix(openai): accept full heartbeat bootstrap envelopes
2026-09-11 09:30:45 +08:00
Wesley Liddick 685e97a3a6 Merge pull request #6904 from m11y/fix-scheduling-threshold-snapshot
fix(scheduler): preserve threshold metadata
2026-09-11 09:30:00 +08:00
Wesley Liddick e71d291b39 Merge pull request #6917 from ouchihao/codex/issue-2149-monitor-base-path
fix(monitor): support upstream base URL paths
2026-09-11 09:29:25 +08:00
Wesley Liddick 4adcef4ff4 Merge pull request #6943 from xiuai-labs/fix/keep-client-system-cache-control
fix(gateway): 不再剥离客户端 system 上的 cache_control / stop stripping client system cache_control
2026-09-11 09:28:55 +08:00
Wesley Liddick 799e9938fb Merge pull request #6945 from r266-tech/feat/model-retrieval-6931
feat(gateway): retrieve models from the visible catalogue
2026-09-11 09:26:41 +08:00
Zero Clover 8f2cba0c20 fix(openai): map new ChatGPT plan tiers to friendly labels
prolite -> Pro 5x (violet, same as Pro), pro/chatgptpro -> Pro 20x, self_serve_business_prolite -> Business Premium (indigo, same as Team), team -> Business Standard.

The tier naming stays OpenAI-only so Antigravity Pro and Grok pro keep their own labels; planTypeDisplayLabel now shares openAIPlanTypeLabel with PlatformTypeBadge instead of duplicating the mapping, and the manual plan_type dropdown gains the Pro 5x / Business Premium presets.
2026-09-11 03:25:44 +08:00
Zero Clover 6feefb7aec fix(openai): keep Codex manifest display names in account model lists 2026-09-11 03:18:00 +08:00
feeeei 9d475f9edb feat(settings): 新增「站点类型」三态开关,关闭订阅后用户端收起所有「订阅」入口与文案
后台功能开关页新增「站点类型」单选:充值 & 订阅(默认,即现状)/ 仅充值 / 仅订阅。
它由两个后端开关派生并在保存时同时写回:
- subscription_enabled(新增;默认 true,缺省/空值视为开启,仅显式 false 关闭),按既有
  开关模式贯通常量、公共设置、SSR 注入载荷、默认值、更新写入、DTO、审计 diff 与前端注册表;
- payment_balance_disabled(支付配置里既有的 BALANCE_PAYMENT_DISABLED,此前只能走接口/数据库
  改),补进公共设置与注入载荷,让用户端在任何鉴权请求之前就能推导站点类型。
两者都关闭是接口层可表达但 UI 不提供的组合,前端归为「仅充值」,后台保存时会把余额充值重新打开。

「仅充值」时的表现:
- 用户侧边栏隐藏「我的订阅」,「充值/订阅」入口收窄为「充值」;管理端侧边栏隐藏「订阅管理」
  入口(页面仍可通过地址访问);
- 购买页不再渲染「订阅」tab,只剩单个 tab 时顶部切换器随之隐藏;tab 列表变化时当前 tab
  自动收敛到可用项(关闭订阅回到充值、仅订阅站点重新打开订阅进入订阅),列表为空时展示
  「充值与订阅均暂未开放」而不是一个必定被后端拒绝的充值表单;
- /purchase 的页头标题/描述与 document.title 改走 resolveRouteMetaKeys 按站点类型切换;
- /subscriptions 路由新增 requiresSubscription 守卫,直达时重定向到仪表盘;
- 顶栏订阅进度徽章不再挂载,App.vue、PaymentView 与徽章组件都不再预加载/轮询订阅接口;
- 用量页隐藏「计费类型(余额/订阅)」筛选,Key 用量公开页「订阅类型」行改为「计费方式」。
「仅订阅」时侧边栏入口与页头显示为「订阅」,购买页只剩订阅 tab(余额下单由后端既有逻辑拒绝)。

购买订阅接口、已有订阅的计费、兑换码发放订阅与管理端订阅管理页面本身均不受影响。
featureFlags 抽出纯函数 resolveFeatureFlag,新增 utils/siteBillingMode 承载三态派生与反解,
PaymentView 测试改用响应式 store mock 覆盖开关双向切换。
2026-09-11 00:50:17 +08:00
alfadb ab9bd9e877 fix(billing): 适配 DeepSeek V4.1-Flash 新价与 pro→Flash 切换
- flash 低谷价更新为 $0.15/$0.60/$0.003 per MTok(2026-09-10 官方降价)
- deepseek-v4-pro 自 2026-09-14 04:00 UTC 起按 Flash 价计费(上游路由变更)
- 计费时点显式驱动 pro→Flash 切换,定价展示与计费两条路径同源
- deepseek-flash 保留 reasoning_effort=max;补 Codex 模型清单与前端白名单
- 价表 JSON 新增 deepseek-flash 条目并同步 flash 系价格
2026-09-10 22:10:29 +08:00
chihao.ou b112805ffa test(ops): align query matcher formatting with gofmt 2026-09-10 21:21:08 +08:00
chihao.ou 8c56eabcdc fix(payment): allow scrolling through renewal plans 2026-09-10 21:20:20 +08:00
chihao.ou d3bd614ba7 test(groups): initialize a valid rate multiplier in peak validation case 2026-09-10 21:17:42 +08:00
chihao.ou e9f5add97c fix(ops): show first-token latency in TTFT request details 2026-09-10 21:13:17 +08:00
chihao.ou ab3b398b5f fix(groups): return bad request for invalid peak-rate settings 2026-09-10 21:05:47 +08:00
chihao.ou 5032d06697 fix(codex): advertise DeepSeek vision image input 2026-09-10 21:04:56 +08:00
xlplbo bed1e3c362 fix(openai): 重试强制新建连接并放宽轮次预检超时 2026-09-10 20:35:53 +08:00
xlplbo a5b07b2960 feat(openai): WS 连接池常驻读循环应答上游 ping 2026-09-10 20:35:53 +08:00
xlplbo df8eceba0c fix(apicompat): chat 桥保留 Codex agent_message 任务正文 2026-09-10 20:25:38 +08:00
xlplbo 95a04c8dff test(apicompat): additional_tools 走 chat 桥的回归用例 2026-09-10 19:50:26 +08:00
xlplbo cd1ee1d1ad fix(openai): WS 接入会话状态改用执行作用域键 2026-09-10 17:50:24 +08:00
xlplbo 9e7c2d713c fix(openai): WS 会话抢占改用执行作用域键 2026-09-10 17:50:24 +08:00
xlplbo 06b61ba96f feat(openai): 解析 codex 线程标识派生 WS 执行作用域 2026-09-10 17:50:23 +08:00
feeeei 4a4b50d807 fix(quota): 平台限额表只保存已配置限额的记录,仪表盘按用量与限额展示平台
user_platform_quotas 只保存至少配置了一档限额的记录;不存在的行等价于不限额。

- 注册播种只为配置了限额的平台建行,一个都没有时不写入
- IncrementUsageWithReset 无行时不再 fail-open 建行
- BatchSnapshotUsage 改为只更新既有活跃行,不再插入无限额的新行
- 仓储 BulkInsertInitial/UpsertForUser 把三档全空的记录视为未配置;
  管理员全量替换接口同样剔除,清空限额即软删并放弃累计用量
- 迁移 238 删除三档全 NULL 的历史行
- 用户仪表盘平台卡片 = 有用量的平台 ∪ 配置了限额的平台,计数改为卡片数
- 管理员限额弹窗对未保存限额的平台禁用"重置窗口"
2026-09-10 16:41:58 +08:00
r266-tech 1c0932e173 feat(gateway): retrieve models from the visible catalogue 2026-09-10 15:57:17 +08:00
nekocode a4edda36d5 fix(gateway): 不再剥离客户端 system 上的 cache_control
OAuth mimic 路径无条件删除 system[*].cache_control,不打日志也不报错。
把稳定前缀锚在 system 上的客户端因此拿到 cache_creation 与 cache_read
双 0 —— 不是没命中,是连写都没写。

这个动作是 46e5ac9 引进时「system 必然被整个重写」的配套:客户端的
system 内容都搬进 messages 了,残留断点指着空气,删它是对的。后来
system 注入变成可配置,于是长出了原设计里不存在的组合 —— system 没被
重写,断点照删。剥离失去了赖以成立的前提,代码却还在。

三处调用点里 count_tokens 那处还是硬编码 true,与另两处的
!systemRewritten 语义不一致。

直接移除该选项而不是再加一个开关:注入开启时 system 已被整个替换、
留在上面的断点是我们自己拼进去的稳定锚点;注入关闭时断点就是客户端的
缓存意图。两种情形都没有删它的理由,而需要开关的是有取舍的行为。

顺带补上 count_tokens 的 4 块上限兜底:五条出口里只有它没在自己的转发
路径上调过 enforceCacheControlLimit,原先那句 strip 是这条路上唯一压制
断点数量的东西。拿掉之后「客户端 system + 客户端 messages + 刚注入的
tools[-1]」实测顶到 5 块,而上游对超限是 400。

messages 层的同类改写见 #2369,那次只落地了 messages 一半。

此前该行为零测试覆盖(stripSystemCacheControl 在 _test.go 里零命中),
本次补 4 个用例,其中上限兜底那条撤掉修复即红。

Claude-Session: https://claude.ai/code/session_01WnTW52pmELGy3g7KPEUXj2
2026-09-10 15:48:17 +08:00
reed 1ed36679bd fix(apicompat): recover Responses text from done and terminal events
The streaming Responses-to-Anthropic converter emitted assistant text only
from output_text.delta, so a stream carrying its answer on
response.output_text.done or in the terminal response.output produced a
protocol-valid message with no text.

Record emitted text per output_text part in a ledger that survives content
block closure, and recover only the suffix a finished payload adds, as #6629
does for function-call arguments. Where the part a payload finishes cannot be
established, decline to recover rather than repeat delivered text: terminal
recovery runs only when nothing was emitted, and a done payload indexed
differently from every delta is ignored.

Give output_text.done its own handler so the shared block-closing helper and
its tool-path caller stay unchanged, and so a payload arriving after
message_stop cannot open a content block past the end of the message.
2026-09-09 18:55:16 -05:00
smyyyyy 4e5632c3e3 fix: validate Codex User-Agent before identity parsing 2026-09-10 03:18:31 +08:00
feeeei 44bc47a3e3 fix(gemini): 原生路径登记 2xx 响应里的带内错误信号
Gemini API-key 原生转发对上游 2xx 只抽 usage 原样透传:finishReason 内容拦截、
promptFeedback.blockReason、事件里的 Google 错误信封、空响应都被当作成功,
ops 错误日志、用户错误页、渠道监控全部没有记录。

- 新增 gemini_response_signal:逐事件判定三类带内信号,流式按优先级登记最高者;
  没有 data 事件时对非 SSE 的兜底正文整段判定,空体登记 EMPTY_STREAM / EMPTY_RESPONSE
- 内容策略类按请求级结果登记(invalid_request_error / 400,business limited,
  不做上游归因、不计 SLA);错误信封、生成异常、空响应按上游失败登记并计 SLA
- OpsStreamError 新增 RequestScoped / NonStream:请求级带内行不受残留上游上下文与
  skip_monitoring 影响,落库状态取 IntendedStatus;中间件保留此前尝试的恢复行
- 客户端字节、wire 状态、用量与计费不变
2026-09-10 02:59:15 +08:00
aofee d4e8ddb0c5 fix(grok): allow quota queries during account cooldowns 2026-09-09 21:09:29 +08:00
chihao.ou 21323c31f8 fix(monitor): support upstream base URL paths 2026-09-09 20:02:25 +08:00
chihao.ou c76db386c0 fix(subscriptions): exclude deleted users from assignment search 2026-09-09 20:01:34 +08:00
chihao.ou 58e6e6b325 fix(risk-control): clarify the async processed counter label 2026-09-09 19:57:23 +08:00
chihao.ou 567ea21dc8 feat(admin): support deleting selected users 2026-09-09 19:50:05 +08:00
chihao.ou b9d0728687 fix(redeem): align subscription duration limit with the backend 2026-09-09 19:47:22 +08:00
wangjunwei de76baaa0d fix(scheduler): preserve Anthropic threshold metadata 2026-09-09 17:13:37 +08:00
anguobao123 26798773cb fix(deploy): support web updates with Apple container 2026-09-09 17:05:45 +08:00
github-actions[bot] 98d86915be chore: sync VERSION to 0.2.4 [skip ci] 2026-09-09 07:05:11 +00:00
Wesley Liddick 5de5e2bed0 Merge pull request #6874 from hansnow/fix/gpt-image-2-5-oauth
fix(openai): 支持 Image 2.5 并修复 OAuth 生图主控模型
2026-09-09 14:43:55 +08:00
刘世俊 a0babc93dd fix(openai): accept full heartbeat bootstrap envelopes 2026-09-09 12:48:57 +08:00
hansnow 7ccc8a6f50 fix(openai): 支持 Image 2.5 并修复 OAuth 生图主控模型 2026-09-09 11:04:59 +08:00
lcy 29a36a10be Merge upstream/main into feat/antigravity-gemini-3.8-flash
Resolve comment-wording conflict in normalizeGeminiThinkingTierAlias by
keeping upstream's phrasing. Function body and behavior are unchanged.
2026-09-09 01:49:32 +08:00
reallyfeishi f180fbb884 fix: anchor channel monitor buckets to UTC 2026-09-08 23:02:06 +08:00
chihao.ou 1d4e0436e4 feat(settings): allow hiding the custom page open button 2026-09-08 21:18:56 +08:00
shaw 270eac6973 chore: update sponsors 2026-09-08 21:18:24 +08:00
chihao.ou 266ac9c11b fix(ops): prioritize time and response in error details 2026-09-08 21:17:13 +08:00
chihao.ou ac770d98fb test(groups): initialize Pinia in Codex manifest regression 2026-09-08 21:16:53 +08:00
chihao.ou fd880839f6 fix(usage): show eight decimal places in cost details 2026-09-08 21:15:55 +08:00
shaw 570106ac17 chore: update sponsors 2026-09-08 20:57:43 +08:00
Wesley Liddick 775348b402 Merge pull request #6706 from ouchihao/codex/issue-3679-draggable-custom-page-button
feat(custom-page): make the open-link button draggable
2026-09-08 20:47:42 +08:00
Wesley Liddick d9efbf8229 Merge pull request #6839 from mason0510/fix/grok-external-web-access
fix(grok): 移除 Chat Completions 中不支持的 external_web_access 参数
2026-09-08 20:47:25 +08:00
Wesley Liddick 233f3dffe6 Merge pull request #6281 from wuji-labs/feat/http2-long-stream-keepalive
feat(upstream): add HTTP/2 PING keepalive for long LLM generation streams
2026-09-08 20:47:07 +08:00
Wesley Liddick f9d7826711 Merge pull request #6513 from anguobao123/codex/optional-apple-container-network-subnet
feat(deploy): support optional Apple network subnet
2026-09-08 20:46:51 +08:00
Wesley Liddick c54897a59d Merge pull request #6815 from Pluviobyte/codex/fix-directed-proxy-backups
fix(proxies): make backup references directed and shareable
2026-09-08 20:46:32 +08:00
Wesley Liddick 29646ba6b4 Merge pull request #6488 from aofee/codex/feat-grok-media-eligibility-ui
feat: add Grok media eligibility controls
2026-09-08 20:46:20 +08:00
Wesley Liddick 6f0d0ababc Merge pull request #6320 from spongehah/fix/runtime-block-honor-persisted-cooldown
fix(schedule): 选号按持久化冷却条件清除本机账号级阻断
2026-09-08 20:46:07 +08:00
Wesley Liddick 52f7bcaedd Merge pull request #6759 from ssharkkky/feat/cmv2-user-ranking-toggle
feat(channel-monitor-v2): add user ranking toggle and keep missing TTFT neutral
2026-09-08 20:44:07 +08:00
Wesley Liddick 95acbf1f03 Merge pull request #6424 from cyhhao/fix/bound-ops-system-log-storage
fix(ops): bound database-backed system log growth
2026-09-08 20:43:54 +08:00
Wesley Liddick 43569bb44c Merge pull request #6434 from swjturay/codex/upstream-client-disconnect-drain
fix(openai-ws): drain upstream after client disconnect
2026-09-08 20:42:59 +08:00
Wesley Liddick 15557e7796 Merge pull request #6235 from StarryKira/codex/fix-6232-channel-cache-invalidation
fix: broadcast channel cache invalidations across instances
2026-09-08 20:42:45 +08:00
Wesley Liddick e2fd418a96 Merge pull request #6372 from clansty/fix/openai-oauth-429-fallback-disabled
fix: 修复关闭 429 默认回避后仍触发 OAuth 运行时冷却
2026-09-08 20:42:35 +08:00
Wesley Liddick 4e9b01fd59 Merge pull request #6838 from atogumo/fix/claude-code-probe-any-model
fix(gateway): accept Claude Code max_tokens=1 probes for any model
2026-09-08 20:42:24 +08:00
Wesley Liddick aa167a25a7 Merge pull request #6775 from xlplbo/fix/plugin-zip-handle-windows
fix(plugin): 提交插件包前先关闭 ZIP 读取器,修正 Windows 下两例单测
2026-09-08 20:12:42 +08:00
Wesley Liddick 5cbb9191a7 Merge pull request #6836 from r266-tech/fix-proxy-expiry-json-range
fix(proxies): reject malformed list responses
2026-09-08 20:12:30 +08:00
Wesley Liddick ae4cc14b28 Merge pull request #6819 from LeeeeeeM/codex/fix-registration-visibility
fix: respect registration visibility on login
2026-09-08 20:12:14 +08:00
Wesley Liddick fa556700c2 Merge pull request #6762 from ouchihao/codex/issue-2045-payment-help-markdown
feat(payment): render help text as sanitized Markdown
2026-09-08 20:11:56 +08:00
Wesley Liddick 68773aab98 Merge pull request #6764 from ouchihao/codex/issue-1499-select-failed-token-refresh
fix(accounts): keep failed token refresh accounts selected
2026-09-08 20:11:08 +08:00
Wesley Liddick 1e6114c270 Merge pull request #6812 from Pluviobyte/codex/fix-model-plaza-subscriptions
fix(model-plaza): include active subscription groups
2026-09-08 20:10:42 +08:00
Wesley Liddick 9e7039ebca Merge pull request #6811 from Pluviobyte/codex/fix-proxy-partial-update
fix(proxies): preserve omitted expiry and fallback settings
2026-09-08 20:10:20 +08:00
Wesley Liddick 1923d1c27d Merge pull request #6814 from feeeei/fix/go-redis-pool-nil-ctx-panic
fix(redis): 升级 go-redis 至 v9.22.0,修复连接池 nil-ctx panic 竞态
2026-09-08 20:09:59 +08:00
Wesley Liddick b638445234 Merge pull request #6754 from ccemoji/codex/minimal-upstream-fix
fix: cancel streaming upstream before closing body
2026-09-08 20:09:37 +08:00
Wesley Liddick 9bcf8a5b80 Merge pull request #6760 from wucm667/feat/issue-6752-weekly-cost-estimate
feat(accounts): show estimated weekly account cost
2026-09-08 20:09:25 +08:00
Wesley Liddick 979fe247f9 Merge pull request #6821 from 22zyfeng-collab/fix/antigravity-oauth-plan-type
fix(antigravity): preserve OAuth plan_type when saving accounts
2026-09-08 20:09:12 +08:00
Wesley Liddick 6378fb0cba Merge pull request #6798 from savvym/codex/fix-account-menu-overflow
fix(frontend): 修复账号操作菜单在视口底部被截断
2026-09-08 20:08:53 +08:00
Wesley Liddick 3ee92b40c5 Merge pull request #6659 from ouchihao/codex/issue-77-remove-inactive-groups
fix(accounts): allow removing inactive group assignments
2026-09-08 20:08:40 +08:00
Wesley Liddick 4892b8f17e Merge pull request #6810 from Pluviobyte/codex/fix-announcement-proxy-date-range
fix: validate announcement and proxy date ranges
2026-09-08 20:08:24 +08:00
Wesley Liddick 28b807a735 Merge pull request #6816 from Pluviobyte/codex/fix-repeated-proxy-fallback
fix(proxies): allow repeated expiry fallback and preserve origin
2026-09-08 20:07:08 +08:00
atogumo 4e5d67df35 fix(gateway): accept Claude Code max_tokens=1 probes for any model
The claude_code_only probe exemption only fired for models containing
"haiku". Claude Code also sends max_tokens=1 requests without a system
prompt to the model currently in use, e.g. when switching models or
refreshing the context usage, so on sonnet/opus groups those requests failed
the system-prompt check and were rejected as non-Claude-Code clients.

Recognise the probe from the request body itself (max_tokens == 1) once the
User-Agent check has passed, regardless of model, and carry max_tokens into
the ParsedRequest projection so the hot path sees it too. The haiku context
flag and the local haiku interception are unchanged; non-haiku probes reach
the pool as ordinary one-token requests. One output token offers nothing to
a client that already forges the CLI User-Agent, so this widens no attack
surface.

Fixes #6591
2026-09-08 19:12:37 +08:00
Wesley Liddick dbe92a1c24 Merge pull request #6758 from DuskLin/feat/minimax-platform
feat(minimax): 增加 MiniMax 平台支持
2026-09-08 18:50:06 +08:00
r266-tech 188e3a9f90 fix(proxies): reject malformed list responses 2026-09-08 18:29:17 +08:00
刘佳林 10940ecf39 fix(minimax): gofmt MiniMax allowlist comments
golangci-lint gofmt failed on aligned comments in the default upstream host list.
2026-09-08 17:49:11 +08:00
刘佳林 3495635a52 fix(minimax): 补齐阈值停调与额度监控接线
调度阈值评估和渠道监控 quota 取数补上 MiniMax 分支;GetCodingPlanProvider 改为只认官方域名,避免把中转 Key 发到厂商额度端点。composite /v1/models 与 Codex 目录纳入 MiniMax;迁移改名为 237;allowlist 去掉未使用的 www.* / api.minimax.cn,abab 前缀收窄到 5/6/7。
2026-09-08 17:41:29 +08:00
mason0510 c8deeb0b05 fix(grok): 移除 Chat Completions 中不支持的 external_web_access 参数
模型:Claude Sonnet 5
修复内容:在 Grok Chat Completions raw 转发流程中添加 external_web_access 参数过滤,修复 Grok API 返回 400 "Argument not supported: external_web_access" 错误
修改理由:Grok xAI API 不支持 external_web_access 参数,Sub2API Responses API 路径已有过滤,但 Chat Completions 路径缺失,导致 grok-4.5 等模型调用失败返回 502
验证结果:代码已通过本地 Demo 验证递归删除逻辑正常,待远端编译部署后验证真实 API 调用
影响范围:仅影响 Grok 平台 Chat Completions API 请求体处理,不影响 Responses API 和其他平台
回滚方式:git revert 本次提交,或手动移除 openai_gateway_chat_completions_raw.go line 159-163 的 sanitizeGrokUnsupportedFields 调用

[AI: 梁心语/Claude Sonnet 5 @ 2026-09-08T17:30]
2026-09-08 16:41:09 +08:00
22zyfeng-collab b6ee9f0a32 fix(antigravity): preserve OAuth subscription plan across account creation 2026-09-08 15:02:32 +08:00
G.Wood-Sun 6c8ad0bd4a fix: respect registration visibility on login 2026-09-08 14:44:41 +08:00
Rain 7137fae2a6 test(proxies): preserve incoming references when editing backups 2026-09-08 13:58:34 +08:00
Rain 859de4c8fd fix(proxies): allow repeated expiry fallback and preserve origin 2026-09-08 13:56:20 +08:00
Rain e835f79819 fix(proxies): make backup references directed and shareable 2026-09-08 13:56:19 +08:00
feeeei 99eba19ffc fix: 升级 go-redis 至 v9.22.0 修复连接池 nil-ctx panic
上游竞态:调用方超时后 wantConn.ctx 被置 nil,拨号 goroutine 用 nil ctx
创建超时上下文触发 panic(go-redis#3630,v9.18.0 起修复)。
生产环境在连接池饥饿 + 请求超时风暴下每秒触发上万次。

同步将 ZRangeByScore 迁移至 ZRangeArgs:v9.22.0 将其标记为 deprecated,
golangci-lint staticcheck 拦截(SA1019)。ZRangeArgs{ByScore: true} 与原
调用发出的 Redis 命令参数完全等价(LIMIT 编码逻辑相同)。
2026-09-08 13:46:59 +08:00
Rain 38cfd7e2d9 fix(proxies): preserve omitted expiry and fallback settings 2026-09-08 13:38:41 +08:00
Rain 3fc08745a6 fix(model-plaza): include active subscription groups 2026-09-08 13:37:53 +08:00
Rain efc6e4a816 fix: validate announcement and proxy date ranges 2026-09-08 13:37:52 +08:00
savvym df64b5f368 fix(frontend): keep account action menu within viewport 2026-09-08 10:46:56 +08:00
github-actions[bot] 772a0382f0 chore: sync VERSION to 0.2.3 [skip ci] 2026-09-08 02:35:11 +00:00
tunsuyandCursor ef891643e9 merge(main): resolve antigravity toolConfig conflict for #6689
Keep always-on toolConfig from main (reasoning models without tools) while
retaining the PR behavior that drops mixed built-in tools when client
function tools are present, so includeServerSideToolInvocations stays unused.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 09:48:44 +08:00
Qilin You 7e62731863 perf: reduce allocations for large Responses image payloads 2026-09-08 01:54:32 +08:00
xlplboandClaude Fable 5.1 b42157a725 test(service): 修正 Windows 下两例环境相关用例
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAJmqcVA9TLacTCD1bLh4i
2026-09-07 23:21:29 +08:00
xlplboandClaude Fable 5.1 335fcdc1d6 fix(plugin): 提交插件包前先关闭 ZIP 读取器
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SAJmqcVA9TLacTCD1bLh4i
2026-09-07 23:21:29 +08:00
tunsuyandCursor 140e172951 chore: retrigger CI after test fix
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:10:50 +08:00
chihao.ou 941a0487ab fix(accounts): allow removing inactive group assignments 2026-09-07 20:05:08 +08:00
tunsuyandCursor 1d4b9ead45 test(antigravity): align buildTools expectations with mixed-tool drop
Update the leftover buildTools unit test that still expected
googleSearch to coexist with client function declarations.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:04:33 +08:00
chihao.ou 7f0f579bb0 fix(accounts): keep failed token refresh accounts selected 2026-09-07 20:01:24 +08:00
chihao.ou dfb3978b9d feat(payment): render help text as sanitized Markdown 2026-09-07 19:51:03 +08:00
刘佳林and刘佳林 6f2295bfc7 test(minimax): 按平台注册表推导调度器 snapshot 期望数量
新增 MiniMax 后 canonical token / 账号查询数增加,硬编码期望值过期。
改为从 schedulerSnapshotPlatforms 派生 bucket 与 query 数量,避免下次加平台再踩坑。
账号查询计数辅助函数仅用于单测,放在 unit test 文件以免 unused。

Co-authored-by: 刘佳林 <DuskLin@users.noreply.github.com>
2026-09-07 11:40:11 +00:00
wucm667 35e69af41b feat(accounts): show estimated OpenAI weekly cost 2026-09-07 18:37:15 +08:00
TT 0d3dbae710 feat(channel-monitor-v2): add user ranking toggle and keep missing TTFT neutral
Give operators a V2 setting (channel_monitor_hide_user_ranking) to hide
the user ranking tab and the /users payload from non-admin channel
monitor v2 viewers. Default false (ranking stays visible). Admin
endpoints and views always keep the ranking.

Also stop painting first-token '-' as a red/empty failure when traffic
is sync-only and has no first-token samples: a missing TTFT is
"not applicable" (health-unknown), not a breached latency budget.

Changes:
- new setting key + fail-open parse (only literal "true" hides), wired
  through public/admin settings DTOs, handlers, and the V2 runtime
- ChannelMonitorV2Service.Users returns an empty list to non-admin
  viewers when the toggle is on
- frontend: feature flag + SettingsView toggle + user V2 view hides the
  ranking tab and skips the /users call
- monitorFormat: isTtftUnavailable/ttftDisplayState keep missing TTFT
  neutral

Tests:
- setting parse defaults to visible and only literal "true" hides
- V2 Users honors the toggle for non-admin viewers
- frontend MetricCell/monitorFormat keep missing TTFT neutral
2026-09-07 18:31:03 +08:00
刘佳林 19382f275e feat(minimax): 增加 MiniMax 平台支持
把 MiniMax 做成与 Kimi / 智谱 / DeepSeek 同级的国产供应商平台:账号创建/编辑、分组、Composite 路由、原生 Token Plan / Coding Plan 额度,以及 OpenAI 兼容模型列表。

额度走 GET api.minimaxi.com|io /v1/api/openplatform/coding_plan/remains(Bearer)。只解析 model_name=general 的 remaining percent;周窗口仅在 current_weekly_status=1 时计入。

Related to #6742
2026-09-07 18:22:56 +08:00
ccemoji be4ab92b2b fix: cancel streaming upstream before closing body 2026-09-07 16:47:51 +08:00
Lawrence c0c4ce1ce6 Merge upstream main and retain blank OAuth promo code regression test 2026-09-07 14:27:55 +08:00
chihao.ou 76efc52fb6 feat(custom-page): make the open-link button draggable 2026-09-06 17:52:24 +08:00
tunsuyandCursor 6c2d2ed043 fix(antigravity): drop mixed web_search when client tools present
Antigravity v1internal rejects googleSearch/codeExecution mixed with
functionDeclarations even with includeServerSideToolInvocations (#6464).
Codex enables web_search by default alongside shell tools, which made
Sub2API return opaque upstream_error. Prefer client function tools so
agent sessions keep working; keep web_search-only fallback intact.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 13:23:53 +08:00
yan9651688 58f461b087 feat(keys): add bulk editing to API key management 2026-09-06 11:25:33 +08:00
whhphd b97a798ebc fix(grok): release abandoned media slots and preserve video ownership
Claim scheduler-acquired slots before media eligibility checks and task-owner
validation. Release abandoned attempts immediately and retain once-only
cleanup on cancellation and forwarding completion.

Select only the resolved video owner, reuse bounded account waiting without
sticky escape, and preserve the task binding and TTL. Keep generation
failover and owner/billing isolation intact.

Regression tests reproduce unreleased account slots on upstream ab99d56e9
and pass with this change. Validation: go test ./..., unit and integration
suites, focused race tests, backend build, and golangci-lint (0 issues).
2026-09-05 20:25:08 +08:00
chihao.ou 017cc62e41 feat(auth): require password confirmation during registration 2026-09-05 19:19:35 +08:00
doublepi123 8ed57b000c feat(antigravity): support Gemini 3.7 Flash models
Google released Gemini 3.7 Flash on 2026-08-13. Register it alongside 3.8
using the same shape as the existing 3.6 entries: bare id plus the
Antigravity -high/-low/-medium/-tiered thinking tiers, the model catalog,
the custom-mapping passthroughs, fallback pricing and the tier alias
normalizer.

Pricing matches 3.8 at $0.75 input / $3.75 output / $0.075 cached input
per MTok. Both are promotional through 2026-12-31 and double on
2027-01-01; the constants note this.

Also corrects the 3.8 catalog timestamps to the documented GA dates.
2026-09-04 16:04:47 +08:00
doublepi123 27bcec7645 feat(antigravity): support Gemini 3.8 Flash models
Google released Gemini 3.8 Flash on 2026-09-02. Register the model and its
Antigravity thinking tiers the same way Gemini 3.6 Flash is registered:

- DefaultAntigravityModelMapping: bare id plus -high/-low/-medium/-tiered
- geminiModels catalog exposed through /antigravity/v1/models
- ensureAntigravityDefaultPassthroughs so accounts with a custom
  model_mapping still resolve the new ids
- fallback pricing and the thinking-tier alias normalizer, so the tiers
  share the base model price card instead of failing pricing lookup

Fallback rates are Google's published prices: $0.75 input / $3.75 output /
$0.075 cached input per MTok. These are promotional through 2026-12-31 and
double on 2027-01-01; the constant carries a note to that effect.

Refs #6523
2026-09-04 16:04:47 +08:00
anguobao123 1859519573 feat(deploy): support optional Apple network subnet 2026-09-02 20:08:57 +08:00
Soulxyz 8ed48e27a6 fix(setup): avoid hardcoded postgres connection 2026-09-02 15:30:59 +08:00
WUJI-Labs f5e4da5e72 style(upstream): gofmt http_upstream_profile.go 2026-09-02 12:40:23 +08:00
WUJI-Labs 9dc4c40bff test(upstream): align HTTP/2 keepalive tests with long-stream profile API 2026-09-02 12:28:37 +08:00
WUJI-Labs 81fd853005 feat(upstream): add HTTP/2 PING keepalive for long LLM generation streams
Long-running LLM inferences (such as high-thinking Gemini models) may experience
silent TCP disconnections across intermediate proxies, NAT gateways, or firewalls
when no data frames are emitted for tens of seconds to minutes.

Go's default http2.Transport sets ReadIdleTimeout=0 (disabling active PING checks).
This commit introduces HTTPUpstreamProfileLongStream with:
- ReadIdleTimeout = 10s
- PingTimeout = 5s

When a pooled H2 connection stays idle for 10s during long streams, active PING frames
are dispatched. Dead connections failing to respond within 5s are proactively evicted,
preventing client generation requests from hanging on dead sockets or failing with EOF/502.

Signed-off-by: WUJI-Labs <zoujincool@gmail.com>
2026-09-02 12:11:17 +08:00
aofee 01bd9b71a2 feat: add Grok media eligibility controls 2026-09-02 11:50:33 +08:00
cxx-cod 6f9fde093f style(openai): apply De Morgan's law to satisfy staticcheck QF1001 2026-09-02 03:30:14 +00:00
cxx-cod 277aa1411d fix(openai): end streaming at terminal event instead of waiting for upstream EOF
The streaming forward loops treated upstream EOF as the only normal exit
condition; response.completed/[DONE] only set a flag. With keep-alive /
HTTP/2 connection reuse to the upstream, the upstream may hold the
stream open for 8-46s after the terminal event, during which the
gateway could only emit downstream keepalives, inflating tail latency.

Finish the stream as soon as the terminal event frame has been fully
written downstream (usage is already parsed from the terminal event),
and close the upstream body to unblock the reader goroutine. Applied
to the guarded/async, sync, and passthrough streaming paths. The WS
HTTP bridge already behaved this way.

Adds a regression test with an upstream that hangs after
response.completed.
2026-09-01 19:32:24 +00:00
Ray a10ff1255c fix(openai-ws): classify canceled client streams 2026-08-31 21:04:29 +08:00
cyh 163eb7ffae fix(ops): bound database-backed system logs 2026-08-31 19:04:58 +08:00
Clansty 5fea83dcae fix: 修复429未耗尽额度仍触发账号退避
- 关闭429默认回避时不再创建OAuth运行时冷却

- 仅在x-codex窗口达到100%时使用上游重置时间

- 补充未耗尽额度和关闭开关的回归测试
2026-08-30 00:02:14 +08:00
spongehah 6d339ec93b fix: honor persisted cooldown when dropping in-process account blocks
- Treat TempUnschedulableUntil/RateLimitResetAt/OverloadUntil as source of truth during account selection
- Drop stale local account-level runtime blocks with generation+deadline CAS
- Leave model-scoped transient and Grok quota blocks unchanged
2026-08-28 14:38:15 +08:00
Lawrence e1eff57c25 fix(auth): preserve promo codes through OAuth registration 2026-08-26 21:12:52 +08:00
haruka 1ee929e4b9 fix: broadcast channel cache invalidations 2026-08-26 11:16:32 +08:00
Nick 89ba561a6f fix(backup): keep the S3 secret encrypted when a save inherits it
UpdateS3Config only encrypted the SecretAccessKey on the branch where the
caller supplied a new one. The other branch inherits the stored secret
through loadS3Config, which *decrypts* it — so that path wrote the
plaintext straight back to the settings row and overwrote the ciphertext.

It is the normal path, not an edge case. UpdateS3Config clears the secret
in its own return value, so the admin form's field is empty afterwards.
Any later save — changing the endpoint, saving the schedule, pressing save
twice — sends an empty secret and takes the inheriting branch. One extra
save is enough to leave the secret in plaintext at rest.

Nothing surfaced because loadS3Config falls back to the raw value when
decryption fails, for compatibility with pre-encryption rows. Backups kept
working and the only trace was a line per read:

  [Backup] S3 SecretAccessKey 解密失败(可能是旧的未加密数据):
  decrypt: cipher: message authentication failed

Seen on a live install: the stored value was 64 characters, exactly the
plaintext length of an R2 secret, where AES-GCM + base64 would have been
124. The compatibility fallback turns a one-time write bug into a
permanent plaintext secret.

It also feeds itself: pg_dump includes the settings table, so the backup
uploaded to the bucket carries the credentials for that same bucket.

Fix: hoist the encryption out of the if/else so it runs for a non-empty
secret whichever way it arrived. The ephemeral-key guard (#4524) moves
with it, and the no-secret-at-all case still skips encryption entirely, so
an update with no stored secret keeps working under an auto-generated key.

The existing KeepExistingSecret test passed either way, because it only
asserted loadS3Config returns the plaintext — true with the fallback too.
The new test asserts on the row itself: still ciphertext after a second
save, not double-wrapped after a third.

Checked the new test fails without the fix and passes with it.
2026-07-25 19:57:51 +07:00
2150 changed files with 228226 additions and 12287 deletions

No files matched your search

+107
View File
@@ -0,0 +1,107 @@
# Security Policy
[English](#english) | [中文](#中文)
## English
### Reporting a Vulnerability
**Please do not report security vulnerabilities through public GitHub issues, pull requests, or discussions.**
Report them privately through GitHub's private vulnerability reporting:
**[Report a vulnerability](https://github.com/Wei-Shaw/sub2api/security/advisories/new)**
(Repository → **Security** tab → **Report a vulnerability**.) Only the maintainers can see the report, and the advisory becomes the place to discuss, fix, and eventually publish the issue.
If you cannot use GitHub private vulnerability reporting, email **dev@sub2api.org** instead, with `[Security]` in the subject line.
A useful report includes:
- The affected component and version (release tag or commit)
- Impact: what an attacker can do and which privileges they need
- Minimal reproduction steps or a proof of concept
- Any non-default configuration required to trigger the issue
- A suggested fix, if you have one
### Supported Versions
Sub2API releases frequently, and fixes ship in a new release rather than being backported.
| Version | Supported |
| ------- | --------- |
| Latest release | ✅ |
| Older releases | ❌ |
Please confirm that the issue reproduces on the latest release or on `main` before reporting.
### Scope
In scope: the Sub2API backend, frontend, official Docker images, and deployment files in this repository.
Usually out of scope:
- Issues that require already-compromised admin credentials or server access
- Risks arising from explicitly weakening documented security settings (for example, disabling `security.url_allowlist`)
- Vulnerabilities in upstream AI providers or third-party dependencies with no Sub2API-specific impact (please report those upstream)
- Missing best-practice headers or scanner output without a demonstrated impact
### Disclosure Process
1. We acknowledge the report and assess its validity and severity.
2. We develop a fix privately in the advisory and may ask you to verify it.
3. We publish a release containing the fix, then publish the GitHub Security Advisory (with a CVE when applicable), crediting you unless you prefer to stay anonymous.
Please keep details private until the advisory is published. This is a volunteer-maintained project, so response times are best effort.
## 中文
### 报告漏洞
**请不要通过公开的 Issue、Pull Request 或 Discussion 报告安全漏洞。**
请使用 GitHub 私密漏洞报告功能提交:
**[提交漏洞报告](https://github.com/Wei-Shaw/sub2api/security/advisories/new)**
(仓库 → **Security** 标签页 → **Report a vulnerability**。)报告仅维护者可见,后续的讨论、修复与公告发布都在该安全公告中进行。
如果无法使用 GitHub 私密漏洞报告,也可以发送邮件至 **dev@sub2api.org**,邮件标题请注明 `[Security]`。
报告中建议包含:
- 受影响的组件与版本(Release tag 或 commit)
- 影响:攻击者能做什么、需要什么权限
- 最小复现步骤或 PoC
- 触发问题所需的非默认配置
- 修复建议(如有)
### 支持的版本
Sub2API 发版频繁,安全修复随新版本发布,不向旧版本回移。
| 版本 | 是否支持 |
| ---- | -------- |
| 最新 Release | ✅ |
| 更早的版本 | ❌ |
报告前请先确认问题在最新 Release 或 `main` 上仍可复现。
### 范围
范围内:本仓库中的 Sub2API 后端、前端、官方 Docker 镜像与部署文件。
通常不在范围内:
- 需要事先已掌握管理员凭据或服务器权限才能利用的问题
- 因主动关闭文档中的安全配置(如关闭 `security.url_allowlist`)而产生的风险
- 上游 AI 服务商或第三方依赖自身的漏洞,且对 Sub2API 无特定影响(请向上游报告)
- 仅缺少最佳实践响应头或扫描器输出,但未证明实际影响
### 披露流程
1. 我们确认收到报告,并评估其有效性与严重程度。
2. 我们在安全公告中私下开发修复,可能请你协助验证。
3. 我们先发布包含修复的版本,再公开 GitHub 安全公告(适用时申请 CVE),并致谢报告者(如你希望匿名则不署名)。
在公告发布前请勿公开漏洞细节。本项目由志愿者维护,响应时间尽力而为。
+6 -6
View File
@@ -3,16 +3,16 @@ exceptions:
- package: xlsx
advisory: "GHSA-4r6h-8v6p-xvw6"
severity: high
reason: "Admin export only; switched to dynamic import to reduce exposure (CVE-2023-30533)"
mitigation: "Load only on export; restrict export permissions and data scope"
expires_on: "2026-10-06"
reason: "Write-only: admin UsageView lazily imports xlsx solely for XLSX.write export; the advisory requires parsing a crafted file and no XLSX.read path exists (CVE-2023-30533)"
mitigation: "Never parse untrusted spreadsheets with xlsx; no patched version on npm, migrate to SheetJS CDN build or another writer before expiry"
expires_on: "2027-01-06"
owner: "security@your-domain"
- package: xlsx
advisory: "GHSA-5pgg-2g8v-p4x9"
severity: high
reason: "Admin export only; switched to dynamic import to reduce exposure (CVE-2024-22363)"
mitigation: "Load only on export; restrict export permissions and data scope"
expires_on: "2026-10-06"
reason: "Write-only: admin UsageView lazily imports xlsx solely for XLSX.write export; the advisory requires parsing a crafted file and no XLSX.read path exists (CVE-2024-22363)"
mitigation: "Never parse untrusted spreadsheets with xlsx; no patched version on npm, migrate to SheetJS CDN build or another writer before expiry"
expires_on: "2027-01-06"
owner: "security@your-domain"
- package: lodash
advisory: "GHSA-r5fr-rjxr-66jc"
+1
View File
@@ -0,0 +1 @@
__pycache__/
+30
View File
@@ -0,0 +1,30 @@
# Release matrix
The release workflow builds the frontend once, then runs each configured Go target on its own Linux runner. `CGO_ENABLED=0` permits cross-compilation. The target matrix is read from `.goreleaser.yaml`, including its exclusions; simple releases select Linux amd64 only.
Each build uses GoReleaser OSS in snapshot mode with the selected release version and one target. Archive naming, bundled files, Go flags and release templates remain in the existing GoReleaser configurations. Every archive is accompanied by its source commit, target, version and SHA256. The publishing job verifies the complete matrix before building images or publishing. It uses GoReleaser's `extra_files` support to publish existing archives and checksums, with builds disabled. No Pro license is needed.
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.
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
From a branch containing this workflow:
```bash
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`.
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.
Helper checks:
```bash
python -m pip install -r .github/release-tools/requirements-release.txt
python -m unittest discover -s .github/release-tools -p 'test_release_matrix.py'
bash -n .github/release-tools/release-images.sh
```
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
: "${RELEASE_VERSION:?}" "${RELEASE_SHA:?}" "${GITHUB_REPOSITORY:?}" "${RUNNER_TEMP:?}"
owner=${GITHUB_REPOSITORY%%/*}
registries=("ghcr.io/${owner,,}/sub2api")
if [[ ${SIMPLE_RELEASE:-false} != true && ${DOCKERHUB_USERNAME:-skip} != skip ]]; then
registries+=("${DOCKERHUB_USERNAME}/sub2api")
fi
arches=(amd64 arm64)
if [[ ${SIMPLE_RELEASE:-false} == true ]]; then arches=(amd64); fi
for arch in "${arches[@]}"; do
args=(--platform "linux/$arch" --file ".release-context/$arch/Dockerfile"
--label "org.opencontainers.image.version=$RELEASE_VERSION"
--label "org.opencontainers.image.revision=$RELEASE_SHA"
--label "org.opencontainers.image.source=https://github.com/$GITHUB_REPOSITORY")
for registry in "${registries[@]}"; do
args+=(--tag "$registry:$RELEASE_VERSION-$arch")
if [[ ${SIMPLE_RELEASE:-false} == true ]]; then
args+=(--tag "$registry:$RELEASE_VERSION" --tag "$registry:latest")
fi
done
if [[ ${DRY_RUN:-false} == true ]]; then
args+=(--output "type=oci,dest=$RUNNER_TEMP/sub2api-$arch.oci.tar")
else
args+=(--push)
fi
docker buildx build "${args[@]}" ".release-context/$arch"
done
if [[ ${DRY_RUN:-false} != true && ${SIMPLE_RELEASE:-false} != true ]]; then
major=${RELEASE_VERSION%%.*}
minor=${RELEASE_VERSION#*.}; minor=${minor%%.*}
for registry in "${registries[@]}"; do
docker buildx imagetools create \
--tag "$registry:$RELEASE_VERSION" --tag "$registry:latest" \
--tag "$registry:$major.$minor" --tag "$registry:$major" \
"$registry:$RELEASE_VERSION-amd64" "$registry:$RELEASE_VERSION-arm64"
done
fi
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""Split GoReleaser builds across runners without requiring GoReleaser Pro."""
import argparse
import hashlib
import itertools
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import tarfile
from datetime import datetime, timezone
import yaml
FULL_CONFIG = Path('.goreleaser.yaml')
SIMPLE_CONFIG = Path('.goreleaser.simple.yaml')
VERSION_FILE = Path('backend/cmd/server/VERSION')
VERSION_RE = re.compile(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?')
def config(simple=False):
return yaml.safe_load((SIMPLE_CONFIG if simple else FULL_CONFIG).read_text())
def targets(simple=False):
build = config()['builds'][0]
result = []
for goos, goarch in itertools.product(build['goos'], build['goarch']):
item = {'goos': goos, 'goarch': goarch}
if any(all(item.get(k) == v for k, v in rule.items()) for rule in build.get('ignore', [])):
continue
if not simple or item == {'goos': 'linux', 'goarch': 'amd64'}:
result.append(item)
if not result:
raise ValueError('empty release target matrix')
return result
def archive_name(version, target):
if not VERSION_RE.fullmatch(version) or target not in targets():
raise ValueError('invalid release version or target')
suffix = 'zip' if target['goos'] == 'windows' else 'tar.gz'
return f"sub2api_{version}_{target['goos']}_{target['goarch']}.{suffix}"
def sha256(path):
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def plan(args):
sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip()
if args.dry_run:
version = VERSION_FILE.read_text().strip()
tag = 'v' + version
else:
tag = args.ref
version = tag.removeprefix('v')
if not tag.startswith('v') or not VERSION_RE.fullmatch(version):
raise ValueError('publishing requires a v-prefixed release version tag')
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')
if not VERSION_RE.fullmatch(version):
raise ValueError('invalid VERSION')
VERSION_FILE.write_text(version + '\n')
result = {'sha': sha, 'tag': tag, 'version': version,
'owner_lower': os.environ.get('GITHUB_REPOSITORY_OWNER', '').lower(),
'simple': str(args.simple).lower(), 'dry_run': str(args.dry_run).lower(),
'date': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'),
'matrix': json.dumps({'include': targets(args.simple)}, separators=(',', ':'))}
with Path(os.environ['GITHUB_OUTPUT']).open('a') as output:
for key, value in result.items():
output.write(f'{key}={value}\n')
def generate_config(args):
data = config(args.simple if args.mode == 'publish' else False)
data['snapshot'] = {'version_template': '{{ .Env.RELEASE_VERSION }}'}
data['dockers'] = []
data['docker_manifests'] = []
if args.mode == 'build':
target = {'goos': args.goos, 'goarch': args.goarch}
if target not in targets():
raise ValueError('unsupported build target')
for build in data['builds']:
build['goos'], build['goarch'], build['ignore'] = [args.goos], [args.goarch], []
build['ldflags'] = [re.sub(r'{{\s*\.Date\s*}}', '{{ .Env.RELEASE_DATE }}', flag)
for flag in build.get('ldflags', [])]
else:
# Artifacts are supplied through the OSS extra_files mechanism. No build
# is repeated on the publishing runner, and release templates stay intact.
data['before'] = {'hooks': []}
data['builds'] = [{'id': 'sub2api', 'skip': True}]
data['archives'] = []
extra = [{'glob': 'release-input/sub2api_*.tar.gz'}, {'glob': 'release-input/sub2api_*.zip'}]
if args.simple:
data['checksum'] = {'disable': True}
else:
data['release']['extra_files'] = extra
data['checksum'] = {'name_template': 'checksums.txt', 'algorithm': 'sha256', 'extra_files': extra}
Path(args.output).write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True))
def collect(args):
target = {'goos': args.goos, 'goarch': args.goarch}
name = archive_name(args.version, target)
source = Path('dist') / name
checksums = {line.split()[1].lstrip('*'): line.split()[0] for line in Path('dist/checksums.txt').read_text().splitlines()}
digest = sha256(source)
if checksums.get(name) != digest:
raise ValueError('archive does not match the build checksum')
output = Path(args.output)
output.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, output / name)
manifest = {'sha': args.sha, 'version': args.version, 'target': target, 'archive': name, 'sha256': digest}
(output / f"manifest-{args.goos}-{args.goarch}.json").write_text(json.dumps(manifest) + '\n')
def verify(args):
directory = Path(args.input)
expected = set()
for target in targets(args.simple):
name = archive_name(args.version, target)
manifest_name = f"manifest-{target['goos']}-{target['goarch']}.json"
expected.update((name, manifest_name))
manifest = json.loads((directory / manifest_name).read_text())
if manifest != {'sha': args.sha, 'version': args.version, 'target': target,
'archive': name, 'sha256': sha256(directory / name)}:
raise ValueError(f'build provenance or checksum mismatch: {name}')
if {p.name for p in directory.iterdir()} != expected:
raise ValueError('missing or unexpected release artifacts')
def contexts(args):
verify(args)
for target in targets(args.simple):
if target['goos'] != 'linux':
continue
dest = Path(args.output) / target['goarch']
dest.mkdir(parents=True, exist_ok=True)
with tarfile.open(Path(args.input) / archive_name(args.version, target), 'r:gz') as archive:
members = [member for member in archive.getmembers() if member.name in ('sub2api', './sub2api')]
if len(members) != 1 or not members[0].isfile():
raise ValueError('archive must contain one regular sub2api binary')
with archive.extractfile(members[0]) as source, (dest / 'sub2api').open('wb') as output:
shutil.copyfileobj(source, output)
(dest / 'sub2api').chmod(0o755)
shutil.copy2('Dockerfile.goreleaser', dest / 'Dockerfile')
(dest / 'deploy').mkdir(exist_ok=True)
shutil.copy2('deploy/docker-entrypoint.sh', dest / 'deploy/docker-entrypoint.sh')
shutil.copytree('backend/resources', dest / 'backend/resources', dirs_exist_ok=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
p = commands.add_parser('plan')
p.add_argument('--ref', required=True)
p.add_argument('--simple', action='store_true')
p.add_argument('--dry-run', action='store_true')
p.set_defaults(run=plan)
p = commands.add_parser('config')
p.add_argument('mode', choices=['build', 'publish'])
p.add_argument('--goos')
p.add_argument('--goarch')
p.add_argument('--simple', action='store_true')
p.add_argument('--output', required=True)
p.set_defaults(run=generate_config)
p = commands.add_parser('collect')
for arg in ('version', 'sha', 'goos', 'goarch', 'output'):
p.add_argument('--' + arg, required=True)
p.set_defaults(run=collect)
for command, handler in [('verify', verify), ('contexts', contexts)]:
p = commands.add_parser(command)
for arg in ('version', 'sha', 'input'):
p.add_argument('--' + arg, required=True)
p.add_argument('--simple', action='store_true')
if command == 'contexts':
p.add_argument('--output', required=True)
p.set_defaults(run=handler)
args = parser.parse_args()
args.run(args)
if __name__ == '__main__':
main()
@@ -0,0 +1 @@
PyYAML==6.0.3
@@ -0,0 +1,191 @@
import argparse
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import tarfile
import tempfile
import unittest
from unittest.mock import patch
import yaml
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('release_matrix', Path(__file__).with_name('release_matrix.py'))
release = importlib.util.module_from_spec(spec)
spec.loader.exec_module(release)
class ReleaseMatrixTest(unittest.TestCase):
def setUp(self):
self.previous = Path.cwd()
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
os.chdir(self.temp.name)
self.addCleanup(os.chdir, self.previous)
for name in ('.goreleaser.yaml', '.goreleaser.simple.yaml'):
shutil.copyfile(ROOT / name, name)
Path('backend/cmd/server').mkdir(parents=True)
release.VERSION_FILE.write_text('9.8.7\n')
def fixture_artifacts(self, simple=False):
directory = Path('release-input')
directory.mkdir()
for target in release.targets(simple):
name = release.archive_name('9.8.7', target)
archive = directory / name
if target['goos'] == 'linux':
with tarfile.open(archive, 'w:gz') as out:
info = tarfile.TarInfo('sub2api')
info.size = 7
info.mode = 0o755
out.addfile(info, io.BytesIO(b'fixture'))
else:
archive.write_bytes(b'fixture archive')
metadata = {'version': '9.8.7', 'sha': 'a' * 40, 'target': target,
'archive': name, 'sha256': release.sha256(archive)}
(directory / f"manifest-{target['goos']}-{target['goarch']}.json").write_text(json.dumps(metadata))
return argparse.Namespace(input='release-input', version='9.8.7', sha='a' * 40, simple=simple, output='contexts')
def test_full_and_simple_matrix_match_existing_targets(self):
full = release.targets()
self.assertEqual(len(full), 5)
self.assertNotIn({'goos': 'windows', 'goarch': 'arm64'}, full)
self.assertEqual(release.targets(True), [{'goos': 'linux', 'goarch': 'amd64'}])
def test_leaf_keeps_packaging_and_selects_only_one_target(self):
original = release.config()
release.generate_config(argparse.Namespace(mode='build', simple=False, goos='darwin', goarch='arm64', output='leaf.yaml'))
leaf = yaml.safe_load(Path('leaf.yaml').read_text())
self.assertEqual(leaf['builds'][0]['goos'], ['darwin'])
self.assertEqual(leaf['builds'][0]['goarch'], ['arm64'])
self.assertEqual(leaf['builds'][0]['ignore'], [])
self.assertEqual(leaf['archives'], original['archives'])
self.assertEqual(leaf['release'], original['release'])
self.assertFalse(leaf['dockers'])
self.assertIn('{{ .Env.RELEASE_DATE }}', '\n'.join(leaf['builds'][0]['ldflags']))
def test_publication_config_has_no_compilation_or_docker_work(self):
for simple in (False, True):
with self.subTest(simple=simple):
original = release.config(simple)
release.generate_config(argparse.Namespace(mode='publish', simple=simple, output='publisher.yaml'))
data = yaml.safe_load(Path('publisher.yaml').read_text())
self.assertTrue(data['builds'][0]['skip'])
self.assertFalse(data['archives'])
self.assertFalse(data['dockers'])
self.assertEqual(data['release']['header'], original['release']['header'])
self.assertEqual(data['release']['footer'], original['release']['footer'])
if simple:
self.assertTrue(data['checksum']['disable'])
self.assertTrue(data['release']['skip_upload'])
else:
self.assertEqual(data['checksum']['extra_files'], data['release']['extra_files'])
def test_collect_and_verify_hash_and_source_binding(self):
args = self.fixture_artifacts()
release.verify(args)
file = next(Path(args.input).glob('*.tar.gz'))
file.write_bytes(b'corrupted')
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):
release.verify(args)
def test_missing_extra_and_wrong_commit_artifacts_are_rejected(self):
args = self.fixture_artifacts(True)
args.sha = 'b' * 40
with self.assertRaises(ValueError):
release.verify(args)
args.sha = 'a' * 40
Path('release-input/unexpected').write_text('not an asset')
with self.assertRaises(ValueError):
release.verify(args)
Path('release-input/unexpected').unlink()
next(Path('release-input').glob('*.tar.gz')).unlink()
with self.assertRaises(FileNotFoundError):
release.verify(args)
def test_linux_context_preserves_binary_executable_mode(self):
args = self.fixture_artifacts()
Path('Dockerfile.goreleaser').write_text('FROM scratch\nCOPY sub2api /sub2api\n')
Path('deploy').mkdir()
Path('deploy/docker-entrypoint.sh').write_text('#!/bin/sh\nexec /app/sub2api\n')
Path('backend/resources').mkdir()
Path('backend/resources/data').write_text('fixture')
release.contexts(args)
for arch in ('amd64', 'arm64'):
binary = Path('contexts') / arch / 'sub2api'
self.assertEqual(binary.read_bytes(), b'fixture')
self.assertEqual(binary.stat().st_mode & 0o777, 0o755)
def test_plan_requires_a_tag_for_publication(self):
args = argparse.Namespace(ref='main', dry_run=False, simple=False)
with patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'):
with self.assertRaisesRegex(ValueError, 'version tag'):
release.plan(args)
args.ref = 'v9.8.7'
with patch.object(subprocess, 'check_output', side_effect=['a' * 40 + '\n', 'b' * 40 + '\n']):
with self.assertRaisesRegex(ValueError, 'does not match'):
release.plan(args)
def test_dry_run_plan_resolves_matrix_without_a_new_tag(self):
with patch.dict(os.environ, {'GITHUB_OUTPUT': 'outputs', 'GITHUB_REPOSITORY_OWNER': 'ExampleOwner'}), patch.object(subprocess, 'check_output', return_value='a' * 40 + '\n'):
release.plan(argparse.Namespace(ref='feature/matrix', dry_run=True, simple=False))
output = dict(line.split('=', 1) for line in Path('outputs').read_text().splitlines())
self.assertEqual(output['dry_run'], 'true')
self.assertEqual(output['owner_lower'], 'exampleowner')
self.assertEqual(len(json.loads(output['matrix'])['include']), 5)
def test_docker_commands_do_not_publish_during_dry_run(self):
fake_bin = Path('bin')
fake_bin.mkdir()
docker = fake_bin / 'docker'
docker.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> "$DOCKER_LOG"\n')
docker.chmod(0o755)
env = {**os.environ, 'PATH': str(fake_bin.resolve()) + os.pathsep + os.environ['PATH'],
'DOCKER_LOG': str(Path('docker.log').resolve()), 'RUNNER_TEMP': self.temp.name,
'RELEASE_VERSION': '9.8.7', 'RELEASE_SHA': 'a' * 40, 'GITHUB_REPOSITORY': 'ExampleOwner/sub2api',
'DRY_RUN': 'true', 'SIMPLE_RELEASE': 'false', 'DOCKERHUB_USERNAME': 'skip'}
subprocess.run(['bash', str(ROOT / '.github/release-tools/release-images.sh')], env=env, check=True)
log = Path('docker.log').read_text()
self.assertEqual(log.count('buildx build'), 2)
self.assertIn('linux/arm64', log)
self.assertNotIn('--push', log)
self.assertNotIn('imagetools', log)
self.assertNotIn('skip/sub2api', log)
self.assertIn('ghcr.io/exampleowner/sub2api', log)
def test_published_full_and_simple_image_tags(self):
fake_bin = Path('bin')
fake_bin.mkdir()
docker = fake_bin / 'docker'
docker.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> "$DOCKER_LOG"\n')
docker.chmod(0o755)
for simple in (False, True):
with self.subTest(simple=simple):
log_path = Path(f'docker-{simple}.log').resolve()
env = {**os.environ, 'PATH': str(fake_bin.resolve()) + os.pathsep + os.environ['PATH'],
'DOCKER_LOG': str(log_path), 'RUNNER_TEMP': self.temp.name,
'RELEASE_VERSION': '9.8.7', 'RELEASE_SHA': 'a' * 40, 'GITHUB_REPOSITORY': 'ExampleOwner/sub2api',
'DRY_RUN': 'false', 'SIMPLE_RELEASE': str(simple).lower(), 'DOCKERHUB_USERNAME': 'fixturehub'}
subprocess.run(['bash', str(ROOT / '.github/release-tools/release-images.sh')], env=env, check=True)
log = log_path.read_text()
self.assertIn('--push', log)
self.assertEqual(log.count('buildx build'), 1 if simple else 2)
if simple:
self.assertNotIn('fixturehub', log)
self.assertNotIn('imagetools', log)
self.assertIn('ghcr.io/exampleowner/sub2api:latest', log)
else:
self.assertEqual(log.count('imagetools create'), 2)
self.assertIn('fixturehub/sub2api:9.8', log)
self.assertIn('ghcr.io/exampleowner/sub2api:9', log)
if __name__ == '__main__':
unittest.main()
+17 -4
View File
@@ -25,6 +25,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Check Docker Compose simple mode environment
run: /bin/sh deploy/tests/docker-compose-simple-mode-env-test.sh
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
@@ -33,7 +35,7 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
go version | grep -q 'go1.27.0'
go version | grep -q 'go1.27.4'
- name: Unit tests
working-directory: backend
run: make test-unit
@@ -52,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
@@ -73,10 +75,21 @@ jobs:
cache-dependency-path: backend/go.sum
- name: Verify Go version
run: |
go version | grep -q 'go1.27.0'
go version | grep -q 'go1.27.4'
- name: golangci-lint
uses: golangci/golangci-lint-action@v9
with:
version: v2.13
version: v2.14.0
args: --timeout=30m
working-directory: backend
release-helpers:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- run: python -m pip install -r .github/release-tools/requirements-release.txt
- run: python -m unittest discover -s .github/release-tools -p 'test_release_matrix.py'
- run: bash -n .github/release-tools/release-images.sh
+217 -115
View File
@@ -7,7 +7,7 @@ on:
workflow_dispatch:
inputs:
tag:
description: 'Tag to release (e.g., v1.0.0)'
description: 'Tag to release (or a branch/ref for dry run)'
required: true
type: string
simple_release:
@@ -15,179 +15,286 @@ on:
required: false
type: boolean
default: false
dry_run:
description: 'Build and verify all selected artifacts without publishing'
required: false
type: boolean
default: false
# 环境变量:合并 workflow_dispatch 输入和 repository variable
# tag push 触发时读取 vars.SIMPLE_RELEASE,workflow_dispatch 时使用输入参数
env:
SIMPLE_RELEASE: ${{ github.event.inputs.simple_release == 'true' || vars.SIMPLE_RELEASE == 'true' }}
concurrency:
group: release-${{ github.repository }}
cancel-in-progress: false
permissions:
contents: write
packages: write
contents: read
env:
SIMPLE_RELEASE: ${{ inputs.simple_release == true || vars.SIMPLE_RELEASE == 'true' }}
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run == true }}
jobs:
# Update VERSION file with tag version
update-version:
prepare:
runs-on: ubuntu-latest
outputs:
sha: ${{ steps.plan.outputs.sha }}
owner_lower: ${{ steps.plan.outputs.owner_lower }}
tag: ${{ steps.plan.outputs.tag }}
version: ${{ steps.plan.outputs.version }}
date: ${{ steps.plan.outputs.date }}
matrix: ${{ steps.plan.outputs.matrix }}
simple: ${{ steps.plan.outputs.simple }}
dry_run: ${{ steps.plan.outputs.dry_run }}
steps:
- name: Checkout
- name: Checkout workflow tooling
uses: actions/checkout@v6
- name: Update VERSION file
with:
ref: ${{ github.sha }}
- name: Preserve tooling for releases of older tags
run: cp -R .github/release-tools "$RUNNER_TEMP/release-tools"
- name: Checkout selected application source
uses: actions/checkout@v6
with:
ref: ${{ inputs.tag || github.ref }}
fetch-depth: 0
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- run: python -m pip install -r "$RUNNER_TEMP/release-tools/requirements-release.txt"
- name: Resolve one source commit and target matrix
id: plan
env:
REQUESTED_REF: ${{ inputs.tag || github.ref_name }}
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
VERSION=${{ github.event.inputs.tag }}
VERSION=${VERSION#v}
else
VERSION=${GITHUB_REF#refs/tags/v}
fi
echo "$VERSION" > backend/cmd/server/VERSION
echo "Updated VERSION file to: $VERSION"
- name: Upload VERSION artifact
uses: actions/upload-artifact@v7
args=(--ref "$REQUESTED_REF")
if [[ "$SIMPLE_RELEASE" == true ]]; then args+=(--simple); fi
if [[ "$DRY_RUN" == true ]]; then args+=(--dry-run); fi
python "$RUNNER_TEMP/release-tools/release_matrix.py" plan "${args[@]}"
- uses: actions/upload-artifact@v7
with:
name: release-tooling
path: ${{ runner.temp }}/release-tools/
retention-days: 1
- uses: actions/upload-artifact@v7
with:
name: version-file
path: backend/cmd/server/VERSION
retention-days: 1
build-frontend:
needs: prepare
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup pnpm
uses: pnpm/action-setup@v6
- uses: actions/checkout@v6
with:
ref: ${{ needs.prepare.outputs.sha }}
- uses: pnpm/action-setup@v6
with:
version: 9
- name: Setup Node.js
uses: actions/setup-node@v6
- uses: actions/setup-node@v6
with:
node-version: '20'
cache: 'pnpm'
node-version: '24'
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Install dependencies
run: pnpm install --frozen-lockfile
- run: pnpm install --frozen-lockfile
working-directory: frontend
- name: Build frontend
run: pnpm run build
- run: pnpm run build
working-directory: frontend
- name: Upload frontend artifact
uses: actions/upload-artifact@v7
- uses: actions/upload-artifact@v7
with:
name: frontend-dist
path: backend/internal/web/dist/
retention-days: 1
release:
needs: [update-version, build-frontend]
build-binaries:
needs: [prepare, build-frontend]
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.prepare.outputs.matrix) }}
env:
RELEASE_VERSION: ${{ needs.prepare.outputs.version }}
RELEASE_DATE: ${{ needs.prepare.outputs.date }}
steps:
- name: Checkout
uses: actions/checkout@v6
- uses: actions/checkout@v6
with:
ref: ${{ needs.prepare.outputs.sha }}
fetch-depth: 0
ref: ${{ github.event.inputs.tag || github.ref }}
- name: Download VERSION artifact
uses: actions/download-artifact@v8
- uses: actions/download-artifact@v8
with:
name: release-tooling
path: ${{ runner.temp }}/release-tools/
- uses: actions/download-artifact@v8
with:
name: version-file
path: backend/cmd/server/
- name: Download frontend artifact
uses: actions/download-artifact@v8
- uses: actions/download-artifact@v8
with:
name: frontend-dist
path: backend/internal/web/dist/
- name: Setup Go
uses: actions/setup-go@v6
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
check-latest: false
cache-dependency-path: backend/go.sum
cache: false
- name: Verify Go version
run: |
go version | grep -q 'go1.27.0'
run: go version | grep -q 'go1.27.4'
- name: Restore target-specific Go cache
id: go-cache
uses: actions/cache/restore@v6
with:
path: |
~/go/pkg/mod
~/.cache/go-build
key: release-go-${{ runner.os }}-${{ runner.arch }}-${{ matrix.goos }}-${{ matrix.goarch }}-${{ hashFiles('backend/go.mod', 'backend/go.sum') }}-${{ needs.prepare.outputs.sha }}
restore-keys: |
release-go-${{ runner.os }}-${{ runner.arch }}-${{ matrix.goos }}-${{ matrix.goarch }}-${{ hashFiles('backend/go.mod', 'backend/go.sum') }}-
release-go-${{ runner.os }}-${{ runner.arch }}-${{ matrix.goos }}-${{ matrix.goarch }}-
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- run: python -m pip install -r "$RUNNER_TEMP/release-tools/requirements-release.txt"
- name: Select one GoReleaser target
env:
TARGET_OS: ${{ matrix.goos }}
TARGET_ARCH: ${{ matrix.goarch }}
run: python "$RUNNER_TEMP/release-tools/release_matrix.py" config build --goos "$TARGET_OS" --goarch "$TARGET_ARCH" --output "$RUNNER_TEMP/goreleaser.matrix.yaml"
- name: Build and archive without publishing
uses: goreleaser/goreleaser-action@v7
with:
version: '~> v2'
args: release --snapshot --clean --skip=validate,publish,docker,announce --config=${{ runner.temp }}/goreleaser.matrix.yaml
env:
GITHUB_REPO_OWNER: ${{ github.repository_owner }}
GITHUB_REPO_OWNER_LOWER: ${{ needs.prepare.outputs.owner_lower }}
GITHUB_REPO_NAME: ${{ github.event.repository.name }}
DOCKERHUB_USERNAME: skip
TAG_MESSAGE: ''
- name: Verify and collect the target archive
env:
TARGET_OS: ${{ matrix.goos }}
TARGET_ARCH: ${{ matrix.goarch }}
RELEASE_SHA: ${{ needs.prepare.outputs.sha }}
run: python "$RUNNER_TEMP/release-tools/release_matrix.py" collect --version "$RELEASE_VERSION" --sha "$RELEASE_SHA" --goos "$TARGET_OS" --goarch "$TARGET_ARCH" --output matrix-output
- uses: actions/upload-artifact@v7
with:
name: release-binary-${{ matrix.goos }}-${{ matrix.goarch }}
path: matrix-output/
if-no-files-found: error
retention-days: 1
- name: Save updated target cache
if: ${{ steps.go-cache.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v6
with:
path: |
~/go/pkg/mod
~/.cache/go-build
key: ${{ steps.go-cache.outputs.cache-primary-key }}
# Docker setup for GoReleaser
release:
needs: [prepare, build-binaries]
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
env:
SIMPLE_RELEASE: ${{ needs.prepare.outputs.simple }}
DRY_RUN: ${{ needs.prepare.outputs.dry_run }}
RELEASE_TAG: ${{ needs.prepare.outputs.tag }}
RELEASE_VERSION: ${{ needs.prepare.outputs.version }}
RELEASE_SHA: ${{ needs.prepare.outputs.sha }}
steps:
- uses: actions/checkout@v6
with:
ref: ${{ needs.prepare.outputs.sha }}
fetch-depth: 0
- uses: actions/download-artifact@v8
with:
name: release-tooling
path: ${{ runner.temp }}/release-tools/
- uses: actions/download-artifact@v8
with:
pattern: release-binary-*
path: release-input
merge-multiple: true
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- run: python -m pip install -r "$RUNNER_TEMP/release-tools/requirements-release.txt"
- name: Verify complete matrix and prepare Docker contexts
run: |
args=(--version "$RELEASE_VERSION" --sha "$RELEASE_SHA" --input release-input --output .release-context)
if [[ "$SIMPLE_RELEASE" == true ]]; then args+=(--simple); fi
python "$RUNNER_TEMP/release-tools/release_matrix.py" contexts "${args[@]}"
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache: false
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
if: ${{ env.DOCKERHUB_USERNAME != '' }}
if: ${{ env.DRY_RUN != 'true' && env.SIMPLE_RELEASE != 'true' && env.DOCKERHUB_USERNAME != '' }}
uses: docker/login-action@v3
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
if: ${{ env.DRY_RUN != 'true' }}
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Fetch tags with annotations
run: |
# 确保获取完整的 annotated tag 信息
git fetch --tags --force
- name: Get tag message
- name: Build images and publish manifests
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME || 'skip' }}
run: bash "$RUNNER_TEMP/release-tools/release-images.sh"
- name: Get annotated tag notes
id: tag_message
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
TAG_NAME=${{ github.event.inputs.tag }}
else
TAG_NAME=${GITHUB_REF#refs/tags/}
fi
echo "Processing tag: $TAG_NAME"
# 获取完整的 tag message(跳过第一行标题)
TAG_MESSAGE=$(git tag -l --format='%(contents:body)' "$TAG_NAME")
# 调试输出
echo "Tag message length: ${#TAG_MESSAGE}"
echo "Tag message preview:"
echo "$TAG_MESSAGE" | head -10
# 使用 EOF 分隔符处理多行内容
echo "message<<EOF" >> $GITHUB_OUTPUT
echo "$TAG_MESSAGE" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Set lowercase owner for GHCR
id: lowercase
run: echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_OUTPUT
- name: Run GoReleaser
TAG_MESSAGE=$(git tag -l --format='%(contents:body)' "$RELEASE_TAG")
DELIMITER="TAG_MESSAGE_$(openssl rand -hex 16)"
{
echo "message<<$DELIMITER"
echo "$TAG_MESSAGE"
echo "$DELIMITER"
} >> "$GITHUB_OUTPUT"
- name: Prepare publication-only GoReleaser config
run: |
args=(publish --output "$RUNNER_TEMP/goreleaser.publisher.yaml")
if [[ "$SIMPLE_RELEASE" == true ]]; then args+=(--simple); fi
python "$RUNNER_TEMP/release-tools/release_matrix.py" config "${args[@]}"
- name: Publish existing archives and release notes
uses: goreleaser/goreleaser-action@v7
with:
version: '~> v2'
args: release --clean --skip=validate ${{ env.SIMPLE_RELEASE == 'true' && '--config=.goreleaser.simple.yaml' || '' }}
args: release --clean --skip=validate,before,docker ${{ env.DRY_RUN == 'true' && '--snapshot --skip=publish,announce' || '' }} --config=${{ runner.temp }}/goreleaser.publisher.yaml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GORELEASER_CURRENT_TAG: ${{ needs.prepare.outputs.tag }}
TAG_MESSAGE: ${{ steps.tag_message.outputs.message }}
GITHUB_REPO_OWNER: ${{ github.repository_owner }}
GITHUB_REPO_OWNER_LOWER: ${{ steps.lowercase.outputs.owner }}
GITHUB_REPO_NAME: ${{ github.event.repository.name }}
GITHUB_REPO_OWNER_LOWER: ${{ needs.prepare.outputs.owner_lower }}
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME || 'skip' }}
- name: Upload dry-run checksums and metadata
if: ${{ env.DRY_RUN == 'true' }}
uses: actions/upload-artifact@v7
with:
name: release-dry-run-report
path: |
dist/checksums.txt
dist/artifacts.json
dist/metadata.json
if-no-files-found: error
retention-days: 3
# Update DockerHub description
- name: Update DockerHub description
if: ${{ env.SIMPLE_RELEASE != 'true' && env.DOCKERHUB_USERNAME != '' }}
if: ${{ env.DRY_RUN != 'true' && env.SIMPLE_RELEASE != 'true' && env.DOCKERHUB_USERNAME != '' }}
uses: peter-evans/dockerhub-description@v5
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
@@ -200,8 +307,9 @@ jobs:
# Send Telegram notification
- name: Send Telegram Notification
if: ${{ env.SIMPLE_RELEASE != 'true' }}
if: ${{ env.DRY_RUN != 'true' && env.SIMPLE_RELEASE != 'true' }}
env:
TAG_MESSAGE: ${{ steps.tag_message.outputs.message }}
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
@@ -213,17 +321,12 @@ jobs:
exit 0
fi
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
TAG_NAME=${{ github.event.inputs.tag }}
else
TAG_NAME=${GITHUB_REF#refs/tags/}
fi
TAG_NAME="$RELEASE_TAG"
VERSION=${TAG_NAME#v}
REPO="${{ github.repository }}"
GHCR_IMAGE="ghcr.io/${REPO,,}" # ${,,} converts to lowercase
# 获取 tag message 内容并转义 Markdown 特殊字符
TAG_MESSAGE='${{ steps.tag_message.outputs.message }}'
TAG_MESSAGE=$(echo "$TAG_MESSAGE" | sed 's/\([_*`\[]\)/\\\1/g')
# 限制消息长度(Telegram 消息限制 4096 字符,预留空间给头尾固定内容)
@@ -273,9 +376,13 @@ jobs:
}')"
sync-version-file:
needs: [release]
if: ${{ needs.release.result == 'success' }}
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
@@ -284,12 +391,7 @@ jobs:
- name: Sync VERSION file to released tag
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
VERSION=${{ github.event.inputs.tag }}
VERSION=${VERSION#v}
else
VERSION=${GITHUB_REF#refs/tags/v}
fi
VERSION="$RELEASE_VERSION"
CURRENT_VERSION=$(tr -d '\r\n' < backend/cmd/server/VERSION || true)
if [ "$CURRENT_VERSION" = "$VERSION" ]; then
+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.0'
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
+9
View File
@@ -133,25 +133,34 @@ 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
!docs/channel-monitor-v2-safe-defaults.md
!docs/codex-credits.md
!docs/legal/
!docs/legal/*.md
!docs/screenshots/
docs/screenshots/*
!docs/screenshots/mobile-account-actions-menu.png
!docs/screenshots/codex-referral-dialog.png
!docs/screenshots/codex-referral-success.png
.serena/
.codex/
frontend/coverage/
aicodex
output/
.codegraph/
issues/
# Vitest / Vite cache at repo root
.vite/
+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.0-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
+18 -1
View File
@@ -4,6 +4,21 @@ FRONTEND_CRITICAL_VITEST := \
src/i18n/__tests__/localeKeyCompleteness.spec.ts \
src/api/__tests__/client.spec.ts \
src/api/__tests__/tokenRefresh.spec.ts \
src/api/__tests__/keys.bulkUpdate.spec.ts \
src/composables/__tests__/useModelWhitelist.spec.ts \
src/components/account/__tests__/OpenAIReferralCell.spec.ts \
src/components/account/__tests__/OpenAIReferralCell.transport.spec.ts \
src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \
src/constants/__tests__/platforms.spec.ts \
src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \
src/components/account/__tests__/CNProviderQuotaCell.spec.ts \
src/components/account/__tests__/CreateAccountModal.spec.ts \
src/components/account/__tests__/EditAccountModal.spec.ts \
src/components/account/__tests__/credentialsBuilder.spec.ts \
src/components/account/__tests__/OpenCodeGoProtocolRulesEditor.spec.ts \
src/components/keys/__tests__/BulkEditKeysModal.spec.ts \
src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts \
src/views/user/__tests__/KeysView.spec.ts \
src/api/__tests__/channelMonitorV2.spec.ts \
src/views/auth/__tests__/LinuxDoCallbackView.spec.ts \
src/views/auth/__tests__/WechatCallbackView.spec.ts \
@@ -11,10 +26,12 @@ FRONTEND_CRITICAL_VITEST := \
src/views/user/__tests__/PaymentResultView.spec.ts \
src/views/user/__tests__/ChannelStatusView.mode.spec.ts \
src/components/user/profile/__tests__/ProfileInfoCard.spec.ts \
src/components/user/profile/__tests__/ProfileIdentityBindingsSection.spec.ts \
src/views/admin/__tests__/SettingsView.spec.ts \
src/features/channel-monitor-v2/__tests__/designSystem.structure.spec.ts \
src/features/channel-monitor-v2/__tests__/monitorFormat.spec.ts \
src/features/channel-monitor-v2/__tests__/monitorZoom.spec.ts
src/features/channel-monitor-v2/__tests__/monitorZoom.spec.ts \
src/components/admin/channel/__tests__/PricingEntryCard.modelDefaultPrice.spec.ts
# 一键编译前后端
build: build-backend build-frontend
+111 -48
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>
@@ -49,13 +60,13 @@ Please read the following carefully before using this project:
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
<td>Thanks to APIKEY.FUN for sponsoring this project! <a href="https://apikey.fun/register?aff=SUB2API">APIKEY.FUN</a> is one of the core contributors to the sub2api open-source project, dedicated to providing open, stable, and cost-effective AI API access. The platform supports API relay services for Claude, OpenAI, Gemini, and other popular models, with pricing starting from as low as 7% of the original rate. Register via the exclusive link: <a href="https://apikey.fun/register?aff=SUB2API">APIKEY</a> to enjoy up to 5% off on all recharges.</td>
<td width="180"><a href="https://apikey.fan/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
<td>Thanks to APIKEY.FUN for sponsoring this project! <a href="https://apikey.fan/register?aff=SUB2API">APIKEY.FUN</a> is one of the core contributors to the sub2api open-source project, dedicated to providing open, stable, and cost-effective AI API access. The platform supports API relay services for Claude, OpenAI, Gemini, and other popular models, with pricing starting from as low as 7% of the original rate. Register via the exclusive link: <a href="https://apikey.fan/register?aff=SUB2API">APIKEY</a> to enjoy up to 5% off on all recharges.</td>
</tr>
<tr>
<td width="180"><a href="https://aigocode.com/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://aigocode.com/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>
@@ -63,11 +74,6 @@ Please read the following carefully before using this project:
<td>Real GPT-5.6 series at 3% of OpenAI pricing — <a href="https://codex-everywhere.com">CodexEverywhere</a> is democratizing access to frontier models for developers worldwide. We believe in transparency and honesty, with model quality verified by active community oversight for months. USD and crypto friendly. Start with a free $20 trial at <a href="https://codex-everywhere.com">codex-everywhere.com</a>.</td>
</tr>
<tr>
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
<td>Huge thanks to BmoPlus for sponsoring this project! BmoPlus is a highly reliable AI account provider built strictly for heavy AI users and developers. They offer rock-solid, ready-to-use accounts and official top-up services for ChatGPT Plus / ChatGPT Pro (Full Warranty) / Claude Pro / Super Grok / Gemini Pro. By registering and ordering through <a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus - Premium AI Accounts & Top-ups</a>, users can unlock the mind-blowing rate of 10% of the official GPT subscription price (90% OFF)</td>
</tr>
<tr>
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
<td>Thanks to Bestproxy for sponsoring this project! <a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> provides high-purity residential IPs with dedicated one-IP-per-account support. By combining real home networks with fingerprint isolation, it enables link environment isolation and reduces the probability of association-based risk control.</td>
@@ -96,26 +102,6 @@ Please read the following carefully before using this project:
</td>
</tr>
<tr>
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
<td>Thanks to Proxy4Free for sponsoring this project! Proxy4Free is a data proxy service provider for developers and AI applications, offering residential proxies, static residential proxies, ISP proxies, and datacenter proxies for scenarios such as Web Scraping, Browser Automation, and AI Agents. With global IP resources, stable connections, and flexible switching, it helps developers improve data collection success rates and reduce the risk of IP bans. Register via <a href="https://www.proxy4free.com/?keyword=4yjqecpc">this link</a> to get started and easily build more stable and efficient automation workflows.
</td>
</tr>
<tr>
<td width="180"><a href="http://www.fastaitoken.com/register"><img src="assets/partners/logos/fastaitoken.jpg" alt="fastaitoken" width="150"></a></td>
<td>🎉 Thanks to FastAIToken for sponsoring this project! <a href="http://www.fastaitoken.com/register">FastAIToken</a> is an AI API aggregation platform for developers, supporting mainstream large models such as OpenAI, Claude, and Gemini. Top-up at 1:1 — 1 CNY = 1 USD of API credit — letting developers use the world's leading large model services at lower cost and with greater convenience.<br>
🚀 The platform offers a variety of channels to choose from: an ultra-low-price 0.02x OpenAI promotional group (limited time), groups as low as 0.25x OpenAI, 0.7x Claude with 95% fixed cache, and a 1.2x Claude Max channel. It also provides a public status page showing real-time availability, latency, and operating status of each group for transparent and reliable service, plus 7×24 human technical support (not bots) with fast responses to developer needs.
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>Thanks to Aimzoon for sponsoring this project! <a href="http://aimzoon.com">Aimzoon</a> provides stable, cost-effective AI API access services, enabling developers to quickly connect popular AI services to coding tools such as Codex, Claude Code, and Gemini CLI. No complex configuration — faster onboarding, more stable calls, and lower costs. Ongoing promotions including discounted Codex rates and special pricing, with free trial credits upon registration, bringing AI coding into your daily workflow. <a href="http://aimzoon.com">Click here</a> to register and try it out!
</td>
</tr>
<tr>
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
<td><a href="https://nagora.ai/">Nagora</a> is a multi-model AI API gateway built for developers and teams. With a single account and API key, you can access more than 26 leading text and image models through one unified interface. It is compatible with OpenAI, Anthropic, and Gemini protocols and integrates seamlessly with development tools such as Claude Code, Codex, and Gemini CLI. The platform provides intelligent routing, automatic failover, transparent pricing, and consolidated billing, along with budget management, rate limiting, and concurrency controls. This makes AI usage more reliable and manageable across individual development, team collaboration, and production environments. No changes to your existing application are required. Simply replace the Base URL and API key to complete the integration in as little as one minute.</td>
@@ -131,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>
@@ -151,23 +132,65 @@ Please read the following carefully before using this project:
<td>Swiftproxy is a high-performance proxy solution built for developers, providing stable and reliable residential and static residential proxy services. With 90M+ clean residential IPs, global coverage, flexible rotation, and precise geo-targeting, it helps projects such as web scraping, AI automation, browser automation, SEO monitoring, and multi-account management overcome access restrictions and improve workflow efficiency. It supports HTTP(S) and SOCKS5 protocols, integrates with popular automation tools like Playwright, Selenium, and Puppeteer, with dynamic proxy traffic that never expires until used and free testing available — <a href="https://www.swiftproxy.net/?ref=sub2api">start your free test now</a>!</td>
</tr>
<tr>
<td width="180"><a href="https://www.duckip.cn/?keyword=cu7oog6y"><img src="assets/partners/logos/duckip.png" alt="DuckIP" width="150"></a></td>
<td><a href="https://www.duckip.cn/?keyword=cu7oog6y">DuckIP</a> - 90M+ global residential network resources across 195+ countries and regions, with rotation and sticky sessions for public data collection, RAG updates, model evaluation, and multi-region data workloads. 🟢Residential Proxy - 20% Off; 🟢Static Residential Proxy - Starting at ¥50.00/IP; 🟢Unlimited Residential Proxy - Starting at ¥19.8/Hour. ✅Get 500M Free Trial.</td>
</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>
</tr>
<tr>
<td width="180"><a href="https://pp.dog/register?aff=SUB2API"><img src="assets/partners/logos/ppdog.png" alt="PP.dog" width="150"></a></td>
<td><a href="https://pp.dog/register?aff=SUB2API">PP.dog</a> is a source-level API gateway with its own massive account pool, purpose-built as an upstream relay for downstream transit stations and high-frequency developers — saving you the hassle of building and maintaining your own account pool. ✅ Direct from source: self-operated account pool with no middleman markup; 🧧 Cost crusher: combined rate multiplier as low as 0.03x, just 0.35% of official pricing; 🚀 Blazing fast: first-token latency < 1s, on par with the official native API. <a href="https://www.pp.dog/register?aff=SUB2API">Get started with PP.dog now</a></td>
</tr>
<tr>
<td width="180"><a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/cola-proxy.jpg" alt="ColaProxy" width="150"></a></td>
<td>ColaProxy provides high-quality residential proxies built for web scraping, automation, and multi-account management. Get a free trial with non-expiring traffic, pricing starting as low as $0.3/GB, unlimited concurrent connections, and intelligent IP rotation for a smoother, more stable proxy experience. Use discount code COLA10 to get 10% off and start scaling your projects with reliable residential proxies today. <a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">Get started with ColaProxy</a></td>
</tr>
<tr>
<td width="180"><a href="https://modelflare.dev/sign-up?utm_source=github&utm_campaign=sub2api"><img src="assets/partners/logos/modelflare.png" alt="Modelflare" width="150"></a></td>
<td>Modelflare: Full strength, stable, nothing watered down. Global SOTA models at a lower cost. Operated by US-based Havenbyte LLC, Modelflare supports GPT, Claude, Gemini, Grok, and other leading models through common compatible protocols, plus 40+ image and video models. Cache compensation is a highlight: selected OpenAI groups (price-first, stable, and premium) guarantee daily cache hit rates of 65%, 75%, or 85%, and if eligible requests fall short, Modelflare refunds the difference, visible on the usage dashboard after settlement. Special offers: a single top-up of US$20 unlocks the GPT discount group at a 0.015x price multiplier, and a single top-up of US$50 unlocks the Claude discount group at a 0.03x multiplier. Register via <a href="https://modelflare.dev/sign-up?utm_source=github&utm_campaign=sub2api">this exclusive link</a> to get started.</td>
</tr>
<tr>
<td width="180"><a href="https://x.com/chenju_ai"><img src="assets/partners/logos/chenju_ai.png" alt="Chenju" width="150"></a></td>
<td>Thanks to <a href="https://x.com/chenju_ai">Chenju</a> for sponsoring this project! This is probably the only ad slot in this section that doesn't ask you to sign up for anything. Good open-source projects deserve to be paid for, so Chenju is chipping in a gift and raising a glass to the author. Find <a href="https://x.com/chenju_ai">Chenju</a> on X to chat about API relays, upstream providers, or just shoot the breeze.</td>
</tr>
<tr>
<td width="180"><a href="https://t.me/AACC8888888"><img src="assets/partners/logos/ooko.ai.png" alt="ooko.ai" width="150"></a></td>
<td>🔑 Buying AI accounts at top prices | Gemini · Claude · GPT | Main and alt accounts all welcome, any channel wanted | Pay-per-usage supported | Seeking first-hand resources from major providers, I'll bring the KEY.<br>WeChat: Liuyou-zawd | Telegram: <a href="https://t.me/AACC8888888">AACC8888888</a></td>
</tr>
<tr>
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> provides affordable global proxy solutions for web scraping, AI agents, automation, and data collection. With residential proxies starting at $0.35/GB across 190+ countries and regions, NiuProxy offers flexible plans and HTTP(S)/SOCKS5 support.<br>🎁 Use code PAY2 for 10% OFF your recharge!</td>
</tr>
<tr>
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
<td>Thanks to <a href="https://soleapi.com/r/sub2api">SoleAPI</a> for supporting this project! SoleAPI is an AI model gateway for developers and enterprises: one API key gives you access to 30+ leading models including Claude, GPT and Gemini. It is natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex, Cursor and your existing SDKs work by simply changing the Base URL. Requests are routed in real time by latency and upstream health, with millisecond-level automatic failover to backup channels, 99.99% service availability and 24/7 technical support. Every call lands on a single bill with per-request token and cost breakdowns you can inspect at any time. Sign up through this project's <a href="https://soleapi.com/r/sub2api">referral link</a> to receive free trial credits, and earn ongoing cashback by inviting friends who top up!</td>
</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.
@@ -352,8 +375,10 @@ JWT_SECRET=your_jwt_secret_here
TOTP_ENCRYPTION_KEY=your_totp_key_here
# Optional: Admin account
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=your_admin_password
# Leave empty to auto-generate a random email (login username) and password, shown in logs on first startup.
# Avoid guessable values such as admin@example.com: they are brute-force targets.
ADMIN_EMAIL=
ADMIN_PASSWORD=
# Optional: Custom port
SERVER_PORT=8080
@@ -402,9 +427,9 @@ docker compose -f docker-compose.local.yml logs -f sub2api
Open `http://YOUR_SERVER_IP:8080` in your browser.
If admin password was auto-generated, find it in logs:
If the admin email (login username) or password was auto-generated, find them in logs:
```bash
docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
docker compose -f docker-compose.local.yml logs sub2api | grep "Generated admin"
```
#### Upgrade
@@ -723,11 +748,24 @@ go generate ./cmd/server
Simple Mode is designed for individual developers or internal teams who want quick access without full SaaS features.
- Enable: Set environment variable `RUN_MODE=simple`
- Default groups are seeded on each startup. Set `SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=false` (or YAML `simple_mode.auto_create_default_groups: false`) to manage groups yourself. The default is `true`; disabling it does not delete existing groups or change runtime auto-binding or admin concurrency setup.
- Difference: Hides SaaS-related features and skips billing process
- Optional key windows: Set `SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=true` to enforce each API key's configured 5-hour, daily, and 7-day spending windows. The default is `false`; balance and subscription debit remain bypassed when enabled.
- Window enforcement uses the database as its source of truth and records only API-key window usage. It is a post-request soft cap, so concurrent in-flight requests can overshoot by their final costs. Historical simple-mode usage is not backfilled.
- Security note: In production, you must also set `SIMPLE_MODE_CONFIRM=true` to allow startup
---
## 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.
@@ -822,6 +860,31 @@ Administrators can override automatic media eligibility through the account crea
---
## TypeSafe / Jev Support
Sub2API supports TypeSafe API-key accounts through Jev's native, non-streaming System One protocol.
- Platform: `typesafe`; account type: API Key
- Default upstream: `https://api.typesafe.ai`
- Public endpoint: `POST /v1/systemone`
- Model: `jev-latest`, also returned by `/v1/models` for TypeSafe groups
- Questions: `noul`, `choice`, and `score`
Requests and successful responses retain the native System One JSON structure. This endpoint is not compatible with Chat Completions, Responses, Anthropic Messages, or streaming clients.
Question validation follows the TypeSafe OpenAPI wire schema (also used by SDK v0.5.7). `instructions` may be omitted or `null` for all question types. Noul `criteria` may be omitted or `null`; its `true`/`false` descriptions and Choice descriptions accept strings, objects, arrays, or `null`. Score `criteria` must be a non-empty array of string, object, or array descriptions; a single level is valid. SDK integer-keyed Score maps are normalized to arrays by the SDK before sending.
```bash
curl https://your-sub2api.example.com/v1/systemone \
-H 'Authorization: Bearer sk-your-sub2api-key' \
-H 'Content-Type: application/json' \
--data '{"model":"jev-latest","state":"Text to evaluate","questions":{"safety":{"type":"noul","instructions":"Evaluate whether the text is unsafe"}}}'
```
The built-in `jev-latest` price is `$0.042` per million input tokens and `$0` for output tokens. Channel pricing can override both values. Credential, billing, permission, rate-limit, overload, server, and network failures (`401`, `402`, `403`, `429`, `529`, `5xx`, transport errors) use the existing account error policy (including custom error codes and temporary-unschedulable rules) and fail over to another account; request errors (`400`, `413`, and `422`) are returned without retrying another account and never change account state. TypeSafe groups (and Composite requests routed to TypeSafe) reject Messages, Chat Completions, Responses, and count_tokens requests with `404`.
---
## Antigravity Support
Sub2API supports [Antigravity](https://antigravity.so/) accounts. After authorization, dedicated endpoints are available for Claude and Gemini models.
+139 -48
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>
@@ -50,13 +61,13 @@
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
<td>感谢 APIKEY.FUN 赞助了本项目!<a href="https://apikey.fun/register?aff=SUB2API">APIKEY.FUN</a> 是 sub2api 开源项目的核心贡献者之一,致力于提供开放、稳定、高性价比的 AI API 接入服务。平台支持 Claude、OpenAI、Gemini 等热门模型的 API 中转服务,价格低至官方原价的 7%。通过专属链接 <a href="https://apikey.fun/register?aff=SUB2API">APIKEY</a> 注册,可享受充值最高 95 折优惠。</td>
<td width="180"><a href="https://apikey.fan/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
<td>感谢 APIKEY.FUN 赞助了本项目!<a href="https://apikey.fan/register?aff=SUB2API">APIKEY.FUN</a> 是 sub2api 开源项目的核心贡献者之一,致力于提供开放、稳定、高性价比的 AI API 接入服务。平台支持 Claude、OpenAI、Gemini 等热门模型的 API 中转服务,价格低至官方原价的 7%。通过专属链接 <a href="https://apikey.fan/register?aff=SUB2API">APIKEY</a> 注册,可享受充值最高 95 折优惠。</td>
</tr>
<tr>
<td width="180"><a href="https://aigocode.com/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://aigocode.com/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>
@@ -64,11 +75,6 @@
<td>Real GPT-5.6 series at 3% of OpenAI pricing — <a href="https://codex-everywhere.com">CodexEverywhere</a> is democratizing access to frontier models for developers worldwide. We believe in transparency and honesty, with model quality verified by active community oversight for months. USD and crypto friendly. Start with a free $20 trial at <a href="https://codex-everywhere.com">codex-everywhere.com</a>.</td>
</tr>
<tr>
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
<td>感谢 BmoPlus 赞助了本项目!BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AI成品号专卖/代充</a>注册下单的用户,可享GPT 官网订阅一折 的震撼价格!</td>
</tr>
<tr>
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
<td>感谢 Bestproxy 赞助了本项目!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> 是一家提供高纯度住宅IP,支持一号一IP独享,结合真实家庭网络与指纹隔离,可实现链路环境隔离,降低关联风控概率。</td>
@@ -99,26 +105,6 @@
</td>
</tr>
<tr>
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
<td>感谢 Proxy4Free 赞助本项目!Proxy4Free 是面向开发者和 AI 应用的数据代理服务商,提供住宅代理、静态住宅代理、ISP 代理及数据中心代理等多种代理解决方案,适用于 Web Scraping、Browser Automation、AI Agent 等场景。支持全球 IP 资源、稳定连接与灵活切换,帮助开发者提升数据采集成功率,降低 IP 封禁风险。通过<a href="https://www.proxy4free.com/?keyword=4yjqecpc">此链接注册</a>即可开始体验,轻松构建更稳定、高效的自动化工作流。
</td>
</tr>
<tr>
<td width="180"><a href="http://www.fastaitoken.com/register"><img src="assets/partners/logos/fastaitoken.jpg" alt="fastaitoken" width="150"></a></td>
<td>🎉 感谢 FastAIToken 对本项目的赞助! <a href="http://www.fastaitoken.com/register">FastAIToken</a> 是面向开发者的 AI API 聚合平台,支持 OpenAI、Claude、Gemini 等主流大模型,充值 1:1,1 元 = 1 美元 API 额度,让开发者以更低成本、更便捷地使用全球领先的大模型服务。<br>
🚀 平台提供多种渠道自由选择:超级低价的0.02x OpenAI 福利分组(限时)、低至 0.25x OpenAI 分组、0.7x Claude 95%固定缓存、1.2x Claude Max 渠道;同时提供公开状态页,实时展示各分组的可用率、延迟及运行状态,服务透明可靠,并提供 7×24 小时真人技术支持(非机器人),快速响应开发者需求。
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>感谢 Aimzoon 对本项目的赞助! <a href="http://aimzoon.com">Aimzoon</a> 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。<a href="http://aimzoon.com">点击这里</a>注册体验!
</td>
</tr>
<tr>
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
<td><a href="https://nagora.ai/">Nagora</a> 是专为开发者和团队打造的多模型 AI API 网关。通过一个账户和一枚 API Key,即可统一调用 26+ 款主流文本与图像模型,兼容 OpenAI、Anthropic 与 Gemini 协议,并可无缝接入 Claude Code、Codex、Gemini CLI 等开发工具。平台提供智能路由、自动故障转移、透明计费与统一账单,同时支持预算、限速、并发控制,让个人开发、团队协作和生产环境中的 AI 调用更稳定、更可控。无需改造现有应用,只需替换 Base URL 与 API Key,最快 1 分钟即可完成接入。</td>
@@ -134,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>
@@ -154,23 +135,65 @@
<td>Swiftproxy 是面向开发者的高性能代理解决方案,提供稳定可靠的住宅代理和静态住宅代理服务。拥有 9000 万+ 纯净住宅 IP,覆盖全球,支持灵活轮换和精准地理定位,帮助网页抓取、AI 自动化、浏览器自动化、SEO 监控和多账号管理等项目突破访问限制,提升工作流效率。支持 HTTP(S) 和 SOCKS5 协议,兼容 Playwright、Selenium、Puppeteer 等主流自动化工具,动态代理流量用完为止永不过期,支持免费测试 — <a href="https://www.swiftproxy.net/?ref=sub2api">立即开始免费测试</a>!</td>
</tr>
<tr>
<td width="180"><a href="https://www.duckip.cn/?keyword=cu7oog6y"><img src="assets/partners/logos/duckip.png" alt="DuckIP" width="150"></a></td>
<td><a href="https://www.duckip.cn/?keyword=cu7oog6y">DuckIP</a> - 9000 万+ 全球住宅网络资源,覆盖 195+ 国家和地区,支持轮换和粘性会话,适用于公共数据采集、RAG 更新、模型评估和多区域数据工作负载。🟢住宅代理 - 8 折优惠;🟢静态住宅代理 - ¥50.00/IP 起;🟢无限住宅代理 - ¥19.8/小时 起。✅免费领取 500M 试用流量。</td>
</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>
</tr>
<tr>
<td width="180"><a href="https://pp.dog/register?aff=SUB2API"><img src="assets/partners/logos/ppdog.png" alt="PP.dog" width="150"></a></td>
<td><a href="https://pp.dog/register?aff=SUB2API">PP.dog</a> 是自建账号池的源头 API 网关,专注为下游中转站与高频开发者提供 API 网关中继服务,帮您省去自建号池的一切麻烦——✅ 源头直供:自持海量账号池,无中间商赚差价;🧧 成本屠夫:综合倍率低至 0.03x,成本仅为官方的千分之3.5;🚀 极速体验:首 Token 延迟 < 1s,流畅媲美官方原生 API。<a href="https://www.pp.dog/register?aff=SUB2API">立即接入PP.dog</a></td>
</tr>
<tr>
<td width="180"><a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/cola-proxy.jpg" alt="ColaProxy" width="150"></a></td>
<td>ColaProxy 提供专为网页抓取、自动化和多账号管理打造的高质量住宅代理。免费试用,流量永不过期,价格低至 $0.3/GB,支持无限并发连接和智能 IP 轮换,带来更流畅、更稳定的代理体验。使用优惠码 COLA10 立享 9 折优惠,立即开始使用可靠的住宅代理扩展您的项目。<a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">立即开始使用 ColaProxy</a></td>
</tr>
<tr>
<td width="180"><a href="https://modelflare.dev/zh/sign-up?utm_source=github&utm_campaign=sub2api"><img src="assets/partners/logos/modelflare.png" alt="Modelflare" width="150"></a></td>
<td>Modelflare:满血稳定不掺水,低成本享受全球 SOTA 模型。站点由美国 LLC 主体 Havenbyte LLC 运营,支持 GPT、Claude、Gemini、Grok 等主流模型和常用兼容协议,还支持 40 多种图片和视频模型。缓存补偿是一大亮点:部分 OpenAI 价格优先、稳定和高级分组提供每日 65%、75%、85% 的缓存命中率保障,符合条件的请求没达到目标的,平台补偿差额,结算后可在用量看板查看。特惠活动:单笔充值 US$20 即可解锁 0.015 倍价格倍率的 GPT 特惠分组,单笔充值 US$50 即可解锁 0.03 倍价格倍率的 Claude 特惠分组。通过<a href="https://modelflare.dev/zh/sign-up?utm_source=github&utm_campaign=sub2api">专属链接</a>注册即可参与</td>
</tr>
<tr>
<td width="180"><a href="https://x.com/chenju_ai"><img src="assets/partners/logos/chenju_ai.png" alt="Chenju" width="150"></a></td>
<td>感谢 <a href="https://x.com/chenju_ai">陈局</a> 赞助了本项目!这大概是本栏唯一一个不让你注册的广告位。好的开源项目值得被付费,陈局来随个份子,敬作者一杯。X 上找 <a href="https://x.com/chenju_ai">陈局</a>,聊中转、聊上游、吹吹水。</td>
</tr>
<tr>
<td width="180"><a href="https://t.me/AACC8888888"><img src="assets/partners/logos/ooko.ai.png" alt="ooko.ai" width="150"></a></td>
<td>🔑 高价收 AI 账号|Gemini · Claude · GPT|大小号通收,各种渠道都要|支持按量跑付|寻一手大厂资源,我上 KEY 。<br>微信:Liuyou-zawd|TG:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
</tr>
<tr>
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> 为网页抓取、AI 智能体、自动化和数据采集提供高性价比的全球代理解决方案。住宅代理低至 $0.35/GB,覆盖 190+ 个国家和地区,套餐灵活,支持 HTTP(S)/SOCKS5 协议。<br>🎁 使用优惠码 PAY2 充值立享 9 折优惠!</td>
</tr>
<tr>
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
<td>感谢 <a href="https://soleapi.com/r/sub2api">SoleAPI</a> 对本项目的支持!SoleAPI 是面向开发者与企业的 AI 模型网关:一个 API Key 即可调用 Claude、GPT、Gemini 等 30+ 主流模型。原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex、Cursor 及现有 SDK 只需修改 Base URL 即可接入。请求按延迟与上游健康度实时路由,毫秒级自动切换至备用通道,服务可用性达 99.99%,并提供 7×24 小时技术支持。所有调用统一账单结算,每次请求的 token 与费用明细随时可查。通过本项目的<a href="https://soleapi.com/r/sub2api">推荐链接</a>注册即可获得免费试用额度,邀请好友充值还可持续获得返现!</td>
</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 服务,平台负责鉴权、计费、负载均衡和请求转发。
@@ -217,6 +240,30 @@ underscores_in_headers on;
Nginx 默认会丢弃名称中含下划线的请求头(如 `session_id`),这会导致多账号环境下的粘性会话功能失效。
## Codex Fast/Flex 策略说明
管理员后台的 `系统设置 -> 网关服务 -> OpenAI Fast/Flex 策略` 只负责处理请求体中的 `service_tier`,不会修改 Codex 客户端的模型目录,也不会让 Codex UI 自动出现 Speed 或 `/fast` 选项。
策略支持以下处理方式:
- `pass`:保留客户端传入的 `service_tier`;`fast` 会规范为上游使用的 `priority`。
- `filter`:移除 `service_tier`,按普通优先级请求。
- `block`:拒绝匹配的 Fast/Flex 请求。
- `force_priority`:将匹配请求强制设置为 `priority`,会按 Priority/Fast 价格计费。为避免升级后改变既有规则语义,`all` 只匹配显式存在的 tier;如需让省略 `service_tier` 的 OpenAI 请求也强制升级,必须新增 `service_tier=missing + force_priority` 规则。非 OpenAI 平台不会执行缺省 tier 注入。这种方式可以让请求实际使用 Fast,但 Codex UI 仍可能不显示 Fast 状态。
Codex 的 Fast 入口由客户端模型目录驱动。只有当前模型目录声明了 `additional_speed_tiers: ["fast"]` 和对应的 `service_tiers`,Codex 才会显示 `/fast`。通过 API Key 或自定义模型提供商连接 Sub2API 时,如果模型目录没有这些字段,即使后台配置了 `force_priority`,重启 Codex 后也不会出现 Speed 选项。
客户端可在 `~/.codex/config.toml` 中直接指定默认请求级别:
```toml
service_tier = "fast"
[features]
fast_mode = true
```
其中 `service_tier = "fast"` 会让请求携带 Fast 设置;`features.fast_mode` 只启用客户端 Fast 功能。模型目录没有声明 Fast 能力时,`/fast` 仍可能不显示。可通过 Sub2API 使用记录确认最终 `service_tier` 是否为 `priority`。
---
## 部署方式
@@ -354,8 +401,10 @@ JWT_SECRET=your_jwt_secret_here
TOTP_ENCRYPTION_KEY=your_totp_key_here
# 可选:管理员账号
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=your_admin_password
# 留空则首次启动时自动生成随机邮箱(登录用户名)和密码,并输出到日志。
# 请勿使用 admin@example.com 这类可被猜中的值,它们是暴力破解的目标。
ADMIN_EMAIL=
ADMIN_PASSWORD=
# 可选:自定义端口
SERVER_PORT=8080
@@ -416,9 +465,9 @@ docker compose -f docker-compose.local.yml logs -f sub2api
在浏览器中打开 `http://你的服务器IP:8080`
如果管理员密码是自动生成的,在日志中查找:
如果管理员邮箱(登录用户名)或密码是自动生成的,在日志中查找:
```bash
docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
docker compose -f docker-compose.local.yml logs sub2api | grep "Generated admin"
```
#### 升级
@@ -696,16 +745,58 @@ go generate ./cmd/server
---
## OpenAI 图片模型
支持 `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 的 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 桥接。
原生端点保留 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 计费继续由既有分组/渠道配置决定。无需数据库迁移或新增环境变量。
## 简易模式
简易模式适合个人开发者或内部团队快速使用,不依赖完整 SaaS 功能。
- 启用方式:设置环境变量 `RUN_MODE=simple`
- 默认每次启动会补齐默认分组。设置 `SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=false`(或 YAML `simple_mode.auto_create_default_groups: false`)可自行管理分组。默认值为 `true`;关闭后不删除已有分组,不改变运行时自动绑定或管理员并发设置。
- 功能差异:隐藏 SaaS 相关功能,跳过计费流程
- 可选密钥窗口:设置 `SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=true` 后,按每个 API Key 配置的 5 小时、1 天、7 天消费窗口进行限制,默认值为 `false`;启用后仍跳过余额和订阅扣费。
- 窗口限制以数据库为准,只记录 API Key 窗口用量。它在请求完成后记账,并发中的请求可能以各自最终费用超过窗口上限。启用前的历史用量不会自动补算。
- 安全注意事项:生产环境需同时设置 `SIMPLE_MODE_CONFIRM=true` 才允许启动
---
## TypeSafe / Jev 使用说明
Sub2API 支持使用 TypeSafe API Key 账户,通过 Jev 原生、非流式的 System One 协议调用模型。
- 平台:`typesafe`;账号类型:API Key
- 默认上游:`https://api.typesafe.ai`
- 对外端点:`POST /v1/systemone`
- 模型:`jev-latest`,TypeSafe 分组的 `/v1/models` 也会返回该模型
- 问题类型:`noul`、`choice`、`score`
请求和成功响应保持 System One 原生 JSON 结构。该端点不兼容 Chat Completions、Responses、Anthropic Messages 或流式客户端。
问题校验遵循 TypeSafe OpenAPI 的线上协议 schema(SDK v0.5.7 也使用该 schema)。所有问题的 `instructions` 都可以省略或为 `null`。Noul 的 `criteria` 可以省略或为 `null`,其中 `true`/`false` 的描述和 Choice 描述支持字符串、对象、数组或 `null`。Score 的 `criteria` 必须是至少包含一档描述的数组,每档支持字符串、对象或数组;单档也合法。SDK 的整数键 Score 映射会由 SDK 在发送前转换为数组。
```bash
curl https://your-sub2api.example.com/v1/systemone \
-H 'Authorization: Bearer sk-your-sub2api-key' \
-H 'Content-Type: application/json' \
--data '{"model":"jev-latest","state":"待评估文本","questions":{"safety":{"type":"noul","instructions":"评估文本是否不安全"}}}'
```
`jev-latest` 内置价格为输入 `$0.042/百万 tokens`、输出 `$0`,渠道定价可以覆盖。凭据、欠费、权限、限流、过载、服务端和网络错误(`401`、`402`、`403`、`429`、`529`、`5xx`、传输错误)沿用现有账号错误策略(含自定义错误码与临时不可调度规则)并切换账号;请求错误(`400`、`413`、`422`)不会切换账号重试,也不会改变账号状态。TypeSafe 分组(以及路由到 TypeSafe 的 Composite 请求)调用 Messages、Chat Completions、Responses、count_tokens 时返回 `404`。
---
## Antigravity 使用说明
Sub2API 支持 [Antigravity](https://antigravity.so/) 账户,授权后可通过专用端点访问 Claude 和 Gemini 模型。
+68 -48
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>
@@ -49,13 +60,13 @@
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
<td>APIKEY.FUN のご支援に感謝します!<a href="https://apikey.fun/register?aff=SUB2API">APIKEY.FUN</a> は sub2api オープンソースプロジェクトのコアコントリビューターの一つであり、オープンで安定した、コストパフォーマンスに優れた AI API アクセスサービスの提供に取り組んでいます。プラットフォームは Claude、OpenAI、Gemini など人気モデルの API 中継サービスをサポートし、価格は公式料金のわずか 7% から。専用リンク <a href="https://apikey.fun/register?aff=SUB2API">APIKEY</a> から登録すると、すべてのチャージで永久 5% 割引をご利用いただけます。</td>
<td width="180"><a href="https://apikey.fan/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
<td>APIKEY.FUN のご支援に感謝します!<a href="https://apikey.fan/register?aff=SUB2API">APIKEY.FUN</a> は sub2api オープンソースプロジェクトのコアコントリビューターの一つであり、オープンで安定した、コストパフォーマンスに優れた AI API アクセスサービスの提供に取り組んでいます。プラットフォームは Claude、OpenAI、Gemini など人気モデルの API 中継サービスをサポートし、価格は公式料金のわずか 7% から。専用リンク <a href="https://apikey.fan/register?aff=SUB2API">APIKEY</a> から登録すると、すべてのチャージで永久 5% 割引をご利用いただけます。</td>
</tr>
<tr>
<td width="180"><a href="https://aigocode.com/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://aigocode.com/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>
@@ -63,11 +74,6 @@
<td>OpenAI 公式価格のわずか 3% で本物の GPT-5.6 シリーズを提供 — <a href="https://codex-everywhere.com">CodexEverywhere</a> は世界中の開発者にフロンティアモデルへのアクセスを民主化しています。私たちは透明性と誠実さを信条とし、モデル品質は数か月にわたるアクティブなコミュニティの監視によって検証されています。USD および暗号通貨に対応。<a href="https://codex-everywhere.com">codex-everywhere.com</a> で $20 の無料トライアルから始めましょう。</td>
</tr>
<tr>
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
<td>本プロジェクトにご支援いただいた BmoPlus に感謝いたします!BmoPlusは、AIサブスクリプションのヘビーユーザー向けに特化した信頼性の高いAIアカウントサービスプロバイダーであり、安定した ChatGPT Plus / ChatGPT Pro (完全保証) / Claude Pro / Super Grok / Gemini Pro の公式代行チャージおよび即納アカウントを提供しています。こちらの<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AIアカウント専門店/代行チャージ</a>経由でご登録・ご注文いただいたユーザー様は、GPTを 公式サイト価格の約1割(90% OFF) という驚異的な価格でご利用いただけます!</td>
</tr>
<tr>
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
<td>Bestproxy のご支援に感謝します!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> は高純度の住宅IPを提供し、1アカウント1IP専有をサポートしています。実際の家庭ネットワークとフィンガープリント分離を組み合わせることで、リンク環境の分離を実現し、関連付けによるリスク管理の確率を低減します。</td>
@@ -98,26 +104,6 @@
</td>
</tr>
<tr>
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
<td>Proxy4Free のご支援に感謝します!Proxy4Free は開発者と AI アプリケーション向けのデータプロキシサービスプロバイダーで、住宅プロキシ、静的住宅プロキシ、ISP プロキシ、データセンタープロキシなど多様なプロキシソリューションを提供しており、Web Scraping、Browser Automation、AI Agent などのシナリオに適しています。グローバル IP リソース、安定した接続、柔軟な切り替えをサポートし、開発者のデータ収集成功率の向上と IP ブロックリスクの低減を支援します。<a href="https://www.proxy4free.com/?keyword=4yjqecpc">こちらのリンクから登録</a>して、より安定した効率的な自動化ワークフローを簡単に構築しましょう。
</td>
</tr>
<tr>
<td width="180"><a href="http://www.fastaitoken.com/register"><img src="assets/partners/logos/fastaitoken.jpg" alt="fastaitoken" width="150"></a></td>
<td>🎉 FastAIToken のご支援に感謝します!<a href="http://www.fastaitoken.com/register">FastAIToken</a> は開発者向けの AI API アグリゲーションプラットフォームで、OpenAI、Claude、Gemini などの主要な大規模モデルに対応しています。チャージは 1:1(1 元 = 1 米ドル分の API クレジット)で、開発者がより低コスト・より手軽に世界トップクラスの大規模モデルサービスを利用できます。<br>
🚀 プラットフォームでは多彩なチャネルを自由に選択できます:超低価格の 0.02x OpenAI 特典グループ(期間限定)、最低 0.25x の OpenAI グループ、0.7x Claude(95% 固定キャッシュ)、1.2x Claude Max チャネル。さらに、各グループの可用率・レイテンシ・稼働状況をリアルタイムで表示する公開ステータスページを提供し、透明で信頼できるサービスを実現。7×24 時間の有人テクニカルサポート(ボットではありません)により、開発者のニーズに迅速に対応します。
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>Aimzoon のご支援に感謝します!<a href="http://aimzoon.com">Aimzoon</a> は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。<a href="http://aimzoon.com">こちら</a>から登録してお試しください!
</td>
</tr>
<tr>
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
<td><a href="https://nagora.ai/">Nagora</a>は、開発者やチーム向けに設計されたマルチモデルAI APIゲートウェイです。1つのアカウントと1つのAPIキーだけで、26種類以上の主要なテキストモデルおよび画像モデルを一元的に利用できます。OpenAI、Anthropic、Geminiの各プロトコルに対応し、Claude Code、Codex、Gemini CLIなどの開発ツールにもシームレスに接続できます。 プラットフォームには、インテリジェントルーティング、自動フェイルオーバー、透明性の高い料金体系、請求の一元管理に加え、予算管理、レート制限、同時実行数の制御機能が備わっています。これにより、個人開発、チームでの共同作業、本番環境におけるAI APIの利用を、より安定的かつ柔軟に管理できます。 既存のアプリケーションを改修する必要はありません。Base URLとAPIキーを置き換えるだけで、最短1分で導入を完了できます。</td>
@@ -133,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>
@@ -153,23 +134,60 @@
<td>Swiftproxy は開発者向けの高性能プロキシソリューションで、安定して信頼できるレジデンシャルおよび静的レジデンシャルプロキシサービスを提供します。9,000 万以上のクリーンな住宅 IP を保有し、グローバルカバレッジ、柔軟なローテーション、精密なジオターゲティングにより、Web スクレイピング、AI オートメーション、ブラウザ自動化、SEO モニタリング、マルチアカウント管理などのプロジェクトがアクセス制限を克服し、ワークフロー効率を向上させます。HTTP(S) および SOCKS5 プロトコルに対応し、Playwright、Selenium、Puppeteer などの主要な自動化ツールと統合可能。動的プロキシトラフィックは使い切るまで期限切れなし、無料テストも利用可能 — <a href="https://www.swiftproxy.net/?ref=sub2api">今すぐ無料テストを開始</a>!</td>
</tr>
<tr>
<td width="180"><a href="https://www.duckip.cn/?keyword=cu7oog6y"><img src="assets/partners/logos/duckip.png" alt="DuckIP" width="150"></a></td>
<td><a href="https://www.duckip.cn/?keyword=cu7oog6y">DuckIP</a> - 195 以上の国と地域にわたる 9,000 万以上のグローバルレジデンシャルネットワークリソース。ローテーションとスティッキーセッションに対応し、パブリックデータ収集、RAG 更新、モデル評価、マルチリージョンデータワークロードに最適。🟢レジデンシャルプロキシ - 20% オフ;🟢スタティックレジデンシャルプロキシ - ¥50.00/IP から;🟢無制限レジデンシャルプロキシ - ¥19.8/時間 から。✅500M 無料トライアルを取得。</td>
</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>
</tr>
<tr>
<td width="180"><a href="https://pp.dog/register?aff=SUB2API"><img src="assets/partners/logos/ppdog.png" alt="PP.dog" width="150"></a></td>
<td><a href="https://pp.dog/register?aff=SUB2API">PP.dog</a> は自社運用の大規模アカウントプールを持つソースレベルの API ゲートウェイで、下流の中継ステーションや高頻度開発者向けに API ゲートウェイリレーサービスを提供し、アカウントプールの自主構築にかかるすべての手間を省きます。✅ ソース直供:自社運用の大規模アカウントプール、中間マージンなし;🧧 コスト最強:総合レート倍率わずか 0.03x、コストは公式の 0.35% のみ;🚀 超高速体験:ファーストトークンレイテンシ 1 秒未満、公式ネイティブ API に匹敵するスムーズさ。<a href="https://www.pp.dog/register?aff=SUB2API">今すぐ PP.dog に接続</a></td>
</tr>
<tr>
<td width="180"><a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/cola-proxy.jpg" alt="ColaProxy" width="150"></a></td>
<td>ColaProxy は、Web スクレイピング、自動化、マルチアカウント管理向けに構築された高品質な住宅プロキシを提供します。有効期限なしのトラフィックで無料トライアルが利用でき、料金は $0.3/GB から、無制限の同時接続とインテリジェントな IP ローテーションにより、よりスムーズで安定したプロキシ体験を実現します。割引コード COLA10 で 10% オフ、信頼性の高い住宅プロキシでプロジェクトを今すぐスケールしましょう。<a href="https://colaproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">ColaProxy を始める</a></td>
</tr>
<tr>
<td width="180"><a href="https://modelflare.dev/ja/sign-up?utm_source=github&utm_campaign=sub2api"><img src="assets/partners/logos/modelflare.png" alt="Modelflare" width="150"></a></td>
<td>Modelflare:フルスペック、安定、水増しなし。世界の SOTA モデルを、より低いコストで。米国拠点の Havenbyte LLC が運営する Modelflare は、一般的な互換プロトコルを通じて GPT、Claude、Gemini、Grok などの主要モデルに対応し、さらに 40 以上の画像・動画モデルも利用できます。注目はキャッシュ補償です。対象の OpenAI グループ(価格優先・安定・プレミアム)は、1 日のキャッシュヒット率をそれぞれ 65%、75%、85% で保証します。対象リクエストがこの水準に達しない場合、Modelflare が差額を返金し、精算後に利用状況ダッシュボードで確認できます。特別オファー:US$20 を 1 回チャージすると、価格倍率 0.015 倍の GPT 割引グループが解放されます。US$50 を 1 回チャージすると、価格倍率 0.03 倍の Claude 割引グループが解放されます。<a href="https://modelflare.dev/ja/sign-up?utm_source=github&utm_campaign=sub2api">こちらの専用リンク</a>から登録して始めましょう。</td>
</tr>
<tr>
<td width="180"><a href="https://x.com/chenju_ai"><img src="assets/partners/logos/chenju_ai.png" alt="Chenju" width="150"></a></td>
<td><a href="https://x.com/chenju_ai">陈局(Chenju)</a>様、本プロジェクトへのご支援ありがとうございます!これはおそらく、この欄で唯一「登録しなくていい」広告枠です。良いオープンソースには対価が払われるべき——というわけで、陈局がご祝儀を包んで作者に一杯おごります。X で <a href="https://x.com/chenju_ai">陈局</a> を見つけて、中継サービスや上流の話、雑談でもどうぞ。</td>
</tr>
<tr>
<td width="180"><a href="https://t.me/AACC8888888"><img src="assets/partners/logos/ooko.ai.png" alt="ooko.ai" width="150"></a></td>
<td>🔑 AI アカウント高価買取|Gemini · Claude · GPT|メイン・サブアカウントすべて買取、チャネル問わず歓迎|従量制での支払いに対応|大手の一次リソースを求めています、KEY は私が用意します。<br>WeChat:Liuyou-zawd|Telegram:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
</tr>
<tr>
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> は、Web スクレイピング、AI エージェント、自動化、データ収集向けに、手頃な価格のグローバルプロキシソリューションを提供します。住宅プロキシは $0.35/GB から、190 以上の国と地域をカバーし、柔軟なプランと HTTP(S)/SOCKS5 に対応しています。<br>🎁 コード PAY2 でチャージが 10% オフ!</td>
</tr>
<tr>
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
<td><a href="https://soleapi.com/r/sub2api">SoleAPI</a> 様、本プロジェクトへのご支援ありがとうございます!SoleAPI は開発者と企業向けの AI モデルゲートウェイです。1 つの API キーで Claude、GPT、Gemini をはじめとする 30 以上の主要モデルを利用できます。OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex、Cursor や既存の SDK も Base URL を変更するだけで動作します。リクエストはレイテンシと上流の稼働状況に応じてリアルタイムにルーティングされ、ミリ秒単位でバックアップチャネルへ自動フェイルオーバーします。サービス可用性は 99.99%、24 時間 365 日の技術サポートも提供しています。すべての呼び出しは 1 つの請求書にまとめられ、リクエストごとの token 数と費用の内訳をいつでも確認できます。本プロジェクトの<a href="https://soleapi.com/r/sub2api">紹介リンク</a>から登録すると無料トライアルクレジットを受け取れ、友人を招待してチャージしてもらうと継続的にキャッシュバックを獲得できます!</td>
</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 サービスにアクセスでき、プラットフォームは認証、課金、負荷分散、リクエスト転送を処理します。
@@ -353,8 +371,10 @@ JWT_SECRET=your_jwt_secret_here
TOTP_ENCRYPTION_KEY=your_totp_key_here
# オプション: 管理者アカウント
ADMIN_EMAIL=admin@example.com
ADMIN_PASSWORD=your_admin_password
# 空欄の場合、初回起動時にランダムなメールアドレス(ログインユーザー名)とパスワードが自動生成され、ログに出力されます。
# admin@example.com のような推測されやすい値は総当たり攻撃の標的になるため避けてください。
ADMIN_EMAIL=
ADMIN_PASSWORD=
# オプション: カスタムポート
SERVER_PORT=8080
@@ -403,9 +423,9 @@ docker compose -f docker-compose.local.yml logs -f sub2api
ブラウザで `http://YOUR_SERVER_IP:8080` を開いてください。
管理者パスワードが自動生成された場合は、ログで確認できます:
管理者メールアドレス(ログインユーザー名)またはパスワードが自動生成された場合は、ログで確認できます:
```bash
docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
docker compose -f docker-compose.local.yml logs sub2api | grep "Generated admin"
```
#### アップグレード
@@ -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: 10 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: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 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: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

+9
View File
@@ -123,6 +123,15 @@ linters:
exclusions:
rules:
# x/net v0.60 deprecated the HTTP/2 compatibility adapters. Keep their
# existing per-protocol idle timeout and PING configuration in this CI fix.
- path: 'internal/(repository/http_upstream(_http2_keepalive_test)?|server/http)\.go$'
linters: [ staticcheck ]
text: 'SA1019: (\(golang\.org/x/net/http2\.(Server|Transport)\)\.|golang\.org/x/net/http2\.(ConfigureServer|ConfigureTransports|Server|Transport)\b)'
# Upstream libraries can still return the legacy typed GOAWAY error.
- path: 'internal/service/openai_codex_models_service(_test)?\.go$'
linters: [ staticcheck ]
text: 'SA1019: golang\.org/x/net/http2\.GoAwayError\b'
# G703/G704 污点分析在测试文件中只会命中 httptest mock 与测试者自设的
# 环境变量路径,不构成攻击面;且该分析跨环境结果不稳定(本地/CI 报告的
# 位置集合不同),逐点 nolint 无法收敛,故按路径豁免。生产代码不豁免,
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.27.0-alpine
FROM golang:1.27.4-alpine
WORKDIR /app
+1 -1
View File
@@ -1 +1 @@
0.2.2
0.2.24
+38
View File
@@ -99,16 +99,21 @@ func provideCleanup(
accountExpiry *service.AccountExpiryService,
cnProviderBalanceCheck *service.CNProviderBalanceCheckService,
codexVersionSync *service.OpenAICodexVersionSyncService,
claudeCodeVersionSync *service.ClaudeCodeVersionSyncService,
proxyExpiry *service.ProxyExpiryService,
subscriptionExpiry *service.SubscriptionExpiryService,
usageCleanup *service.UsageCleanupService,
idempotencyCleanup *service.IdempotencyCleanupService,
geminiCachedContent *service.GeminiCachedContentService,
batchImageCleanup *service.BatchImageCleanupService,
batchImageWorker *service.BatchImageWorkerRuntime,
pricing *service.PricingService,
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,
@@ -124,6 +129,7 @@ func provideCleanup(
quotaFlusher *service.UserPlatformQuotaUsageFlusher,
upstreamBillingProbe *service.UpstreamBillingProbeService,
ollamaCloudUsage *service.OllamaCloudUsageService,
opencodeGoUsage *service.OpenCodeGoUsageService,
auditLog *service.AuditLogService,
openAIAutoReset *service.OpenAIQuotaAutoResetService,
promptAudit *securityaudit.PromptService,
@@ -140,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()
@@ -242,6 +260,12 @@ func provideCleanup(
}
return nil
}},
{"GeminiCachedContentService", func() error {
if geminiCachedContent != nil {
geminiCachedContent.Stop()
}
return nil
}},
{"BatchImageCleanupService", func() error {
if batchImageCleanup != nil {
batchImageCleanup.Stop()
@@ -272,6 +296,10 @@ func provideCleanup(
codexVersionSync.Stop()
return nil
}},
{"ClaudeCodeVersionSyncService", func() error {
claudeCodeVersionSync.Stop()
return nil
}},
{"ProxyExpiryService", func() error {
proxyExpiry.Stop()
return nil
@@ -304,6 +332,10 @@ func provideCleanup(
}
return nil
}},
{"UsageBillingLaneCombiner", func() error {
usageBillingLanes.Stop()
return nil
}},
{"OAuthService", func() error {
oauth.Stop()
return nil
@@ -380,6 +412,12 @@ func provideCleanup(
}
return nil
}},
{"OpenCodeGoUsageService", func() error {
if opencodeGoUsage != nil {
opencodeGoUsage.Stop()
}
return nil
}},
}
infraSteps := []cleanupStep{
+70 -18
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)
@@ -117,10 +123,12 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
openAI403CounterCache := repository.NewOpenAI403CounterCache(redisClient)
geminiTokenCache := repository.NewGeminiTokenCache(redisClient)
compositeTokenCacheInvalidator := service.NewCompositeTokenCacheInvalidator(geminiTokenCache)
rateLimitService := service.ProvideRateLimitService(accountRepository, usageLogRepository, configConfig, geminiQuotaService, tempUnschedCache, timeoutCounterCache, openAI403CounterCache, settingService, compositeTokenCacheInvalidator)
httpUpstream := repository.NewHTTPUpstream(configConfig)
leaderLockCache := repository.NewLeaderLockCache(redisClient)
ollamaCloudUsageService := service.ProvideOllamaCloudUsageService(accountRepository, httpUpstream, settingService, secretEncryptor, configConfig, leaderLockCache, db)
rateLimitService := service.ProvideRateLimitService(accountRepository, usageLogRepository, configConfig, geminiQuotaService, tempUnschedCache, timeoutCounterCache, openAI403CounterCache, settingService, compositeTokenCacheInvalidator, ollamaCloudUsageService)
identityCache := repository.NewIdentityCache(redisClient)
identityService := service.NewIdentityService(identityCache)
httpUpstream := repository.NewHTTPUpstream(configConfig)
timingWheelService, err := service.ProvideTimingWheelService()
if err != nil {
return nil, err
@@ -137,7 +145,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
tlsFingerprintProfileCache := repository.NewTLSFingerprintProfileCache(redisClient)
tlsFingerprintProfileService := service.NewTLSFingerprintProfileService(tlsFingerprintProfileRepository, tlsFingerprintProfileCache)
channelRepository := repository.NewChannelRepository(db)
channelService := service.NewChannelService(channelRepository, groupRepository, apiKeyAuthCacheInvalidator, pricingService)
channelCachePubSub := repository.NewChannelCache(redisClient)
channelService := service.NewChannelService(channelRepository, groupRepository, apiKeyAuthCacheInvalidator, pricingService, channelCachePubSub)
modelPricingResolver := service.NewModelPricingResolver(channelService, billingService)
compositeModelRouteRepository := repository.NewCompositeModelRouteRepository(client)
compositeRouteResolver := service.NewCompositeRouteResolver(compositeModelRouteRepository)
@@ -182,14 +191,13 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
dashboardAggregationRepository := repository.NewDashboardAggregationRepository(db)
dashboardStatsCache := repository.NewDashboardCache(redisClient, configConfig)
dashboardService := service.NewDashboardService(usageLogRepository, dashboardAggregationRepository, dashboardStatsCache, configConfig)
leaderLockCache := repository.NewLeaderLockCache(redisClient)
dashboardAggregationService := service.ProvideDashboardAggregationService(dashboardAggregationRepository, timingWheelService, leaderLockCache, db, configConfig)
dashboardAggregationService := service.ProvideDashboardAggregationService(dashboardAggregationRepository, timingWheelService, leaderLockCache, db, configConfig, settingRepository)
dashboardHandler := admin.NewDashboardHandler(dashboardService, dashboardAggregationService)
adminGroupRepository := repository.NewAdminGroupRepository(client, db)
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)
@@ -197,12 +205,14 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository, configConfig)
grokQuotaFetcher := service.NewGrokQuotaFetcher()
grokQuotaService := service.ProvideGrokQuotaService(accountRepository, proxyRepository, grokTokenProvider, httpUpstream, configConfig, usageLogRepository, settingService)
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIGatewayService)
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)
pluginRepository := repository.NewPluginRepository(db)
pluginHostInfo := providePluginHostInfo(buildInfo)
pluginManager := service.NewPluginManager(pluginRepository, secretEncryptor, configConfig, pluginHostInfo)
pluginKVStore := repository.NewPluginKVStore(redisClient)
pluginManager := service.ProvidePluginManager(pluginRepository, secretEncryptor, configConfig, pluginHostInfo, pluginKVStore, openAIGatewayService)
accountTestService := service.ProvideAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService, openAIGatewayService, settingService, pluginManager)
crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig)
accountHandler := admin.ProvideAccountHandler(configConfig, adminService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService, sessionLimitCache, rpmCache, compositeTokenCacheInvalidator, grokQuotaService)
@@ -283,15 +293,19 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
auditLogService := service.ProvideAuditLogService(auditLogRepository, settingService)
auditLogHandler := admin.NewAuditLogHandler(auditLogService, totpService)
upstreamBillingProbeService := service.ProvideUpstreamBillingProbeService(accountRepository, accountTestService, settingService, leaderLockCache, db)
ollamaCloudUsageService := service.ProvideOllamaCloudUsageService(accountRepository, httpUpstream, settingService, secretEncryptor, configConfig, leaderLockCache, db)
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, backupHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, grokOAuthHandler, cnProviderHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, tlsFingerprintProfileHandler, pluginHandler, adminAPIKeyHandler, scheduledTestHandler, channelHandler, channelMonitorHandler, channelMonitorRequestTemplateHandler, contentModerationHandler, promptAdminHandler, paymentHandler, affiliateHandler, complianceHandler, auditLogHandler, upstreamBillingProbeService, ollamaCloudUsageService)
openCodeGoUsageService := service.ProvideOpenCodeGoUsageService(accountRepository, httpUpstream, settingService, leaderLockCache, db)
idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig)
claudeResetCreditService := service.ProvideClaudeResetCreditService(accountRepository, claudeTokenProvider, proxyRepository, settingService, idempotencyCoordinator, leaderLockCache)
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, backupHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, grokOAuthHandler, cnProviderHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, tlsFingerprintProfileHandler, pluginHandler, adminAPIKeyHandler, scheduledTestHandler, channelHandler, channelMonitorHandler, channelMonitorRequestTemplateHandler, contentModerationHandler, promptAdminHandler, paymentHandler, affiliateHandler, complianceHandler, auditLogHandler, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, claudeResetCreditService)
usageRecordWorkerPool := service.NewUsageRecordWorkerPool(configConfig)
userMsgQueueCache := repository.NewUserMsgQueueCache(redisClient)
userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, configConfig)
legacyEngine := securityaudit.NewLegacyModerationAdapter(contentModerationService)
coordinator := securityaudit.NewCoordinator(legacyEngine, promptService)
gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator)
openAIGatewayHandler := handler.ProvideOpenAIGatewayHandler(openAIGatewayService, pluginManager, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, grokQuotaService, configConfig, coordinator)
geminiCachedContentRepository := repository.NewGeminiCachedContentRepository(db)
geminiCachedContentService := service.ProvideGeminiCachedContentService(geminiCachedContentRepository, geminiMessagesCompatService, configConfig)
gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator, geminiCachedContentService)
openAIGatewayHandler := handler.ProvideOpenAIGatewayHandler(openAIGatewayService, pluginManager, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, grokQuotaService, configConfig, coordinator, compositeRouteResolver)
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo, notificationEmailService)
totpHandler := handler.NewTotpHandler(totpService)
passkeyRepository := repository.NewPasskeyRepository(db)
@@ -317,10 +331,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig)
batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig)
batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler)
idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig)
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)
@@ -338,6 +351,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
cnProviderBalanceCheckService := service.ProvideCNProviderBalanceCheckService(accountRepository, cnProviderBalanceService, cnProviderQuotaService, configConfig)
openAICodexVersionSyncService := service.ProvideOpenAICodexVersionSyncService(settingRepository, settingService, gitHubReleaseClient)
claudeCodeVersionSyncService := service.ProvideClaudeCodeVersionSyncService(settingRepository, settingService, gitHubReleaseClient)
proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository)
subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db)
batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig)
@@ -347,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, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, 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,
@@ -402,16 +416,21 @@ func provideCleanup(
accountExpiry *service.AccountExpiryService,
cnProviderBalanceCheck *service.CNProviderBalanceCheckService,
codexVersionSync *service.OpenAICodexVersionSyncService,
claudeCodeVersionSync *service.ClaudeCodeVersionSyncService,
proxyExpiry *service.ProxyExpiryService,
subscriptionExpiry *service.SubscriptionExpiryService,
usageCleanup *service.UsageCleanupService,
idempotencyCleanup *service.IdempotencyCleanupService,
geminiCachedContent *service.GeminiCachedContentService,
batchImageCleanup *service.BatchImageCleanupService,
batchImageWorker *service.BatchImageWorkerRuntime,
pricing *service.PricingService,
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,
@@ -427,6 +446,7 @@ func provideCleanup(
quotaFlusher *service.UserPlatformQuotaUsageFlusher,
upstreamBillingProbe *service.UpstreamBillingProbeService,
ollamaCloudUsage *service.OllamaCloudUsageService,
opencodeGoUsage *service.OpenCodeGoUsageService,
auditLog *service.AuditLogService,
openAIAutoReset *service.OpenAIQuotaAutoResetService,
promptAudit *securityaudit.PromptService,
@@ -442,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()
@@ -544,6 +576,12 @@ func provideCleanup(
}
return nil
}},
{"GeminiCachedContentService", func() error {
if geminiCachedContent != nil {
geminiCachedContent.Stop()
}
return nil
}},
{"BatchImageCleanupService", func() error {
if batchImageCleanup != nil {
batchImageCleanup.Stop()
@@ -574,6 +612,10 @@ func provideCleanup(
codexVersionSync.Stop()
return nil
}},
{"ClaudeCodeVersionSyncService", func() error {
claudeCodeVersionSync.Stop()
return nil
}},
{"ProxyExpiryService", func() error {
proxyExpiry.Stop()
return nil
@@ -606,6 +648,10 @@ func provideCleanup(
}
return nil
}},
{"UsageBillingLaneCombiner", func() error {
usageBillingLanes.Stop()
return nil
}},
{"OAuthService", func() error {
oauth.Stop()
return nil
@@ -682,6 +728,12 @@ func provideCleanup(
}
return nil
}},
{"OpenCodeGoUsageService", func() error {
if opencodeGoUsage != nil {
opencodeGoUsage.Stop()
}
return nil
}},
}
infraSteps := []cleanupStep{
+7
View File
@@ -41,6 +41,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
)
accountExpirySvc := service.NewAccountExpiryService(nil, time.Second)
codexVersionSyncSvc := service.NewOpenAICodexVersionSyncService(nil, nil, nil, time.Second)
claudeCodeVersionSyncSvc := service.NewClaudeCodeVersionSyncService(nil, nil, nil, time.Second)
proxyExpirySvc := service.NewProxyExpiryService(nil, time.Second)
subscriptionExpirySvc := service.NewSubscriptionExpiryService(nil, time.Second)
pricingSvc := service.NewPricingService(cfg, nil)
@@ -68,16 +69,21 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
accountExpirySvc,
nil, // cnProviderBalanceCheck
codexVersionSyncSvc,
claudeCodeVersionSyncSvc,
proxyExpirySvc,
subscriptionExpirySvc,
&service.UsageCleanupService{},
idempotencyCleanupSvc,
service.NewGeminiCachedContentService(nil, nil, cfg),
&service.BatchImageCleanupService{},
nil, // batchImageWorker
pricingSvc,
emailQueueSvc,
billingCacheSvc,
&service.UsageRecordWorkerPool{},
nil, // usageBillingLanes
service.ProvideBalanceNotifyService(nil, nil, nil, nil),
service.NewDigestSessionStore(),
&service.SubscriptionService{},
oauthSvc,
openAIOAuthSvc,
@@ -93,6 +99,7 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
nil, // quotaFlusher
nil, // upstreamBillingProbe
nil, // ollamaCloudUsage
nil, // opencodeGoUsage
nil, // auditLog
nil, // openAIAutoReset
nil, // promptAudit
+3 -1
View File
@@ -182,6 +182,8 @@ const (
ProviderKimi Provider = "kimi"
ProviderZhipu Provider = "zhipu"
ProviderDeepseek Provider = "deepseek"
ProviderMinimax Provider = "minimax"
ProviderOpencodeGo Provider = "opencode_go"
)
func (pr Provider) String() string {
@@ -191,7 +193,7 @@ func (pr Provider) String() string {
// ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save.
func ProviderValidator(pr Provider) error {
switch pr {
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek:
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo:
return nil
default:
return fmt.Errorf("channelmonitor: invalid enum value for provider field: %q", pr)
@@ -108,6 +108,8 @@ const (
ProviderKimi Provider = "kimi"
ProviderZhipu Provider = "zhipu"
ProviderDeepseek Provider = "deepseek"
ProviderMinimax Provider = "minimax"
ProviderOpencodeGo Provider = "opencode_go"
)
func (pr Provider) String() string {
@@ -117,7 +119,7 @@ func (pr Provider) String() string {
// ProviderValidator is a validator for the "provider" field enum values. It is called by the builders before save.
func ProviderValidator(pr Provider) error {
switch pr {
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek:
case ProviderOpenai, ProviderAnthropic, ProviderGemini, ProviderGrok, ProviderAntigravity, ProviderKimi, ProviderZhipu, ProviderDeepseek, ProviderMinimax, ProviderOpencodeGo:
return nil
default:
return fmt.Errorf("channelmonitorrequesttemplate: invalid enum value for provider field: %q", pr)
+17 -1
View File
@@ -4595,6 +4595,22 @@ func (c *ProxyClient) QueryAccounts(_m *Proxy) *AccountQuery {
return query
}
// QueryPrimaryProxies queries the primary_proxies edge of a Proxy.
func (c *ProxyClient) QueryPrimaryProxies(_m *Proxy) *ProxyQuery {
query := (&ProxyClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(proxy.Table, proxy.FieldID, id),
sqlgraph.To(proxy.Table, proxy.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, proxy.PrimaryProxiesTable, proxy.PrimaryProxiesColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryBackupProxy queries the backup_proxy edge of a Proxy.
func (c *ProxyClient) QueryBackupProxy(_m *Proxy) *ProxyQuery {
query := (&ProxyClient{config: c.config}).Query()
@@ -4603,7 +4619,7 @@ func (c *ProxyClient) QueryBackupProxy(_m *Proxy) *ProxyQuery {
step := sqlgraph.NewStep(
sqlgraph.From(proxy.Table, proxy.FieldID, id),
sqlgraph.To(proxy.Table, proxy.FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, proxy.BackupProxyTable, proxy.BackupProxyColumn),
sqlgraph.Edge(sqlgraph.M2O, false, proxy.BackupProxyTable, proxy.BackupProxyColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
+37 -2
View File
@@ -30,6 +30,8 @@ type Group struct {
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description *string `json:"description,omitempty"`
// 名称与描述的界面语言译文:语言代码 -> {name, description};缺失的语言沿用 name/description
I18n domain.GroupI18n `json:"i18n,omitempty"`
// RateMultiplier holds the value of the "rate_multiplier" field.
RateMultiplier float64 `json:"rate_multiplier,omitempty"`
// 是否启用高峰时段倍率
@@ -62,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 时生效
@@ -124,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 类型账号关联到此分组
@@ -258,9 +264,9 @@ func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings:
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)
@@ -323,6 +329,14 @@ func (_m *Group) assignValues(columns []string, values []any) error {
_m.Description = new(string)
*_m.Description = value.String
}
case group.FieldI18n:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field i18n", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.I18n); err != nil {
return fmt.Errorf("unmarshal field i18n: %w", err)
}
}
case group.FieldRateMultiplier:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field rate_multiplier", values[i])
@@ -423,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])
@@ -630,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])
@@ -817,6 +843,9 @@ func (_m *Group) String() string {
builder.WriteString(*v)
}
builder.WriteString(", ")
builder.WriteString("i18n=")
builder.WriteString(fmt.Sprintf("%v", _m.I18n))
builder.WriteString(", ")
builder.WriteString("rate_multiplier=")
builder.WriteString(fmt.Sprintf("%v", _m.RateMultiplier))
builder.WriteString(", ")
@@ -873,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(", ")
@@ -992,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(", ")
+25
View File
@@ -26,6 +26,8 @@ const (
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldI18n holds the string denoting the i18n field in the database.
FieldI18n = "i18n"
// FieldRateMultiplier holds the string denoting the rate_multiplier field in the database.
FieldRateMultiplier = "rate_multiplier"
// FieldPeakRateEnabled holds the string denoting the peak_rate_enabled field in the database.
@@ -58,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.
@@ -120,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.
@@ -228,6 +234,7 @@ var Columns = []string{
FieldDeletedAt,
FieldName,
FieldDescription,
FieldI18n,
FieldRateMultiplier,
FieldPeakRateEnabled,
FieldPeakStart,
@@ -244,6 +251,7 @@ var Columns = []string{
FieldDefaultValidityDays,
FieldAllowImageGeneration,
FieldAllowBatchImageGeneration,
FieldImageCountBilling,
FieldImageRateIndependent,
FieldImageRateMultiplier,
FieldImagePrice1k,
@@ -275,6 +283,7 @@ var Columns = []string{
FieldAllowMessagesDispatch,
FieldAllowLive,
FieldForceOpenaiFast,
FieldForceOpenaiUltrafast,
FieldFreeOpenaiFast,
FieldRequireOauthOnly,
FieldRequirePrivacySet,
@@ -326,6 +335,8 @@ var (
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultI18n holds the default value on creation for the "i18n" field.
DefaultI18n domain.GroupI18n
// DefaultRateMultiplier holds the default value on creation for the "rate_multiplier" field.
DefaultRateMultiplier float64
// DefaultPeakRateEnabled holds the default value on creation for the "peak_rate_enabled" field.
@@ -362,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.
@@ -400,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.
@@ -549,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()
@@ -684,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))
+187
View File
@@ -92,6 +92,12 @@ func (_c *GroupCreate) SetNillableDescription(v *string) *GroupCreate {
return _c
}
// SetI18n sets the "i18n" field.
func (_c *GroupCreate) SetI18n(v domain.GroupI18n) *GroupCreate {
_c.mutation.SetI18n(v)
return _c
}
// SetRateMultiplier sets the "rate_multiplier" field.
func (_c *GroupCreate) SetRateMultiplier(v float64) *GroupCreate {
_c.mutation.SetRateMultiplier(v)
@@ -316,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)
@@ -718,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)
@@ -1047,6 +1081,10 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
if _, ok := _c.mutation.I18n(); !ok {
v := group.DefaultI18n
_c.mutation.SetI18n(v)
}
if _, ok := _c.mutation.RateMultiplier(); !ok {
v := group.DefaultRateMultiplier
_c.mutation.SetRateMultiplier(v)
@@ -1095,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)
@@ -1155,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)
@@ -1230,6 +1276,9 @@ func (_c *GroupCreate) check() error {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Group.name": %w`, err)}
}
}
if _, ok := _c.mutation.I18n(); !ok {
return &ValidationError{Name: "i18n", err: errors.New(`ent: missing required field "Group.i18n"`)}
}
if _, ok := _c.mutation.RateMultiplier(); !ok {
return &ValidationError{Name: "rate_multiplier", err: errors.New(`ent: missing required field "Group.rate_multiplier"`)}
}
@@ -1296,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"`)}
}
@@ -1361,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"`)}
}
@@ -1465,6 +1520,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldDescription, field.TypeString, value)
_node.Description = &value
}
if value, ok := _c.mutation.I18n(); ok {
_spec.SetField(group.FieldI18n, field.TypeJSON, value)
_node.I18n = value
}
if value, ok := _c.mutation.RateMultiplier(); ok {
_spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value)
_node.RateMultiplier = value
@@ -1529,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
@@ -1653,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
@@ -1925,6 +1992,18 @@ func (u *GroupUpsert) ClearDescription() *GroupUpsert {
return u
}
// SetI18n sets the "i18n" field.
func (u *GroupUpsert) SetI18n(v domain.GroupI18n) *GroupUpsert {
u.Set(group.FieldI18n, v)
return u
}
// UpdateI18n sets the "i18n" field to the value that was provided on create.
func (u *GroupUpsert) UpdateI18n() *GroupUpsert {
u.SetExcluded(group.FieldI18n)
return u
}
// SetRateMultiplier sets the "rate_multiplier" field.
func (u *GroupUpsert) SetRateMultiplier(v float64) *GroupUpsert {
u.Set(group.FieldRateMultiplier, v)
@@ -2159,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)
@@ -2735,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)
@@ -3039,6 +3142,20 @@ func (u *GroupUpsertOne) ClearDescription() *GroupUpsertOne {
})
}
// SetI18n sets the "i18n" field.
func (u *GroupUpsertOne) SetI18n(v domain.GroupI18n) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetI18n(v)
})
}
// UpdateI18n sets the "i18n" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdateI18n() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdateI18n()
})
}
// SetRateMultiplier sets the "rate_multiplier" field.
func (u *GroupUpsertOne) SetRateMultiplier(v float64) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
@@ -3312,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) {
@@ -3984,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) {
@@ -4485,6 +4630,20 @@ func (u *GroupUpsertBulk) ClearDescription() *GroupUpsertBulk {
})
}
// SetI18n sets the "i18n" field.
func (u *GroupUpsertBulk) SetI18n(v domain.GroupI18n) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetI18n(v)
})
}
// UpdateI18n sets the "i18n" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdateI18n() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdateI18n()
})
}
// SetRateMultiplier sets the "rate_multiplier" field.
func (u *GroupUpsertBulk) SetRateMultiplier(v float64) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
@@ -4758,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) {
@@ -5430,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) {
+86
View File
@@ -97,6 +97,12 @@ func (_u *GroupUpdate) ClearDescription() *GroupUpdate {
return _u
}
// SetI18n sets the "i18n" field.
func (_u *GroupUpdate) SetI18n(v domain.GroupI18n) *GroupUpdate {
_u.mutation.SetI18n(v)
return _u
}
// SetRateMultiplier sets the "rate_multiplier" field.
func (_u *GroupUpdate) SetRateMultiplier(v float64) *GroupUpdate {
_u.mutation.ResetRateMultiplier()
@@ -367,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)
@@ -1003,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)
@@ -1581,6 +1615,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if _u.mutation.DescriptionCleared() {
_spec.ClearField(group.FieldDescription, field.TypeString)
}
if value, ok := _u.mutation.I18n(); ok {
_spec.SetField(group.FieldI18n, field.TypeJSON, value)
}
if value, ok := _u.mutation.RateMultiplier(); ok {
_spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value)
}
@@ -1656,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)
}
@@ -1861,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)
}
@@ -2291,6 +2334,12 @@ func (_u *GroupUpdateOne) ClearDescription() *GroupUpdateOne {
return _u
}
// SetI18n sets the "i18n" field.
func (_u *GroupUpdateOne) SetI18n(v domain.GroupI18n) *GroupUpdateOne {
_u.mutation.SetI18n(v)
return _u
}
// SetRateMultiplier sets the "rate_multiplier" field.
func (_u *GroupUpdateOne) SetRateMultiplier(v float64) *GroupUpdateOne {
_u.mutation.ResetRateMultiplier()
@@ -2561,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)
@@ -3197,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)
@@ -3805,6 +3882,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
if _u.mutation.DescriptionCleared() {
_spec.ClearField(group.FieldDescription, field.TypeString)
}
if value, ok := _u.mutation.I18n(); ok {
_spec.SetField(group.FieldI18n, field.TypeJSON, value)
}
if value, ok := _u.mutation.RateMultiplier(); ok {
_spec.SetField(group.FieldRateMultiplier, field.TypeFloat64, value)
}
@@ -3880,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)
}
@@ -4085,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)
}
+38 -32
View File
@@ -623,7 +623,7 @@ var (
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek"}},
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}},
{Name: "check_mode", Type: field.TypeString, Size: 32, Default: "probe"},
{Name: "account_id", Type: field.TypeInt64, Nullable: true},
{Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"},
@@ -776,7 +776,7 @@ var (
{Name: "created_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "updated_at", Type: field.TypeTime, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek"}},
{Name: "provider", Type: field.TypeEnum, Enums: []string{"openai", "anthropic", "gemini", "grok", "antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"}},
{Name: "api_mode", Type: field.TypeString, Size: 32, Default: "chat_completions"},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 500, Default: ""},
{Name: "extra_headers", Type: field.TypeJSON},
@@ -908,6 +908,7 @@ var (
{Name: "deleted_at", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"postgres": "timestamptz"}},
{Name: "name", Type: field.TypeString, Size: 100},
{Name: "description", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}},
{Name: "i18n", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "peak_rate_enabled", Type: field.TypeBool, Default: false},
{Name: "peak_start", Type: field.TypeString, Size: 5, Default: ""},
@@ -924,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)"}},
@@ -955,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},
@@ -979,22 +982,22 @@ var (
{
Name: "group_status",
Unique: false,
Columns: []*schema.Column{GroupsColumns[12]},
Columns: []*schema.Column{GroupsColumns[13]},
},
{
Name: "group_platform",
Unique: false,
Columns: []*schema.Column{GroupsColumns[14]},
Columns: []*schema.Column{GroupsColumns[15]},
},
{
Name: "group_subscription_type",
Unique: false,
Columns: []*schema.Column{GroupsColumns[15]},
Columns: []*schema.Column{GroupsColumns[16]},
},
{
Name: "group_is_exclusive",
Unique: false,
Columns: []*schema.Column{GroupsColumns[11]},
Columns: []*schema.Column{GroupsColumns[12]},
},
{
Name: "group_deleted_at",
@@ -1004,12 +1007,12 @@ var (
{
Name: "group_sort_order",
Unique: false,
Columns: []*schema.Column{GroupsColumns[49]},
Columns: []*schema.Column{GroupsColumns[51]},
},
{
Name: "idx_groups_duplicate_operation_id_active",
Unique: true,
Columns: []*schema.Column{GroupsColumns[13]},
Columns: []*schema.Column{GroupsColumns[14]},
Annotation: &entsql.IndexAnnotation{
Where: "duplicate_operation_id IS NOT NULL AND deleted_at IS NULL",
},
@@ -1128,6 +1131,7 @@ var (
{Name: "amount", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "decimal(20,2)"}},
{Name: "pay_amount", Type: field.TypeFloat64, SchemaType: map[string]string{"postgres": "decimal(20,2)"}},
{Name: "fee_rate", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
{Name: "bonus_amount", Type: field.TypeFloat64, Default: 0, SchemaType: map[string]string{"postgres": "decimal(20,2)"}},
{Name: "recharge_code", Type: field.TypeString, Size: 64},
{Name: "out_trade_no", Type: field.TypeString, Size: 64, Default: ""},
{Name: "payment_type", Type: field.TypeString, Size: 30},
@@ -1170,7 +1174,7 @@ var (
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "payment_orders_users_payment_orders",
Columns: []*schema.Column{PaymentOrdersColumns[39]},
Columns: []*schema.Column{PaymentOrdersColumns[40]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
@@ -1179,7 +1183,7 @@ var (
{
Name: "paymentorder_out_trade_no",
Unique: true,
Columns: []*schema.Column{PaymentOrdersColumns[8]},
Columns: []*schema.Column{PaymentOrdersColumns[9]},
Annotation: &entsql.IndexAnnotation{
Where: "out_trade_no <> ''",
},
@@ -1187,37 +1191,37 @@ var (
{
Name: "paymentorder_user_id",
Unique: false,
Columns: []*schema.Column{PaymentOrdersColumns[39]},
Columns: []*schema.Column{PaymentOrdersColumns[40]},
},
{
Name: "paymentorder_status",
Unique: false,
Columns: []*schema.Column{PaymentOrdersColumns[21]},
Columns: []*schema.Column{PaymentOrdersColumns[22]},
},
{
Name: "paymentorder_expires_at",
Unique: false,
Columns: []*schema.Column{PaymentOrdersColumns[29]},
Columns: []*schema.Column{PaymentOrdersColumns[30]},
},
{
Name: "paymentorder_created_at",
Unique: false,
Columns: []*schema.Column{PaymentOrdersColumns[37]},
Columns: []*schema.Column{PaymentOrdersColumns[38]},
},
{
Name: "paymentorder_paid_at",
Unique: false,
Columns: []*schema.Column{PaymentOrdersColumns[30]},
Columns: []*schema.Column{PaymentOrdersColumns[31]},
},
{
Name: "paymentorder_payment_type_paid_at",
Unique: false,
Columns: []*schema.Column{PaymentOrdersColumns[9], PaymentOrdersColumns[30]},
Columns: []*schema.Column{PaymentOrdersColumns[10], PaymentOrdersColumns[31]},
},
{
Name: "paymentorder_order_type",
Unique: false,
Columns: []*schema.Column{PaymentOrdersColumns[14]},
Columns: []*schema.Column{PaymentOrdersColumns[15]},
},
},
}
@@ -1413,7 +1417,7 @@ var (
{Name: "expires_at", Type: field.TypeTime, Nullable: true},
{Name: "fallback_mode", Type: field.TypeString, Size: 20, Default: "none"},
{Name: "expiry_warn_days", Type: field.TypeInt, Default: 7},
{Name: "backup_proxy_id", Type: field.TypeInt64, Unique: true, Nullable: true},
{Name: "backup_proxy_id", Type: field.TypeInt64, Nullable: true},
}
// ProxiesTable holds the schema information for the "proxies" table.
ProxiesTable = &schema.Table{
@@ -1652,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)"}},
@@ -1692,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,
},
@@ -1725,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",
@@ -1770,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]},
},
},
}
+539 -33
View File
@@ -22086,6 +22086,7 @@ type GroupMutation struct {
deleted_at *time.Time
name *string
description *string
i18n *domain.GroupI18n
rate_multiplier *float64
addrate_multiplier *float64
peak_rate_enabled *bool
@@ -22108,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
@@ -22159,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
@@ -22505,6 +22508,42 @@ func (m *GroupMutation) ResetDescription() {
delete(m.clearedFields, group.FieldDescription)
}
// SetI18n sets the "i18n" field.
func (m *GroupMutation) SetI18n(di domain.GroupI18n) {
m.i18n = &di
}
// I18n returns the value of the "i18n" field in the mutation.
func (m *GroupMutation) I18n() (r domain.GroupI18n, exists bool) {
v := m.i18n
if v == nil {
return
}
return *v, true
}
// OldI18n returns the old "i18n" 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) OldI18n(ctx context.Context) (v domain.GroupI18n, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldI18n is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldI18n requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldI18n: %w", err)
}
return oldValue.I18n, nil
}
// ResetI18n resets all changes to the "i18n" field.
func (m *GroupMutation) ResetI18n() {
m.i18n = nil
}
// SetRateMultiplier sets the "rate_multiplier" field.
func (m *GroupMutation) SetRateMultiplier(f float64) {
m.rate_multiplier = &f
@@ -23256,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
@@ -24984,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
@@ -25921,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, 66)
fields := make([]string, 0, 69)
if m.created_at != nil {
fields = append(fields, group.FieldCreatedAt)
}
@@ -25937,6 +26048,9 @@ func (m *GroupMutation) Fields() []string {
if m.description != nil {
fields = append(fields, group.FieldDescription)
}
if m.i18n != nil {
fields = append(fields, group.FieldI18n)
}
if m.rate_multiplier != nil {
fields = append(fields, group.FieldRateMultiplier)
}
@@ -25985,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)
}
@@ -26078,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)
}
@@ -26138,6 +26258,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
return m.Name()
case group.FieldDescription:
return m.Description()
case group.FieldI18n:
return m.I18n()
case group.FieldRateMultiplier:
return m.RateMultiplier()
case group.FieldPeakRateEnabled:
@@ -26170,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:
@@ -26232,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:
@@ -26279,6 +26405,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
return m.OldName(ctx)
case group.FieldDescription:
return m.OldDescription(ctx)
case group.FieldI18n:
return m.OldI18n(ctx)
case group.FieldRateMultiplier:
return m.OldRateMultiplier(ctx)
case group.FieldPeakRateEnabled:
@@ -26311,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:
@@ -26373,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:
@@ -26445,6 +26577,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
}
m.SetDescription(v)
return nil
case group.FieldI18n:
v, ok := value.(domain.GroupI18n)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetI18n(v)
return nil
case group.FieldRateMultiplier:
v, ok := value.(float64)
if !ok {
@@ -26557,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 {
@@ -26774,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 {
@@ -27398,6 +27551,9 @@ func (m *GroupMutation) ResetField(name string) error {
case group.FieldDescription:
m.ResetDescription()
return nil
case group.FieldI18n:
m.ResetI18n()
return nil
case group.FieldRateMultiplier:
m.ResetRateMultiplier()
return nil
@@ -27446,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
@@ -27539,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
@@ -30113,6 +30275,8 @@ type PaymentOrderMutation struct {
addpay_amount *float64
fee_rate *float64
addfee_rate *float64
bonus_amount *float64
addbonus_amount *float64
recharge_code *string
out_trade_no *string
payment_type *string
@@ -30580,6 +30744,62 @@ func (m *PaymentOrderMutation) ResetFeeRate() {
m.addfee_rate = nil
}
// SetBonusAmount sets the "bonus_amount" field.
func (m *PaymentOrderMutation) SetBonusAmount(f float64) {
m.bonus_amount = &f
m.addbonus_amount = nil
}
// BonusAmount returns the value of the "bonus_amount" field in the mutation.
func (m *PaymentOrderMutation) BonusAmount() (r float64, exists bool) {
v := m.bonus_amount
if v == nil {
return
}
return *v, true
}
// OldBonusAmount returns the old "bonus_amount" field's value of the PaymentOrder entity.
// If the PaymentOrder object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PaymentOrderMutation) OldBonusAmount(ctx context.Context) (v float64, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldBonusAmount is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldBonusAmount requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldBonusAmount: %w", err)
}
return oldValue.BonusAmount, nil
}
// AddBonusAmount adds f to the "bonus_amount" field.
func (m *PaymentOrderMutation) AddBonusAmount(f float64) {
if m.addbonus_amount != nil {
*m.addbonus_amount += f
} else {
m.addbonus_amount = &f
}
}
// AddedBonusAmount returns the value that was added to the "bonus_amount" field in this mutation.
func (m *PaymentOrderMutation) AddedBonusAmount() (r float64, exists bool) {
v := m.addbonus_amount
if v == nil {
return
}
return *v, true
}
// ResetBonusAmount resets all changes to the "bonus_amount" field.
func (m *PaymentOrderMutation) ResetBonusAmount() {
m.bonus_amount = nil
m.addbonus_amount = nil
}
// SetRechargeCode sets the "recharge_code" field.
func (m *PaymentOrderMutation) SetRechargeCode(s string) {
m.recharge_code = &s
@@ -32123,7 +32343,7 @@ func (m *PaymentOrderMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *PaymentOrderMutation) Fields() []string {
fields := make([]string, 0, 39)
fields := make([]string, 0, 40)
if m.user != nil {
fields = append(fields, paymentorder.FieldUserID)
}
@@ -32145,6 +32365,9 @@ func (m *PaymentOrderMutation) Fields() []string {
if m.fee_rate != nil {
fields = append(fields, paymentorder.FieldFeeRate)
}
if m.bonus_amount != nil {
fields = append(fields, paymentorder.FieldBonusAmount)
}
if m.recharge_code != nil {
fields = append(fields, paymentorder.FieldRechargeCode)
}
@@ -32263,6 +32486,8 @@ func (m *PaymentOrderMutation) Field(name string) (ent.Value, bool) {
return m.PayAmount()
case paymentorder.FieldFeeRate:
return m.FeeRate()
case paymentorder.FieldBonusAmount:
return m.BonusAmount()
case paymentorder.FieldRechargeCode:
return m.RechargeCode()
case paymentorder.FieldOutTradeNo:
@@ -32350,6 +32575,8 @@ func (m *PaymentOrderMutation) OldField(ctx context.Context, name string) (ent.V
return m.OldPayAmount(ctx)
case paymentorder.FieldFeeRate:
return m.OldFeeRate(ctx)
case paymentorder.FieldBonusAmount:
return m.OldBonusAmount(ctx)
case paymentorder.FieldRechargeCode:
return m.OldRechargeCode(ctx)
case paymentorder.FieldOutTradeNo:
@@ -32472,6 +32699,13 @@ func (m *PaymentOrderMutation) SetField(name string, value ent.Value) error {
}
m.SetFeeRate(v)
return nil
case paymentorder.FieldBonusAmount:
v, ok := value.(float64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetBonusAmount(v)
return nil
case paymentorder.FieldRechargeCode:
v, ok := value.(string)
if !ok {
@@ -32713,6 +32947,9 @@ func (m *PaymentOrderMutation) AddedFields() []string {
if m.addfee_rate != nil {
fields = append(fields, paymentorder.FieldFeeRate)
}
if m.addbonus_amount != nil {
fields = append(fields, paymentorder.FieldBonusAmount)
}
if m.addplan_id != nil {
fields = append(fields, paymentorder.FieldPlanID)
}
@@ -32739,6 +32976,8 @@ func (m *PaymentOrderMutation) AddedField(name string) (ent.Value, bool) {
return m.AddedPayAmount()
case paymentorder.FieldFeeRate:
return m.AddedFeeRate()
case paymentorder.FieldBonusAmount:
return m.AddedBonusAmount()
case paymentorder.FieldPlanID:
return m.AddedPlanID()
case paymentorder.FieldSubscriptionGroupID:
@@ -32777,6 +33016,13 @@ func (m *PaymentOrderMutation) AddField(name string, value ent.Value) error {
}
m.AddFeeRate(v)
return nil
case paymentorder.FieldBonusAmount:
v, ok := value.(float64)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddBonusAmount(v)
return nil
case paymentorder.FieldPlanID:
v, ok := value.(int64)
if !ok {
@@ -32976,6 +33222,9 @@ func (m *PaymentOrderMutation) ResetField(name string) error {
case paymentorder.FieldFeeRate:
m.ResetFeeRate()
return nil
case paymentorder.FieldBonusAmount:
m.ResetBonusAmount()
return nil
case paymentorder.FieldRechargeCode:
m.ResetRechargeCode()
return nil
@@ -37366,33 +37615,36 @@ func (m *PromoCodeUsageMutation) ResetEdge(name string) error {
// ProxyMutation represents an operation that mutates the Proxy nodes in the graph.
type ProxyMutation struct {
config
op Op
typ string
id *int64
created_at *time.Time
updated_at *time.Time
deleted_at *time.Time
name *string
protocol *string
host *string
port *int
addport *int
username *string
password *string
status *string
expires_at *time.Time
fallback_mode *string
expiry_warn_days *int
addexpiry_warn_days *int
clearedFields map[string]struct{}
accounts map[int64]struct{}
removedaccounts map[int64]struct{}
clearedaccounts bool
backup_proxy *int64
clearedbackup_proxy bool
done bool
oldValue func(context.Context) (*Proxy, error)
predicates []predicate.Proxy
op Op
typ string
id *int64
created_at *time.Time
updated_at *time.Time
deleted_at *time.Time
name *string
protocol *string
host *string
port *int
addport *int
username *string
password *string
status *string
expires_at *time.Time
fallback_mode *string
expiry_warn_days *int
addexpiry_warn_days *int
clearedFields map[string]struct{}
accounts map[int64]struct{}
removedaccounts map[int64]struct{}
clearedaccounts bool
primary_proxies map[int64]struct{}
removedprimary_proxies map[int64]struct{}
clearedprimary_proxies bool
backup_proxy *int64
clearedbackup_proxy bool
done bool
oldValue func(context.Context) (*Proxy, error)
predicates []predicate.Proxy
}
var _ ent.Mutation = (*ProxyMutation)(nil)
@@ -38156,6 +38408,60 @@ func (m *ProxyMutation) ResetAccounts() {
m.removedaccounts = nil
}
// AddPrimaryProxyIDs adds the "primary_proxies" edge to the Proxy entity by ids.
func (m *ProxyMutation) AddPrimaryProxyIDs(ids ...int64) {
if m.primary_proxies == nil {
m.primary_proxies = make(map[int64]struct{})
}
for i := range ids {
m.primary_proxies[ids[i]] = struct{}{}
}
}
// ClearPrimaryProxies clears the "primary_proxies" edge to the Proxy entity.
func (m *ProxyMutation) ClearPrimaryProxies() {
m.clearedprimary_proxies = true
}
// PrimaryProxiesCleared reports if the "primary_proxies" edge to the Proxy entity was cleared.
func (m *ProxyMutation) PrimaryProxiesCleared() bool {
return m.clearedprimary_proxies
}
// RemovePrimaryProxyIDs removes the "primary_proxies" edge to the Proxy entity by IDs.
func (m *ProxyMutation) RemovePrimaryProxyIDs(ids ...int64) {
if m.removedprimary_proxies == nil {
m.removedprimary_proxies = make(map[int64]struct{})
}
for i := range ids {
delete(m.primary_proxies, ids[i])
m.removedprimary_proxies[ids[i]] = struct{}{}
}
}
// RemovedPrimaryProxies returns the removed IDs of the "primary_proxies" edge to the Proxy entity.
func (m *ProxyMutation) RemovedPrimaryProxiesIDs() (ids []int64) {
for id := range m.removedprimary_proxies {
ids = append(ids, id)
}
return
}
// PrimaryProxiesIDs returns the "primary_proxies" edge IDs in the mutation.
func (m *ProxyMutation) PrimaryProxiesIDs() (ids []int64) {
for id := range m.primary_proxies {
ids = append(ids, id)
}
return
}
// ResetPrimaryProxies resets all changes to the "primary_proxies" edge.
func (m *ProxyMutation) ResetPrimaryProxies() {
m.primary_proxies = nil
m.clearedprimary_proxies = false
m.removedprimary_proxies = nil
}
// ClearBackupProxy clears the "backup_proxy" edge to the Proxy entity.
func (m *ProxyMutation) ClearBackupProxy() {
m.clearedbackup_proxy = true
@@ -38597,10 +38903,13 @@ func (m *ProxyMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *ProxyMutation) AddedEdges() []string {
edges := make([]string, 0, 2)
edges := make([]string, 0, 3)
if m.accounts != nil {
edges = append(edges, proxy.EdgeAccounts)
}
if m.primary_proxies != nil {
edges = append(edges, proxy.EdgePrimaryProxies)
}
if m.backup_proxy != nil {
edges = append(edges, proxy.EdgeBackupProxy)
}
@@ -38617,6 +38926,12 @@ func (m *ProxyMutation) AddedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
case proxy.EdgePrimaryProxies:
ids := make([]ent.Value, 0, len(m.primary_proxies))
for id := range m.primary_proxies {
ids = append(ids, id)
}
return ids
case proxy.EdgeBackupProxy:
if id := m.backup_proxy; id != nil {
return []ent.Value{*id}
@@ -38627,10 +38942,13 @@ func (m *ProxyMutation) AddedIDs(name string) []ent.Value {
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *ProxyMutation) RemovedEdges() []string {
edges := make([]string, 0, 2)
edges := make([]string, 0, 3)
if m.removedaccounts != nil {
edges = append(edges, proxy.EdgeAccounts)
}
if m.removedprimary_proxies != nil {
edges = append(edges, proxy.EdgePrimaryProxies)
}
return edges
}
@@ -38644,16 +38962,25 @@ func (m *ProxyMutation) RemovedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
case proxy.EdgePrimaryProxies:
ids := make([]ent.Value, 0, len(m.removedprimary_proxies))
for id := range m.removedprimary_proxies {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *ProxyMutation) ClearedEdges() []string {
edges := make([]string, 0, 2)
edges := make([]string, 0, 3)
if m.clearedaccounts {
edges = append(edges, proxy.EdgeAccounts)
}
if m.clearedprimary_proxies {
edges = append(edges, proxy.EdgePrimaryProxies)
}
if m.clearedbackup_proxy {
edges = append(edges, proxy.EdgeBackupProxy)
}
@@ -38666,6 +38993,8 @@ func (m *ProxyMutation) EdgeCleared(name string) bool {
switch name {
case proxy.EdgeAccounts:
return m.clearedaccounts
case proxy.EdgePrimaryProxies:
return m.clearedprimary_proxies
case proxy.EdgeBackupProxy:
return m.clearedbackup_proxy
}
@@ -38690,6 +39019,9 @@ func (m *ProxyMutation) ResetEdge(name string) error {
case proxy.EdgeAccounts:
m.ResetAccounts()
return nil
case proxy.EdgePrimaryProxies:
m.ResetPrimaryProxies()
return nil
case proxy.EdgeBackupProxy:
m.ResetBackupProxy()
return nil
@@ -44470,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
@@ -45651,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
@@ -47196,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)
}
@@ -47260,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)
}
@@ -47388,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:
@@ -47491,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:
@@ -47699,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 {
@@ -47910,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)
}
@@ -47974,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:
@@ -48060,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 {
@@ -48383,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
+12 -1
View File
@@ -33,6 +33,8 @@ type PaymentOrder struct {
PayAmount float64 `json:"pay_amount,omitempty"`
// FeeRate holds the value of the "fee_rate" field.
FeeRate float64 `json:"fee_rate,omitempty"`
// BonusAmount holds the value of the "bonus_amount" field.
BonusAmount float64 `json:"bonus_amount,omitempty"`
// RechargeCode holds the value of the "recharge_code" field.
RechargeCode string `json:"recharge_code,omitempty"`
// OutTradeNo holds the value of the "out_trade_no" field.
@@ -132,7 +134,7 @@ func (*PaymentOrder) scanValues(columns []string) ([]any, error) {
values[i] = new([]byte)
case paymentorder.FieldForceRefund:
values[i] = new(sql.NullBool)
case paymentorder.FieldAmount, paymentorder.FieldPayAmount, paymentorder.FieldFeeRate, paymentorder.FieldRefundAmount:
case paymentorder.FieldAmount, paymentorder.FieldPayAmount, paymentorder.FieldFeeRate, paymentorder.FieldBonusAmount, paymentorder.FieldRefundAmount:
values[i] = new(sql.NullFloat64)
case paymentorder.FieldID, paymentorder.FieldUserID, paymentorder.FieldPlanID, paymentorder.FieldSubscriptionGroupID, paymentorder.FieldSubscriptionDays:
values[i] = new(sql.NullInt64)
@@ -204,6 +206,12 @@ func (_m *PaymentOrder) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.FeeRate = value.Float64
}
case paymentorder.FieldBonusAmount:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field bonus_amount", values[i])
} else if value.Valid {
_m.BonusAmount = value.Float64
}
case paymentorder.FieldRechargeCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field recharge_code", values[i])
@@ -480,6 +488,9 @@ func (_m *PaymentOrder) String() string {
builder.WriteString("fee_rate=")
builder.WriteString(fmt.Sprintf("%v", _m.FeeRate))
builder.WriteString(", ")
builder.WriteString("bonus_amount=")
builder.WriteString(fmt.Sprintf("%v", _m.BonusAmount))
builder.WriteString(", ")
builder.WriteString("recharge_code=")
builder.WriteString(_m.RechargeCode)
builder.WriteString(", ")
+10
View File
@@ -28,6 +28,8 @@ const (
FieldPayAmount = "pay_amount"
// FieldFeeRate holds the string denoting the fee_rate field in the database.
FieldFeeRate = "fee_rate"
// FieldBonusAmount holds the string denoting the bonus_amount field in the database.
FieldBonusAmount = "bonus_amount"
// FieldRechargeCode holds the string denoting the recharge_code field in the database.
FieldRechargeCode = "recharge_code"
// FieldOutTradeNo holds the string denoting the out_trade_no field in the database.
@@ -115,6 +117,7 @@ var Columns = []string{
FieldAmount,
FieldPayAmount,
FieldFeeRate,
FieldBonusAmount,
FieldRechargeCode,
FieldOutTradeNo,
FieldPaymentType,
@@ -166,6 +169,8 @@ var (
UserNameValidator func(string) error
// DefaultFeeRate holds the default value on creation for the "fee_rate" field.
DefaultFeeRate float64
// DefaultBonusAmount holds the default value on creation for the "bonus_amount" field.
DefaultBonusAmount float64
// RechargeCodeValidator is a validator for the "recharge_code" field. It is called by the builders before save.
RechargeCodeValidator func(string) error
// DefaultOutTradeNo holds the default value on creation for the "out_trade_no" field.
@@ -249,6 +254,11 @@ func ByFeeRate(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFeeRate, opts...).ToFunc()
}
// ByBonusAmount orders the results by the bonus_amount field.
func ByBonusAmount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBonusAmount, opts...).ToFunc()
}
// ByRechargeCode orders the results by the recharge_code field.
func ByRechargeCode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRechargeCode, opts...).ToFunc()
+45
View File
@@ -90,6 +90,11 @@ func FeeRate(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldEQ(FieldFeeRate, v))
}
// BonusAmount applies equality check predicate on the "bonus_amount" field. It's identical to BonusAmountEQ.
func BonusAmount(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldEQ(FieldBonusAmount, v))
}
// RechargeCode applies equality check predicate on the "recharge_code" field. It's identical to RechargeCodeEQ.
func RechargeCode(v string) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldEQ(FieldRechargeCode, v))
@@ -590,6 +595,46 @@ func FeeRateLTE(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldLTE(FieldFeeRate, v))
}
// BonusAmountEQ applies the EQ predicate on the "bonus_amount" field.
func BonusAmountEQ(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldEQ(FieldBonusAmount, v))
}
// BonusAmountNEQ applies the NEQ predicate on the "bonus_amount" field.
func BonusAmountNEQ(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldNEQ(FieldBonusAmount, v))
}
// BonusAmountIn applies the In predicate on the "bonus_amount" field.
func BonusAmountIn(vs ...float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldIn(FieldBonusAmount, vs...))
}
// BonusAmountNotIn applies the NotIn predicate on the "bonus_amount" field.
func BonusAmountNotIn(vs ...float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldNotIn(FieldBonusAmount, vs...))
}
// BonusAmountGT applies the GT predicate on the "bonus_amount" field.
func BonusAmountGT(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldGT(FieldBonusAmount, v))
}
// BonusAmountGTE applies the GTE predicate on the "bonus_amount" field.
func BonusAmountGTE(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldGTE(FieldBonusAmount, v))
}
// BonusAmountLT applies the LT predicate on the "bonus_amount" field.
func BonusAmountLT(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldLT(FieldBonusAmount, v))
}
// BonusAmountLTE applies the LTE predicate on the "bonus_amount" field.
func BonusAmountLTE(v float64) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldLTE(FieldBonusAmount, v))
}
// RechargeCodeEQ applies the EQ predicate on the "recharge_code" field.
func RechargeCodeEQ(v string) predicate.PaymentOrder {
return predicate.PaymentOrder(sql.FieldEQ(FieldRechargeCode, v))
+85
View File
@@ -81,6 +81,20 @@ func (_c *PaymentOrderCreate) SetNillableFeeRate(v *float64) *PaymentOrderCreate
return _c
}
// SetBonusAmount sets the "bonus_amount" field.
func (_c *PaymentOrderCreate) SetBonusAmount(v float64) *PaymentOrderCreate {
_c.mutation.SetBonusAmount(v)
return _c
}
// SetNillableBonusAmount sets the "bonus_amount" field if the given value is not nil.
func (_c *PaymentOrderCreate) SetNillableBonusAmount(v *float64) *PaymentOrderCreate {
if v != nil {
_c.SetBonusAmount(*v)
}
return _c
}
// SetRechargeCode sets the "recharge_code" field.
func (_c *PaymentOrderCreate) SetRechargeCode(v string) *PaymentOrderCreate {
_c.mutation.SetRechargeCode(v)
@@ -517,6 +531,10 @@ func (_c *PaymentOrderCreate) defaults() {
v := paymentorder.DefaultFeeRate
_c.mutation.SetFeeRate(v)
}
if _, ok := _c.mutation.BonusAmount(); !ok {
v := paymentorder.DefaultBonusAmount
_c.mutation.SetBonusAmount(v)
}
if _, ok := _c.mutation.OutTradeNo(); !ok {
v := paymentorder.DefaultOutTradeNo
_c.mutation.SetOutTradeNo(v)
@@ -577,6 +595,9 @@ func (_c *PaymentOrderCreate) check() error {
if _, ok := _c.mutation.FeeRate(); !ok {
return &ValidationError{Name: "fee_rate", err: errors.New(`ent: missing required field "PaymentOrder.fee_rate"`)}
}
if _, ok := _c.mutation.BonusAmount(); !ok {
return &ValidationError{Name: "bonus_amount", err: errors.New(`ent: missing required field "PaymentOrder.bonus_amount"`)}
}
if _, ok := _c.mutation.RechargeCode(); !ok {
return &ValidationError{Name: "recharge_code", err: errors.New(`ent: missing required field "PaymentOrder.recharge_code"`)}
}
@@ -725,6 +746,10 @@ func (_c *PaymentOrderCreate) createSpec() (*PaymentOrder, *sqlgraph.CreateSpec)
_spec.SetField(paymentorder.FieldFeeRate, field.TypeFloat64, value)
_node.FeeRate = value
}
if value, ok := _c.mutation.BonusAmount(); ok {
_spec.SetField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
_node.BonusAmount = value
}
if value, ok := _c.mutation.RechargeCode(); ok {
_spec.SetField(paymentorder.FieldRechargeCode, field.TypeString, value)
_node.RechargeCode = value
@@ -1030,6 +1055,24 @@ func (u *PaymentOrderUpsert) AddFeeRate(v float64) *PaymentOrderUpsert {
return u
}
// SetBonusAmount sets the "bonus_amount" field.
func (u *PaymentOrderUpsert) SetBonusAmount(v float64) *PaymentOrderUpsert {
u.Set(paymentorder.FieldBonusAmount, v)
return u
}
// UpdateBonusAmount sets the "bonus_amount" field to the value that was provided on create.
func (u *PaymentOrderUpsert) UpdateBonusAmount() *PaymentOrderUpsert {
u.SetExcluded(paymentorder.FieldBonusAmount)
return u
}
// AddBonusAmount adds v to the "bonus_amount" field.
func (u *PaymentOrderUpsert) AddBonusAmount(v float64) *PaymentOrderUpsert {
u.Add(paymentorder.FieldBonusAmount, v)
return u
}
// SetRechargeCode sets the "recharge_code" field.
func (u *PaymentOrderUpsert) SetRechargeCode(v string) *PaymentOrderUpsert {
u.Set(paymentorder.FieldRechargeCode, v)
@@ -1711,6 +1754,27 @@ func (u *PaymentOrderUpsertOne) UpdateFeeRate() *PaymentOrderUpsertOne {
})
}
// SetBonusAmount sets the "bonus_amount" field.
func (u *PaymentOrderUpsertOne) SetBonusAmount(v float64) *PaymentOrderUpsertOne {
return u.Update(func(s *PaymentOrderUpsert) {
s.SetBonusAmount(v)
})
}
// AddBonusAmount adds v to the "bonus_amount" field.
func (u *PaymentOrderUpsertOne) AddBonusAmount(v float64) *PaymentOrderUpsertOne {
return u.Update(func(s *PaymentOrderUpsert) {
s.AddBonusAmount(v)
})
}
// UpdateBonusAmount sets the "bonus_amount" field to the value that was provided on create.
func (u *PaymentOrderUpsertOne) UpdateBonusAmount() *PaymentOrderUpsertOne {
return u.Update(func(s *PaymentOrderUpsert) {
s.UpdateBonusAmount()
})
}
// SetRechargeCode sets the "recharge_code" field.
func (u *PaymentOrderUpsertOne) SetRechargeCode(v string) *PaymentOrderUpsertOne {
return u.Update(func(s *PaymentOrderUpsert) {
@@ -2643,6 +2707,27 @@ func (u *PaymentOrderUpsertBulk) UpdateFeeRate() *PaymentOrderUpsertBulk {
})
}
// SetBonusAmount sets the "bonus_amount" field.
func (u *PaymentOrderUpsertBulk) SetBonusAmount(v float64) *PaymentOrderUpsertBulk {
return u.Update(func(s *PaymentOrderUpsert) {
s.SetBonusAmount(v)
})
}
// AddBonusAmount adds v to the "bonus_amount" field.
func (u *PaymentOrderUpsertBulk) AddBonusAmount(v float64) *PaymentOrderUpsertBulk {
return u.Update(func(s *PaymentOrderUpsert) {
s.AddBonusAmount(v)
})
}
// UpdateBonusAmount sets the "bonus_amount" field to the value that was provided on create.
func (u *PaymentOrderUpsertBulk) UpdateBonusAmount() *PaymentOrderUpsertBulk {
return u.Update(func(s *PaymentOrderUpsert) {
s.UpdateBonusAmount()
})
}
// SetRechargeCode sets the "recharge_code" field.
func (u *PaymentOrderUpsertBulk) SetRechargeCode(v string) *PaymentOrderUpsertBulk {
return u.Update(func(s *PaymentOrderUpsert) {
+54
View File
@@ -154,6 +154,27 @@ func (_u *PaymentOrderUpdate) AddFeeRate(v float64) *PaymentOrderUpdate {
return _u
}
// SetBonusAmount sets the "bonus_amount" field.
func (_u *PaymentOrderUpdate) SetBonusAmount(v float64) *PaymentOrderUpdate {
_u.mutation.ResetBonusAmount()
_u.mutation.SetBonusAmount(v)
return _u
}
// SetNillableBonusAmount sets the "bonus_amount" field if the given value is not nil.
func (_u *PaymentOrderUpdate) SetNillableBonusAmount(v *float64) *PaymentOrderUpdate {
if v != nil {
_u.SetBonusAmount(*v)
}
return _u
}
// AddBonusAmount adds value to the "bonus_amount" field.
func (_u *PaymentOrderUpdate) AddBonusAmount(v float64) *PaymentOrderUpdate {
_u.mutation.AddBonusAmount(v)
return _u
}
// SetRechargeCode sets the "recharge_code" field.
func (_u *PaymentOrderUpdate) SetRechargeCode(v string) *PaymentOrderUpdate {
_u.mutation.SetRechargeCode(v)
@@ -881,6 +902,12 @@ func (_u *PaymentOrderUpdate) sqlSave(ctx context.Context) (_node int, err error
if value, ok := _u.mutation.AddedFeeRate(); ok {
_spec.AddField(paymentorder.FieldFeeRate, field.TypeFloat64, value)
}
if value, ok := _u.mutation.BonusAmount(); ok {
_spec.SetField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
}
if value, ok := _u.mutation.AddedBonusAmount(); ok {
_spec.AddField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
}
if value, ok := _u.mutation.RechargeCode(); ok {
_spec.SetField(paymentorder.FieldRechargeCode, field.TypeString, value)
}
@@ -1217,6 +1244,27 @@ func (_u *PaymentOrderUpdateOne) AddFeeRate(v float64) *PaymentOrderUpdateOne {
return _u
}
// SetBonusAmount sets the "bonus_amount" field.
func (_u *PaymentOrderUpdateOne) SetBonusAmount(v float64) *PaymentOrderUpdateOne {
_u.mutation.ResetBonusAmount()
_u.mutation.SetBonusAmount(v)
return _u
}
// SetNillableBonusAmount sets the "bonus_amount" field if the given value is not nil.
func (_u *PaymentOrderUpdateOne) SetNillableBonusAmount(v *float64) *PaymentOrderUpdateOne {
if v != nil {
_u.SetBonusAmount(*v)
}
return _u
}
// AddBonusAmount adds value to the "bonus_amount" field.
func (_u *PaymentOrderUpdateOne) AddBonusAmount(v float64) *PaymentOrderUpdateOne {
_u.mutation.AddBonusAmount(v)
return _u
}
// SetRechargeCode sets the "recharge_code" field.
func (_u *PaymentOrderUpdateOne) SetRechargeCode(v string) *PaymentOrderUpdateOne {
_u.mutation.SetRechargeCode(v)
@@ -1974,6 +2022,12 @@ func (_u *PaymentOrderUpdateOne) sqlSave(ctx context.Context) (_node *PaymentOrd
if value, ok := _u.mutation.AddedFeeRate(); ok {
_spec.AddField(paymentorder.FieldFeeRate, field.TypeFloat64, value)
}
if value, ok := _u.mutation.BonusAmount(); ok {
_spec.SetField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
}
if value, ok := _u.mutation.AddedBonusAmount(); ok {
_spec.AddField(paymentorder.FieldBonusAmount, field.TypeFloat64, value)
}
if value, ok := _u.mutation.RechargeCode(); ok {
_spec.SetField(paymentorder.FieldRechargeCode, field.TypeString, value)
}
+18 -2
View File
@@ -55,11 +55,13 @@ type Proxy struct {
type ProxyEdges struct {
// Accounts holds the value of the accounts edge.
Accounts []*Account `json:"accounts,omitempty"`
// PrimaryProxies holds the value of the primary_proxies edge.
PrimaryProxies []*Proxy `json:"primary_proxies,omitempty"`
// BackupProxy holds the value of the backup_proxy edge.
BackupProxy *Proxy `json:"backup_proxy,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
loadedTypes [3]bool
}
// AccountsOrErr returns the Accounts value or an error if the edge
@@ -71,12 +73,21 @@ func (e ProxyEdges) AccountsOrErr() ([]*Account, error) {
return nil, &NotLoadedError{edge: "accounts"}
}
// PrimaryProxiesOrErr returns the PrimaryProxies value or an error if the edge
// was not loaded in eager-loading.
func (e ProxyEdges) PrimaryProxiesOrErr() ([]*Proxy, error) {
if e.loadedTypes[1] {
return e.PrimaryProxies, nil
}
return nil, &NotLoadedError{edge: "primary_proxies"}
}
// BackupProxyOrErr returns the BackupProxy value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ProxyEdges) BackupProxyOrErr() (*Proxy, error) {
if e.BackupProxy != nil {
return e.BackupProxy, nil
} else if e.loadedTypes[1] {
} else if e.loadedTypes[2] {
return nil, &NotFoundError{label: proxy.Label}
}
return nil, &NotLoadedError{edge: "backup_proxy"}
@@ -221,6 +232,11 @@ func (_m *Proxy) QueryAccounts() *AccountQuery {
return NewProxyClient(_m.config).QueryAccounts(_m)
}
// QueryPrimaryProxies queries the "primary_proxies" edge of the Proxy entity.
func (_m *Proxy) QueryPrimaryProxies() *ProxyQuery {
return NewProxyClient(_m.config).QueryPrimaryProxies(_m)
}
// QueryBackupProxy queries the "backup_proxy" edge of the Proxy entity.
func (_m *Proxy) QueryBackupProxy() *ProxyQuery {
return NewProxyClient(_m.config).QueryBackupProxy(_m)
+28 -1
View File
@@ -45,6 +45,8 @@ const (
FieldExpiryWarnDays = "expiry_warn_days"
// EdgeAccounts holds the string denoting the accounts edge name in mutations.
EdgeAccounts = "accounts"
// EdgePrimaryProxies holds the string denoting the primary_proxies edge name in mutations.
EdgePrimaryProxies = "primary_proxies"
// EdgeBackupProxy holds the string denoting the backup_proxy edge name in mutations.
EdgeBackupProxy = "backup_proxy"
// Table holds the table name of the proxy in the database.
@@ -56,6 +58,10 @@ const (
AccountsInverseTable = "accounts"
// AccountsColumn is the table column denoting the accounts relation/edge.
AccountsColumn = "proxy_id"
// PrimaryProxiesTable is the table that holds the primary_proxies relation/edge.
PrimaryProxiesTable = "proxies"
// PrimaryProxiesColumn is the table column denoting the primary_proxies relation/edge.
PrimaryProxiesColumn = "backup_proxy_id"
// BackupProxyTable is the table that holds the backup_proxy relation/edge.
BackupProxyTable = "proxies"
// BackupProxyColumn is the table column denoting the backup_proxy relation/edge.
@@ -219,6 +225,20 @@ func ByAccounts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
}
}
// ByPrimaryProxiesCount orders the results by primary_proxies count.
func ByPrimaryProxiesCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newPrimaryProxiesStep(), opts...)
}
}
// ByPrimaryProxies orders the results by primary_proxies terms.
func ByPrimaryProxies(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newPrimaryProxiesStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByBackupProxyField orders the results by backup_proxy field.
func ByBackupProxyField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
@@ -232,10 +252,17 @@ func newAccountsStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.O2M, true, AccountsTable, AccountsColumn),
)
}
func newPrimaryProxiesStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, PrimaryProxiesTable, PrimaryProxiesColumn),
)
}
func newBackupProxyStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, BackupProxyTable, BackupProxyColumn),
sqlgraph.Edge(sqlgraph.M2O, false, BackupProxyTable, BackupProxyColumn),
)
}
+24 -1
View File
@@ -913,12 +913,35 @@ func HasAccountsWith(preds ...predicate.Account) predicate.Proxy {
})
}
// HasPrimaryProxies applies the HasEdge predicate on the "primary_proxies" edge.
func HasPrimaryProxies() predicate.Proxy {
return predicate.Proxy(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, PrimaryProxiesTable, PrimaryProxiesColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasPrimaryProxiesWith applies the HasEdge predicate on the "primary_proxies" edge with a given conditions (other predicates).
func HasPrimaryProxiesWith(preds ...predicate.Proxy) predicate.Proxy {
return predicate.Proxy(func(s *sql.Selector) {
step := newPrimaryProxiesStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasBackupProxy applies the HasEdge predicate on the "backup_proxy" edge.
func HasBackupProxy() predicate.Proxy {
return predicate.Proxy(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, BackupProxyTable, BackupProxyColumn),
sqlgraph.Edge(sqlgraph.M2O, false, BackupProxyTable, BackupProxyColumn),
)
sqlgraph.HasNeighbors(s, step)
})
+33 -2
View File
@@ -202,6 +202,21 @@ func (_c *ProxyCreate) AddAccounts(v ...*Account) *ProxyCreate {
return _c.AddAccountIDs(ids...)
}
// AddPrimaryProxyIDs adds the "primary_proxies" edge to the Proxy entity by IDs.
func (_c *ProxyCreate) AddPrimaryProxyIDs(ids ...int64) *ProxyCreate {
_c.mutation.AddPrimaryProxyIDs(ids...)
return _c
}
// AddPrimaryProxies adds the "primary_proxies" edges to the Proxy entity.
func (_c *ProxyCreate) AddPrimaryProxies(v ...*Proxy) *ProxyCreate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddPrimaryProxyIDs(ids...)
}
// SetBackupProxy sets the "backup_proxy" edge to the Proxy entity.
func (_c *ProxyCreate) SetBackupProxy(v *Proxy) *ProxyCreate {
return _c.SetBackupProxyID(v.ID)
@@ -432,13 +447,29 @@ func (_c *ProxyCreate) createSpec() (*Proxy, *sqlgraph.CreateSpec) {
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.PrimaryProxiesIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: proxy.PrimaryProxiesTable,
Columns: []string{proxy.PrimaryProxiesColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.BackupProxyIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: proxy.BackupProxyTable,
Columns: []string{proxy.BackupProxyColumn},
Bidi: true,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
+92 -16
View File
@@ -21,13 +21,14 @@ import (
// ProxyQuery is the builder for querying Proxy entities.
type ProxyQuery struct {
config
ctx *QueryContext
order []proxy.OrderOption
inters []Interceptor
predicates []predicate.Proxy
withAccounts *AccountQuery
withBackupProxy *ProxyQuery
modifiers []func(*sql.Selector)
ctx *QueryContext
order []proxy.OrderOption
inters []Interceptor
predicates []predicate.Proxy
withAccounts *AccountQuery
withPrimaryProxies *ProxyQuery
withBackupProxy *ProxyQuery
modifiers []func(*sql.Selector)
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
@@ -86,6 +87,28 @@ func (_q *ProxyQuery) QueryAccounts() *AccountQuery {
return query
}
// QueryPrimaryProxies chains the current query on the "primary_proxies" edge.
func (_q *ProxyQuery) QueryPrimaryProxies() *ProxyQuery {
query := (&ProxyClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(proxy.Table, proxy.FieldID, selector),
sqlgraph.To(proxy.Table, proxy.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, proxy.PrimaryProxiesTable, proxy.PrimaryProxiesColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryBackupProxy chains the current query on the "backup_proxy" edge.
func (_q *ProxyQuery) QueryBackupProxy() *ProxyQuery {
query := (&ProxyClient{config: _q.config}).Query()
@@ -100,7 +123,7 @@ func (_q *ProxyQuery) QueryBackupProxy() *ProxyQuery {
step := sqlgraph.NewStep(
sqlgraph.From(proxy.Table, proxy.FieldID, selector),
sqlgraph.To(proxy.Table, proxy.FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, proxy.BackupProxyTable, proxy.BackupProxyColumn),
sqlgraph.Edge(sqlgraph.M2O, false, proxy.BackupProxyTable, proxy.BackupProxyColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
@@ -295,13 +318,14 @@ func (_q *ProxyQuery) Clone() *ProxyQuery {
return nil
}
return &ProxyQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]proxy.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Proxy{}, _q.predicates...),
withAccounts: _q.withAccounts.Clone(),
withBackupProxy: _q.withBackupProxy.Clone(),
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]proxy.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Proxy{}, _q.predicates...),
withAccounts: _q.withAccounts.Clone(),
withPrimaryProxies: _q.withPrimaryProxies.Clone(),
withBackupProxy: _q.withBackupProxy.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
@@ -319,6 +343,17 @@ func (_q *ProxyQuery) WithAccounts(opts ...func(*AccountQuery)) *ProxyQuery {
return _q
}
// WithPrimaryProxies tells the query-builder to eager-load the nodes that are connected to
// the "primary_proxies" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *ProxyQuery) WithPrimaryProxies(opts ...func(*ProxyQuery)) *ProxyQuery {
query := (&ProxyClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withPrimaryProxies = query
return _q
}
// WithBackupProxy tells the query-builder to eager-load the nodes that are connected to
// the "backup_proxy" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *ProxyQuery) WithBackupProxy(opts ...func(*ProxyQuery)) *ProxyQuery {
@@ -408,8 +443,9 @@ func (_q *ProxyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Proxy,
var (
nodes = []*Proxy{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
loadedTypes = [3]bool{
_q.withAccounts != nil,
_q.withPrimaryProxies != nil,
_q.withBackupProxy != nil,
}
)
@@ -441,6 +477,13 @@ func (_q *ProxyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Proxy,
return nil, err
}
}
if query := _q.withPrimaryProxies; query != nil {
if err := _q.loadPrimaryProxies(ctx, query, nodes,
func(n *Proxy) { n.Edges.PrimaryProxies = []*Proxy{} },
func(n *Proxy, e *Proxy) { n.Edges.PrimaryProxies = append(n.Edges.PrimaryProxies, e) }); err != nil {
return nil, err
}
}
if query := _q.withBackupProxy; query != nil {
if err := _q.loadBackupProxy(ctx, query, nodes, nil,
func(n *Proxy, e *Proxy) { n.Edges.BackupProxy = e }); err != nil {
@@ -483,6 +526,39 @@ func (_q *ProxyQuery) loadAccounts(ctx context.Context, query *AccountQuery, nod
}
return nil
}
func (_q *ProxyQuery) loadPrimaryProxies(ctx context.Context, query *ProxyQuery, nodes []*Proxy, init func(*Proxy), assign func(*Proxy, *Proxy)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int64]*Proxy)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
if len(query.ctx.Fields) > 0 {
query.ctx.AppendFieldOnce(proxy.FieldBackupProxyID)
}
query.Where(predicate.Proxy(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(proxy.PrimaryProxiesColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.BackupProxyID
if fk == nil {
return fmt.Errorf(`foreign-key "backup_proxy_id" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "backup_proxy_id" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *ProxyQuery) loadBackupProxy(ctx context.Context, query *ProxyQuery, nodes []*Proxy, init func(*Proxy), assign func(*Proxy, *Proxy)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*Proxy)
+170 -8
View File
@@ -262,6 +262,21 @@ func (_u *ProxyUpdate) AddAccounts(v ...*Account) *ProxyUpdate {
return _u.AddAccountIDs(ids...)
}
// AddPrimaryProxyIDs adds the "primary_proxies" edge to the Proxy entity by IDs.
func (_u *ProxyUpdate) AddPrimaryProxyIDs(ids ...int64) *ProxyUpdate {
_u.mutation.AddPrimaryProxyIDs(ids...)
return _u
}
// AddPrimaryProxies adds the "primary_proxies" edges to the Proxy entity.
func (_u *ProxyUpdate) AddPrimaryProxies(v ...*Proxy) *ProxyUpdate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddPrimaryProxyIDs(ids...)
}
// SetBackupProxy sets the "backup_proxy" edge to the Proxy entity.
func (_u *ProxyUpdate) SetBackupProxy(v *Proxy) *ProxyUpdate {
return _u.SetBackupProxyID(v.ID)
@@ -293,6 +308,27 @@ func (_u *ProxyUpdate) RemoveAccounts(v ...*Account) *ProxyUpdate {
return _u.RemoveAccountIDs(ids...)
}
// ClearPrimaryProxies clears all "primary_proxies" edges to the Proxy entity.
func (_u *ProxyUpdate) ClearPrimaryProxies() *ProxyUpdate {
_u.mutation.ClearPrimaryProxies()
return _u
}
// RemovePrimaryProxyIDs removes the "primary_proxies" edge to Proxy entities by IDs.
func (_u *ProxyUpdate) RemovePrimaryProxyIDs(ids ...int64) *ProxyUpdate {
_u.mutation.RemovePrimaryProxyIDs(ids...)
return _u
}
// RemovePrimaryProxies removes "primary_proxies" edges to Proxy entities.
func (_u *ProxyUpdate) RemovePrimaryProxies(v ...*Proxy) *ProxyUpdate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemovePrimaryProxyIDs(ids...)
}
// ClearBackupProxy clears the "backup_proxy" edge to the Proxy entity.
func (_u *ProxyUpdate) ClearBackupProxy() *ProxyUpdate {
_u.mutation.ClearBackupProxy()
@@ -492,13 +528,58 @@ func (_u *ProxyUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.PrimaryProxiesCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: proxy.PrimaryProxiesTable,
Columns: []string{proxy.PrimaryProxiesColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedPrimaryProxiesIDs(); len(nodes) > 0 && !_u.mutation.PrimaryProxiesCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: proxy.PrimaryProxiesTable,
Columns: []string{proxy.PrimaryProxiesColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.PrimaryProxiesIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: proxy.PrimaryProxiesTable,
Columns: []string{proxy.PrimaryProxiesColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.BackupProxyCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: proxy.BackupProxyTable,
Columns: []string{proxy.BackupProxyColumn},
Bidi: true,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
@@ -507,11 +588,11 @@ func (_u *ProxyUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
if nodes := _u.mutation.BackupProxyIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: proxy.BackupProxyTable,
Columns: []string{proxy.BackupProxyColumn},
Bidi: true,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
@@ -774,6 +855,21 @@ func (_u *ProxyUpdateOne) AddAccounts(v ...*Account) *ProxyUpdateOne {
return _u.AddAccountIDs(ids...)
}
// AddPrimaryProxyIDs adds the "primary_proxies" edge to the Proxy entity by IDs.
func (_u *ProxyUpdateOne) AddPrimaryProxyIDs(ids ...int64) *ProxyUpdateOne {
_u.mutation.AddPrimaryProxyIDs(ids...)
return _u
}
// AddPrimaryProxies adds the "primary_proxies" edges to the Proxy entity.
func (_u *ProxyUpdateOne) AddPrimaryProxies(v ...*Proxy) *ProxyUpdateOne {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddPrimaryProxyIDs(ids...)
}
// SetBackupProxy sets the "backup_proxy" edge to the Proxy entity.
func (_u *ProxyUpdateOne) SetBackupProxy(v *Proxy) *ProxyUpdateOne {
return _u.SetBackupProxyID(v.ID)
@@ -805,6 +901,27 @@ func (_u *ProxyUpdateOne) RemoveAccounts(v ...*Account) *ProxyUpdateOne {
return _u.RemoveAccountIDs(ids...)
}
// ClearPrimaryProxies clears all "primary_proxies" edges to the Proxy entity.
func (_u *ProxyUpdateOne) ClearPrimaryProxies() *ProxyUpdateOne {
_u.mutation.ClearPrimaryProxies()
return _u
}
// RemovePrimaryProxyIDs removes the "primary_proxies" edge to Proxy entities by IDs.
func (_u *ProxyUpdateOne) RemovePrimaryProxyIDs(ids ...int64) *ProxyUpdateOne {
_u.mutation.RemovePrimaryProxyIDs(ids...)
return _u
}
// RemovePrimaryProxies removes "primary_proxies" edges to Proxy entities.
func (_u *ProxyUpdateOne) RemovePrimaryProxies(v ...*Proxy) *ProxyUpdateOne {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemovePrimaryProxyIDs(ids...)
}
// ClearBackupProxy clears the "backup_proxy" edge to the Proxy entity.
func (_u *ProxyUpdateOne) ClearBackupProxy() *ProxyUpdateOne {
_u.mutation.ClearBackupProxy()
@@ -1034,13 +1151,58 @@ func (_u *ProxyUpdateOne) sqlSave(ctx context.Context) (_node *Proxy, err error)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.PrimaryProxiesCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: proxy.PrimaryProxiesTable,
Columns: []string{proxy.PrimaryProxiesColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedPrimaryProxiesIDs(); len(nodes) > 0 && !_u.mutation.PrimaryProxiesCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: proxy.PrimaryProxiesTable,
Columns: []string{proxy.PrimaryProxiesColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.PrimaryProxiesIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: proxy.PrimaryProxiesTable,
Columns: []string{proxy.PrimaryProxiesColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.BackupProxyCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: proxy.BackupProxyTable,
Columns: []string{proxy.BackupProxyColumn},
Bidi: true,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
@@ -1049,11 +1211,11 @@ func (_u *ProxyUpdateOne) sqlSave(ctx context.Context) (_node *Proxy, err error)
}
if nodes := _u.mutation.BackupProxyIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: proxy.BackupProxyTable,
Columns: []string{proxy.BackupProxyColumn},
Bidi: true,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
+121 -83
View File
@@ -906,7 +906,21 @@ func init() {
// compositemodelroute.DefaultTargetPlatform holds the default value on creation for the target_platform field.
compositemodelroute.DefaultTargetPlatform = compositemodelrouteDescTargetPlatform.Default.(string)
// compositemodelroute.TargetPlatformValidator is a validator for the "target_platform" field. It is called by the builders before save.
compositemodelroute.TargetPlatformValidator = compositemodelrouteDescTargetPlatform.Validators[0].(func(string) error)
compositemodelroute.TargetPlatformValidator = func() func(string) error {
validators := compositemodelrouteDescTargetPlatform.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(target_platform string) error {
for _, fn := range fns {
if err := fn(target_platform); err != nil {
return err
}
}
return nil
}
}()
// compositemodelrouteDescUpstreamModel is the schema descriptor for upstream_model field.
compositemodelrouteDescUpstreamModel := compositemodelrouteFields[4].Descriptor()
// compositemodelroute.DefaultUpstreamModel holds the default value on creation for the upstream_model field.
@@ -1023,204 +1037,216 @@ func init() {
return nil
}
}()
// groupDescI18n is the schema descriptor for i18n field.
groupDescI18n := groupFields[2].Descriptor()
// group.DefaultI18n holds the default value on creation for the i18n field.
group.DefaultI18n = groupDescI18n.Default.(domain.GroupI18n)
// groupDescRateMultiplier is the schema descriptor for rate_multiplier field.
groupDescRateMultiplier := groupFields[2].Descriptor()
groupDescRateMultiplier := groupFields[3].Descriptor()
// group.DefaultRateMultiplier holds the default value on creation for the rate_multiplier field.
group.DefaultRateMultiplier = groupDescRateMultiplier.Default.(float64)
// groupDescPeakRateEnabled is the schema descriptor for peak_rate_enabled field.
groupDescPeakRateEnabled := groupFields[3].Descriptor()
groupDescPeakRateEnabled := groupFields[4].Descriptor()
// group.DefaultPeakRateEnabled holds the default value on creation for the peak_rate_enabled field.
group.DefaultPeakRateEnabled = groupDescPeakRateEnabled.Default.(bool)
// groupDescPeakStart is the schema descriptor for peak_start field.
groupDescPeakStart := groupFields[4].Descriptor()
groupDescPeakStart := groupFields[5].Descriptor()
// group.DefaultPeakStart holds the default value on creation for the peak_start field.
group.DefaultPeakStart = groupDescPeakStart.Default.(string)
// group.PeakStartValidator is a validator for the "peak_start" field. It is called by the builders before save.
group.PeakStartValidator = groupDescPeakStart.Validators[0].(func(string) error)
// groupDescPeakEnd is the schema descriptor for peak_end field.
groupDescPeakEnd := groupFields[5].Descriptor()
groupDescPeakEnd := groupFields[6].Descriptor()
// group.DefaultPeakEnd holds the default value on creation for the peak_end field.
group.DefaultPeakEnd = groupDescPeakEnd.Default.(string)
// group.PeakEndValidator is a validator for the "peak_end" field. It is called by the builders before save.
group.PeakEndValidator = groupDescPeakEnd.Validators[0].(func(string) error)
// groupDescPeakRateMultiplier is the schema descriptor for peak_rate_multiplier field.
groupDescPeakRateMultiplier := groupFields[6].Descriptor()
groupDescPeakRateMultiplier := groupFields[7].Descriptor()
// group.DefaultPeakRateMultiplier holds the default value on creation for the peak_rate_multiplier field.
group.DefaultPeakRateMultiplier = groupDescPeakRateMultiplier.Default.(float64)
// groupDescIsExclusive is the schema descriptor for is_exclusive field.
groupDescIsExclusive := groupFields[7].Descriptor()
groupDescIsExclusive := groupFields[8].Descriptor()
// group.DefaultIsExclusive holds the default value on creation for the is_exclusive field.
group.DefaultIsExclusive = groupDescIsExclusive.Default.(bool)
// groupDescStatus is the schema descriptor for status field.
groupDescStatus := groupFields[8].Descriptor()
groupDescStatus := groupFields[9].Descriptor()
// group.DefaultStatus holds the default value on creation for the status field.
group.DefaultStatus = groupDescStatus.Default.(string)
// group.StatusValidator is a validator for the "status" field. It is called by the builders before save.
group.StatusValidator = groupDescStatus.Validators[0].(func(string) error)
// groupDescDuplicateOperationID is the schema descriptor for duplicate_operation_id field.
groupDescDuplicateOperationID := groupFields[9].Descriptor()
groupDescDuplicateOperationID := groupFields[10].Descriptor()
// group.DuplicateOperationIDValidator is a validator for the "duplicate_operation_id" field. It is called by the builders before save.
group.DuplicateOperationIDValidator = groupDescDuplicateOperationID.Validators[0].(func(string) error)
// groupDescPlatform is the schema descriptor for platform field.
groupDescPlatform := groupFields[10].Descriptor()
groupDescPlatform := groupFields[11].Descriptor()
// group.DefaultPlatform holds the default value on creation for the platform field.
group.DefaultPlatform = groupDescPlatform.Default.(string)
// group.PlatformValidator is a validator for the "platform" field. It is called by the builders before save.
group.PlatformValidator = groupDescPlatform.Validators[0].(func(string) error)
// groupDescSubscriptionType is the schema descriptor for subscription_type field.
groupDescSubscriptionType := groupFields[11].Descriptor()
groupDescSubscriptionType := groupFields[12].Descriptor()
// group.DefaultSubscriptionType holds the default value on creation for the subscription_type field.
group.DefaultSubscriptionType = groupDescSubscriptionType.Default.(string)
// group.SubscriptionTypeValidator is a validator for the "subscription_type" field. It is called by the builders before save.
group.SubscriptionTypeValidator = groupDescSubscriptionType.Validators[0].(func(string) error)
// groupDescDefaultValidityDays is the schema descriptor for default_validity_days field.
groupDescDefaultValidityDays := groupFields[15].Descriptor()
groupDescDefaultValidityDays := groupFields[16].Descriptor()
// group.DefaultDefaultValidityDays holds the default value on creation for the default_validity_days field.
group.DefaultDefaultValidityDays = groupDescDefaultValidityDays.Default.(int)
// groupDescAllowImageGeneration is the schema descriptor for allow_image_generation field.
groupDescAllowImageGeneration := groupFields[16].Descriptor()
groupDescAllowImageGeneration := groupFields[17].Descriptor()
// group.DefaultAllowImageGeneration holds the default value on creation for the allow_image_generation field.
group.DefaultAllowImageGeneration = groupDescAllowImageGeneration.Default.(bool)
// groupDescAllowBatchImageGeneration is the schema descriptor for allow_batch_image_generation field.
groupDescAllowBatchImageGeneration := groupFields[17].Descriptor()
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[18].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[19].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[23].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[24].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[25].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[26].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[32].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[33].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[34].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[35].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[36].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[38].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[42].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[43].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[44].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[45].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[46].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[47].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[48].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[49].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[50].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[51].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[52].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[53].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[54].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[55].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[56].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[57].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[58].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[59].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[60].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[61].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[62].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()
@@ -1323,70 +1349,74 @@ func init() {
paymentorderDescFeeRate := paymentorderFields[6].Descriptor()
// paymentorder.DefaultFeeRate holds the default value on creation for the fee_rate field.
paymentorder.DefaultFeeRate = paymentorderDescFeeRate.Default.(float64)
// paymentorderDescBonusAmount is the schema descriptor for bonus_amount field.
paymentorderDescBonusAmount := paymentorderFields[7].Descriptor()
// paymentorder.DefaultBonusAmount holds the default value on creation for the bonus_amount field.
paymentorder.DefaultBonusAmount = paymentorderDescBonusAmount.Default.(float64)
// paymentorderDescRechargeCode is the schema descriptor for recharge_code field.
paymentorderDescRechargeCode := paymentorderFields[7].Descriptor()
paymentorderDescRechargeCode := paymentorderFields[8].Descriptor()
// paymentorder.RechargeCodeValidator is a validator for the "recharge_code" field. It is called by the builders before save.
paymentorder.RechargeCodeValidator = paymentorderDescRechargeCode.Validators[0].(func(string) error)
// paymentorderDescOutTradeNo is the schema descriptor for out_trade_no field.
paymentorderDescOutTradeNo := paymentorderFields[8].Descriptor()
paymentorderDescOutTradeNo := paymentorderFields[9].Descriptor()
// paymentorder.DefaultOutTradeNo holds the default value on creation for the out_trade_no field.
paymentorder.DefaultOutTradeNo = paymentorderDescOutTradeNo.Default.(string)
// paymentorder.OutTradeNoValidator is a validator for the "out_trade_no" field. It is called by the builders before save.
paymentorder.OutTradeNoValidator = paymentorderDescOutTradeNo.Validators[0].(func(string) error)
// paymentorderDescPaymentType is the schema descriptor for payment_type field.
paymentorderDescPaymentType := paymentorderFields[9].Descriptor()
paymentorderDescPaymentType := paymentorderFields[10].Descriptor()
// paymentorder.PaymentTypeValidator is a validator for the "payment_type" field. It is called by the builders before save.
paymentorder.PaymentTypeValidator = paymentorderDescPaymentType.Validators[0].(func(string) error)
// paymentorderDescPaymentTradeNo is the schema descriptor for payment_trade_no field.
paymentorderDescPaymentTradeNo := paymentorderFields[10].Descriptor()
paymentorderDescPaymentTradeNo := paymentorderFields[11].Descriptor()
// paymentorder.PaymentTradeNoValidator is a validator for the "payment_trade_no" field. It is called by the builders before save.
paymentorder.PaymentTradeNoValidator = paymentorderDescPaymentTradeNo.Validators[0].(func(string) error)
// paymentorderDescOrderType is the schema descriptor for order_type field.
paymentorderDescOrderType := paymentorderFields[14].Descriptor()
paymentorderDescOrderType := paymentorderFields[15].Descriptor()
// paymentorder.DefaultOrderType holds the default value on creation for the order_type field.
paymentorder.DefaultOrderType = paymentorderDescOrderType.Default.(string)
// paymentorder.OrderTypeValidator is a validator for the "order_type" field. It is called by the builders before save.
paymentorder.OrderTypeValidator = paymentorderDescOrderType.Validators[0].(func(string) error)
// paymentorderDescProviderInstanceID is the schema descriptor for provider_instance_id field.
paymentorderDescProviderInstanceID := paymentorderFields[18].Descriptor()
paymentorderDescProviderInstanceID := paymentorderFields[19].Descriptor()
// paymentorder.ProviderInstanceIDValidator is a validator for the "provider_instance_id" field. It is called by the builders before save.
paymentorder.ProviderInstanceIDValidator = paymentorderDescProviderInstanceID.Validators[0].(func(string) error)
// paymentorderDescProviderKey is the schema descriptor for provider_key field.
paymentorderDescProviderKey := paymentorderFields[19].Descriptor()
paymentorderDescProviderKey := paymentorderFields[20].Descriptor()
// paymentorder.ProviderKeyValidator is a validator for the "provider_key" field. It is called by the builders before save.
paymentorder.ProviderKeyValidator = paymentorderDescProviderKey.Validators[0].(func(string) error)
// paymentorderDescStatus is the schema descriptor for status field.
paymentorderDescStatus := paymentorderFields[21].Descriptor()
paymentorderDescStatus := paymentorderFields[22].Descriptor()
// paymentorder.DefaultStatus holds the default value on creation for the status field.
paymentorder.DefaultStatus = paymentorderDescStatus.Default.(string)
// paymentorder.StatusValidator is a validator for the "status" field. It is called by the builders before save.
paymentorder.StatusValidator = paymentorderDescStatus.Validators[0].(func(string) error)
// paymentorderDescRefundAmount is the schema descriptor for refund_amount field.
paymentorderDescRefundAmount := paymentorderFields[22].Descriptor()
paymentorderDescRefundAmount := paymentorderFields[23].Descriptor()
// paymentorder.DefaultRefundAmount holds the default value on creation for the refund_amount field.
paymentorder.DefaultRefundAmount = paymentorderDescRefundAmount.Default.(float64)
// paymentorderDescForceRefund is the schema descriptor for force_refund field.
paymentorderDescForceRefund := paymentorderFields[25].Descriptor()
paymentorderDescForceRefund := paymentorderFields[26].Descriptor()
// paymentorder.DefaultForceRefund holds the default value on creation for the force_refund field.
paymentorder.DefaultForceRefund = paymentorderDescForceRefund.Default.(bool)
// paymentorderDescRefundRequestedBy is the schema descriptor for refund_requested_by field.
paymentorderDescRefundRequestedBy := paymentorderFields[28].Descriptor()
paymentorderDescRefundRequestedBy := paymentorderFields[29].Descriptor()
// paymentorder.RefundRequestedByValidator is a validator for the "refund_requested_by" field. It is called by the builders before save.
paymentorder.RefundRequestedByValidator = paymentorderDescRefundRequestedBy.Validators[0].(func(string) error)
// paymentorderDescClientIP is the schema descriptor for client_ip field.
paymentorderDescClientIP := paymentorderFields[34].Descriptor()
paymentorderDescClientIP := paymentorderFields[35].Descriptor()
// paymentorder.ClientIPValidator is a validator for the "client_ip" field. It is called by the builders before save.
paymentorder.ClientIPValidator = paymentorderDescClientIP.Validators[0].(func(string) error)
// paymentorderDescSrcHost is the schema descriptor for src_host field.
paymentorderDescSrcHost := paymentorderFields[35].Descriptor()
paymentorderDescSrcHost := paymentorderFields[36].Descriptor()
// paymentorder.SrcHostValidator is a validator for the "src_host" field. It is called by the builders before save.
paymentorder.SrcHostValidator = paymentorderDescSrcHost.Validators[0].(func(string) error)
// paymentorderDescCreatedAt is the schema descriptor for created_at field.
paymentorderDescCreatedAt := paymentorderFields[37].Descriptor()
paymentorderDescCreatedAt := paymentorderFields[38].Descriptor()
// paymentorder.DefaultCreatedAt holds the default value on creation for the created_at field.
paymentorder.DefaultCreatedAt = paymentorderDescCreatedAt.Default.(func() time.Time)
// paymentorderDescUpdatedAt is the schema descriptor for updated_at field.
paymentorderDescUpdatedAt := paymentorderFields[38].Descriptor()
paymentorderDescUpdatedAt := paymentorderFields[39].Descriptor()
// paymentorder.DefaultUpdatedAt holds the default value on creation for the updated_at field.
paymentorder.DefaultUpdatedAt = paymentorderDescUpdatedAt.Default.(func() time.Time)
// paymentorder.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
@@ -2052,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()
+1 -1
View File
@@ -36,7 +36,7 @@ func (ChannelMonitor) Fields() []ent.Field {
MaxLen(100),
field.Enum("provider").
Values("openai", "anthropic", "gemini", "grok",
"antigravity", "kimi", "zhipu", "deepseek"),
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"),
// check_mode: 'probe' | 'quota' | 'quota_probe'
// probe - LLM 探活(默认,原有行为)
// quota - 仅查关联账号的用量/余额(零 LLM 成本;endpoint/api_key 可空)
@@ -40,7 +40,7 @@ func (ChannelMonitorRequestTemplate) Fields() []ent.Field {
MaxLen(100),
field.Enum("provider").
Values("openai", "anthropic", "gemini", "grok",
"antigravity", "kimi", "zhipu", "deepseek"),
"antigravity", "kimi", "zhipu", "deepseek", "minimax", "opencode_go"),
field.String("api_mode").
Default("chat_completions").
MaxLen(32).
@@ -1,6 +1,8 @@
package schema
import (
"fmt"
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"github.com/Wei-Shaw/sub2api/internal/domain"
@@ -45,6 +47,13 @@ func (CompositeModelRoute) Fields() []ent.Field {
field.String("target_platform").
MaxLen(50).
Default(domain.PlatformOpenAI).
Validate(func(s string) error {
// 目标平台须为平台清单中的具体平台;数据库不再维护 CHECK 约束。
if !domain.IsConcretePlatform(s) {
return fmt.Errorf("target_platform %q is not a concrete platform", s)
}
return nil
}).
Comment("Concrete provider platform."),
field.String("upstream_model").
MaxLen(200).
+11
View File
@@ -44,6 +44,11 @@ func (Group) Fields() []ent.Field {
Optional().
Nillable().
SchemaType(map[string]string{dialect.Postgres: "text"}),
// 名称与描述的界面语言译文 (added by migration 242)
field.JSON("i18n", domain.GroupI18n{}).
Default(domain.GroupI18n{}).
SchemaType(map[string]string{dialect.Postgres: "jsonb"}).
Comment("名称与描述的界面语言译文:语言代码 -> {name, description};缺失的语言沿用 name/description"),
field.Float("rate_multiplier").
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
Default(1.0),
@@ -104,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 表示共享分组有效倍率"),
@@ -245,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
@@ -50,6 +50,10 @@ func (PaymentOrder) Fields() []ent.Field {
field.Float("fee_rate").
SchemaType(map[string]string{dialect.Postgres: "decimal(10,4)"}).
Default(0),
// 充值赠送额度(USD)。已计入 amount;单独记录用于订单展示与推广返利基数剔除。
field.Float("bonus_amount").
SchemaType(map[string]string{dialect.Postgres: "decimal(20,2)"}).
Default(0),
field.String("recharge_code").
MaxLen(64),
+4
View File
@@ -73,6 +73,10 @@ func (Proxy) Edges() []ent.Edge {
// accounts: 使用此代理的账户(反向边)
edge.From("accounts", Account.Type).
Ref("proxy"),
// Directed many-to-one: a backup can serve multiple primary proxies.
// The inverse edge prevents Ent from treating this self-reference as symmetric.
edge.From("primary_proxies", Proxy.Type).
Ref("backup_proxy"),
edge.To("backup_proxy", Proxy.Type).
Field("backup_proxy_id").
Unique(),
+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").
+5 -7
View File
@@ -11,6 +11,7 @@ import (
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"github.com/Wei-Shaw/sub2api/ent/schema/mixins"
"github.com/Wei-Shaw/sub2api/internal/domain"
)
// UserPlatformQuota holds the schema definition for per-user per-platform quota.
@@ -38,15 +39,12 @@ func (UserPlatformQuota) Fields() []ent.Field {
MaxLen(32).
NotEmpty().
Validate(func(s string) error {
// 注意:平台列表的单一权威源为 service.AllowedQuotaPlatforms;
// 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。
switch s {
case "anthropic", "openai", "gemini", "antigravity", "grok",
"kimi", "zhipu", "deepseek":
return nil
default:
// 平台白名单为平台清单(domain/platforms.go)中的全部具体平台,
// 与 service.AllowedQuotaPlatforms 同源;数据库不再维护 CHECK 约束。
if !domain.IsConcretePlatform(s) {
return fmt.Errorf("platform %q is not allowed", s)
}
return nil
}),
// 日 / 周 / 月 USD 上限:
+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)
}
+29 -23
View File
@@ -1,16 +1,17 @@
module github.com/Wei-Shaw/sub2api
go 1.27.0
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
@@ -19,19 +20,22 @@ require (
github.com/coder/websocket v1.8.14
github.com/dgraph-io/ristretto v0.2.0
github.com/gin-gonic/gin v1.9.1
github.com/go-playground/validator/v10 v10.14.0
github.com/go-webauthn/webauthn v0.17.4
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/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.17.2
github.com/redis/go-redis/v9 v9.22.0
github.com/refraction-networking/utls v1.8.2
github.com/robfig/cron/v3 v3.0.1
github.com/shirou/gopsutil/v4 v4.25.6
@@ -50,13 +54,13 @@ 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.53.0
golang.org/x/crypto v0.58.0
golang.org/x/image v0.41.0
golang.org/x/mod v0.37.0
golang.org/x/net v0.56.0
golang.org/x/sync v0.21.0
golang.org/x/term v0.44.0
google.golang.org/grpc v1.82.1
golang.org/x/mod v0.41.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
gopkg.in/yaml.v3 v3.0.1
@@ -101,7 +105,6 @@ require (
github.com/containerd/platforms v0.2.1 // indirect
github.com/cpuguy83/dockercfg v0.3.2 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/dlclark/regexp2/v2 v2.1.0 // indirect
github.com/docker/docker v28.5.1+incompatible // indirect
@@ -121,7 +124,6 @@ require (
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/go-webauthn/x v0.2.6 // indirect
github.com/goccy/go-json v0.10.2 // indirect
@@ -135,7 +137,7 @@ require (
github.com/hashicorp/yamux v0.1.2 // indirect
github.com/icholy/digest v1.1.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/magiconair/properties v1.8.10 // indirect
@@ -168,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
@@ -188,25 +192,27 @@ 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
github.com/zclconf/go-cty-yaml v1.1.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
go.opentelemetry.io/otel v1.43.0 // indirect
go.opentelemetry.io/otel/metric v1.43.0 // indirect
go.opentelemetry.io/otel/trace v1.43.0 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/automaxprocs v1.6.0 // indirect
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.46.0 // indirect
golang.org/x/text v0.39.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.47.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // 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
modernc.org/mathutil v1.7.1 // indirect
+70 -47
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=
@@ -159,8 +161,6 @@ github.com/dgraph-io/ristretto v0.2.0 h1:XAfl+7cmoUDWW/2Lx8TGZQjjxIQ2Ley9DSf52dr
github.com/dgraph-io/ristretto v0.2.0/go.mod h1:8uBHCU/PBV4Ag0CJrP47b9Ofby5dqWNh4FicAdoqFNU=
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y=
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/dlclark/regexp2/v2 v2.1.0 h1:jHXRmHRZGbuQzDZjMlCAXOvQb75iv3HyLDzXGj5H1AY=
@@ -253,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=
@@ -263,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=
@@ -297,11 +301,11 @@ 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.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@@ -327,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=
@@ -351,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=
@@ -365,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=
@@ -393,12 +403,14 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0=
github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk=
github.com/redis/go-redis/v9 v9.17.2 h1:P2EGsA4qVIM3Pp+aPocCJ7DguDHhqrXNhVcEp4ViluI=
github.com/redis/go-redis/v9 v9.17.2/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo=
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=
@@ -407,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=
@@ -434,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=
@@ -500,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=
@@ -511,30 +531,32 @@ github.com/zclconf/go-cty v1.14.4 h1:uXXczd9QDGsgu0i/QFR/hzI5NYCHLf6NQw/atrbnhq8
github.com/zclconf/go-cty v1.14.4/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE=
github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0=
github.com/zclconf/go-cty-yaml v1.1.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
github.com/zeromicro/go-zero v1.9.4 h1:aRLFoISqAYijABtkbliQC5SsI5TbizJpQvoHc9xup8k=
github.com/zeromicro/go-zero v1.9.4/go.mod h1:a17JOTch25SWxBcUgJZYps60hygK3pIYdw7nGwlcS38=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw=
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.24.0 h1:t6wl9SPayj+c7lEIFgm4ooDBZVb01IhLB4InpomhRw8=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.24.0/go.mod h1:iSDOcsnSA5INXzZtwaBPrKp/lWu/V14Dd+llD0oI2EA=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.24.0 h1:Xw8U6u2f8DK2XAkGRFV7BBLENgnTGX9i4rQRxJf+/vs=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.24.0/go.mod h1:6KW1Fm6R/s6Z3PGXwSJN2K4eT6wQB3vXX6CVnYX9NmM=
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0=
go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8=
go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=
go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=
go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
@@ -562,8 +584,8 @@ 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.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
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=
@@ -578,8 +600,8 @@ 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.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -601,9 +623,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.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
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=
@@ -614,8 +638,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.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
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=
@@ -633,7 +657,6 @@ golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -648,8 +671,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.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
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=
@@ -662,8 +685,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.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
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=
@@ -674,8 +697,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.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
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=
@@ -690,8 +713,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.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
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=
@@ -702,16 +725,16 @@ google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17 h1:wpZ8pe2x1Q3f2KyT5f8oP/fa9rHAKgFPr/HZdNuS+PQ=
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec=
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
+220 -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"`
@@ -89,6 +93,7 @@ type Config struct {
Pricing PricingConfig `mapstructure:"pricing"`
Gateway GatewayConfig `mapstructure:"gateway"`
APIKeyAuth APIKeyAuthCacheConfig `mapstructure:"api_key_auth_cache"`
APIKeyCreate APIKeyCreateConfig `mapstructure:"api_key_create"`
SubscriptionCache SubscriptionCacheConfig `mapstructure:"subscription_cache"`
SubscriptionMaintenance SubscriptionMaintenanceConfig `mapstructure:"subscription_maintenance"`
Dashboard DashboardCacheConfig `mapstructure:"dashboard_cache"`
@@ -96,6 +101,7 @@ type Config struct {
UsageCleanup UsageCleanupConfig `mapstructure:"usage_cleanup"`
Concurrency ConcurrencyConfig `mapstructure:"concurrency"`
TokenRefresh TokenRefreshConfig `mapstructure:"token_refresh"`
SimpleMode SimpleModeConfig `mapstructure:"simple_mode" yaml:"simple_mode"`
RunMode string `mapstructure:"run_mode" yaml:"run_mode"`
Timezone string `mapstructure:"timezone"` // e.g. "Asia/Shanghai", "UTC"
Gemini GeminiConfig `mapstructure:"gemini"`
@@ -104,6 +110,62 @@ type Config struct {
BatchImage BatchImageConfig `mapstructure:"batch_image"`
ImageStorage ImageStorageConfig `mapstructure:"image_storage"`
Plugins PluginConfig `mapstructure:"plugins"`
// Enforce only API-key spending windows in simple mode.
SimpleModeKeyRateLimitEnabled bool `mapstructure:"simple_mode_key_rate_limit_enabled" yaml:"simple_mode_key_rate_limit_enabled"`
}
// SimpleModeConfig controls startup behavior in simple mode.
type SimpleModeConfig struct {
AutoCreateDefaultGroups bool `mapstructure:"auto_create_default_groups" yaml:"auto_create_default_groups"`
}
// 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 控制管理员手动上传的本地进程插件。
@@ -504,6 +566,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
@@ -912,6 +992,29 @@ type BillingConfig struct {
// UserPlatformQuotaSentinelTTLSeconds sentinel(无 limit 占位)entry 的 TTL,
// 显著短于 quota cache 默认 86400s 以控 Redis 内存;默认 3600=1h。
UserPlatformQuotaSentinelTTLSeconds int `mapstructure:"user_platform_quota_sentinel_ttl_seconds"`
// InflightReservation 余额模式在途请求预留(Redis),防止并发请求在预检时看到同一份余额而集体透支。
InflightReservation InflightReservationConfig `mapstructure:"inflight_reservation"`
}
// InflightReservationConfig 余额模式在途预留配置。
// 准入时按 输入估算 + 输出单价 × max_tokens 估算单请求费用,在 Redis 中原子地
// 校验 缓存余额 - 在途预留合计 >= 估算 后登记预留,请求结束(任意路径)释放。
// 估算失败或 Redis 不可用时 fail-open,退回旧的仅余额 > 阈值检查。
type InflightReservationConfig struct {
Enabled bool `mapstructure:"enabled"`
// TTLSeconds 单条预留的最长存活时间;进程崩溃等泄漏的预留到期自动失效。
TTLSeconds int `mapstructure:"ttl_seconds"`
// DefaultMaxTokens 请求未携带 max_tokens 时用于估算的输出 token 数。
DefaultMaxTokens int `mapstructure:"default_max_tokens"`
// MaxOutputTokens 估算输出 token 的上限(max_tokens 超出时截断)。
MaxOutputTokens int `mapstructure:"max_output_tokens"`
// MaxInputTokens 输入 token 估算(请求体字节数 / 4)的上限。
MaxInputTokens int `mapstructure:"max_input_tokens"`
// MaxReservationUSD 单请求预留金额上限;0 表示不设上限。
MaxReservationUSD float64 `mapstructure:"max_reservation_usd"`
// FailClosedOnUnpriced 无法为请求估算费用(模型/分组/渠道均无定价)时是否拒绝请求。
// 默认 false:放行且不预留(fail-open,节流告警日志)。
FailClosedOnUnpriced bool `mapstructure:"fail_closed_on_unpriced"`
}
type CircuitBreakerConfig struct {
@@ -922,7 +1025,7 @@ type CircuitBreakerConfig struct {
}
type ConcurrencyConfig struct {
// PingInterval: 并发等待期间的 SSE ping 间隔(秒)
// PingInterval: 并发等待期间的 SSE ping 间隔(秒),0 禁用 ping
PingInterval int `mapstructure:"ping_interval"`
}
@@ -946,12 +1049,16 @@ const (
// GatewayConfig API网关相关配置
type GatewayConfig struct {
// MinOutputTokens is the minimum max_output_tokens used when
// converting Chat Completions or Anthropic requests to Responses.
MinOutputTokens int `mapstructure:"min_output_tokens"`
// 等待上游响应头的超时时间(秒),0表示无超时
// 注意:这不影响流式数据传输,只控制等待响应头的时间
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"`
@@ -962,6 +1069,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"`
// 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大
@@ -972,6 +1086,8 @@ type GatewayConfig struct {
ProxyProbeResponseReadMaxBytes int64 `mapstructure:"proxy_probe_response_read_max_bytes"`
// Gemini 上游响应头调试日志开关(默认关闭,避免高频日志开销)
GeminiDebugResponseHeaders bool `mapstructure:"gemini_debug_response_headers"`
// GeminiCachedContentMaxTTLSeconds: Gemini 显式缓存单次可设置的最长有效期(秒),<=0 时按 86400 处理
GeminiCachedContentMaxTTLSeconds int `mapstructure:"gemini_cached_content_max_ttl_seconds"`
// ConnectionPoolIsolation: 上游连接池隔离策略(proxy/account/account_proxy)
ConnectionPoolIsolation string `mapstructure:"connection_pool_isolation"`
// ForceCodexCLI: 强制将 OpenAI `/v1/responses` 请求按 Codex CLI 处理。
@@ -1054,7 +1170,10 @@ 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"`
@@ -1071,6 +1190,8 @@ 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"`
// Antigravity 429 fallback 限流时间(分钟),解析重置时间失败时使用
AntigravityFallbackCooldownMinutes int `mapstructure:"antigravity_fallback_cooldown_minutes"`
@@ -1274,11 +1395,15 @@ type GatewayOpenAIWSConfig struct {
MaxConnsPerAccount int `mapstructure:"max_conns_per_account"`
MinIdlePerAccount int `mapstructure:"min_idle_per_account"`
MaxIdlePerAccount int `mapstructure:"max_idle_per_account"`
// DynamicMaxConnsByAccountConcurrencyEnabled: 是否按账号并发动态计算连接池上限
// DynamicMaxConnsByAccountConcurrencyEnabled: 是否按账号并发动态计算连接池上限。
// 旧版及 mode_router_v2 的 ctx_pool 共用此开关和类型系数;关闭后使用 max_conns_per_account。
// mode_router_v2 下并发数 <= 0 的账号仍不可调度。
DynamicMaxConnsByAccountConcurrencyEnabled bool `mapstructure:"dynamic_max_conns_by_account_concurrency_enabled"`
// OAuthMaxConnsFactor: OAuth 账号连接池系数(effective=ceil(concurrency*factor))
// OAuthMaxConnsFactor: OAuth 账号连接池系数(effective=ceil(concurrency*factor),再受 max_conns_per_account 封顶)。
// ctx_pool 接入下每个客户端会话在整个生命周期(含轮次之间)持有一条上游连接,此上限限制的是同时持有连接的会话数,
// 在飞请求数另由账号并发槽限制;系数 1.0 会让存活会话数一到并发数就返回 1013 busy,默认 5.0。
OAuthMaxConnsFactor float64 `mapstructure:"oauth_max_conns_factor"`
// APIKeyMaxConnsFactor: API Key 账号连接池系数(effective=ceil(concurrency*factor))
// APIKeyMaxConnsFactor: API Key 账号连接池系数,含义与 OAuthMaxConnsFactor 相同,默认 5.0。
APIKeyMaxConnsFactor float64 `mapstructure:"apikey_max_conns_factor"`
DialTimeoutSeconds int `mapstructure:"dial_timeout_seconds"`
ReadTimeoutSeconds int `mapstructure:"read_timeout_seconds"`
@@ -1613,10 +1738,10 @@ type OpsCleanupConfig struct {
Enabled bool `mapstructure:"enabled"`
Schedule string `mapstructure:"schedule"`
// Retention days (0 disables that cleanup target).
//
// vNext requirement: default 30 days across ops datasets.
// Retention days. Error and metrics targets accept 0 as an explicit truncate;
// system logs require a positive value because their runtime setting is bounded.
ErrorLogRetentionDays int `mapstructure:"error_log_retention_days"`
SystemLogRetentionDays int `mapstructure:"system_log_retention_days"`
MinuteMetricsRetentionDays int `mapstructure:"minute_metrics_retention_days"`
HourlyMetricsRetentionDays int `mapstructure:"hourly_metrics_retention_days"`
}
@@ -1683,6 +1808,14 @@ type APIKeyAuthCacheConfig struct {
InvalidAbuse InvalidAuthAbuseConfig `mapstructure:"invalid_abuse"`
}
// APIKeyCreateConfig 用户创建 API Key 的防滥用限制(0 表示不限制)
type APIKeyCreateConfig struct {
// MaxActivePerUser 单个用户同时存在(未删除)的 API Key 上限
MaxActivePerUser int `mapstructure:"max_active_per_user"`
// MaxPerUserPerHour 单个用户每小时可创建的 API Key 次数(删除不返还次数)
MaxPerUserPerHour int `mapstructure:"max_per_user_per_hour"`
}
type InvalidAuthAbuseConfig struct {
Enabled bool `mapstructure:"enabled"`
Threshold int `mapstructure:"threshold"`
@@ -1822,6 +1955,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
}
@@ -1988,6 +2130,9 @@ func configureConfigSource(setConfigFile, addConfigPath func(string)) {
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_key_rate_limit_enabled", false)
// Server
viper.SetDefault("server.host", "0.0.0.0")
@@ -2029,6 +2174,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.
@@ -2043,10 +2189,13 @@ func setDefaults() {
"api.openai.com",
"api.anthropic.com",
"api.kimi.com",
"api.kimi.ai",
"api.moonshot.ai",
"api.moonshot.cn",
"open.bigmodel.cn",
"api.minimaxi.com",
"api.minimaxi.com", // MiniMax CN quota + inference
"api.minimax.io", // MiniMax intl; frozen allowlists must add this host to use the intl site
"opencode.ai",
"generativelanguage.googleapis.com",
"cloudcode-pa.googleapis.com",
"*.openai.azure.com",
@@ -2076,6 +2225,13 @@ func setDefaults() {
viper.SetDefault("billing.minimum_balance_reserve", 0.000001)
viper.SetDefault("billing.user_platform_quota_cache_ttl_seconds", 86400)
viper.SetDefault("billing.user_platform_quota_sentinel_ttl_seconds", 3600)
viper.SetDefault("billing.inflight_reservation.enabled", true)
viper.SetDefault("billing.inflight_reservation.ttl_seconds", 900)
viper.SetDefault("billing.inflight_reservation.default_max_tokens", 8192)
viper.SetDefault("billing.inflight_reservation.max_output_tokens", 128000)
viper.SetDefault("billing.inflight_reservation.max_input_tokens", 200000)
viper.SetDefault("billing.inflight_reservation.max_reservation_usd", 0)
viper.SetDefault("billing.inflight_reservation.fail_closed_on_unpriced", false)
// Turnstile
viper.SetDefault("turnstile.required", false)
@@ -2250,6 +2406,7 @@ func setDefaults() {
viper.SetDefault("ops.cleanup.schedule", "0 2 * * *")
// Retention days: vNext defaults to 30 days across ops datasets.
viper.SetDefault("ops.cleanup.error_log_retention_days", 30)
viper.SetDefault("ops.cleanup.system_log_retention_days", 30)
viper.SetDefault("ops.cleanup.minute_metrics_retention_days", 30)
viper.SetDefault("ops.cleanup.hourly_metrics_retention_days", 30)
viper.SetDefault("ops.aggregation.enabled", true)
@@ -2314,6 +2471,8 @@ func setDefaults() {
viper.SetDefault("api_key_auth_cache.invalid_abuse.window_seconds", 60)
viper.SetDefault("api_key_auth_cache.invalid_abuse.block_seconds", 60)
viper.SetDefault("api_key_auth_cache.invalid_abuse.capacity", 16384)
viper.SetDefault("api_key_create.max_active_per_user", 200)
viper.SetDefault("api_key_create.max_per_user_per_hour", 60)
// Subscription auth L1 cache
viper.SetDefault("subscription_cache.l1_size", 16384)
@@ -2359,6 +2518,7 @@ 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)
@@ -2368,12 +2528,13 @@ func setDefaults() {
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)
viper.SetDefault("gateway.codex_image_generation_bridge_enabled", false)
viper.SetDefault("gateway.openai_passthrough_allow_timeout_headers", false)
viper.SetDefault("gateway.openai_compact_model", "gpt-5.4")
viper.SetDefault("gateway.openai_compact_model", "gpt-5.5")
viper.SetDefault("gateway.live.max_session_duration_seconds", 3600)
// OpenAI Responses WebSocket(默认开启;可通过 force_http 紧急回滚)
viper.SetDefault("gateway.openai_ws.enabled", true)
@@ -2399,8 +2560,8 @@ func setDefaults() {
viper.SetDefault("gateway.openai_ws.min_idle_per_account", 4)
viper.SetDefault("gateway.openai_ws.max_idle_per_account", 12)
viper.SetDefault("gateway.openai_ws.dynamic_max_conns_by_account_concurrency_enabled", true)
viper.SetDefault("gateway.openai_ws.oauth_max_conns_factor", 1.0)
viper.SetDefault("gateway.openai_ws.apikey_max_conns_factor", 1.0)
viper.SetDefault("gateway.openai_ws.oauth_max_conns_factor", 5.0)
viper.SetDefault("gateway.openai_ws.apikey_max_conns_factor", 5.0)
viper.SetDefault("gateway.openai_ws.dial_timeout_seconds", 10)
viper.SetDefault("gateway.openai_ws.read_timeout_seconds", 900)
viper.SetDefault("gateway.openai_ws.write_timeout_seconds", 120)
@@ -2463,11 +2624,17 @@ func setDefaults() {
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)
viper.SetDefault("gateway.proxy_probe_response_read_max_bytes", int64(1024*1024))
viper.SetDefault("gateway.gemini_debug_response_headers", false)
viper.SetDefault("gateway.gemini_cached_content_max_ttl_seconds", 86400)
viper.SetDefault("gateway.connection_pool_isolation", ConnectionPoolIsolationAccountProxy)
// HTTP 上游连接池配置(针对 5000+ 并发用户优化)
viper.SetDefault("gateway.max_idle_conns", 2560) // 最大空闲连接总数(高并发场景可调大)
@@ -2483,6 +2650,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)
@@ -2644,6 +2814,9 @@ func setEnvReachableDefaults() {
}
func (c *Config) Validate() error {
if c.Gateway.MinOutputTokens < 16 {
return fmt.Errorf("gateway.min_output_tokens must be at least 16")
}
forwardedClientIPHeaders, err := NormalizeForwardedClientIPHeaders(c.Security.ForwardedClientIPHeaders)
if err != nil {
return fmt.Errorf("security.forwarded_client_ip_headers: %w", err)
@@ -2693,6 +2866,12 @@ func (c *Config) Validate() error {
return fmt.Errorf("server.h2c.max_upload_buffer_per_stream must be positive")
}
}
if c.APIKeyCreate.MaxActivePerUser < 0 {
return fmt.Errorf("api_key_create.max_active_per_user must be non-negative")
}
if c.APIKeyCreate.MaxPerUserPerHour < 0 {
return fmt.Errorf("api_key_create.max_per_user_per_hour must be non-negative")
}
if c.APIKeyAuth.InvalidAbuse.Enabled {
if c.APIKeyAuth.InvalidAbuse.Threshold < 10 {
return fmt.Errorf("api_key_auth_cache.invalid_abuse.threshold must be at least 10")
@@ -2780,6 +2959,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)
@@ -3044,6 +3226,11 @@ func (c *Config) Validate() error {
if c.Billing.MinimumBalanceReserve < 0 {
return fmt.Errorf("billing.minimum_balance_reserve must be non-negative")
}
if c.Billing.InflightReservation.TTLSeconds < 0 || c.Billing.InflightReservation.DefaultMaxTokens < 0 ||
c.Billing.InflightReservation.MaxOutputTokens < 0 || c.Billing.InflightReservation.MaxInputTokens < 0 ||
c.Billing.InflightReservation.MaxReservationUSD < 0 {
return fmt.Errorf("billing.inflight_reservation values must be non-negative")
}
if c.Database.MaxOpenConns <= 0 {
return fmt.Errorf("database.max_open_conns must be positive")
}
@@ -3269,6 +3456,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")
}
@@ -3290,6 +3489,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")
@@ -3673,6 +3875,9 @@ func (c *Config) Validate() error {
if c.Ops.Cleanup.ErrorLogRetentionDays < 0 {
return fmt.Errorf("ops.cleanup.error_log_retention_days must be non-negative")
}
if c.Ops.Cleanup.Enabled && c.Ops.Cleanup.SystemLogRetentionDays <= 0 {
return fmt.Errorf("ops.cleanup.system_log_retention_days must be positive when ops cleanup is enabled")
}
if c.Ops.Cleanup.MinuteMetricsRetentionDays < 0 {
return fmt.Errorf("ops.cleanup.minute_metrics_retention_days must be non-negative")
}
@@ -3682,8 +3887,8 @@ func (c *Config) Validate() error {
if c.Ops.Cleanup.Enabled && strings.TrimSpace(c.Ops.Cleanup.Schedule) == "" {
return fmt.Errorf("ops.cleanup.schedule is required when ops.cleanup.enabled=true")
}
if c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30 {
return fmt.Errorf("concurrency.ping_interval must be between 5-30 seconds")
if c.Concurrency.PingInterval != 0 && (c.Concurrency.PingInterval < 5 || c.Concurrency.PingInterval > 30) {
return fmt.Errorf("concurrency.ping_interval must be 0 (disabled) or between 5-30 seconds")
}
if c.Gateway.Grok.FreeQuotaSoftGateEnabled {
if c.Gateway.Grok.FreeQuotaTokenLimit <= 0 {
+250 -17
View File
@@ -10,6 +10,7 @@ import (
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/util/urlvalidator"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
)
@@ -21,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) {
@@ -30,6 +117,42 @@ func TestLoadDefaultModelsListReadMaxBytes(t *testing.T) {
require.Equal(t, DefaultModelsListReadMaxBytes, cfg.Gateway.ModelsListReadMaxBytes)
}
func TestLoadDefaultMinOutputTokens(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 128, cfg.Gateway.MinOutputTokens)
}
func TestLoadMinOutputTokensFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_MIN_OUTPUT_TOKENS", "16")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 16, cfg.Gateway.MinOutputTokens)
}
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()
require.NoError(t, err)
cfg.Gateway.MinOutputTokens = 15
require.EqualError(t, cfg.Validate(), "gateway.min_output_tokens must be at least 16")
}
func TestLoadTimezonePrecedence(t *testing.T) {
tests := []struct {
name string
@@ -79,6 +202,15 @@ func TestLoadServerTimingConfig(t *testing.T) {
})
}
func TestLoadSimpleModeKeyRateLimitEnabledFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED", "true")
cfg, err := Load()
require.NoError(t, err)
require.True(t, cfg.SimpleModeKeyRateLimitEnabled)
}
func TestLoadRedisUsernameFromEnvironment(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("REDIS_USERNAME", "app-user")
@@ -98,6 +230,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)
@@ -452,11 +590,11 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
if !cfg.Gateway.OpenAIWS.DynamicMaxConnsByAccountConcurrencyEnabled {
t.Fatalf("Gateway.OpenAIWS.DynamicMaxConnsByAccountConcurrencyEnabled = false, want true")
}
if cfg.Gateway.OpenAIWS.OAuthMaxConnsFactor != 1.0 {
t.Fatalf("Gateway.OpenAIWS.OAuthMaxConnsFactor = %v, want 1.0", cfg.Gateway.OpenAIWS.OAuthMaxConnsFactor)
if cfg.Gateway.OpenAIWS.OAuthMaxConnsFactor != 5.0 {
t.Fatalf("Gateway.OpenAIWS.OAuthMaxConnsFactor = %v, want 5.0", cfg.Gateway.OpenAIWS.OAuthMaxConnsFactor)
}
if cfg.Gateway.OpenAIWS.APIKeyMaxConnsFactor != 1.0 {
t.Fatalf("Gateway.OpenAIWS.APIKeyMaxConnsFactor = %v, want 1.0", cfg.Gateway.OpenAIWS.APIKeyMaxConnsFactor)
if cfg.Gateway.OpenAIWS.APIKeyMaxConnsFactor != 5.0 {
t.Fatalf("Gateway.OpenAIWS.APIKeyMaxConnsFactor = %v, want 5.0", cfg.Gateway.OpenAIWS.APIKeyMaxConnsFactor)
}
if cfg.Gateway.OpenAIWS.StickySessionTTLSeconds != 3600 {
t.Fatalf("Gateway.OpenAIWS.StickySessionTTLSeconds = %d, want 3600", cfg.Gateway.OpenAIWS.StickySessionTTLSeconds)
@@ -574,7 +712,7 @@ func TestLoadDefaultOpenAICompactModel(t *testing.T) {
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, "gpt-5.4", cfg.Gateway.OpenAICompactModel)
require.Equal(t, "gpt-5.5", cfg.Gateway.OpenAICompactModel)
}
func TestLoadOpenAICompactModelFromEnv(t *testing.T) {
@@ -822,6 +960,7 @@ func TestLoadDefaultSecurityToggles(t *testing.T) {
wantHosts := []string{
"api.kimi.com",
"api.kimi.ai",
"api.moonshot.ai",
"api.moonshot.cn",
}
@@ -834,6 +973,19 @@ func TestLoadDefaultSecurityToggles(t *testing.T) {
t.Fatalf("URLAllowlist.UpstreamHosts missing %q; got %v", want, cfg.Security.URLAllowlist.UpstreamHosts)
}
}
opts := urlvalidator.ValidationOptions{
AllowedHosts: cfg.Security.URLAllowlist.UpstreamHosts,
RequireAllowlist: true,
AllowPrivate: cfg.Security.URLAllowlist.AllowPrivateHosts,
}
for _, host := range []string{"api.kimi.com", "api.kimi.ai"} {
target := "https://" + host + "/coding/v1/usages"
normalized, err := urlvalidator.ValidateHTTPSURL(target, opts)
require.NoError(t, err)
require.Equal(t, target, normalized)
_, err = urlvalidator.ValidateHTTPSURL("https://"+host+".attacker.example/coding/v1/usages", opts)
require.Error(t, err)
}
}
func TestLoadDefaultServerMode(t *testing.T) {
@@ -1191,6 +1343,21 @@ func TestLoadDefaultUsageCleanupConfig(t *testing.T) {
}
}
func TestLoadDefaultOpsCleanupConfig(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
if !cfg.Ops.Cleanup.Enabled {
t.Fatal("Ops.Cleanup.Enabled = false, want true")
}
if cfg.Ops.Cleanup.SystemLogRetentionDays != 30 {
t.Fatalf("Ops.Cleanup.SystemLogRetentionDays = %d, want 30", cfg.Ops.Cleanup.SystemLogRetentionDays)
}
}
func TestValidateUsageCleanupConfigEnabled(t *testing.T) {
resetViperWithJWTSecret(t)
@@ -1410,18 +1577,20 @@ func TestValidateOpsCleanupScheduleRequired(t *testing.T) {
func TestValidateConcurrencyPingInterval(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
cfg.Concurrency.PingInterval = 3
err = cfg.Validate()
if err == nil {
t.Fatalf("Validate() expected error for concurrency.ping_interval")
}
if !strings.Contains(err.Error(), "concurrency.ping_interval") {
t.Fatalf("Validate() expected concurrency.ping_interval error, got: %v", err)
for _, interval := range []int{-1, 0, 1, 3, 4, 5, 10, 30, 31} {
cfg, err := Load()
if err != nil {
t.Fatalf("Load() error: %v", err)
}
cfg.Concurrency.PingInterval = interval
err = cfg.Validate()
valid := interval == 0 || (interval >= 5 && interval <= 30)
if valid && err != nil {
t.Errorf("Validate() interval %d: %v", interval, err)
}
if !valid && (err == nil || !strings.Contains(err.Error(), "concurrency.ping_interval")) {
t.Errorf("Validate() interval %d: expected concurrency.ping_interval error, got %v", interval, err)
}
}
}
@@ -1559,6 +1728,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 },
@@ -1825,6 +2004,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 },
@@ -2137,6 +2326,11 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Ops.Cleanup.ErrorLogRetentionDays = -1 },
wantErr: "ops.cleanup.error_log_retention_days",
},
{
name: "ops cleanup system log retention",
mutate: func(c *Config) { c.Ops.Cleanup.SystemLogRetentionDays = 0 },
wantErr: "ops.cleanup.system_log_retention_days",
},
{
name: "ops cleanup minute retention",
mutate: func(c *Config) { c.Ops.Cleanup.MinuteMetricsRetentionDays = -1 },
@@ -2610,3 +2804,42 @@ func TestLoad_DefaultGatewayImageStreamConfig(t *testing.T) {
t.Fatalf("image stream timeout = %d, want greater than ordinary stream timeout %d", cfg.Gateway.ImageStreamDataIntervalTimeout, cfg.Gateway.StreamDataIntervalTimeout)
}
}
func TestLoadSimpleModeAutoCreateDefaultGroups(t *testing.T) {
for _, loader := range []struct {
name string
load func() (*Config, error)
}{{"Load", Load}, {"LoadForBootstrap", LoadForBootstrap}} {
t.Run(loader.name, func(t *testing.T) {
for _, tt := range []struct {
name string
yaml string
env string
unset bool
want bool
}{
{name: "unset env uses application default", unset: true, want: true},
{name: "empty env uses application default", want: true},
{name: "unset env preserves yaml false", unset: true, yaml: "simple_mode:\n auto_create_default_groups: false\n", want: false},
{name: "empty env preserves yaml false", yaml: "simple_mode:\n auto_create_default_groups: false\n", want: false},
{name: "env false overrides yaml true", yaml: "simple_mode:\n auto_create_default_groups: true\n", env: "false", want: false},
{name: "env false without yaml", env: "false", want: false},
{name: "env true overrides yaml false", yaml: "simple_mode:\n auto_create_default_groups: false\n", env: "true", want: true},
} {
t.Run(tt.name, func(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS", tt.env)
if tt.unset {
require.NoError(t, os.Unsetenv("SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS"))
}
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte("run_mode: simple\n"+tt.yaml), 0o600))
t.Setenv("CONFIG_FILE", path)
cfg, err := loader.load()
require.NoError(t, err)
require.Equal(t, tt.want, cfg.SimpleMode.AutoCreateDefaultGroups)
})
}
})
}
}
@@ -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)
})
}
}
@@ -19,7 +19,8 @@ import "time"
// - "7d" 7 天窗口(Claude/Codex)
// - "7d-sonnet" Claude 7 天 Sonnet 独立额度
// - "7d-fable" Claude 7 天 Fable 独立额度
// - "weekly" 周窗口(Kimi/Zhipu coding plan)
// - "weekly" 周窗口(Kimi/Zhipu coding plan / OpenCode Go)
// - "monthly" 月窗口(OpenCode Go)
// - "daily" 日窗口(Gemini 日配额 / Grok 日请求)
// - "30d" 30 天窗口(Grok 月度)
// - "total" 无窗口语义的总量额度(Antigravity per-model 等)
+50 -6
View File
@@ -24,9 +24,20 @@ const (
PlatformAntigravity = "antigravity"
PlatformGrok = "grok"
// 国产 OpenAI 兼容供应商(经 OpenAI 网关转发,按 Chat Completions 协议)。
PlatformKimi = "kimi" // Kimi (月之暗面 / Moonshot)
PlatformZhipu = "zhipu" // 智谱 GLM (bigmodel)
PlatformDeepseek = "deepseek" // DeepSeek
PlatformKimi = "kimi" // Kimi (月之暗面 / Moonshot)
PlatformZhipu = "zhipu" // 智谱 GLM (bigmodel)
PlatformDeepseek = "deepseek" // DeepSeek
PlatformMiniMax = "minimax" // MiniMax (M 系列)
PlatformTypeSafe = "typesafe" // TypeSafe AI System One (Jev)
// PlatformOpenCodeGo 是 OpenCode 平台(账号类型 Zen 按量 / Go 订阅)。
// 值保持 opencode_go 以兼容已落库的账号、分组、配额与 Composite 路由。
PlatformOpenCodeGo = "opencode_go"
// PlatformCommandCode 是 Command Code Provider API(多模型聚合,积分计费,
// 订阅套餐另有 5 小时 / 每周滚动窗口)。
PlatformCommandCode = "command_code"
// PlatformCline 是 Cline API(多模型聚合,OpenAI 兼容 Chat Completions;按量积分计费,
// 另有 ClinePass 订阅)。
PlatformCline = "cline"
PlatformComposite = "composite"
)
@@ -35,6 +46,8 @@ const (
const (
AccountModePayG = "payg" // 按量付费:消耗余额,做余额检测冷却
AccountModeCoding = "coding" // Coding Plan:滚动用量窗口冷却(5h / weekly)
AccountModeZen = "zen" // OpenCode Zen:按量付费,https://opencode.ai/zen/v1
AccountModeGo = "go" // OpenCode Go:订阅额度窗口,https://opencode.ai/zen/go/v1
)
// API protocol constants 国产供应商的上游 API 协议维度。存储于
@@ -43,7 +56,7 @@ const (
const (
APIProtocolChatCompletions = "chat_completions" // OpenAI Chat Completions(默认)
APIProtocolAnthropic = "anthropic" // 原生 Anthropic /v1/messages(适配 Claude Code)
APIProtocolResponses = "responses" // OpenAI Responses(deepseek / kimi 原生端点,适配 Codex)
APIProtocolResponses = "responses" // OpenAI Responses(deepseek / kimi / minimax 原生端点,适配 Codex)
APIProtocolAdaptive = "adaptive" // 按入站协议优先选择供应商原生端点
)
@@ -100,6 +113,14 @@ var DefaultAntigravityModelMapping = map[string]string{
// Claude 白名单
"claude-fable-5-1": "claude-fable-5-1", // 官方模型
"claude-fable-5": "claude-fable-5", // 官方模型
"claude-opus-5-5": "claude-opus-5-5-high", // 简称映射
"claude-opus-5-5-high": "claude-opus-5-5-high", // 官方模型
"claude-opus-5-5-medium": "claude-opus-5-5-medium", // 官方模型
"claude-opus-5-5-low": "claude-opus-5-5-low", // 官方模型
"claude-sonnet-5-5": "claude-sonnet-5-5-high", // 简称映射
"claude-sonnet-5-5-high": "claude-sonnet-5-5-high", // 官方模型
"claude-sonnet-5-5-medium": "claude-sonnet-5-5-medium", // 官方模型
"claude-sonnet-5-5-low": "claude-sonnet-5-5-low", // 官方模型
"claude-opus-4-8": "claude-opus-4-8", // 官方模型
"claude-opus-4-7": "claude-opus-4-7", // 官方模型
"claude-opus-4-6-thinking": "claude-opus-4-6-thinking", // 官方模型
@@ -145,6 +166,25 @@ var DefaultAntigravityModelMapping = map[string]string{
"gemini-3.6-flash-low": "gemini-3.6-flash-low",
"gemini-3.6-flash-medium": "gemini-3.6-flash-medium",
"gemini-3.6-flash-tiered": "gemini-3.6-flash-tiered",
// Gemini 3.7 Flash tiered models
"gemini-3.7-flash": "gemini-3.7-flash",
"gemini-3.7-flash-high": "gemini-3.7-flash-high",
"gemini-3.7-flash-low": "gemini-3.7-flash-low",
"gemini-3.7-flash-medium": "gemini-3.7-flash-medium",
"gemini-3.7-flash-tiered": "gemini-3.7-flash-tiered",
// Gemini 3.8 Flash tiered models
"gemini-3.8-flash": "gemini-3.8-flash",
"gemini-3.8-flash-high": "gemini-3.8-flash-high",
"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 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",
"gemini-4-argon-medium": "gemini-4-argon-medium",
// Gemini 3 image 兼容映射(向 3.1 image 迁移)
"gemini-3-pro-image": "gemini-3.1-flash-image",
"gemini-3-pro-image-preview": "gemini-3.1-flash-image",
@@ -159,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",
@@ -172,6 +214,8 @@ var DefaultBedrockModelMapping = map[string]string{
"claude-opus-4-1": "us.anthropic.claude-opus-4-1-20250805-v1:0",
"claude-opus-4-20250514": "us.anthropic.claude-opus-4-20250514-v1:0",
// Claude Sonnet
// Sonnet 5.5 is available on bedrock-runtime through Global inference only.
"claude-sonnet-5-5": "global.anthropic.claude-sonnet-5-5",
"claude-sonnet-5": "us.anthropic.claude-sonnet-5-v1",
"claude-sonnet-4-6-thinking": "us.anthropic.claude-sonnet-4-6",
"claude-sonnet-4-6": "us.anthropic.claude-sonnet-4-6",
+45 -3
View File
@@ -89,13 +89,55 @@ func TestDefaultAntigravityModelMapping_Gemini36FlashModels(t *testing.T) {
}
}
func TestDefaultAntigravityModelMapping_Gemini37FlashModels(t *testing.T) {
for _, model := range []string{"gemini-3.7-flash", "gemini-3.7-flash-high", "gemini-3.7-flash-low", "gemini-3.7-flash-medium", "gemini-3.7-flash-tiered"} {
if got := DefaultAntigravityModelMapping[model]; got != model {
t.Fatalf("expected %s to map to itself, got %q", model, got)
}
}
}
func TestDefaultAntigravityModelMapping_Gemini38FlashModels(t *testing.T) {
for _, model := range []string{"gemini-3.8-flash", "gemini-3.8-flash-high", "gemini-3.8-flash-low", "gemini-3.8-flash-medium", "gemini-3.8-flash-tiered"} {
if got := DefaultAntigravityModelMapping[model]; got != model {
t.Fatalf("expected %s to map to itself, got %q", model, got)
}
}
}
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",
"gemini-4-argon-medium": "gemini-4-argon-medium",
"claude-opus-5-5": "claude-opus-5-5-high",
"claude-opus-5-5-high": "claude-opus-5-5-high",
"claude-opus-5-5-low": "claude-opus-5-5-low",
"claude-opus-5-5-medium": "claude-opus-5-5-medium",
"claude-sonnet-5-5": "claude-sonnet-5-5-high",
"claude-sonnet-5-5-high": "claude-sonnet-5-5-high",
"claude-sonnet-5-5-low": "claude-sonnet-5-5-low",
"claude-sonnet-5-5-medium": "claude-sonnet-5-5-medium",
}
for from, want := range cases {
if got := DefaultAntigravityModelMapping[from]; got != want {
t.Fatalf("expected %s to map to %q, got %q", from, want, got)
}
}
}
func TestDefaultBedrockModelMapping_ContainsNewClaudeModels(t *testing.T) {
t.Parallel()
cases := map[string]string{
"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",
"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",
"claude-sonnet-5-5": "global.anthropic.claude-sonnet-5-5",
}
for from, want := range cases {
got, ok := DefaultBedrockModelMapping[from]
+113
View File
@@ -0,0 +1,113 @@
package domain
import (
"strconv"
"strings"
)
// GroupLocaleText 是分组名称与描述在某个界面语言下的译文。
// 字段为空表示该语言沿用分组自身的 name/description。
type GroupLocaleText struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
}
// GroupI18n 以界面语言代码(如 "en"、"zh")为键保存分组展示文案的译文。
// 仅用于页面展示;分组的唯一性、搜索与各类日志仍以 name 为准。
type GroupI18n map[string]GroupLocaleText
// Localize 返回 name、description 在请求首选语言下的版本;该语言没有译文的字段保持原值。
// acceptLanguage 是 Accept-Language 请求头。只采用其中优先级最高的语言:原字段的语言
// 未知,退到次选语言的译文不一定比原字段更合适。
func (m GroupI18n) Localize(acceptLanguage, name, description string) (string, string) {
text, ok := m.lookup(preferredLanguage(acceptLanguage))
if !ok {
return name, description
}
if text.Name != "" {
name = text.Name
}
if text.Description != "" {
description = text.Description
}
return name, description
}
// LocalizeName 是只需要名称时的 Localize。
func (m GroupI18n) LocalizeName(acceptLanguage, name string) string {
name, _ = m.Localize(acceptLanguage, name, "")
return name
}
// CanonicalLocale 按 BCP 47 的惯用大小写书写语言代码:主语言小写,4 位文字代码首字母大写,
// 2 位地区代码大写,其余小写(zh-hant-tw -> zh-Hant-TW);单字母扩展标记之后的部分全部小写。
// 只调整大小写,不校验代码是否合法。
func CanonicalLocale(locale string) string {
subtags := strings.Split(locale, "-")
extension := false
for i, subtag := range subtags {
subtag = strings.ToLower(subtag)
switch {
case i == 0 || extension:
case len(subtag) == 1:
extension = true
case len(subtag) == 2:
subtag = strings.ToUpper(subtag)
case len(subtag) == 4:
subtag = strings.ToUpper(subtag[:1]) + subtag[1:]
}
subtags[i] = subtag
}
return strings.Join(subtags, "-")
}
// lookup 先按完整语言代码匹配(zh-TW),再按主语言匹配(zh-CN -> zh),不区分大小写。
// 写入时语言代码已统一为 CanonicalLocale,同一语言只有一个键;若存有仅大小写不同的多个键,
// 规范写法的键优先,其余按字节序取最小者,保证同一请求语言的结果固定。
func (m GroupI18n) lookup(tag string) (GroupLocaleText, bool) {
if tag == "" || len(m) == 0 {
return GroupLocaleText{}, false
}
primary, _, _ := strings.Cut(tag, "-")
for _, candidate := range []string{tag, primary} {
candidate = CanonicalLocale(candidate)
if text, ok := m[candidate]; ok {
return text, true
}
matched := ""
for locale := range m {
if strings.EqualFold(locale, candidate) && (matched == "" || locale < matched) {
matched = locale
}
}
if matched != "" {
return m[matched], true
}
}
return GroupLocaleText{}, false
}
// preferredLanguage 取 Accept-Language 中权重最高的语言代码,权重相同取靠前者;
// 通配符 * 与 q=0 的条目不参与。
func preferredLanguage(acceptLanguage string) string {
best, bestQ := "", 0.0
for _, part := range strings.Split(acceptLanguage, ",") {
tag, params, _ := strings.Cut(part, ";")
tag = strings.ReplaceAll(strings.TrimSpace(tag), "_", "-")
if tag == "" || tag == "*" {
continue
}
q := 1.0
if value, ok := strings.CutPrefix(strings.TrimSpace(params), "q="); ok {
parsed, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
if err != nil {
continue
}
q = parsed
}
if q > bestQ {
best, bestQ = tag, q
}
}
return best
}
+107
View File
@@ -0,0 +1,107 @@
package domain
import "testing"
func TestGroupI18nLocalize(t *testing.T) {
i18n := GroupI18n{
"en": {Name: "Standard", Description: "Pro + Max pool"},
"zh-TW": {Name: "標準"},
"ja": {Description: "説明のみ"},
}
const name, description = "标准", "号池"
tests := []struct {
title string
acceptLanguage string
wantName string
wantDescription string
}{
{"exact locale", "en", "Standard", "Pro + Max pool"},
{"region falls back to the primary language", "en-US", "Standard", "Pro + Max pool"},
{"locale match ignores case and underscore", "ZH_tw", "標準", description},
{"a missing field keeps the original text", "ja", name, "説明のみ"},
{"no translation for the language keeps both", "zh", name, description},
{"primary language does not match a regional translation", "zh-CN", name, description},
{"empty header keeps both", "", name, description},
{"wildcard only keeps both", "*", name, description},
// 原字段的语言未知,不退到次选语言:浏览器的 zh 用户不应拿到英文译文。
{"only the preferred language is considered", "zh-CN,zh;q=0.9,en;q=0.8", name, description},
{"highest weight wins over position", "zh;q=0.5, en;q=0.9", "Standard", "Pro + Max pool"},
{"equal weight keeps the first", "en, zh", "Standard", "Pro + Max pool"},
{"entries with q=0 are ignored", "en;q=0, ja", name, "説明のみ"},
{"malformed weight is skipped", "en;q=abc, ja", name, "説明のみ"},
}
for _, tt := range tests {
t.Run(tt.title, func(t *testing.T) {
gotName, gotDescription := i18n.Localize(tt.acceptLanguage, name, description)
if gotName != tt.wantName || gotDescription != tt.wantDescription {
t.Fatalf("Localize(%q) = (%q, %q), want (%q, %q)",
tt.acceptLanguage, gotName, gotDescription, tt.wantName, tt.wantDescription)
}
})
}
}
func TestGroupI18nLocalize_NilMap(t *testing.T) {
var i18n GroupI18n
name, description := i18n.Localize("en", "标准", "号池")
if name != "标准" || description != "号池" {
t.Fatalf("nil translations must keep the original text, got (%q, %q)", name, description)
}
if got := i18n.LocalizeName("en", "标准"); got != "标准" {
t.Fatalf("LocalizeName on nil translations = %q", got)
}
}
func TestGroupI18nLocalizeName(t *testing.T) {
i18n := GroupI18n{"en": {Name: "Standard"}}
if got := i18n.LocalizeName("en", "标准"); got != "Standard" {
t.Fatalf("LocalizeName(en) = %q", got)
}
if got := i18n.LocalizeName("zh", "标准"); got != "标准" {
t.Fatalf("LocalizeName(zh) = %q", got)
}
}
func TestCanonicalLocale(t *testing.T) {
tests := map[string]string{
"en": "en",
"EN": "en",
"zh-tw": "zh-TW",
"ZH-Hant-tw": "zh-Hant-TW",
"es-419": "es-419",
"de-CH-1901": "de-CH-1901",
"en-US-x-Twain": "en-US-x-twain",
}
for in, want := range tests {
if got := CanonicalLocale(in); got != want {
t.Errorf("CanonicalLocale(%q) = %q, want %q", in, got, want)
}
}
}
// 写入路径已拒绝仅大小写不同的语言代码;已存在的此类数据读取时也必须得到固定结果。
func TestGroupI18nLocalize_CaseCollidingKeysAreDeterministic(t *testing.T) {
tests := []struct {
title string
i18n GroupI18n
acceptLanguage string
want string
}{
{"canonical key wins", GroupI18n{"EN": {Name: "B"}, "en": {Name: "A"}, "En": {Name: "C"}}, "en", "A"},
{"otherwise the smallest key wins", GroupI18n{"eN": {Name: "B"}, "EN": {Name: "A"}}, "en", "A"},
{"primary language fallback is deterministic too", GroupI18n{"ZH": {Name: "B"}, "zh": {Name: "A"}}, "zh-CN", "A"},
}
for _, tt := range tests {
t.Run(tt.title, func(t *testing.T) {
for range 200 {
if got := tt.i18n.LocalizeName(tt.acceptLanguage, "原名"); got != tt.want {
t.Fatalf("LocalizeName(%q) = %q, want %q", tt.acceptLanguage, got, tt.want)
}
}
})
}
}
+137
View File
@@ -0,0 +1,137 @@
package domain
// 平台清单:平台的单一数据来源。"所有平台"类列表(分组平台、用户额度、组合
// 路由目标、调度快照、定价匹配等)与"某网关族"类列表都从这里派生;新增平台
// 登记一条即可在这些位置生效,无需逐处修改或新增数据库约束迁移。
//
// 依赖具体实现的能力(OAuth、渠道监控、余额 / Coding Plan 探测、用量窗口、
// Codex 模型目录等)仍由各自的代码显式列出,不在此处声明。
// PlatformGateway 标识平台请求由哪个网关服务处理。
type PlatformGateway string
const (
// PlatformGatewayAnthropic 由 GatewayService 处理(Claude Messages 协议,以及 TypeSafe 的 /v1/systemone)。
PlatformGatewayAnthropic PlatformGateway = "anthropic"
// PlatformGatewayOpenAI 由 OpenAIGatewayService 处理(OpenAI、Grok 与多协议 API Key 供应商)。
PlatformGatewayOpenAI PlatformGateway = "openai"
// PlatformGatewayGemini 由 Gemini 兼容网关处理。
PlatformGatewayGemini PlatformGateway = "gemini"
// PlatformGatewayAntigravity 由 Antigravity 网关处理。
PlatformGatewayAntigravity PlatformGateway = "antigravity"
)
// PlatformSpec 描述一个具体(非 composite)平台。
type PlatformSpec struct {
ID string `json:"id"`
DisplayName string `json:"display_name"`
Gateway PlatformGateway `json:"gateway"`
// CNProvider 标识国产单一厂商(Kimi / 智谱 / DeepSeek / MiniMax),共享国产
// 供应商的余额 / Coding Plan 等能力。
CNProvider bool `json:"cn_provider"`
// LiteLLMProvider 是定价目录中的 provider 名;空表示不支持从定价目录同步模型。
LiteLLMProvider string `json:"litellm_provider,omitempty"`
}
// platformList 的顺序即平台的展示顺序。
var platformList = []PlatformSpec{
{ID: PlatformAnthropic, DisplayName: "Anthropic", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "anthropic"},
{ID: PlatformOpenAI, DisplayName: "OpenAI", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "openai"},
{ID: PlatformGemini, DisplayName: "Gemini", Gateway: PlatformGatewayGemini, LiteLLMProvider: "gemini"},
{ID: PlatformAntigravity, DisplayName: "Antigravity", Gateway: PlatformGatewayAntigravity, LiteLLMProvider: "anthropic"},
{ID: PlatformGrok, DisplayName: "Grok", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "xai"},
{ID: PlatformKimi, DisplayName: "Kimi", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "moonshot"},
{ID: PlatformZhipu, DisplayName: "Zhipu GLM", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "zhipu"},
{ID: PlatformDeepseek, DisplayName: "DeepSeek", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "deepseek"},
{ID: PlatformMiniMax, DisplayName: "MiniMax", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "minimax"},
{ID: PlatformOpenCodeGo, DisplayName: "OpenCode", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "opencode-go"},
{ID: PlatformTypeSafe, DisplayName: "TypeSafe / Jev", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "typesafe"},
{ID: PlatformCommandCode, DisplayName: "Command Code", Gateway: PlatformGatewayOpenAI},
{ID: PlatformCline, DisplayName: "Cline", Gateway: PlatformGatewayOpenAI},
}
var platformIndex = func() map[string]int {
index := make(map[string]int, len(platformList))
for i, spec := range platformList {
index[spec.ID] = i
}
return index
}()
// Platforms 返回全部具体平台(副本),按展示顺序。
func Platforms() []PlatformSpec {
out := make([]PlatformSpec, len(platformList))
copy(out, platformList)
return out
}
// LookupPlatform 返回具体平台的登记信息;composite 与未知值返回 false。
func LookupPlatform(id string) (PlatformSpec, bool) {
i, ok := platformIndex[id]
if !ok {
return PlatformSpec{}, false
}
return platformList[i], true
}
// IsConcretePlatform 报告 id 是否为已登记的具体平台(不含 composite)。
func IsConcretePlatform(id string) bool {
_, ok := platformIndex[id]
return ok
}
// IsGroupPlatform 报告 id 是否可作为分组平台(具体平台或 composite)。
func IsGroupPlatform(id string) bool {
return id == PlatformComposite || IsConcretePlatform(id)
}
// ConcretePlatformIDs 返回全部具体平台标识,按展示顺序。
func ConcretePlatformIDs() []string {
return PlatformIDsWhere(func(PlatformSpec) bool { return true })
}
// PlatformIDsWhere 返回满足条件的具体平台标识,按展示顺序。
func PlatformIDsWhere(match func(PlatformSpec) bool) []string {
out := make([]string, 0, len(platformList))
for _, spec := range platformList {
if match(spec) {
out = append(out, spec.ID)
}
}
return out
}
// compositePrecedenceHead 是组合分组查找顺序的固定前缀(历史顺序:Gemini 先于 OpenAI)。
var compositePrecedenceHead = []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI}
// CompositePrecedencePlatformIDs 返回按平台依次回退时的顺序:组合分组在请求目标
// 解析前逐平台查找定价 / 模型映射(先命中者生效)、拼接默认模型列表,以及调度快照
// 遍历。沿用历史顺序 anthropic、gemini、openai,其余按展示顺序,新登记的平台追加在末尾。
func CompositePrecedencePlatformIDs() []string {
out := make([]string, 0, len(platformList))
seen := make(map[string]struct{}, len(platformList))
for _, id := range compositePrecedenceHead {
if IsConcretePlatform(id) {
out = append(out, id)
seen[id] = struct{}{}
}
}
for _, spec := range platformList {
if _, ok := seen[spec.ID]; !ok {
out = append(out, spec.ID)
}
}
return out
}
// UsesOpenAIGateway 报告平台是否由 OpenAI 网关处理。
func UsesOpenAIGateway(id string) bool {
spec, ok := LookupPlatform(id)
return ok && spec.Gateway == PlatformGatewayOpenAI
}
// IsCNProviderPlatform 报告平台是否为国产单一厂商。
func IsCNProviderPlatform(id string) bool {
spec, ok := LookupPlatform(id)
return ok && spec.CNProvider
}
+74
View File
@@ -0,0 +1,74 @@
package domain
import (
"testing"
"github.com/stretchr/testify/require"
)
// 重构前各处手写的平台列表,作为平台清单派生结果的等价基准;重构后新登记的平台
// (Command Code、Cline)按同类平台(OpenCode)的位置补入。
var (
legacyDisplayOrder = []string{
PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok,
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
PlatformCommandCode,
PlatformCline,
}
legacyCompositePrecedence = []string{
PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok,
PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe,
PlatformCommandCode,
PlatformCline,
}
legacyOpenAIGateway = []string{
PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo,
PlatformCommandCode,
PlatformCline,
}
legacyCNProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax}
legacyLiteLLMByPlatf = map[string]string{
PlatformAnthropic: "anthropic", PlatformOpenAI: "openai", PlatformGemini: "gemini",
PlatformAntigravity: "anthropic", PlatformGrok: "xai", PlatformKimi: "moonshot",
PlatformZhipu: "zhipu", PlatformDeepseek: "deepseek", PlatformMiniMax: "minimax",
PlatformOpenCodeGo: "opencode-go", PlatformTypeSafe: "typesafe", PlatformCommandCode: "", PlatformCline: "",
}
)
func TestPlatformListMatchesLegacyLists(t *testing.T) {
require.Equal(t, legacyDisplayOrder, ConcretePlatformIDs())
require.Equal(t, legacyCompositePrecedence, CompositePrecedencePlatformIDs())
require.Equal(t, legacyOpenAIGateway, PlatformIDsWhere(func(spec PlatformSpec) bool {
return spec.Gateway == PlatformGatewayOpenAI
}))
require.Equal(t, legacyCNProviders, PlatformIDsWhere(func(spec PlatformSpec) bool { return spec.CNProvider }))
for platform, provider := range legacyLiteLLMByPlatf {
spec, ok := LookupPlatform(platform)
require.True(t, ok, platform)
require.Equal(t, provider, spec.LiteLLMProvider, platform)
}
}
func TestPlatformListPredicates(t *testing.T) {
for _, platform := range legacyDisplayOrder {
require.True(t, IsConcretePlatform(platform), platform)
require.True(t, IsGroupPlatform(platform), platform)
spec, ok := LookupPlatform(platform)
require.True(t, ok, platform)
require.NotEmpty(t, spec.DisplayName, platform)
require.NotEmpty(t, spec.Gateway, platform)
}
require.False(t, IsConcretePlatform(PlatformComposite))
require.True(t, IsGroupPlatform(PlatformComposite))
for _, invalid := range []string{"", "moonshot", "Kimi", "openai ", "glm", "bogus"} {
require.False(t, IsConcretePlatform(invalid), invalid)
require.False(t, IsGroupPlatform(invalid), invalid)
require.False(t, UsesOpenAIGateway(invalid), invalid)
}
}
func TestPlatformsReturnsCopy(t *testing.T) {
platforms := Platforms()
platforms[0].ID = "mutated"
require.Equal(t, PlatformAnthropic, Platforms()[0].ID)
}
@@ -908,14 +908,16 @@ func buildCodexAgentIdentityKeys(accountID string) []string {
return []string{"account:" + accountID}
}
// buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度,
// 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。
// buildCodexStoredIdentityKeys 生成存量账号索引键,按 workspace/account
// 和 user 组合隔离身份,避免同一用户在不同 workspace 的账号误合并。
func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string {
keys := make([]string, 0, 3)
accountID = strings.TrimSpace(accountID)
userID = strings.TrimSpace(userID)
accessToken = strings.TrimSpace(accessToken)
if userID != "" {
if accountID != "" && userID != "" {
keys = append(keys, "account_user:"+codexCompositeIdentityKey(accountID, userID))
} else if userID != "" {
keys = append(keys, "user:"+userID)
}
if accountID == "" && userID == "" {
@@ -932,6 +934,10 @@ func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string)
return keys
}
func codexCompositeIdentityKey(accountID, userID string) string {
return fmt.Sprintf("%d:%s%d:%s", len(accountID), accountID, len(userID), userID)
}
func buildCodexAccountIndex(accounts []service.Account) *codexAccountIndex {
index := &codexAccountIndex{
accountsByKey: map[string][]service.Account{},
@@ -303,8 +303,8 @@ func TestResolveCodexImportExpiryForNoRefreshTokenUsesEarlierRequestExpiry(t *te
func TestCodexIdentityKeysPreferStrongIdentifiers(t *testing.T) {
keys := buildCodexImportIdentityKeys("acct-1", "user-1", "same@example.com", "token", "refresh")
if len(keys) == 0 || keys[0] != "user:user-1" {
t.Fatalf("user key should have highest priority when refresh token exists: %v", keys)
if len(keys) == 0 || keys[0] != "account_user:6:acct-16:user-1" {
t.Fatalf("workspace-scoped user key should have highest priority when refresh token exists: %v", keys)
}
if keys[len(keys)-1] != "account:acct-1" {
t.Fatalf("shared account key should be the last fallback: %v", keys)
@@ -465,12 +465,84 @@ func TestCodexAccountIndexKeepsAllCandidatesForSharedAccountKey(t *testing.T) {
if got == nil || got.ID != member.ID {
t.Fatalf("Find by user key = %v, want member account ID %d", got, member.ID)
}
if matchedKey != "user:user-2" {
t.Fatalf("matched key = %q, want user:user-2", matchedKey)
if matchedKey != "account_user:6:team-16:user-2" {
t.Fatalf("matched key = %q, want account_user:6:team-16:user-2", matchedKey)
}
}
}
func TestImportCodexSessionsSameUserDifferentWorkspacesCreatesSeparateAccounts(t *testing.T) {
svc := newCodexImportMemoryAdminService(nil)
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
entries := []codexImportEntry{
{Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "shared-user", "refresh-1")},
{Index: 2, Value: buildCodexRefreshImportValue(t, "workspace-2", "shared-user", "refresh-2")},
}
result, err := handler.importCodexSessions(context.Background(), req, entries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if result.Created != 2 || result.Updated != 0 || result.Skipped != 0 || result.Failed != 0 {
t.Fatalf("result = %+v, want two created accounts", result)
}
if len(svc.createdAccounts) != 2 {
t.Fatalf("created accounts = %d, want 2", len(svc.createdAccounts))
}
if got := svc.createdAccounts[0].Credentials["chatgpt_account_id"]; got != "workspace-1" {
t.Fatalf("first workspace = %v, want workspace-1", got)
}
if got := svc.createdAccounts[1].Credentials["chatgpt_account_id"]; got != "workspace-2" {
t.Fatalf("second workspace = %v, want workspace-2", got)
}
}
func TestCodexImportIdentityKeySeparatesDelimiterValues(t *testing.T) {
left := buildCodexImportIdentityKeys("ab:c", "shared-user", "", "", "refresh")
right := buildCodexImportIdentityKeys("ab", "c:shared-user", "", "", "refresh")
if left[0] == right[0] {
t.Fatalf("composite identity keys collided: %q", left[0])
}
}
func TestImportCodexSessionsSameWorkspaceAccountUpdatesAndDifferentUserIsolated(t *testing.T) {
svc := newCodexImportMemoryAdminService(nil)
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
req := CodexSessionImportRequest{SkipDefaultGroupBind: boolPtr(true)}
initialEntries := []codexImportEntry{
{Index: 1, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-1")},
{Index: 2, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-2", "refresh-2")},
}
initialResult, err := handler.importCodexSessions(context.Background(), req, initialEntries)
if err != nil {
t.Fatalf("importCodexSessions error = %v", err)
}
if initialResult.Created != 2 || initialResult.Updated != 0 || initialResult.Skipped != 0 || initialResult.Failed != 0 {
t.Fatalf("initial result = %+v, want two created accounts", initialResult)
}
updateResult, err := handler.importCodexSessions(context.Background(), req, []codexImportEntry{
{Index: 3, Value: buildCodexRefreshImportValue(t, "workspace-1", "user-1", "refresh-3")},
})
if err != nil {
t.Fatalf("importCodexSessions update error = %v", err)
}
if updateResult.Created != 0 || updateResult.Updated != 1 || updateResult.Skipped != 0 || updateResult.Failed != 0 {
t.Fatalf("update result = %+v, want one updated account", updateResult)
}
if len(svc.createdAccounts) != 2 || len(svc.updatedAccounts) != 1 {
t.Fatalf("created = %d, updated = %d, want 2 and 1", len(svc.createdAccounts), len(svc.updatedAccounts))
}
if svc.updatedAccounts[0].id != 100 {
t.Fatalf("updated account ID = %d, want user-1 account ID 100", svc.updatedAccounts[0].id)
}
if got := svc.updatedAccounts[0].input.Credentials["chatgpt_user_id"]; got != "user-1" {
t.Fatalf("updated user = %v, want user-1", got)
}
}
func TestCodexAccountIndexUpsertReplacesSameAccount(t *testing.T) {
legacy := service.Account{
ID: 40,
+10 -6
View File
@@ -309,15 +309,17 @@ func (h *AccountHandler) importData(ctx context.Context, req DataImportRequest)
_, _ = h.adminService.UpdateProxy(ctx, existingID, &service.UpdateProxyInput{
Status: normalizedStatus,
ExpiresAt: existingExpiresAt,
ClearExpiresAt: existingExpiresAt == nil,
FallbackMode: existingFallbackMode,
BackupProxyID: existingBackupProxyID,
ExpiryWarnDays: item.ExpiryWarnDays,
ClearBackupID: existingBackupProxyID == nil,
ExpiryWarnDays: &item.ExpiryWarnDays,
Name: proxy.Name,
Protocol: proxy.Protocol,
Host: proxy.Host,
Port: proxy.Port,
Username: proxy.Username,
Password: proxy.Password,
Username: &proxy.Username,
Password: &proxy.Password,
})
}
}
@@ -383,15 +385,17 @@ func (h *AccountHandler) importData(ctx context.Context, req DataImportRequest)
_, _ = h.adminService.UpdateProxy(ctx, created.ID, &service.UpdateProxyInput{
Status: normalizedStatus,
ExpiresAt: expiresAt,
ClearExpiresAt: expiresAt == nil,
FallbackMode: fallbackMode,
BackupProxyID: backupProxyID,
ExpiryWarnDays: item.ExpiryWarnDays,
ClearBackupID: backupProxyID == nil,
ExpiryWarnDays: &item.ExpiryWarnDays,
Name: created.Name,
Protocol: created.Protocol,
Host: created.Host,
Port: created.Port,
Username: created.Username,
Password: created.Password,
Username: &created.Username,
Password: &created.Password,
})
}
}
+118 -21
View File
@@ -27,6 +27,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/pkg/timezone"
"github.com/Wei-Shaw/sub2api/internal/pkg/typesafe"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -48,6 +49,7 @@ func NewOAuthHandler(oauthService *service.OAuthService) *OAuthHandler {
// AccountHandler handles admin account management
type AccountHandler struct {
claudeResetCredits claudeResetReader
adminService service.AdminService
oauthService *service.OAuthService
openaiOAuthService *service.OpenAIOAuthService
@@ -66,6 +68,7 @@ type AccountHandler struct {
upstreamBillingProbe *service.UpstreamBillingProbeService
ollamaCloudUsage *service.OllamaCloudUsageService
cfg *config.Config
opencodeGoUsage *service.OpenCodeGoUsageService
}
// SetUpstreamBillingProbeService attaches the optional remote billing probe service.
@@ -77,6 +80,10 @@ func (h *AccountHandler) SetOllamaCloudUsageService(usage *service.OllamaCloudUs
h.ollamaCloudUsage = usage
}
func (h *AccountHandler) SetOpenCodeGoUsageService(usage *service.OpenCodeGoUsageService) {
h.opencodeGoUsage = usage
}
// NewAccountHandler creates a new admin account handler
func NewAccountHandler(
adminService service.AdminService,
@@ -129,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"` // 用户确认混合渠道风险
}
@@ -150,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"` // 用户确认混合渠道风险
}
@@ -674,14 +683,22 @@ func (h *AccountHandler) List(c *gin.Context) {
response.ErrorFrom(c, err)
return
}
if h.ollamaCloudUsage != nil && len(accounts) > 0 {
if len(accounts) > 0 {
accountPointers := make([]*service.Account, len(accounts))
for index := range accounts {
accountPointers[index] = &accounts[index]
}
if err := h.ollamaCloudUsage.ResolveAccounts(c.Request.Context(), accountPointers); err != nil {
response.ErrorFrom(c, err)
return
if h.ollamaCloudUsage != nil {
if err := h.ollamaCloudUsage.ResolveAccounts(c.Request.Context(), accountPointers); err != nil {
response.ErrorFrom(c, err)
return
}
}
if h.opencodeGoUsage != nil {
if err := h.opencodeGoUsage.ResolveOpenCodeGoUsageAccounts(c.Request.Context(), accountPointers); err != nil {
response.ErrorFrom(c, err)
return
}
}
}
@@ -942,8 +959,18 @@ func (h *AccountHandler) GetByID(c *gin.Context) {
return
}
}
if h.opencodeGoUsage != nil {
if err := h.opencodeGoUsage.ResolveOpenCodeGoUsageAccounts(c.Request.Context(), []*service.Account{account}); err != nil {
response.ErrorFrom(c, err)
return
}
}
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.
@@ -1037,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 {
@@ -1169,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,
})
@@ -1205,7 +1234,7 @@ func (h *AccountHandler) Update(c *gin.Context) {
// 网关会按"现状即证据"默认走 Responses。
func (h *AccountHandler) scheduleOpenAIResponsesProbe(account *service.Account) {
if account == nil || account.Type != service.AccountTypeAPIKey ||
(account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform)) {
(account.Platform != service.PlatformOpenAI && !account.RoutesProtocolByInbound()) {
return
}
if h.accountTestService == nil {
@@ -1398,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
}
@@ -1450,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
}
@@ -1506,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
}
@@ -1545,6 +1581,7 @@ func (h *AccountHandler) Refresh(c *gin.Context) {
if warning == "missing_project_id_temporary" {
response.Success(c, gin.H{
"account": h.buildAccountResponseWithRuntime(c.Request.Context(), updatedAccount),
"message": "Token refreshed successfully, but project_id could not be retrieved (will retry automatically)",
"warning": "missing_project_id_temporary",
})
@@ -1608,6 +1645,10 @@ func (h *AccountHandler) ApplyOAuthCredentials(c *gin.Context) {
return
}
// Re-auth only returns authentication fields. Preserve account configuration
// stored alongside them (for example model_mapping), while allowing the new
// OAuth values to replace their existing counterparts.
req.Credentials = service.MergeCredentials(existing.Credentials, req.Credentials)
// Drop SSO/password residue; re-auth must leave only OAuth tokens on disk.
req.Credentials = service.SanitizeStoredCredentials(existing.Platform, req.Credentials)
@@ -1697,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
}
@@ -2778,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,
@@ -2868,10 +2913,9 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
return
}
// Handle Antigravity accounts: return Claude + Gemini models
// Explicit account mappings expose their request-side names to connectivity tests.
if account.Platform == service.PlatformAntigravity {
// 直接复用 antigravity.DefaultModels(),与 /v1/models 端点保持同步
response.Success(c, antigravity.DefaultModels())
response.Success(c, antigravityAccountTestModels(account.Credentials["model_mapping"]))
return
}
@@ -2925,6 +2969,12 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
return
}
// TypeSafe accounts serve only the native System One model.
if account.IsTypeSafe() {
response.Success(c, []claude.Model{{ID: typesafe.JevLatestModel, Type: "model", DisplayName: typesafe.JevLatestModel}})
return
}
// Handle Claude/Anthropic accounts
// For OAuth and Setup-Token accounts: return default models
if account.IsOAuth() {
@@ -2966,6 +3016,48 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
response.Success(c, models)
}
// antigravityAccountTestModels uses the stored mapping rather than GetModelMapping,
// which supplies defaults and compatibility aliases that the administrator did not configure.
func antigravityAccountTestModels(rawMapping any) []antigravity.ClaudeModel {
var mappedIDs []string
switch mapping := rawMapping.(type) {
case map[string]any:
for id := range mapping {
if strings.TrimSpace(id) != "" && !strings.Contains(id, "*") {
mappedIDs = append(mappedIDs, id)
}
}
case map[string]string:
for id := range mapping {
if strings.TrimSpace(id) != "" && !strings.Contains(id, "*") {
mappedIDs = append(mappedIDs, id)
}
}
}
if len(mappedIDs) == 0 {
return antigravity.DefaultModels()
}
sort.Strings(mappedIDs)
defaultByID := make(map[string]antigravity.ClaudeModel)
for _, model := range antigravity.DefaultModels() {
defaultByID[model.ID] = model
}
models := make([]antigravity.ClaudeModel, 0, len(mappedIDs))
for _, id := range mappedIDs {
if model, ok := defaultByID[id]; ok {
models = append(models, model)
continue
}
models = append(models, antigravity.ClaudeModel{
ID: id,
Type: "model",
DisplayName: id,
})
}
return models
}
// SyncUpstreamModels handles syncing live supported models from an account's upstream.
// POST /api/v1/admin/accounts/:id/models/sync-upstream
func (h *AccountHandler) SyncUpstreamModels(c *gin.Context) {
@@ -3006,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)
}
@@ -10,6 +10,7 @@ import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
@@ -330,6 +331,50 @@ func TestAccountHandlerGetAvailableModels_GeminiGoogleOneUsesConservativeCatalog
require.NotContains(t, ids, "gemini-2.5-flash-image")
}
func TestAccountHandlerGetAvailableModels_Antigravity(t *testing.T) {
defaults := antigravity.DefaultModels()
known := defaults[0]
custom := antigravity.ClaudeModel{ID: "claude-custom-alias", Type: "model", DisplayName: "claude-custom-alias"}
cases := []struct {
name string
credentials map[string]any
want []antigravity.ClaudeModel
}{
{name: "nil credentials", want: defaults},
{name: "missing mapping", credentials: map[string]any{}, want: defaults},
{name: "empty JSON mapping", credentials: map[string]any{"model_mapping": map[string]any{}}, want: defaults},
{name: "empty string mapping", credentials: map[string]any{"model_mapping": map[string]string{}}, want: defaults},
{name: "blank key", credentials: map[string]any{"model_mapping": map[string]any{" ": "upstream-model"}}, want: defaults},
{name: "wildcard only falls back to defaults", credentials: map[string]any{"model_mapping": map[string]any{"claude-*": "claude-sonnet-4-6", "gemini-3*": "gemini-3-flash"}}, want: defaults},
{name: "JSON mapping keys and metadata skips wildcards", credentials: map[string]any{"model_mapping": map[string]any{
known.ID: known.ID, custom.ID: "upstream-model", "claude-*": "claude-sonnet-4-6",
}}, want: []antigravity.ClaudeModel{custom, known}},
{name: "string mapping keys and metadata skips wildcards", credentials: map[string]any{"model_mapping": map[string]string{
known.ID: known.ID, custom.ID: "upstream-model", "gemini-*": "gemini-3-flash",
}}, want: []antigravity.ClaudeModel{custom, known}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
for _, accountType := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} {
t.Run(accountType, func(t *testing.T) {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
account: service.Account{ID: 51, Platform: service.PlatformAntigravity, Type: accountType, Credentials: tc.credentials},
}
rec := httptest.NewRecorder()
setupAvailableModelsRouter(svc).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/51/models", nil))
require.Equal(t, http.StatusOK, rec.Code)
var resp struct {
Data []antigravity.ClaudeModel `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Equal(t, tc.want, resp.Data)
})
}
})
}
}
func TestAccountHandlerSyncUpstreamModels_ConfigErrorReturnsBadRequest(t *testing.T) {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
@@ -526,3 +571,36 @@ func TestAccountHandlerSyncUpstreamModels_MetadataEnrichmentFailureReturnsWarnin
require.Len(t, resp.Data.Warnings, 1)
require.Equal(t, "upstream_model_metadata_incomplete", resp.Data.Warnings[0].Code)
}
func TestAccountHandlerGetAvailableModels_TypeSafeOnlyReturnsJev(t *testing.T) {
for _, credentials := range []map[string]any{
{"api_key": "ts-secret"},
{"api_key": "ts-secret", "model_mapping": map[string]any{"jev-latest": "jev-latest"}},
} {
svc := &availableModelsAdminService{
stubAdminService: newStubAdminService(),
account: service.Account{
ID: 46,
Name: "typesafe",
Platform: service.PlatformTypeSafe,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Credentials: credentials,
},
}
router := setupAvailableModelsRouter(svc)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts/46/models", nil))
require.Equal(t, http.StatusOK, rec.Code)
var resp struct {
Data []struct {
ID string `json:"id"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
require.Len(t, resp.Data, 1)
require.Equal(t, "jev-latest", resp.Data[0].ID)
}
}
@@ -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)
}
@@ -142,6 +142,44 @@ func TestApplyOAuthCredentialsRejectsMalformedOpenAILongContextBillingBeforeMuta
require.Zero(t, stub.updateAccountExtraCalls)
}
func TestApplyOAuthCredentialsPreservesExistingNonAuthCredentials(t *testing.T) {
gin.SetMode(gin.TestMode)
stub := newStubAdminService()
stub.getAccountResult = &service.Account{
ID: 1,
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Credentials: map[string]any{
"access_token": "old-token",
"refresh_token": "old-refresh-token",
"model_mapping": map[string]any{"gpt-5": "gpt-5"},
"account_id": "existing-account-id",
"password": "must-not-survive",
"sso_token": "must-not-survive",
"cookie": "must-not-survive",
},
}
handler := NewAccountHandler(stub, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.POST("/accounts/:id/apply-oauth-credentials", handler.ApplyOAuthCredentials)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/accounts/1/apply-oauth-credentials", bytes.NewBufferString(
`{"type":"oauth","credentials":{"access_token":"new-token","refresh_token":"new-refresh-token"}}`,
))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, 1, stub.updateAccountCalls)
require.Equal(t, map[string]any{
"access_token": "new-token",
"refresh_token": "new-refresh-token",
"model_mapping": map[string]any{"gpt-5": "gpt-5"},
"account_id": "existing-account-id",
}, stub.lastUpdateAccountInput.Credentials)
}
func TestOpenAIOAuthCodexPATBoundaryRejectsMalformedOpenAILongContextBillingValueBeforeTokenValidation(t *testing.T) {
gin.SetMode(gin.TestMode)
handler := NewOpenAIOAuthHandler(nil, newStubAdminService(), nil, nil)
@@ -0,0 +1,121 @@
package admin
import (
"strconv"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
type openCodeGoUsageAutoRefreshRequest struct {
Enabled *bool `json:"enabled" binding:"required"`
}
func (h *AccountHandler) GetOpenCodeGoUsageSettings(c *gin.Context) {
if h.opencodeGoUsage == nil {
response.ErrorFrom(c, service.ErrOpenCodeGoUsageUnavailable)
return
}
settings, err := h.opencodeGoUsage.GetSettings(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, settings)
}
func (h *AccountHandler) UpdateOpenCodeGoUsageSettings(c *gin.Context) {
if h.opencodeGoUsage == nil {
response.ErrorFrom(c, service.ErrOpenCodeGoUsageUnavailable)
return
}
var req service.OpenCodeGoUsageSettings
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
if err := h.opencodeGoUsage.UpdateSettings(c.Request.Context(), &req); err != nil {
response.ErrorFrom(c, err)
return
}
settings, err := h.opencodeGoUsage.GetSettings(c.Request.Context())
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, settings)
}
func (h *AccountHandler) GetOpenCodeGoUsage(c *gin.Context) {
if !h.requireOpenCodeGoUsage(c) {
return
}
accountID, ok := openCodeGoUsageAccountID(c)
if !ok {
return
}
state, err := h.opencodeGoUsage.GetState(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, state)
}
func (h *AccountHandler) SetOpenCodeGoUsageAutoRefresh(c *gin.Context) {
if !h.requireOpenCodeGoUsage(c) {
return
}
accountID, ok := openCodeGoUsageAccountID(c)
if !ok {
return
}
var req openCodeGoUsageAutoRefreshRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
return
}
state, err := h.opencodeGoUsage.SetAutoRefresh(c.Request.Context(), accountID, *req.Enabled)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, state)
}
func (h *AccountHandler) RefreshOpenCodeGoUsage(c *gin.Context) {
if !h.requireOpenCodeGoUsage(c) {
return
}
accountID, ok := openCodeGoUsageAccountID(c)
if !ok {
return
}
state, err := h.opencodeGoUsage.Refresh(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, state)
}
func (h *AccountHandler) requireOpenCodeGoUsage(c *gin.Context) bool {
if h != nil && h.opencodeGoUsage != nil {
return true
}
response.ErrorFrom(c, service.ErrOpenCodeGoUsageUnavailable)
return false
}
func openCodeGoUsageAccountID(c *gin.Context) (int64, bool) {
if c == nil {
return 0, false
}
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || accountID <= 0 {
response.BadRequest(c, "Invalid account ID")
return 0, false
}
return accountID, true
}
Loaded 100 of 2150 files, more files were not shown because too many files have changed in this diff. Show more