Commit Graph
8336 Commits
Author SHA1 Message Date
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