Follow-up to #8302 (f7ec8b3ce).
Placing the unresolved `previous_response_id` 1008 rejection at the top of the
HTTP bridge turn loop ran before `hooks.BeforeTurn` and before the `historyLost`
1013 (`StatusTryAgainLater`) check from #9203, and rejected valid turn-1 sticky
API-key continuations (`store != false` bound in `stateStore`) as well as Grok
HTTP bridge turns.
Move the 1008 check after `BeforeTurn` and `historyLost`, allow turn-1 API-key
continuations bound to the selected account when `store != false`, and preserve
Grok HTTP bridge handling while keeping all #8302 unresolved-parent cases closed
with 1008.
Generated with [Devin](https://devin.ai)
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- Ignore explicit JSON `null` values on `mask` and native image options so
prompt-only requests with null placeholders stay on basic capability.
- Reject empty objects/strings inside `images[]`, `image`, and `mask` instead of
silently dropping malformed image entries.
- Skip same-account `/images/edits` -> `/images/generations` retry when a 404 is
explicitly `model_not_found` so account failover runs without an extra round-trip.
Generated with [Devin](https://devin.ai)
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
When a capacity-shed event (`slow_down` / `server_is_overloaded`) arrives with a
429 status and an explicit `Retry-After` exceeding the 8s same-account budget,
skip opening the 2-minute OAuth 429 retry deadline window as well, and emit
`upstream_retry_after` across WebSocket, Embeddings, and AlphaSearch logs.
Generated with [Devin](https://devin.ai)
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
xAI rejects an oversized prompt with HTTP 400
{"code":"invalid-argument","error":"Failed to start sampling: [input_too_large] The prompt is too long for this model’s context window (612345 tokens > 500000 tokens)"}.
The shared extractor cannot read this flat body, so Responses clients got the
generic "Upstream rejected the request" and could not tell an oversized
prompt from any other rejected request.
For Grok accounts, a 400 that carries the explicit [input_too_large] tag is now
returned as 400 {"error":{"type":"invalid_request_error",
"code":"context_length_exceeded","message":...}}. Token counts are copied only
when the upstream message states them. X-Grok-Context-Window is forwarded from
the upstream when it is a positive integer, otherwise taken from the stated
limit, otherwise omitted. Other 400s keep their existing shape, and the error
still does not fail over or cool down the account.
GPT Image 2.6 callers using the unified `/v1/images/generations` protocol pass
reference `images` / `image`, `mask`, and `markup` directly on `generations`
rather than `/v1/images/edits`. Previously, input-image parsing and Codex OAuth
payload construction were gated behind `IsEdits()`, silently dropping image
inputs (and skipping image moderation) on `/v1/images/generations`.
- Parse, validate, moderate, and forward `images`/`image`, `mask`, and `markup`
on `/v1/images/generations` (JSON and multipart) as well as `/v1/images/edits`.
- Recognize bare `gpt-image-2.6` and `gpt-image-2.6-*` snapshots consistently in
direct routing, Responses-fallback guard, and fallback pricing.
- Automatically fall forward from `/backend-api/codex/images/edits` to
`/backend-api/codex/images/generations` when upstream returns 404/405.
Fixes#9156
Generated with [Devin](https://devin.ai)
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
When an OpenAI upstream sheds capacity (`server_is_overloaded` / `slow_down`)
and advertises an explicit `Retry-After` longer than the per-retry delay cap
(8s, e.g. 315-369s in #9183), replaying a single-credential account every 8s
cannot satisfy the upstream window and delays switching to healthy accounts.
Switch non-pool accounts immediately on long capacity-shed `Retry-After` hints
while keeping short/unspecified blips and pool-mode relays retryable, preserve
request-scoped transient semantics (no persistent account cooldown), and log
`upstream_retry_after` on retry and switch events.
Fixes#9183
Generated with [Devin](https://devin.ai)
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Raise the direct dependency and the pnpm override floor to 3.5.0, the first release patched for GHSA-hrxw-jjj6-2g2j (CVE-2026-144292). pnpm 9 resolves the direct dependency and the transitive copies to 3.5.1. The regenerated lockfile changes only DOMPurify entries.
Root cause: openAIResponsesCompletedEventIsEmpty classified a terminal
response.completed as non-empty whenever usage reported any tokens, so a
stream whose output held only reasoning items (reasoning tokens, no message
text or tool call) was recorded as a successful empty turn (issue #8966).
Change: classify emptiness by the terminal output items instead of usage.
Message items count only with visible text or a refusal; function_call,
custom_tool_call, tool_search_call, image_generation_call and any unknown
item type count as visible products; reasoning-only output is empty. When
output is missing, null, non-array or empty and usage exists, the previous
usage fallback still applies, so partial terminal events are not failed over.
The failover message now says "no visible output".
Tests: table cases for reasoning-only completed (inline and accumulated
usage), message text/refusal, empty message content, tool calls, image
generation, top-level output and malformed output fallback; stream-level
tests assert reasoning-only completed produces UpstreamFailoverError while
reasoning plus message text completes normally.
- The non-ASCII header test now reproduces the case-folded offset bug.
- Add a mixed fake/real data URI test.
- Check the image signature on the first bytes before decoding the whole
payload, and stop pre-growing the output buffer to the input size.
- Describe the accepted residual accurately.
Drop the API-key exemption: the HTTP path also rejects a previous_response_id
whose owner record expired, and the HTTP bridge would strip the id silently.
Only the per-selection strict affinity re-evaluation remains, now pinned by
a regression test for a current-turn failover replay after a continuation.
- Only the payload of a verified image is replaced; the media type and
parameters stay in the scan so prose cannot be smuggled through them.
- The payload is located by regexp submatch indices instead of a
case-folded copy, so non-ASCII header characters cannot shift it.
- The whole payload must strictly decode to a PNG/JPEG/GIF/WEBP file with
its trailer; padding is only accepted at the end.
- Skip the regexp entirely when the text has no ;base64, marker.
Use the configured-manifest candidate set (mapping keys, plus the default
catalog only when an account serves unmapped models) and tag the fallback
log with the group.
- Drop the per-segment 64K truncation: everything forwarded upstream must be
audited, and over-long prompts keep the existing fail-closed timeout path.
- Strip a data URI only when its payload uses the standard base64 alphabet,
is at least 256 characters, and decodes to a PNG/JPEG/GIF/WEBP signature.
Prose dressed up as a data URI (hyphens, spaces, plain letter runs, SVG
markup) stays in the scan.
The fallback list now passes through FilterCodexModelIDsForGroup, the same
listing filter /v1/models uses. A wildcard-only allowlist expands its
patterns against account mappings and the default catalog instead of
falling through to the unfiltered default catalog. Serving the fallback is
logged with the upstream error, since clients only see a 200.
- A current-turn failover replay clears previous_response_id because the
retry payload already carries the full input; the strict affinity check is
now computed on every selection so that replay is no longer rejected with
previous_response_not_found.
- API-key accounts resolve previous_response_id upstream, matching the HTTP
path; a missing local binding forwards the id unchanged instead of failing
loudly. OAuth-like accounts keep the fail-loud behavior.
A pool-mode account hitting a deterministic model-not-found must still fail
the current attempt over (404 is not in the generic failover set), only the
30-minute model cooldown is skipped. Rejected proxy credentials are a local
configuration fault, so only reachability failures skip the transport
cooldown for pool-mode accounts.
WebSocket turns closed the connection with 1013 as soon as the user was
at its concurrency limit, after the client had already uploaded the full
request. Clients such as Codex then retry and eventually switch the
session to HTTP, which resends the whole context on every turn.
Wait in the same bounded per-user queue as HTTP requests instead. The
wait is 60 seconds, longer than the HTTP wait because a rejected
WebSocket turn is more expensive. Timeouts, a full queue and a closed
connection still end with 1013.
Pool mode promises that upstream errors leave local account state alone
and are retried on the same account. Two paths still marked it:
- HandleUpstreamModelNotFound put a 30-minute model rate limit on the
account for a 404 model_not_found, although HandleUpstreamError and
HandleTempUnschedulable already skip pool-mode accounts without custom
error codes. The OpenAI fast path calls it first, so the skip never
applied there.
- tempUnscheduleOpenAITransportError marked the account unschedulable
after a transport error.
A pool-mode upstream that restarts briefly answers 404 for its models
and refuses connections; the account then stayed blocked for up to 30
minutes after the upstream recovered. Custom error codes still opt a
pool-mode account into the model rate limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Keep upstream HTTP Retry-After handling. Retain client frame cleanup and
bounded same-account retries for replay-safe WebSocket failures, with
regression coverage. Drop unrelated allocation test changes.
Root cause: selection failure diagnostics collapsed every persisted model
cooldown into a single model_rate_limited counter, so the operator could not
tell an upstream 404 model_not_found, a real upstream 429, a plan-gated or
temp-unschedulable cooldown, or legacy data apart. The decision log also had no
request_id to join the failure with the request.
Change:
- read the persisted cooldown reason from the account model_rate_limits
snapshot through a diagnostics-only helper; selection behavior is unchanged
- keep only existing reason values (bounded allowlist), classify structured
rule reasons, and bucket empty/unknown reasons as "other"
- add per-reason counts to selectionFailureStats and openAISelectionFilterStats
- append model_rate_limited_reasons=<reason:count,...> after the legacy
summary while keeping the aggregate model_rate_limited=<n> token intact for
the no_account_error regex and the existing 429 upgrade
- include request_id in the SelectAccountDetailed log line
Tests:
- breakdown across upstream_404_model_not_found, image 429 cooldown,
empty/other, scheduling-threshold JSON and temp-unschedulable JSON
- OpenAI load-aware no-account error carries the model cooldown breakdown
- legacy summary is byte-identical without a breakdown
- handler regex still upgrades the aggregate count to 429
- go build ./... and go test ./internal/service/ pass
Root cause: Codex /models requests always fetch the manifest from a
scheduled upstream. Custom API-key upstreams that do not implement
/v1/models return 5xx, an empty catalog, or a non-standard body, so the
gateway exhausts account failover and returns 502 even when the group
can describe its models locally.
Change: generate a local Codex manifest when every candidate fails (or
the account switch budget is exhausted) and when an upstream returns an
empty manifest. Sources follow the group's models_list_config, then the
group accounts' model_mapping keys, then the default OpenAI catalog, with
the same retired-model filter as /v1/models. The local list only replaces
the upstream error when it is non-empty, keeps ETag/304 revalidation, and
leaves successful upstream manifests untouched. Pinned discovery mode
keeps its explicit FallbackToScheduler contract.
Tests: cover 5xx/empty/non-JSON upstream fallback, all-candidates-failed
fallback, source priority, upstream success regression, ETag
revalidation, and preserving the original error when the local list is
empty.
Root cause:
- The OpenAI proxy stream circuit was keyed only on proxy_id. One account
whose Responses SSE streams kept disconnecting quarantined every healthy
account sharing that egress proxy, emptying the pool for 10 minutes (#5010).
- Every 'no available accounts' response called
DiagnoseModelAvailabilityForPlatform, which ran a candidates query per
request; retrying clients turned that into a database query storm.
Change:
- Key the circuit on (account_id, proxy_id) and pass the owning account at
every record/clear/check call site. The failure threshold (2 in 60s) and
10-minute quarantine TTL are unchanged, as is fail-open selection.
- Add a bounded in-process TTL (5s) cache with singleflight for the model
availability diagnosis on both gateway services. Keys include platform,
group, model and, for the context-sensitive generic check, request-scoped
composite-route/thinking inputs. Lookup failures are not cached so callers
keep the conservative 503 fallback and retry the database.
- Update the circuit config doc comment and the scheduler tests that relied
on proxy-wide quarantine.
Tests:
- go test ./internal/service -run 'TestOpenAIProxyStream' -count=1
- go test -tags=unit ./internal/service -run 'TestDiagnoseModelAvailabilityForPlatform|TestOpenAIDiagnoseModelAvailability|TestGatewayDiagnoseModelAvailability|TestModelAvailabilityDiagnosisCache|TestOpenAIProxyStream|TestOpenAIGatewayService_SelectAccountWithScheduler_(SkipsQuarantinedSharedProxy|QuarantinedAccountKeepsPeerOnSharedProxy|FailsOpenWhenAllProxiesQuarantined)|TestSelectAccountWithSchedulerForImages_UnspecifiedSizePrefersHealthyProxyOverQuarantinedUnrestricted' -count=1
- go test -tags=unit ./internal/handler -run 'TestClassifyNoAccount|TestClassifySelectionFailure|TestGPT55Retirement' -count=1
- go build ./... and gofmt -l are clean.
The ChatGPT Codex backend announces the largest WebSocket message it
accepts in x-codex-websocket-max-message-bytes (currently 128 MiB). The
gateway ignored it and bridged every session whose first message reached
a fixed 15 MiB to HTTP, after which each turn replays the full input to
the upstream instead of continuing incrementally over WebSocket.
Record the announced limit per account on every successful upstream
handshake and derive the bridge threshold from it, minus a margin for
fields the gateway adds. http_bridge_threshold_bytes now defaults to 0
(follow the upstream); an explicit value caps the upstream limit, and the
15 MiB default still applies until a limit is known.
Also announce the gateway's client read limit in the same header on the
client handshake, so Codex clients stop before uploading a message the
gateway would reject.
- Excluded accounts no longer suppress image_safety / cyber_policy evidence,
ban counting or notifications; those are upstream verdicts, not our audit.
- Sampled multi-image inputs (more images than the audit sends) skip the clean
cache and singleflight so one clean random sample cannot pin the verdict.
- Account search truncates by rune and drops invalid UTF-8 so PG does not
reject the pattern with a 500.
- Account directory lookups are part of ContentModerationRepository instead of
a runtime type assertion; lookup errors now propagate from Get/UpdateConfig.
- Remove the never-set BodyValidated flag and the frontend id-only fallback.
The sync-version-file job committed the VERSION bump to main only after
publishing, so every tag pointed at a commit whose VERSION was the previous
release (v0.2.19 through v0.2.26). Published artifacts were unaffected because
prepare rewrites VERSION from the tag, but source builds of a tag (go build,
GitHub source archives, Docker builds without .git) reported the old version.
prepare now fails before building or publishing when VERSION at the tag does
not match the tag version. A manual run with allow_version_mismatch=true
downgrades this to a warning for re-releasing older tags. The post-release
sync job is removed: the VERSION bump is committed before tagging instead.
Retaining a turn can need more budget than the turn held because the replay
and failover sequences get separate header arrays. When that growth does not
fit, drop the history instead of keeping it under-accounted. Count a shared
body only when both pointer and length match, and skip the common prefix by
index so the lookup set covers only the diverging tail.
SSE data lines may omit "type"; the HTTP SSE path already resolved the event
type from the event: line, so strip with that instead of re-reading the
payload.
Root cause:
- POST create with custom_key returned API_KEY_EXISTS (409) when the key
already existed, letting authenticated callers confirm that a guessed key
belongs to someone else and then use it.
- Malformed keys returned distinct API_KEY_TOO_SHORT / API_KEY_INVALID_CHARS
errors, so the collision error could be told apart from other failures.
Change:
- Add ErrAPIKeyUnavailable (400, API_KEY_UNAVAILABLE, generic message) and
return it for malformed custom keys and collisions alike, including a
unique-constraint race on insert.
- Keep detailed reasons in server logs only; keep the failed-attempt counter
on collisions and the internal ErrAPIKeyExists for repository translation.
- Normal custom-key creation (including reusing a soft-deleted key whose
credential was tombstoned) and generated keys are unchanged.
Tests:
- go build ./...
- go test -tags=unit ./internal/service -count=1
- go test -tags=unit ./internal/repository -run TestAPIKeyRepository
- go test -tags=unit ./internal/handler -run TestValidateAPIKey
Root cause: PR #8385 applied the account error policy to the Chat
Completions and Responses compatibility paths, but statuses outside the
failover whitelist (for example 410 Gone from a migrated upstream base
URL) still fell through to writeGatewayCCError/writeResponsesError with
the upstream status and raw message. Global passthrough rules were not
consulted either, so the client saw a bare 410 and the upstream
migration hint.
Change:
- Apply applyErrorPassthroughRule before writing the non-failover error,
so configured rules can remap status and message.
- Record the original upstream status plus an http_error Ops event, then
collapse unknown 4xx statuses (notably 410) into a generic 502
"Upstream request failed", matching /v1/messages and avoiding exposure
of upstream migration hints. 400/404/413/422 keep their request-level
status and sanitized message.
- Leave 410 out of shouldFailoverUpstreamError to avoid changing retry
semantics.
Tests: extend the compat account policy regression to assert 410 -> 502
without the upstream message, request-level 4xx passthrough and Ops
bookkeeping; add a passthrough-rule remap case for both entrypoints.
Validation:
- go build ./...
- go test -tags=unit ./internal/service -count=1
- go test -tags=unit ./internal/service -run 'TestAnthropicCompat(AccountErrorPolicy|NonFailoverErrorAppliesPassthroughRule)$' -count=1
The automatic reset sorts the available credits by expiry and consumes the
first one by id, but the admin reset button sent no credit_id and let
upstream pick. Upstream can then spend a later credit and leave the one
closest to expiry to lapse, while the account list shows that earliest
expiry next to the button.
ResetCredit now reads the credit list first and targets the credit that
expires first. When the list cannot name it (request failed, a credit
without expiry or id, fewer credits listed than available, unparsable
expiry) the request stays untargeted as before.
Root cause: structured input_image parts are skipped during extraction, but an
image serialized as JSON into a plain input_text kept its base64 data URI in
the scan text. A single 384x384 PNG data URI (~590k chars) was split into
hundreds of guard chunks that all shared the same audit deadline, so the
request ended in prompt_guard_unavailable.
Change:
- Replace data:image/...;base64,... data URIs (plain and JSON-escaped, with
optional media parameters) with "[image data omitted]" while extracting
prompt text; the surrounding text and the message itself are preserved.
- Cap every extracted text segment at 65536 runes and mark the cut with
"[truncated]" so one client-controlled field cannot expand without bound.
- Structured input_image parts remain skipped.
Tests: a synthetic 384x384 PNG data URI embedded in a serialized history JSON
now produces one guard chunk and a single scanner call. JSON-escaped data URIs,
rune-boundary truncation, structured image skipping, and normal long-text
chunking are covered in prompt_inline_data_test.go.
Root cause: once semantic output is committed, failover replay is unsafe, so
the stream is forwarded as-is. Only explicit response.failed events were
recorded (PR #6736); bare error frames and the synthesized terminal failure
they produce had no ops upstream-error record, leaving post-output capacity
failures invisible in ops_error_logs.
Change: record after-output terminal failures in both the native and
passthrough Responses stream handlers with kind stream_failed_after_output,
passing the raw upstream payload and upstream request ID. A bare error is
recorded when the authoritative response.failed arrives, or at EOF when the
Codex terminal synthesis is used; one record per stream avoids duplicates.
No failover, replay, or client-visible error shape is changed.
Tests: new TestOpenAIStreamBareErrorAfterOutputIsRecorded covers OAuth
native/passthrough synthesis and the API-key forwarded-error path; the
existing after-output processing-failure test now asserts the new kind.
Also ran go build ./... and go test ./internal/service/ -count=1.
Root cause: GetLatestUsedAtByUserIDs aggregated every historical usage_logs
row for the requested users (MAX(created_at) ... GROUP BY user_id). The
existing idx_usage_logs_user_created(user_id, created_at) index could not be
used to early-stop, so the admin user list paid O(history) per page and took
9-10s on million-row tables.
Change: probe only the newest row per requested user with
unnest($1::bigint[]) CROSS JOIN LATERAL (SELECT created_at FROM usage_logs
WHERE user_id = u.user_id ORDER BY created_at DESC LIMIT 1). Each inner
subquery is a single backward index scan on idx_usage_logs_user_created,
making the lookup O(page size * log n). The inner join preserves the previous
semantics: users without usage rows are absent from the returned map, and
timestamps are still normalized to UTC. GetLatestUsedAtByUserID keeps reusing
the batch function.
Tests: new sqlmock unit tests assert the lateral/ORDER BY ... LIMIT 1 query
shape, per-user latest result, missing-user omission, UTC normalization, empty
input short-circuit, no-rows, singleton reuse and error propagation. The
integration suite extends GetLatestUsedAtByUserIDs coverage with out-of-order
inserts across multiple users, a user without usage, and empty input.
GATEWAY_ANTIGRAVITY_FORWARD_BASE_URL and
GATEWAY_ANTIGRAVITY_FALLBACK_COOLDOWN_SECONDS are read with os.Getenv, but the
Compose files only interpolate an explicit list of variables. Setting either
one in deploy/.env therefore never reached the container.
Register both in .env.example (empty, so the built-in behavior is unchanged),
pass them through every Compose file, and document the
gateway.antigravity_fallback_cooldown_minutes key they fall back to. The
existing docker-compose gateway env test now covers both variables.
Rebasing onto #9152 made browser_tabs a known context name; add it to the
known list so it keeps its <external_browser_tabs> tag and empty-output
check instead of falling to the generic branch.
Render unknown agent context names the way Codex renders context it does
not send as a tool output, <external_{name}>, when the name has the shape
Codex derives names in ([A-Za-z0-9_]{1,128}). Other names still use the
generic <external_agent_context> tag, so a client supplied name is never
embedded unchecked.
Codex manifests fetched from upstream carry automatic modes such as
codex-auto-review, which upstream already hides from the model picker and
Codex uses to review approvals. The gateway removes every automatic mode the
group model list does not select, so Codex falls back to the main model for
reviews and the forwarded manifest always differs from upstream.
Add keep_hidden_auto_modes to the group Codex manifest config. When enabled,
automatic modes that upstream marks as hidden are forwarded byte-for-byte;
visible ones are still removed unless selected, and explicit selections keep
listing them in the picker. The switch is off by default, so existing groups
behave as before, and the admin group dialog exposes it next to the pinned
accounts settings.
Codex caches the /models catalog together with its ETag and, on every
Responses WebSocket turn, compares that ETag with the x-models-etag header
of the codex.response.metadata event. Upstream reports the ETag of its own
catalog, but the gateway serves a group-specific manifest whose ETag changes
as soon as group policy adjusts it, so Codex re-downloaded the full catalog
on every turn.
Record, per group, which served ETag corresponds to each upstream catalog
ETag, and translate the metadata header when relaying WebSocket events in
both ctx_pool and passthrough modes. Unknown values are removed so clients
fall back to their regular catalog cache TTL. Pinned manifests keep the
upstream ETags of every merged account, and generated manifests now use weak
ETags so the value still matches behind a compressing reverse proxy.
Root cause: an upstream HTTP/2 connection multiplexes many in-flight
requests. When a CDN resets that TCP connection, every stream multiplexed
on it fails at once. Before any byte reached the client the gateway either
returned 502 (reset before response headers) or a failover error that
switched accounts (reset while reading the stream). The upstream keeps
reading the request and bills it in full, so the request is charged
upstream while the gateway records zero usage downstream.
Change: Forward now treats a connection reset / unexpected EOF on an
established upstream connection as a transport incident, not an account
failure. When the client is still connected, the request body is
replayable and this attempt wrote no client-visible byte (semantic output
accounting; keepalive comments excluded), it rebuilds the request and
replays it once on the same account. The replay never touches
failover/account-health or sticky-session accounting; if it fails again
the original failover error is returned and the existing path runs.
Timeouts, context cancellation, client disconnects, dial failures and
plugin hand-offs that may already have executed upstream are never
replayed. Stream read errors expose a new ConnectionResetBeforeOutput
marker so Forward can distinguish this window from other failovers.
Tests: new openai_upstream_connection_reset_retry_test.go covers a reset
before any client output (both the pre-header transport form and the
stream-read form) retried once and succeeding, a second reset not
starting a third attempt, a reset after client output not retried,
timeout/cancel not retried, a non-replayable body not retried, the reset
classifier, and the marker only being set before output.
Root cause: downstream 429/503 responses carried no Retry-After. The
no-account classifier had no recovery time at all; the earliest account
cooldown only existed inside scheduler log lines; and upstream error paths
either dropped the provider's response headers (shouldDisable failures,
final compat write) or copied Retry-After verbatim, including capacity-shed
windows that clients would honor by sleeping for minutes.
Change:
- Diagnose the earliest cooldown among model-capable accounts (account
rate limit, overload, temporary unschedulable, and per-model rate limit)
and expose it as ModelAvailabilityDiagnosis.RetryAfterSeconds, capped by
the new gateway.retry_after_max_seconds option (default 300s).
- Emit Retry-After for 429/503 no-account classifications only when a
recovery time is known; 404 model_not_found and unknown values omit it.
- Forward upstream Retry-After / retry-after-ms (header or body) only for
explicit 429 rate limits, converting to integer seconds with a ceiling
and the same cap. Capacity-shed/server_is_overloaded and generic 5xx
hints stay dropped to stay compatible with #8560/#8938.
- Preserve upstream response headers on failover errors and route every
failover-exhaustion path through the gated helper instead of copying
arbitrary Retry-After values.
- Status codes, error types, and messages are unchanged.
Tests:
- service: retry-after parsing (header, retry-after-ms rounding, body
fields), cap/default/config override, capacity-shed rejection, non-429
statuses ignored, cooldown computation and unknown recovery.
- handler: no-account 429/503 emit the diagnosed value, unknown recovery
and model_not_found omit it, failover exhaustion forwards upstream 429
hints (including body retry-after-ms) and omits capacity-shed hints.
Root cause: writeAccountIDs unconditionally SET every account payload and
metadata record on each scheduler refresh. After 0.2.26 stopped embedding
expanded group objects the payload is smaller, but refreshes driven by
snapshots or account updates still rewrote all keys even when their content
was identical, amplifying AOF and replication traffic when several instances
share one Redis.
Change: read the previous full and metadata payloads with one chunked MGET
per write chunk and compare bytes before writing. Only payloads that changed
are SET; unchanged accounts are still returned in the account ID list so
bucket membership is unchanged. Platform revisions advance only when a
payload was actually written and stay in the last writing chunk, after all
metadata writes. The fallback path used when the read fails keeps the
original unconditional write and SET ... GET platform-change detection
(fail-open). Redis remains the source of truth; no in-process caching is
added.
Tests: new unit tests cover repeated identical writes issuing no SET and no
revision, changed payloads being rewritten, per-chunk skipping, platform
changes still advancing the global revision, and the MGET-failure fallback.
Existing scheduler cache revision tests were updated for the read-first write
layout. Validated with go build ./..., go test -tags=unit
./internal/repository/, and gofmt.
Root cause: normalizeCodexUntrustedContext only rewrote function_call_output
items whose name matched a fixed list of Codex context tools. Newer Codex
clients send page/tab context under new names (for example browser_tabs), so
the item kept its missing call_id and validateFunctionCallOutputRequest
rejected the whole request with HTTP 400.
Change: gate agent context by namespace == "agent" and a missing or blank
call_id instead of an enumerated name list. Known context names keep their
existing tags and format checks; any other agent-namespace name is rendered
under the generic <external_agent_context> tag so client-supplied names are
never interpolated into tags unchecked. Items with a call_id, without the
agent namespace, with a non-string output, or with duplicate members are left
untouched and keep the original validation path. A zero-copy namespace probe
replaces the name-literal fast path.
Tests: add browser_tabs, unknown/renamed agent context names, escaped
namespace, blank call_id, real tool outputs still rejected (400), and
call_id regression cases; adapt existing unrelated-tool-result fixtures to
model real tool outputs without the agent namespace. Full handler and service
unit packages pass; go build and gofmt are clean.
Self-hosted routers such as vllm-router keep a session on one decode
replica by the X-Session-ID header, but the Chat Completions outbound path
forwards only accept-language and user-agent from the client. The new
account extra key `openai_chat_session_id` makes that path send the
client's session as X-Session-ID, isolated per API key with
isolateOpenAIUpstreamSessionID. The session comes from the same sources
as x-opencode-session: client session headers first, then the
prompt_cache_key or metadata.user_id remembered before protocol
conversion, so /v1/responses and /v1/messages requests converted to Chat
Completions keep their sessions. Account header overrides still apply
last, and accounts without the key send the same headers as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NewContentModerationService starts 32 workers and a cleanup goroutine that
loop forever with no way to stop them. Production keeps one service for the
process lifetime, but the service package tests construct it in 27 places and
every one leaks its goroutines until the test binary exits. The workers call
time.Now() every second, so tests that later switch time.Local through
timezone.Init race with them; under -race the test binary has segfaulted on
the torn time.Local.
Add Stop: it closes a stop channel, waits for the workers and the cleanup
goroutine, then waits for an in-flight runtime snapshot refresh by taking
runtimeRefreshMu. Workers finish the task they hold before exiting; idle
waits, the configuration back-off and the cleanup timer all wake on the stop
channel. Stop is idempotent and safe on services that started no goroutines.
Production wiring does not call it, so runtime behaviour is unchanged.
Tests that construct a service with workers register t.Cleanup(svc.Stop), and
the stale-scope cyber test stops the workers before it rewrites the snapshot
TTL they read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On the http_bridge path, a response.create whose previous_response_id
cannot be resolved on this connection was silently stripped of the id
and posted as a delta-only request, losing the entire prior context.
Fail closed instead: close the socket with 1008 and tell the client to
resend the full input without previous_response_id.
The bridge tracks the last completed turn's response id; a parent is
resolvable only when it matches that id and a non-empty replay history
exists. Covers fresh connections, id mismatches, empty replay, missing
upstream response ids, and failed parent turns.
Claude Code sends {role: "system"} messages inside messages: one with the
environment after the first user message, and a notice after every tool
result, which stays in the history. buildContents moved all of them to the
end of systemInstruction. systemInstruction precedes the contents, so every
tool round changed the start of the prompt and Gemini's implicit prefix cache
matched only the tools and the fixed system prompt: in a Claude Code tool loop
on gemini-4-neon cache_read stayed at about 34k tokens of a 100k-200k token
conversation (9.4% of input tokens over 3947 requests).
System messages before the first model turn still go to systemInstruction.
Later ones stay at their position as <system-reminder> text at the end of the
user turn they follow; one that follows a model turn joins the next user turn
after its tool results, so a functionCall is still followed directly by its
functionResponse. System message text is trimmed in both wire forms, since
Claude Code sends the newest one as cache_control blocks and the same message
as a string once it is history.
The ChatGPT codex backend rejects a string `input` with
"Input must be a list". The HTTP path already converts it in
applyCodexOAuthTransform (#919), but the Responses WebSocket ingress
forwarded the client frame unchanged, so the same request succeeded over
HTTP and failed over WS. Clients that treat a failed WS turn as "WS
unsupported" then fall back to HTTP for the whole provider.
Convert only the copy written to the native upstream WS, using the same
rule as the HTTP path. The session's stored client payloads and the
http_bridge path are unchanged.
Codex 0.17x reports `disable_response_storage` and
`windows_wsl_setup_acknowledged` as unknown configuration fields, and
rejects the top-level `network_access = "enabled"` because the key only
exists as a boolean under [sandbox_workspace_write].
Remove the two removed keys from every generated config.toml and express
the network intent with the supported sandbox table. The commented Grok
template drops the same stale lines.
Forward carried only marked thinking signatures (vertex-thought-v1:) for
Vertex accounts. For every other Gemini account it carried any real
thinking signature from history. Those accounts render responses with the
compat emitter, which never sends a thinking signature, so the only real
thinking signatures in their history are foreign: after a switch from a
Claude model in the same session, Anthropic signatures. They reached
Gemini as thoughtSignature, Gemini answered with a signature 400, and the
signature retry ran on every request of the session. main sends none.
Failure modes this commit guards against:
- An AI Studio (or OAuth) account sends an Anthropic thinking signature on
a functionCall part or on a text part.
- The first request and the signature retry follow different rules.
- Vertex changes: marked signatures still go back without the marker, and
unmarked ones are still not carried.
- tool_use.signature handling changes.
Changes:
- Forward builds the request with markedThinkingSignatures on for every
account, on the first request and on the signature retry. Only the
Vertex renderer emits marked signatures, so other accounts carry no
thinking signature, as on main. A functionCall without a signature still
gets the dummy.
Tests:
- New TestGeminiCompatForward_AIStudioSendsNoThinkingSignatureFromHistory:
an AI Studio account with Anthropic thinking signatures before a call
and before text. Upstream gets the dummy on the call, no signature on
the text, and no Anthropic signature. It fails on the parent commit. For
the same request, the upstream body is byte-identical to main.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Vertex renderer commit let a non-thought part that carries only a
thoughtSignature (an empty text part, or a part with no text key) reach
the text path. On the Vertex path the text-part signature is dropped
since then, so the change has no effect there. On the antigravity
platform it added an empty thinking block for such a part: a stream whose
signature arrives in an empty final part ended [text, thinking("")], and
Claude Code reports an empty result for a turn that ends with a thinking
block. main renders [text].
Failure modes this commit guards against:
- Antigravity (zero options): "Hello world" followed by an empty final
part with a signature, or a part with only a signature, renders an
extra empty thinking block (stream with the signature in its own chunk,
and non-stream).
- Vertex options (marker prefix, text signatures dropped): the output
changes. A scratch probe over 8 part shapes (signature-only part before
text, after text, after thinking, between text and a call, after a
call; signed text; signed image), stream and non-stream, gives the same
bytes before and after this commit. With zero options the same probe
gives the bytes of main.
Changes:
- StreamingProcessor and NonStreamingProcessor: the text branch runs
again only for a part with text or a thought part, as on main.
Tests:
- New TestSignatureOnlyTextPartAddsNoBlock: [text] for both tail shapes,
stream (two chunks) and non-stream, with zero options and with the
Vertex options. The zero-option cases fail on the parent commit.
- TestProcessorsKeepSignatureOnlyPartsAndEmptyToolInput loses its two
signature-only cases and becomes
TestProcessorsKeepEmptyToolInputAndImageSignature.
- TestDropTextSignatures: with the drop off, a trailing empty signed part
now gives [text].
- TestThinkingSignaturePrefixMarksOnlyThinkingBlocks: the carried text
signature now comes from a signed non-empty text part, so the test still
checks that the carrier thinking block gets the prefix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Vertex rejects a function declaration whose parameters carry a keyword
outside its Schema type: a live call with propertyNames returns
400 Unknown name "propertyNames" on every Gemini 4 model. zod-generated MCP
tool schemas emit propertyNames for records, and Claude Code adds a deferred
tool to tools[] once ToolSearch loads it, so every later request in the
session fails with a 400.
The cleaner now keeps only the fields of the Vertex v1 Schema type
(https://docs.cloud.google.com/vertex-ai/docs/reference/rest/v1/Schema).
The keywords it already dropped stay dropped. oneOf becomes anyOf when the
node has no anyOf. A format value stays only when the reference lists it for
the node's type. Every other dropped keyword is appended to the node's
description as "[Constraint: key: value, ...]", in key order, the same hint
shape as the antigravity schema cleaner. No tool is removed.
Failure modes this commit guards against:
- A non-Vertex keyword (propertyNames, not, if/then/else, allOf,
prefixItems, contains, uniqueItems, multipleOf, exclusiveMaximum,
unevaluated*, dependentSchemas, dependencies, ...) reaches parameters at
any depth and Vertex returns 400.
- oneOf is sent under its own name, or its branches are lost.
- A format the reference does not list (uri, uuid) is sent, or a listed one
(date, date-time, int64, double) is dropped.
- A dropped constraint disappears without a trace for the model.
- A property whose name equals a keyword (not, format, propertyNames) is
dropped.
- The same schema gives different request bytes on two turns, which breaks
implicit prefix caching.
- A tool is removed from functionDeclarations.
Test changes:
- TestCleanToolSchema_PreservesNestedOneOfCombinator becomes
TestCleanToolSchema_MapsNestedOneOfToAnyOf: oneOf is not a Vertex Schema
field, so the branches now arrive under anyOf.
- TestCleanToolSchema_TraversesRetainedSchemaValuedKeywords becomes
TestCleanToolSchema_DropsNonVertexSchemaValuedKeywordsIntoDescription:
additionalItems, unevaluatedItems, unevaluatedProperties and dependencies
are not Vertex Schema fields, so they move into the description hint.
- New: gemini_messages_tool_schema_test.go.
Gemini 3 and later put a thoughtSignature on the last part of a turn. When
that part is text (or an empty text part, as streaming does), the
antigravity processors emit an empty thinking block after the text only to
carry the signature. A final Vertex turn then ends [text, thinking("")],
and Claude Code reports an empty result for it, because it reads the last
block. Headless callers that read the result get "".
Vertex enforces signatures only on functionCall parts. A missing signature
on a text part causes no error ("The API does not strictly enforce
validation for signatures in non-functionCall parts"), see
https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thought-signatures
So on the Vertex-account path the text-part signature is dropped.
Failure modes this commit guards against:
- A Vertex text turn with a signature on its text part, or in a trailing
empty text part, ends with an empty thinking block (stream and
non-stream).
- An empty thinking block is emitted between text and a function call, or
after a function call, only to carry a text-part signature.
- A real thinking block loses its signature (signature_delta), or loses the
vertex-thought-v1 marker.
- A function call loses tool_use.signature.
- Text is lost or reordered when its signature is dropped.
- The antigravity platform output changes: it must still emit the empty
thinking block with the raw signature.
Changes:
- pkg/antigravity: ResponseTransformOptions.DropTextSignatures and
StreamingProcessor.SetDropTextSignatures. When set, a non-thought text
part is processed without its signature. The zero value keeps today's
output.
- streamGeminiSSEAsClaude takes antigravity.ResponseTransformOptions
instead of the prefix string, so stream and non-stream use one option
set. The antigravity platform passes the zero value.
- G: geminiVertexResponseOptions (the vertex-thought-v1 marker plus
DropTextSignatures) for the Vertex stream and non-stream renderers, the
same switch as the marker.
Tests (go test -tags=unit):
- pkg/antigravity TestDropTextSignatures: 5 cases, stream and non-stream,
drop on and off. Text-part signature, trailing empty part, real thinking
plus signed text, signed text before a function call, and text split
around a signed part. With the drop on, there is no empty thinking
block; thinking and tool_use signatures stay, and the text stays in
order. With it off, the output is today's.
- service TestGeminiCompatForward_VertexTextPartSignatures: a real Forward,
stream and non-stream. A text turn renders [thinking(marker+sig), text
"PROBE_DONE"] with no text signature; a call turn renders [text,
tool_use(SIG_CALL)] with no empty thinking.
- service TestAntigravityClaudeStreamKeepsTextSignatureCarrier: the
antigravity handler still emits [text, thinking] with the raw signature.
- Updated to the new rule: the Vertex render test no longer expects the
trailing SIG_TAIL thinking block after tool_use. The Vertex signature
test now gets its marked signature from a thought part, and checks that
the text-part signature is not sent.
After a switch from Claude to Gemini in the middle of a session, the history
holds thinking blocks with Anthropic signatures. The converter carries any
real thinking signature as thoughtSignature, so Vertex gets a foreign
signature, answers with a signature 400, and Forward retries with the
thinking blocks downgraded. That costs one extra upstream call on every
request for the rest of the session. tool_use.signature is not affected:
Anthropic tool_use blocks carry no signature.
Failure modes this commit guards against:
- A thinking signature from another upstream (no marker) reaches Vertex as
thoughtSignature on a text or functionCall part.
- A thinking signature that the Vertex path emitted no longer round-trips:
the marker reaches Vertex, or the signature is dropped.
- A marker in front of an empty or skip_thought_signature_validator
signature is carried.
- tool_use.signature changes on the Vertex path.
- The Vertex response sends a thinking signature without the marker, or
marks tool_use.signature.
- The signature-error retry rebuilds the request without the rule.
- The antigravity platform changes: its /v1/messages responses and its
compat path (which uses the same converter) must keep raw signatures.
Changes:
- Vertex responses (stream and non-stream) send thinking-block signatures
as "vertex-thought-v1:" + signature. tool_use signatures stay raw.
- pkg/antigravity: StreamingProcessor.SetThinkingSignaturePrefix and
TransformGeminiToClaudeWithOptions(ResponseTransformOptions). The zero
value keeps today's output; the antigravity callers do not set them.
- convertClaudeMessagesToGeminiRequest(body, model, markedThinkingSignatures):
Forward sets it for Vertex accounts, on the first request and on the
signature retry. With it set, a thinking signature is carried only when it
has the marker, and without the marker. Without the marker the block falls
back to today's handling: no signature on text, the dummy on a call.
convertClaudeMessagesToGeminiGenerateContent keeps the old behaviour for
every other caller.
Histories written by the Vertex path before this commit carry unmarked
signatures. They now fall back the same way, which costs only reasoning
continuity on those old turns.
Test changes: three assertions in gemini_messages_vertex_render_test.go now
expect the marker on thinking signatures. tool_use.signature assertions are
unchanged.
New: gemini_messages_vertex_signature_test.go,
pkg/antigravity/thinking_signature_prefix_test.go.
The antigravity response processors, which now also render Vertex
/v1/messages responses, mapped every finish reason except MAX_TOKENS to
end_turn (or tool_use). A blocked or broken turn then looked like a
successful empty answer: Claude Code ends the turn and the run reports
success.
Failure modes this commit guards against:
- SAFETY, PROHIBITED_CONTENT, SPII, BLOCKLIST, IMAGE_SAFETY or RECITATION
ends as end_turn. It is now stop_reason "refusal", in stream and
non-stream.
- A prompt blocked by promptFeedback.blockReason, with no candidates, ends
as end_turn. It is now "refusal".
- MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS or
MALFORMED_RESPONSE with no text and no tool_use ends as an empty
end_turn. Thinking blocks do not count as content: with thinking on, a
thought summary comes before almost every invalid call. The stream now
ends with an SSE error event of type api_error, which Claude Code
retries. Non-stream returns ErrMalformedFunctionCall or
ErrInvalidOutputWithoutContent, which callers write as a 502.
- The same reasons after text or a tool call must still end normally
(end_turn, or tool_use after a call). Non-stream MALFORMED_FUNCTION_CALL
with text now gives end_turn too; the antigravity collect path still
fails it before conversion, as before.
- After the error event, no later chunk may emit content, message_delta or
message_stop, and the usage must still be collected for billing.
- STOP, MAX_TOKENS, OTHER and tool calls without a refusal reason keep
their mapping. A refusal reason wins over tool_use.
Only the mapping changes; no safetySettings are added. Effects on the other
antigravity paths:
- Claude, chat-completions and responses non-stream now return 502 for
UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS and MALFORMED_RESPONSE without
text or tool calls, where they returned an empty 200 before.
- The chat-completions and responses stream adapters buffer the error event
like the empty end_turn before it, so they still report an empty stream.
- Not mapped, and so still end_turn: MODEL_ARMOR, IMAGE_PROHIBITED_CONTENT,
IMAGE_RECITATION, IMAGE_OTHER, NO_IMAGE and CONTINUATION.
Tests: pkg/antigravity/finish_reason_test.go (stream and non-stream per
reason), gemini_messages_vertex_finish_test.go (Vertex /v1/messages through
Forward).
Four request-side defects in convertClaudeMessagesToGeminiContents. They
apply to every caller of the Gemini compat converter, including the
antigravity compat path for gemini-* models.
Failure modes this commit guards against:
- Two parallel calls of the same tool get each other's results. Claude Code
sends tool results in completion order, and Vertex v1 matches a
functionResponse to its functionCall by position, because ids are stripped
(Vertex documents them for v1beta1 only, and the compat path calls /v1).
- A result whose tool_use_id is not in the previous model turn lands among
the known results.
- Reordering moves other parts of the user message.
- is_error is dropped, so the model cannot tell a failed call from output.
- A PDF read by Claude Code arrives as a document block inside tool_result
and is dropped. The "PDF file read: ..." text must also stay.
- A top-level base64 document is sent as JSON text with the base64 inside,
and a text-source document is not sent as plain text.
- A real thinking signature from history is dropped. An empty or
skip_thought_signature_validator signature must not be attached,
tool_use.signature must win over a thinking signature, and a parallel
sibling call must keep the dummy signature, also when the first call has
its own signature.
- A signature-only thinking block that follows a text block is lost. The
antigravity processors emit a text part's signature this way (text first,
then an empty thinking block with the signature), and a signature from a
final empty text part the same way at the end of the message. Such a
block is the text's own signature, so it also replaces a signature that
the text got from an earlier thinking block.
Changes:
- Results: each user message's functionResponse parts are reordered, in
place, to the call order of the previous model turn by tool_use_id.
Unknown ids go after the known ones. Other parts keep their positions.
stripGeminiFunctionIDs stays.
- is_error: response is {"error": text}; otherwise {"content": text} as
before.
- Documents: a base64 document becomes inlineData, a text-source document a
text part, other sources keep the JSON-text fallback. Inside tool_result,
base64 documents travel with images: in functionResponse.parts on models
with multimodal function responses (Gemini 3+), else as trailing parts.
- Signatures: the shape of upstream PR #8545, made stricter. A real
signature on a thinking block goes to the very next text or functionCall
part only. If that part has its own signature, the carried one is
dropped, so later parallel calls keep the dummy. A signature-only
thinking block right after a text part goes back to that text part.
ensureGeminiFunctionCallThoughtSignatures stays as the fallback.
- After a switch from Claude in the same session, Anthropic thinking
signatures in history now reach Vertex in place of the dummy. Vertex then
answers with a signature error, and the existing signature retry in
Forward downgrades the thinking blocks and sends the request again.
Tests: gemini_messages_history_test.go replays the block shapes of a
captured Claude Code session (signature echoes, out-of-order parallel
results, a PDF read, an error result, a tool_reference result).
Vertex accounts (service account JSON and API key) on /v1/messages keep the
Gemini compat request converter and the Vertex transport. Their responses are
now rendered by pkg/antigravity's StreamingProcessor (stream) and
NonStreamingProcessor (non-stream), the same processors that the antigravity
compat path already uses for gemini-* models. Both read plain Vertex
responses with no v1internal wrapper. Other account types keep the compat
emitters unchanged.
Failure modes this commit guards against:
- The client usage carries no cache_read_input_tokens when Vertex reports
cachedContentTokenCount. Claude Code then starts auto-compaction late or
never, and long sessions fail.
- The thoughtSignature of a functionCall part does not reach
tool_use.signature, so the next turn falls back to the dummy signature.
- The signature of a thought part is not sent as a signature_delta.
- A signature that arrives in a final empty text part is lost. Vertex
documents that a stream can return the signature this way. The
antigravity processors had the trailing-signature branch, but processPart
never reached it for an empty text part.
- Non-stream: no thought text (includeThoughts was set for stream only), no
signatures, and a call without args has no input object.
- A text chunk that is a prefix of earlier text is dropped as a duplicate.
- Web search grounding sources (groundingMetadata) never reach the client.
- Billing drifts: the recorded usage must still come from the upstream
usageMetadata (input minus cached, cache read, output plus thoughts, image
output tokens), and image outputs must still be counted.
- An empty upstream stream must fail over before a byte reaches the client.
- A client that leaves before any usage arrives must stay unbilled, as in
the compat stream handler.
- Non-Vertex accounts must keep the compat emitter.
Changes:
- AntigravityGatewayService.handleClaudeStreamingResponse becomes a thin
wrapper around streamGeminiSSEAsClaude(cfg, observeLine). The antigravity
path passes its own config and line observer, so its behaviour does not
change.
- GeminiMessagesCompatService.Forward: for Vertex accounts, the stream is
rendered by streamGeminiSSEAsClaude, and the non-stream body by
antigravity.TransformGeminiToClaude. Model, image and usage observation
per upstream payload stay as in the compat emitters, so billing keeps its
source. includeThoughts is also requested for non-stream calls.
- pkg/antigravity: a tool_use with no args serializes "input": {}, and a part
that carries only a thoughtSignature reaches the trailing-signature path.
An image part keeps today's behaviour.
The non-stream path keeps upstream generateContent, so the existing Vertex
endpoint tests still apply unchanged.
Behaviour changes beyond the fixes:
- The signature-only part fix is in pkg/antigravity, so the antigravity
platform's own Claude responses now also carry such a signature as an
empty thinking block, where it was dropped before.
- Vertex image models on /v1/messages now return generated images as
markdown data-URL text, as the antigravity processors render them. The
compat emitter did not forward images on this endpoint.
Tests: gemini_messages_vertex_render_test.go (Forward with a Vertex API key
account and scripted Vertex chunks), pkg/antigravity/signature_part_test.go.
Add top-level CacheControl to apicompat.AnthropicRequest and inject {"type":"ephemeral"} on Chat Completions to Anthropic API-key forwarding paths for Claude models, respecting explicit client cache_control overrides and null/false opt-out. Also count top-level cache_control objects toward Anthropic's 4-breakpoint limit in enforceCacheControlBlockLimit.
The golangci-lint CI job fails because check-type-assertions is enabled
and version.Load().(string) uses the unchecked single-value form.
Switch to the two-value form so the linter is satisfied.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The Codex desktop in-app browser sends the open tabs as an agent-namespace
function_call_output named browser_tabs without a call_id. It is not on the
untrusted-context allowlist, so HTTP Responses requests are rejected with
"function_call_output requires call_id". Add it next to browser_info and
terminal_info so it is rewritten into a user message like the others.
Some OpenAI-compatible relays reject the standalone Codex search endpoint
with HTTP 400 while serving /v1/responses normally. The 400 was passed
straight to the client, so search failed even when another account in the
group could serve it.
For API-key accounts, a 400 from /v1/alpha/search now fails over to the
next eligible account without account-health side effects or same-account
retries. When failover is exhausted the last upstream status and body are
returned unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ResponsesToAnthropicRequest defaults max_tokens to 8192 when the
Responses request has no max_output_tokens, and turns any effort above
low into thinking.type=enabled with an effort-derived budget: 10240 for
high, 32768 for xhigh/max. Anthropic requires max_tokens to be greater
than budget_tokens, so every effort above medium was rejected with
"budget_tokens must be less than max_tokens". Codex never sends
max_output_tokens, so its users could not work around it.
After the conversion, raise max_tokens to budget_tokens + 1000 when an
enabled budget does not fit, the same rule and padding the Antigravity
transformer applies in ensureMaxTokensGreaterThanBudget. Requests that
already fit, adaptive thinking, and requests without thinking are
unchanged.
Fixes#6569
The admin "Test" button for web search emulation always showed
"internal error". Manager.TestSearch dropped every provider's error with
a bare `continue` and returned "no available provider", and the handler
passed that plain error to response.ErrorFrom, which maps it to a 500
with the generic message. A wrong key, an exhausted plan, a proxy
failure and an unsaved config all looked the same.
Keep each provider's error in TestSearch and join them when every
provider fails, and return the cause from the handler as a 400, the
same way the SMTP connection test already does. TestSearch is admin
only; the production SearchWithBestProvider path is unchanged.
Refs #7201
Tavily's /search endpoint documents a single credential scheme,
`Authorization: Bearer <key>`, and its official Python/JS SDKs send only
that header. The provider still put the key in an `api_key` body field
and sent no Authorization header, so web search emulation through
Tavily relied on an undocumented contract. Brave and Exa in the same
package already send their keys as headers.
Send the key as a Bearer token and drop it from the request body. The
old unit test only marshalled the request struct and asserted the body
`api_key`, so it locked in the stale contract without exercising
Search(); replace it with a test that drives Search() through a
recording transport and checks the outgoing headers and body.
Refs #7201
Google AI Studio rejects replayed function calls without a thought signature (400 "Function call is missing a thought_signature in functionCall parts"). The signature arrives in tool_calls[].extra_content.google, which Codex Responses history cannot preserve, so follow-up turns after tool calls fail when routed to AI Studio.
Before a Chat Completions request goes to generativelanguage.googleapis.com, give each assistant tool call without an existing thought_signature the dummy value skip_thought_signature_validator (matching the native Gemini path). Signatures embedded in Unity/LiteLLM "__thought__" call-id suffixes are not reused because they are issued by a different Google backend and fail with INVALID_THOUGHT_SIGNATURE; the call id itself is kept intact so tool outputs still match. Other upstreams are byte-for-byte unchanged.
Google AI Studio OpenAI-compatible streams send parallel tool calls
without an index, each whole in its own chunk with its own id. A missing
index defaulted to 0, so both calls merged into one item with arguments
like {"cmd":"ls"}{"cmd":"date"} and the stream failed with
invalid tool call arguments (502). Without an index, continue the last
call when the delta has no id or the same id, otherwise open the next
contiguous slot. Indexed streams are unchanged.
Content moderation collected Anthropic image blocks only from source.data, never
from source.url. Since #8312 the /v1/messages -> OpenAI Responses bridge forwards
URL image sources upstream as input_image, so an image sent as
{"type":"url","url":...} (including a data: URI) reached the model without
being moderated, while the same image sent as base64 was. The native Anthropic
path forwarded such images unmoderated as well.
Collect source.url like the other image URL fields; addModerationImage still
accepts only http(s) and data: values.
The previous Codex catalog advertised only "none" for k3.1-pro, so Codex
clients that still hold it send reasoning.effort=none. Preserving none for
K3.1 made those requests fail upstream with HTTP 400 (K3.1 cannot disable
thinking) instead of running at the default effort as they do today.
Keep the existing compatible-upstream rule on the Responses path: strip the
none placeholder for K3.1 exactly like every other Kimi model. The new
catalog no longer advertises none, so current clients are unaffected.
openCodeSessionHintBody built the hint with strconv.Quote, which emits Go
escapes such as \U000f0001 that are not JSON. A session id containing such a
rune (private-use or tag characters, e.g. subdivision flag emoji) was read
back truncated, so different conversations could share one
x-opencode-session. Encode with json.Marshal instead.
Also measure the compaction allocation budget in a child test process, as
main already does for other process-wide allocation counters, so background
goroutines left by other service tests cannot fail it intermittently.
The Anthropic /v1/responses bridge had the same gap as the Chat Completions
bridge: successful OAuth/setup-token responses never refreshed the 5h/7d
subscription windows. Sample the response headers on 2xx exactly like the
Chat Completions path, and cover both bridges in one regression test.
HelpTooltip always centered its popup above the trigger, so on a ~375px
screen any info icon near the left or right edge (ops dashboard cards,
accounts table headers, modal fields) pushed the tooltip off screen.
Several forms also hand-rolled CSS-only hover popups that are absolutely
positioned from the icon and get cut off by the viewport and the dialog
body.
- Move the placement logic from UsageTable into a shared
getTooltipPosition helper (utils/floatingPanel.ts): prefer one side,
flip to the opposite side when it does not fit, otherwise pin to the
viewport edge; clamp the cross axis.
- HelpTooltip measures its popup and uses the helper (above, flipping
below near the top of the screen); the arrow keeps pointing at the icon.
- UsageTable token/cost tooltips use the same helper.
- Replace the hand-rolled info popups in GroupsView, Create/EditAccountModal
and the usage stats cache breakdown with HelpTooltip.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The token and cost detail tooltips in the usage table were always placed
8px to the right of the info icon. On narrow (mobile) screens the cost
column sits near the right edge, so the non-wrapping tooltip was cut off.
After rendering, measure the tooltip: flip it to the left of the icon when
it does not fit on the right, pin it to the right edge when neither side
fits, and clamp it vertically to the viewport.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up:
- Stop treating parameter errors as safety rejections. The message
matcher no longer uses a bare "moderation" keyword and rejects
"unknown/unrecognized/unsupported parameter" style messages, so
Azure-style "Unrecognized request argument supplied: moderation"
(param null) and error-passthrough rewrites (which drop param/code)
are not recorded with the user's prompt.
- Check explicit safety codes before the param exclusion, so Azure
content filtering (code=content_filter, param=prompt), contentFilter
and ResponsibleAIPolicyViolation are recorded; response_incomplete is
only a 400 for content_filter/moderation reasons and counts as well.
- Show image_safety rows with the hit badge instead of the amber error
badge, and exclude them from the "error" result filter.
Review follow-up for the proxy account count refresh:
- Apply a proxy list response only if it is newer than the last applied
one. Previously a failed newer refresh also discarded a slower older
success, which could leave the selector empty.
- Refresh proxy counts on every `created` event. Batch creation can
partially succeed and keep the dialog open, so opening the dialog was
not enough.
- Test ProxySelector with the real vue-i18n and locale files instead of
a hand-written mock of the plural rule.
The proxy selector in the account dialogs showed a bare number next to
the proxy name, and AccountsView loaded the counts only once on mount,
so they went stale after accounts were created, deleted, imported or
rebound.
- Show "N 个账号" / "N account(s)" on the right of each proxy row, before
the test button, with a tooltip.
- Reload proxies with counts whenever the create, edit or bulk-edit
dialog opens. A sequence guard drops out-of-order responses and a
failed reload keeps the previous list.
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
Anthropic reports thinking tokens in usage.output_tokens_details.thinking_tokens,
a subset of output_tokens. AnthropicUsage had no such field, so Anthropic
accounts served through /v1/chat/completions and /v1/responses never exposed
reasoning_tokens.
Decode the field, carry it through the stream state and the buffered
ClaudeUsage merge (a reported value, even 0, replaces the previous one), and
emit it as Responses output_tokens_details.reasoning_tokens, which the existing
Responses-to-Chat mapping turns into completion_tokens_details.reasoning_tokens.
Billing is unchanged.
Fixes#9048
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>
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>
Without a client effort, the Anthropic bridge sends `medium`. DeepSeek's
reasoning scale is low/high/max, as the Codex manifest already declares,
and DeepSeek-V4.1 rejects `medium`. Every Anthropic-format request without
an explicit effort therefore failed on DeepSeek models. The bridge now
sends DeepSeek's default level instead. Explicit efforts, disabled thinking
and other models are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Codex manifest advertises image input from synced upstream metadata
or a few known model names. Multimodal models served by vLLM or SGLang
match neither, so Codex blocks image attachments for them. The new account
extra key `image_input_models` lists upstream model IDs that accept image
input, and the manifest honors it ahead of synced metadata.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
vLLM and SGLang stream reasoning in `reasoning`, while DeepSeek-style
clients read `reasoning_content`. The raw Chat Completions path already
mirrors these fields for Ollama Cloud accounts. The new account extra key
`openai_chat_reasoning_content` enables the same normalization for other
OpenAI API-key accounts. Ollama Cloud keeps it unconditionally.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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>
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.
Count provider-owned, non-business-limited rows in ops_error_logs per
account (same definition as the ops dashboard) and expose them as
`upstream_errors` on today stats and per-day account usage history.
- Today stats column shows today's upstream errors (highlighted when > 0).
- Usage statistics modal adds an upstream error trend line plus today and
30-day totals; days with only errors are merged into the history.
- Counts are omitted when ops monitoring is disabled so the UI hides them
instead of showing a misleading 0. Failover intermediate attempts are
attributed only to the last failing account.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ignore usageMetadata without counters so a trailing placeholder cannot overwrite measured input, output, or cached tokens. Preserve explicit zero counters and add regression coverage for the Gemini native, Chat Completions, Messages, and stream collection paths.
Conflict in backend/internal/service/openai_oauth_model_support_test.go:
upstream moved claude-sonnet-4-6 / claude-3-opus-20240229 into the
foreign-model list, while this branch added k3.1 / k3.1-pro-preview to the
servable list. Keep both sides: upstream's list plus the K3.1 aliases.
On streams the response side renames tool names back on each SSE event by itself, so a rewritten name split across two text_delta or input_json_delta events matches in neither and reaches the client unrestored.
Keep, per content block, the tail of a text or partial_json payload that could be the start of a rewritten name and join it to the block's next text or JSON delta before renaming back. Held bytes go out as one more delta before content_block_stop, or before the closing event when the stream ends another way. Other delta types such as citations_delta pass through and leave the tail held. The native stream applies this to the events it writes, the Chat Completions and Responses bridges to the upstream event before conversion.
js-genai before 1.32.0 parses the stream with
/^\s*data: (.*)(?:\n\n|\r\r|\r\n\r\n)/ anchored at the head of its
buffer, so the first ":\n\n" keepalive blocks every later event and the
stream fails with "Incomplete JSON segment at the end". Gemini CLI (up to
0.70.0) pins js-genai 1.30.0 and sends it in X-Goog-Api-Client
("google-genai-sdk/1.30.0 gl-node/..."), so long native Gemini streams
fail for every Gemini CLI user (#8941). js-genai 1.32.0 (c9c1359) splits
the buffer at each delimiter and drops non-data events, so newer Node
clients keep the keepalive.
Treat gl-node clients with google-genai-sdk < 1.32 like go-genai and
python-genai. The old "js-genai tolerates comments" test case used 1.9.0,
which also stalls; it now expects the skip.
Fixes#8941
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.
TestFilterThinkingBlocksSignedHistorySkipsDecode asserts testing.AllocsPerRun < 16, and AllocsPerRun reads the process-wide malloc counter, so allocations by background goroutines that earlier tests in the package leave running are counted against it and the test fails intermittently in full package runs.
Run the measurement in a child test process that runs only this test, as TestOpenAIResponsesOrphanPrecheckLargeEscapedContent already does. The assertions and the threshold are unchanged.
The usage refresh key has no Gemini quota input. When a Gemini account's
tier changes, as when the token refresher re-detects the Google One tier,
auto refresh replaces the row but the key is unchanged: the tier badge
shows the new tier, the quota bars keep the old limits until the account
is used, Refresh is clicked or the page is reloaded. An API key account
moved from a third-party base URL to the official one gets no bars for
the same reason.
The Gemini key now carries credentials.oauth_type, project_id, tier_id and
base_url, the credentials geminiQuotaTierKeyForAccount depends on. Gemini
usage is read from local usage logs, so the refetch sends nothing
upstream, and a token refresh that leaves these four fields alone keeps
the key.
Use the final structured rate-limit delay for cooldown, including long delays that no longer qualify for in-place retries. Keep capacity policy and unrelated model responses separate.
Co-Authored-By: Claude Code <noreply@anthropic.com>
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.
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
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
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
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
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
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)
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)
Abort the online update when the release has no checksums.txt, the
archive is not listed in it, or it cannot be fetched (fail closed).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
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>
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).
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.
Keep upstream's subprocess isolation in the overlapping tool-schema test.
Preserve the capacity-shed retry-delay and WS passthrough fixes, together
with the remaining allocation-test isolation guards.
Add HTTP failover coverage: capacity-shed exhaustion omits Retry-After,
while the existing ordinary 429 test continues to preserve that header.
Validation on Go 1.27.4:
- GOMAXPROCS=4 go test -tags=unit -count=1 ./...:
28,223 test cases including subtests passed; 40 skipped.
- golangci-lint 2.14.0: 0 issues.
- Independent review of the complete PR diff: no material findings.
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
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.
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.
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.
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>
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.
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.
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.
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.
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)
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.
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
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
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
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.
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
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.
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.
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.
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.
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.
With auto-refresh on, the accounts page replaces a row only when OpenAI or Grok usage inputs change, and AccountUsageCell watches only the OpenAI usage key, so Claude OAuth, setup-token and Gemini bars stay at what they loaded until the refresh button is clicked.
Add usage refresh keys for Claude (session window columns, passive samples in extra, last_used_at) and Gemini (updated_at, last_used_at), replace a row when either changes, and have the cell watch one key across the three platforms.
A change asks the batch loader for a forced refetch, or outside batch mode drops the cached entry and reloads, passive for Claude. Both backend paths read local data only, so a refetch per changed row sends no upstream request.
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.
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.
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.
#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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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>
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.
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.
- 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.
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.
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.
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.
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.
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.
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.
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.
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.
Resolve the overlapping test change by keeping the upstream implementation from PR8603 unchanged. Preserve PR8560 capacity-shed handling and the other service allocation isolation fixes.
Validated the merged tree with focused service overload, WS lifecycle and allocation tests; handler failover/retry tests; golangci-lint2.14.0 (0 issues). The separately staged BWH0.2.20 release is unchanged.
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.
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.
The full CI suite exposed the same process-wide allocation counter interference in signed thinking-history filtering. Reuse one subprocess helper for all six service allocation tests while retaining the original thresholds and assertions. Verify the named child test actually executed and propagate its failures.
Validation: allocation tests passed twice; related precheck, model mapping, Gemini, compaction and tool schema tests passed; golangci-lint 2.14.0 reported 0 issues. A copying-parser negative control still fails the zero-allocation assertion.
Merge the current upstream base so CI exercises the same orphan precheck. Run the zero-allocation assertion in a fresh test process to exclude background workers from process-wide allocation counters. Keep the strict zero-allocation assertion and remove the trailing blank line from the WS regression test.
Validated: service precheck and passthrough lifecycle tests; handler capacity/failover tests; golangci-lint 2.14.0 (0 issues). Background-allocation pressure fails before isolation and passes after; a copying-parser negative control still fails.
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>
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.
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.
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.
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>
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>
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>
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>
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>
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>
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>
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>
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>
- 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>
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.
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>
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>
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>
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>
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.
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.
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>
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.
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.
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.
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.
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>
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>
- 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>
- 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>
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>
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.
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.
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.
Preserve URL image sources in Anthropic user messages and tool results across both upstream request bridges. Add regression coverage with base64 controls.
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
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
1289 changed files with 111264 additions and 7736 deletions
@@ -6,6 +6,8 @@ Each build uses GoReleaser OSS in snapshot mode with the selected release versio
Go caches are isolated by target and refreshed on each source commit, with fallback to the preceding target cache. Save uses the original restore key, even if a build hook changes `go.sum`. Matrix jobs upload uniquely named artifacts. The publishing job extracts only the regular Linux binary from each verified archive and restores its executable permission before constructing Docker contexts. QEMU remains limited to runtime-image instructions. DockerHub images are omitted when its credentials are absent; GHCR is always retained. Simple mode still publishes only the amd64 GHCR image and the simple release description.
A tag push is rejected in `prepare`, before anything is built or published, unless `backend/cmd/server/VERSION` at the tagged commit already equals the tag version: commit the VERSION bump first, then tag that commit. Source builds of the tag (`go build`, GitHub source archives, Docker builds without `.git`) embed that file. To re-release an older tag created before this rule, run the workflow manually with `allow_version_mismatch=true`; it then emits a warning and builds with the tag version.
All build jobs use the commit resolved by `prepare`, including a manual release's selected tag. Helper scripts come from the workflow revision and are passed as a run-local artifact, so older application tags do not need to contain the new scripts. The workflow serializes release runs to prevent simultaneous updates to moving image tags.
A dry run builds all selected archives and both runtime images, verifies artifact provenance and produces the final checksum file. It exports images locally as OCI archives instead of pushing them. It skips registry logins, GitHub Release publication, DockerHub description updates, Telegram notifications and VERSION synchronization. Test the simple path separately with `simple_release=true`.
A dry run builds all selected archives and both runtime images, verifies artifact provenance and produces the final checksum file. It exports images locally as OCI archives instead of pushing them. It skips registry logins, GitHub Release publication, DockerHub description updates, and Telegram notifications. Test the simple path separately with `simple_release=true`.
Dry-run artifacts are available in the Actions run, including `release-dry-run-report`. Compare job start/end times, GoReleaser's build duration and cache restore results. Do not present an initial cold-cache run as a warmed-cache benchmark; publishing network time is not measured by dry runs.
**[WandAPI](https://wandapi.ai/r/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.
**[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.ai/r/sub2api) to claim free trial credits.
**Free trial credits**: sign up via [this exclusive link](https://wandapi.com/go/sub2api) to claim free trial credits.
---
@@ -65,8 +65,8 @@ Please read the following carefully before using this project:
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for sub2api users: if you register via <a href="https://api.aigocode.dev/invite/SUB2API">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
<td>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>
@@ -117,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>
<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>
<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>
@@ -138,13 +133,8 @@ Please read the following carefully before using this project:
<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>
<td>Thanks to AxisNow for sponsoring this project! <a href="https://www.axisnow.io/">AxisNow</a> protects and accelerates websites and APIs, delivering an optimal access experience across mainland China and globally, while extending acceleration and security capabilities to native/mobile apps through client SDKs — <strong>self-hosted private-deployment CDN</strong> | <strong>subscription-based DDoS-protected CDN</strong> | <strong>autonomous, flexibly composable CDN network</strong>.</td>
<td>Protect and accelerate your Sub2API with AxisNow<br>Optimized routes for users in mainland China, WAF and rate limiting to protect your API entry point, and support for self-hosted or subscription CDN edge nodes. <a href="https://www.axisnow.io/zh/docs/guide/sub2api">View the Sub2API integration guide →</a></td>
</tr>
<tr>
@@ -173,13 +163,23 @@ Please read the following carefully before using this project:
<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>
<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>
<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>
<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>
<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>
<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>
@@ -751,6 +751,16 @@ Simple Mode is designed for individual developers or internal teams who want qui
---
## OpenAI Image Output Formats
On `/v1/images/generations` and `/v1/images/edits`, OAuth / Setup Token requests use the Codex-native Images endpoints when the mapped upstream model is a supported GPT Image 1.5, 2, 2.5, or 2.6 model. Models before 2.6 can fall back to Responses if the native endpoint returns 404 or 405.
Sub2API forwards `output_format` and `output_compression`, but whether they take effect depends on the upstream account and endpoint. An upstream may reject a format with a 4xx error or return HTTP 200 with a different format: for example, requesting `jpeg` or `svg` can yield `output_format: "png"` and PNG data. This behavior has also been reported for `gpt-image-2.5-flare` requests for `jpeg`.
Before saving or serving an image, compare the returned `output_format` (including any per-image value) with the request and verify the actual image format. Use the actual output format for the filename extension and MIME type. A successful response containing a different format retains its status, image content, and usage; it can still incur charges. Automatically retrying may generate and bill another image.
---
## Asynchronous Image Tasks
Long-running OpenAI/Grok image generation and editing can be submitted through `/v1/images/generations/async` or `/v1/images/edits/async`, then polled at `/v1/images/tasks/{task_id}` without holding a CDN connection open. See [Asynchronous Image Tasks](docs/ASYNC_IMAGE_TASKS.md) for request and response examples.
<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>
<td>AIGoCode のご支援に感謝します!トークン従量課金だけではない、サブスクリプション型の AI コーディングプラットフォームです。1 つのアカウント・月額プランで Claude Code、Codex、Gemini を使い放題。中国本土から直接接続でき、レスポンスも高速です。<a href="https://api.aigocode.dev/invite/SUB2API">こちらのリンク</a>から購読すると、10% の追加クレジットをプレゼント!</td>
</tr>
<tr>
@@ -119,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>
<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>
// group.MaxReasoningEffortOverLimitValidator is a validator for the "max_reasoning_effort_over_limit" field. It is called by the builders before save.
Loaded 100 of 1289 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.