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