- Track the running response identity in the Codex websocket session and reject interrupts that do not target it, so an interrupt after response.completed is never forwarded upstream while turn teardown is pending.
- Gate the handler's local interrupt path by explicit turn ownership and close it before terminal payloads are written downstream, preventing fabricated response.incomplete events and silently dropped claimed frames.
- Add deterministic regression tests covering late and unknown interrupts across completion, failure, queued rejection, upstream loss, and HTTP fallback turns.
Closes: #7065
When an upstream Codex WebSocket returns an early 429 usage_limit_reached (via an error or response.failed frame) before any downstream payload chunk is emitted, notifying UpstreamDisconnectChan caused the Responses WebSocket handler to close the client connection and cancel the request context before the conductor could fail over to another eligible credential.
Suppress downstream disconnect notification on pre-output upstream WebSocket errors and treat bootstrap usage-limit terminal failures as failover-eligible while bootstrap buffering is active, allowing the conductor to retry another credential on the same downstream WebSocket connection.
Fixes#7051
- Build un-defaulted original request payloads for xAI image generation and edit handlers and propagate them via execution context so payload default rules can distinguish omitted client fields from built-in defaults.
- Pass normalized original requests into the xAI image executor payload finalizer and report finalized response_format values back to handlers via metadata callbacks across streaming and non-streaming responses.
- Add unit and handler regression tests covering payload default, default-raw, and override rules for xAI image endpoints.
Closes: #7048
- Attach content-free log diagnostics to Devin apply_patch 502 rejections with fixed reason categories, argument byte counts, prefix shapes, and parse error classes.
- Buffer and recover complete, well-framed bare Codex patches from Devin invalid_json_str arguments via applypatch.WrapInput after a clean EOS trailer in streaming and non-streaming execution.
- Keep truncated streams, trailer errors, mixed argument sources, and malformed patches fail-closed without exposing patch content.
Closes: #7046
Keep the client's /v1/responses websocket open when an upstream Codex websocket drops during or between turns, report correlated non-closing error frames without replaying in-flight turns, fence pre-loss queued input across handler and executor boundaries, and preserve pinned credential affinity across Home turn releases.
Closes: #7028
- Strip SSE data prefixes and ignore control lines before initializing stream state.
- Cover translated content, usage, and completion across vertex authentication paths.
Closes: #7025
Without a protobuf wrapper, the ciphertext after the Tink prefix byte is
indistinguishable from uniform random bytes. Matching only the 0x01
prefix byte claimed about 1/256 of unenveloped payloads as Gemini: xAI
encrypted_content starting with 0x01 was then rejected by the Grok
validator and dropped from replay, and Kimi signatures were misclassified.
- require the observed Vertex key id (8f3d6b5f) in addition to the
prefix byte; a rotated key falls back to the bypass sentinel, which is
the behavior before bare-Tink recognition
- expose IsGeminiVertexBareTinkSignature and scope the Gemini
Interactions sanitizer: the public endpoint drops bare-Tink thought
steps, the Vertex Interactions endpoint keeps them
- restore the xAI seed and Kimi ordering tests that had been adjusted
around the false positive, and add regressions for a 0x01-leading Grok
payload and an unknown key id
- Classify Codex turn-rate and model-capacity 429s as transient per-model rate limits via a new executor contract, honour upstream Retry-After headers behind quota resets, and cool only the reporting model without quota labelling or exponential backoff.
- Carry the trusted retry deadline to terminal clients and retry scheduling across direct, streaming, bootstrap, and Home paths, keeping Home aggregated deadlines authoritative over per-attempt hints.
Closes: #7017
DecodeResponseBody used zstd.NewReader with its default options, which
hands blocks to up to four asynchronous decoders: allocations and handoff
latency on every streamed response for no gain on bodies read as they
arrive. Decode with WithDecoderConcurrency(1) instead.
A response without Content-Encoding was sniffed for gzip/zstd magic with
Peek(4) before DecodeResponseBody returned, blocking the caller until the
upstream sent its first bytes. Detect on the first Read instead, waiting
for more than one byte only when the first byte can start a gzip or zstd
frame.
Live replay showed Antigravity (cloudcode-pa) and AI Studio
(generativelanguage) reject Vertex bare-Tink thought signatures with
400 "Corrupted thought signature", while Vertex accepts them natively.
After recognizing bare-Tink as a Gemini envelope, history issued by
Vertex and routed to those endpoints was replayed verbatim and failed.
- add SanitizeNonVertexGeminiRequestThoughtSignatures, which treats
bare-Tink as incompatible: the first functionCall in a group gets the
bypass sentinel and other parts drop the signature
- use it in the Antigravity, Gemini API and AI Studio executors; the
Vertex executor keeps the preserving sanitizer
- cover the endpoint split in the signature package and with mocked
upstream bodies for the Gemini API and Antigravity executors
Vertex serve paths emit the Tink primitive output directly as the whole
thoughtSignature (0x01 prefix + 4-byte key id + ciphertext) instead of the
protobuf field-2 wrapper used by AI Studio and Antigravity, so every Vertex
Gemini signature was misclassified and rewritten to
skip_thought_signature_validator (#7007).
- add GeminiThoughtSignatureEnvelopeBareTink with a bounded structural check
(prefix byte + key id + 16-byte auth-tag floor)
- register the 0x01-derived 'A' first char in the self-describing prefilter
- cover detection, replay preservation, floor rejection and cross-family
non-claims with synthetic fixtures
- document envelope precedence in the Kimi ordering test; move the xAI cache
seed off the 0x01-colliding seed 14
- Tag locally synthesized missing-finishReason failures as stream-truncated in the Gemini and Vertex executors, and carry that classification through the auth manager so it skips credential cooldown and stops cross-credential replay while the public 502 and partial usage are preserved.
- Carry the truncation classification through usage reporting and the Home queue payload so Home-side schedulers also skip the spurious cooldown, and add regression coverage for both the manager and usage paths.
Closes: #7005
- Fall back to schema prompts for Antigravity Claude 5.5 while preserving unrelated request settings.
- Normalize unsupported forced tool choices before thinking preparation in direct Claude execution and token-count paths.
- Add regression coverage for schema integrity, model boundaries, retries, and final payload rule precedence.
Closes: #7000
- Cache the latest valid usage frame in both Interactions translators and emit interaction.completed with the done sentinel once usage at or after the finish frame arrives, keeping earlier cached usage only as the explicit-[DONE] fallback so split finish/usage frames keep the final token counts.
- Recognize a bare [DONE] payload in the Antigravity stream parser (previously misparsed as a JSON array) and restore filter-renamed cpaUsageMetadata in the Gemini translator so executor-filtered frames still complete the stream.
- Document that a clean Antigravity EOF terminates Interactions streams even without finishReason, matching real tool-call streams, while read errors still surface without a synthetic completion.
Closes: #7003
- Stamp Codex commentary thinking blocks with the CLIProxyAPI-internal marker `cpa:commentary:v1` in streaming and non-streaming Claude responses, keeping real reasoning signatures isolated.
- Restore marked blocks on replay before any provider signature handling: as an assistant `phase: "commentary"` message for Codex targets and as plain assistant text for Claude-compatible, OpenAI, Gemini, Interactions, and Antigravity targets, so the marker never reaches an upstream.
- Add the unconditional marker restore at the Claude upstream sanitize entry so non-Claude model names cannot bypass it, with round-trip and cross-format regression tests.
Closes: #6994
- Compress finalized Codex OAuth request bodies with zstd on the verified ChatGPT backend path, with size/benefit gating, header-body alignment, and one uncompressed retry on 400/415 rejection.
- Negotiate downstream HTTP response compression under server.response-compression (zstd/gzip with q-values, SSE-safe flushing, commit-time Vary merging) and enable negotiated permessage-deflate on Codex and downstream WebSockets.
- Advertise Accept-Encoding to Codex upstreams and decode gzip/deflate/br/zstd upstream responses through a shared decoder before parsing or relaying.
Closes: #6905
- generate a unique selection_id for each handled Scheduler.Pick decision and freeze it into the execution context and UsageReporter
- propagate SelectionID through core usage records and pluginapi.UsageRecord while clearing stale IDs on unhandled, rejected, Home, and credits fallback paths
Closes: #6988
- Split SSE-formatted wsrelay stream chunks at blank lines into individual data frames while preserving non-SSE JSON payloads whole.
- Run response model observation, usage extraction, metadata filtering, and stream translation per frame so trailing finish reasons and token usage are not dropped.
- Add regression tests covering multi-frame relay chunks across OpenAI Chat, OpenAI Responses, and Claude formats.
Closes: #6977
- Number test server connections before upgrading in TestWebsocketRetryBindFailureClearsActiveSessionState so connection order matches sequential client dials.
- Wait for the client request payload to arrive before sending the completion frame and closing the server socket in xAI keepalive upload tests, and guard hook channel closes with sync.Once.
Closes: #6983
- Aggregate -{level}-lightning compound suffixes into a single swe-2-lightning catalog entry and preserve the Lightning display name suffix across registry and fetch_devin_models.
- Resolve -lightning base models into stem-{effort}-lightning UIDs while passing through complete upstream lightning UIDs and regenerating the embedded Devin catalog.
Closes: #6975
- Deduplicate normalized xAI tool declarations and promoted additional_tools entries by tool name with first-wins precedence so top-level tools remain authoritative over historical copies.
- Deduplicate flattened tool counts and merge repeated namespaces during folding so overlapping historical tools do not prematurely trigger namespace folding or emit duplicate dispatchers.
- Align namespace reference collection and dispatcher child unwrapping with the winning declaration to preserve response tool call restoration.
Closes: #6962
- Expose the opaque caller scope handle on request interception structs and accept it on HostModelExecutionRequest and internal model execution requests so replayed executions retain caller-scoped metadata without exposing client API keys.
- Resolve Claude MCP tool alias secrets from caller_scope metadata before falling back to hashed context API keys so plugin replays reproduce the original upstream tool names and derived session identities.
Closes: #6961
- Resolve the bound duplex turn model from request metadata (`RequestedModelMetadataKey`) before falling back to the initial payload and upstream model so request interceptors that strip or rewrite `model` do not alter per-turn authorization.
- Match explicit continuation models against the bound client model in `processCreatePayload` so continuations naming the client alias proceed in place without triggering replay.
Closes: #6952
- Defer context cancellation in TestCancelableConnClosesUnderlyingTransportWhenCloseRacesCancel to satisfy go vet lostcancel across all control flow paths.
- Remove the unused streamBridgeStream.close wrapper left behind after the closeWithError refactor in internal/pluginhost.
- Annotate shared "gin" string context keys in TestIssue6825SDKCallerReplayIsolation with nolint:staticcheck directives.
Closes: #6953
- Apply canonical thinking normalization, suffix stripping, and plugin model metadata fallback in prepareExecutorCall across Execute, ExecuteStream, and CountTokens.
- Resolve plugin-registered ThinkingApplier by provider key before format fallback and validate unknown thinking suffixes on non-native-Responses models.
- Run thinking normalization before NewPayloadFinalizer so user payload rules act as the final host-side mutation.
Closes: #6940
- Use stream-wide tool call indices in Gemini OpenAI chat response translation and preserve explicit upstream tool call IDs across stream and non-stream responses.
- Bind preceding turn thought signatures to unsigned function calls, mark completed non-stream candidate payloads as terminal, and clone request payloads before envelope mutation.
- Fall back to context API keys for reasoning replay caller isolation when explicit caller scope metadata is absent.
Closes: #6825
Map Gemini and Antigravity safety/filter/malformed finishReason values (SAFETY, RECITATION, BLOCKLIST, PROHIBITED_CONTENT, SPII, IMAGE_SAFETY, MALFORMED_RESPONSE, MALFORMED_FUNCTION_CALL) to non-normal terminal states across OpenAI Chat Completions, OpenAI Responses, and Claude translators, and ensure Gemini OpenAI streaming emits cached finish reasons even when usageMetadata arrives separately or is absent. Also surface candidate-less promptFeedback.blockReason responses in Gemini and Vertex executors as explicit 502 errors while preserving usage reporting, and enforce finishReason truncation checks for OpenAI streams.
Fixes#6906
- Reset parallel function-call group tracking in SanitizeGeminiRequestThoughtSignatures and geminiContentsThoughtSignaturesNeedSanitize when a non-thought part intervenes so the next functionCall retains its compatible signature or receives the bypass sentinel.
- Align ValidateGeminiThoughtSignatures with the same parallel-group boundary rule and add regression tests for tool calls separated by text parts.
Closes: #6911
- Populate Detail.ResponseServiceTier from usage.speed in parseClaudeUsageNode so non-streaming and streaming Claude usage records carry the billed response speed tier.
- Add regression tests verifying non-streaming usage.speed extraction and retention across message_start and message_delta stream events.
Closes: #6884
- Capture the post-translation, post-payload-rule service tier on UsageReporter and propagate EffectiveServiceTier through SDK usage records, plugin usage adapters, and Redis usage queue payloads.
- Ensure executors record translated request metadata after final payload configuration rules so server-side service_tier overrides are accurately reported alongside client and response tiers.
Closes: #6873
- Route multi-region locations us and eu to https://aiplatform.{us,eu}.rep.googleapis.com in both native Gemini and OpenAPI Vertex host builders.
- Recognize official Vertex REP domains in IsGoogleVertexHost so location rewriting and credential checks handle REP base URLs accurately.
Closes: #6867
- Pass the active configuration to ApplyClaudeLegacyDeviceHeaders under cloak_mode never while allowing plausible newer SDK and runtime versions for confirmed clients.
- Document that cloak_mode never preserves confirmed caller headers ahead of stabilize-device-profile pinning and add regression coverage.
Closes: #6863
- Map Claude model_context_window_exceeded stop reason to finish_reason length in OpenAI Chat Completions and remove the synthetic context_length_exceeded HTTP 400 error path so generated content, tool calls, and usage are preserved.
- Preserve finish_reason length when non-streaming Chat Completions responses are truncated inside a tool call by max_tokens or model_context_window_exceeded.
Closes: #6861
- Add response.metadata to isCodexBootstrapBufferableEvent so prompt-moderation metadata frames do not prematurely release uncommitted Codex streams before server_is_overloaded rejections.
- Add unit tests covering response.metadata classification and bootstrap overload failover across SSE and WebSocket transports.
Closes: #6856
- Re-run AccessManager authentication before each responses websocket turn and duplex continuation using a cloned POST request with handshake headers stripped.
- Add AuthErrorCodeDenied and NewDeniedError in sdk/access so terminal provider refusals preserve their HTTP status and stop the provider chain.
- Add DenyStatusCode and DenyMessage to pluginapi.FrontendAuthResponse and map explicit plugin denials in accessAdapter.Authenticate.
Closes: #6843
- Select the original OAuth partition for ChatGPT Alpha Search without changing SIWC Responses behavior.
- Reject missing original OAuth tokens before sending and preserve existing API-key and custom-header behavior.
- Add real-executor transport and API regression coverage for credential partition isolation.
Closes: #6830
- Honor explicit output_config.effort without thinking in Claude parsing and Codex translation.
- Preserve native Claude thinking defaults and existing budget, suffix, and payload rule priorities.
- Add regression coverage for standalone effort and finalized streaming and non-streaming requests.
Closes: #6827
- Keep stream tool indices unique and retain tool declarations when tool choice is none.
- Decouple OpenAI replay history from current tool policy while preserving context checks and caller isolation.
- Add two-turn regression coverage for signature replay, session aliases, and final payload rules.
Closes: #6825
- Treat cancellation after an emitted terminal event as successful completion while retaining observed token usage.
- Preserve buffered usage on genuine stream failures and share terminal detection with Vertex.
- Add regression coverage for terminal disconnects, EOF, usage tails, and read errors.
Closes: #6821
- Filter out empty and whitespace-only text parts in OpenAI Responses and Chat Completions to Claude request translators while preserving preceding block cache_control ordering.
- Ensure automatic and message-level cache_control injection skips empty or whitespace-only text blocks and stamps the last eligible non-empty block.
Closes: #6820
- Persist the real SIWC token expiration time from expires_in and evaluate local SIWC status using real expiration (or JWT exp) and upstream 401 rejection state without triggering network requests.
- Track SIWC token rejections independently from outer Codex OAuth refreshes, execution retries, and use_siwc toggles until the SIWC token is replaced.
- Expose the read-only v8 management SIWC status endpoint and summary field for Codex credentials.
Closes: #6819
- Add per-model and per-credential openapi and openapi-location settings across Vertex API-key configs, OAuth model aliases/settings, and service-account auth files with precedence over automatic publisher detection.
- Preserve alias-specific OpenAPI overrides across credential prefixes, thinking suffixes, and mixed model arrays while synchronizing explicit OpenAPI location overrides in full and short base URLs.
- Populate publisher ownership and default reasoning levels for Vertex OpenAPI models registered via vertex-api-key configurations.
Closes: #6763