1892 Commits
Author SHA1 Message Date
Wesley Liddick 1d65de5cae Merge pull request #8295 from r266-tech/codex/fix-responses-tool-failover
fix(openai): fail over Sol/Terra tool requests on Chat-only accounts
2026-11-27 17:05:43 +08:00
r266-tech abe5903a17 Merge main and use the upstream allocation test isolation 2026-11-27 15:07:06 +09:00
shaw 75e6df8f4a fix(risk-control): record image safety-system rejections in the risk center
Image requests rejected by the upstream safety system (for example
"Your request was rejected by the safety system") were only visible in
the ops error log. They are now also written to the risk control center
as log-only evidence (action=image_safety, mode=risk_control_log_only):
no hash blacklist, no auto-ban count, no email, response unchanged.

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

Refs #8992
2026-11-27 13:51:32 +08:00
Wesley Liddick eef63ee7cd Merge pull request #9099 from PMExtra/feat/channel-expose-response-model
feat(channel): 渠道支持向用户显示实际响应模型
2026-11-26 11:49:58 +08:00
Wesley Liddick 164d7056ed Merge pull request #9088 from PMExtra/feat/proxy-ip-checked-at
feat(proxy): 代理列表显示出口 IP 与最后检测时间
2026-11-26 11:49:18 +08:00
Wesley Liddick bb7fb85cd5 Merge pull request #9081 from bin-bash-dev/fix/sse-keepalive-retry-accounting
fix(openai): account SSE keepalive bytes across failover attempts
2026-11-26 11:48:25 +08:00
Wesley Liddick 6f34149c15 Merge pull request #9004 from Anankke/fix/sticky-session-rebind-cas
fix(gateway): do not overwrite a sticky rebind after a long forward
2026-11-26 11:46:10 +08:00
Wesley Liddick e3eb96c0b5 Merge pull request #8994 from wucm667/fix/issue-8991-terminal-context
fix(openai): normalize standalone terminal context
2026-11-26 11:45:44 +08:00
PMExtraandClaude Opus 5.5 8c4336eb58 fix(usage): chain Localized on user usage DTO mapping line
TestUserFacingGroupDTOsAreLocalized statically requires every user-facing
dto.*FromService call to chain .Localized( on the same line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 01:01:21 +08:00
PMExtraandClaude Opus 5.5 a1c7be6e90 feat(channel): optionally show actual response model to users
Add a channel-level toggle (features_config.expose_response_model, off by
default). When enabled, regular users see the final response model next to
the requested model in their usage records; the intermediate mapping chain
stays admin-only.

- Channel.IsResponseModelExposed + ChannelService.ResponseModelExposedChannels
  read from the in-memory channel cache, so no extra DB queries
- User usage list/detail fill the new optional response_model field
  (upstream_response_model -> upstream_model -> model, omitted when equal
  to the requested model)
- Channel form toggle, UsageTable rendering and i18n

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:45:37 +08:00
PMExtraandClaude Opus 5.5 1ba1ae8ef0 feat(proxy): show exit IP and last check time in proxy list
- Expose latency_checked_at (from cached UpdatedAt) on admin proxy list
- Show exit IP under location and last check time under created_at
- Include region/city in quality check result
- Quality check now updates row latency/IP/location on failure too,
  matching the backend snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:27:06 +08:00
bin-bash-dev 1f5ca63440 fix(openai): account SSE keepalive bytes across failover attempts
Problem: on /v1/responses passthrough accounts with
gateway.stream_keepalive_interval enabled, a failover-eligible upstream
error (e.g. an overloaded `event: error` before any visible output) is
only failed over once. If the first attempt has already written a
keepalive comment, the next attempt that fails the same way is treated
as if semantic output had reached the client: the error is delivered as
response.failed and the remaining schedulable accounts are never tried.

Root cause: handleStreamingResponsePassthrough starts a new SSE
keepalive for every attempt, and startOpenAISSEKeepalive replaces the
instance stored on the gin.Context. Keepalive bytes were tracked per
instance, so OpenAICompactKeepaliveAdjustedWrittenSize subtracted only
the current instance's bytes from c.Writer.Size(); comments written by
an earlier attempt stayed in Size() and were counted as real output.
openAIStreamClientOutputStarted therefore reported output as started
and the passthrough stream stopped proposing failover.
StopOpenAICompactSSEKeepaliveCommitted had the same per-instance blind
spot and reported "not committed" when only an earlier instance had
committed the 200 response.

Fix: keep the keepalive byte count in a request-scoped atomic counter
stored on the gin.Context and shared by every keepalive instance of the
request (retries and nested starts). AdjustedWrittenSize subtracts the
cumulative count, and the committed check also reports true once any
keepalive of the request has written a comment. Single-keepalive
behaviour is unchanged.

Tests: a handler-level regression test drives the real Responses
handler with three passthrough accounts (the first attempt emits a real
keepalive and then fails over, the second fails immediately, the third
succeeds); on the previous code only accounts [1 2] are called and the
client receives response.failed. Service-level tests cover cumulative
accounting across restarts, the committed check after a previous
attempt, restarts without beats, and nested keepalives; they drive beats
manually instead of relying on timer scheduling.
2026-11-25 04:01:48 +08:00
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
Brisbanehuang 03aa05fd9f feat(accounts): 按账号自动同步上游分组名称与备注 2026-11-21 07:02:53 -08:00
Brisbanehuang a95c9e2631 feat(accounts): 支持从上游分组同步账号名称与备注 2026-11-21 06:03:52 -08:00
Anankke c3219a14ed fix(gateway): do not overwrite a sticky rebind after a long forward
GatewayHandler.Messages writes the sticky binding back after a successful forward. The write was a plain SET, so a long request put its account back over a binding another request made while it was forwarding.

The write now runs a Lua compare in the Redis cache. It sets the key when the key is missing or holds an account this request was admitted on under profit control and failed over from, refreshes the TTL when the key already holds the served account, and leaves any other value alone.

The compare sits behind GatewayStickySessionCompareCache, an optional capability; a cache without it keeps the plain write.
2026-11-20 21:20:09 -08:00
wucm667 88b1924bd9 fix(openai): normalize standalone terminal context 2026-11-20 21:39:18 +08: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 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 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 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 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
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
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
wucm667 92fd567a47 fix(grok): accept five edit sources and classify input errors 2026-11-19 15:47:59 +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
r266-tech b36cb244f3 fix(channels): support configurable Ultra Fast pricing 2026-11-18 07:05:45 +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
wucm667 570d59e9ac fix(anthropic): expose metadata-backed long-context models 2026-11-17 15:13:03 +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
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 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
shaw 589166e320 Merge remote-tracking branch 'gh/main' into fix-8669 2026-11-16 19:26:42 +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
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
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 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 568db32f22 Merge pull request #8806 from feeeei/fix/usage-account-filter-actual-cost
fix(usage): 按账户筛选时模型与端点分布的实际扣费不再替换为账号成本
2026-11-16 16:34:16 +08:00