chore(upstream-sync): merge upstream v7.2.105 - #156
Merged
Conversation
Add name and auth_index filtering to the auth-files management API and allow status updates to verify auth_index before mutating an auth entry. This lets downstream tools target one auth file without fetching the entire list, and avoids toggling a same-name auth when an auth_index snapshot is available.
- Replaced per-item `sjson.SetRawBytes(out, "input.-1"/"messages.-1", ...)` appends, which reparsed and rewrote the growing output document on every conversation item, causing O(n^2) work on long histories. - Applied the same approach to both interactions translation directions and the OpenAI Responses to Chat Completions path.
… pass - Replaced per-item `sjson.SetRawBytes(out, "system.-1"/"messages.-1", ...)` appends, which reparsed and rewrote the growing output document on every conversation item, causing O(n^2) work on long histories. - Collected system and message blocks into slices and wrote each array once via `common.JoinRawArray`, moving the cache_control post-processing and system-only fallback turn onto the collected slices.
- Introduced dedicated plugin sync operation timeout (`homePluginSyncOperationTimeout`) for improved task handling. - Added `cloneRedisOptions` function to safely duplicate Redis options and prevent mutation. - Modified plugin sync to use a dedicated Redis client with independent configurations. - Enhanced `GetPluginSync` logic to handle cancellation, timeouts, and TLS handshake gracefully. - Expanded unit tests to validate new Redis client behavior, plugin sync timeouts, and cancellation handling.
- Modified `CredentialFileName` to incorporate `hashAccountID` for better disambiguation when available. - Updated fallback behavior to maintain compatibility with legacy email-based filenames. - Refined test suite to validate scenarios with and without account hash and plan type. Closes: #4425
…and enhance model availability logic - Implemented logic to differentiate between generic and explicit model-not-found errors for the `count_tokens` endpoint. - Introduced `recordAvailabilityNeutralResult` to ensure models remain active for generic endpoint errors. - Expanded test coverage to verify behavior for various 404 scenarios, including error propagation and model suspension handling. - Refactored error-parsing utilities to identify structured and nested model-not-found errors. Closes: #4410
perf(translator): build input and messages arrays in a single pass
…on-fix perf(translator): 降低 Claude → Codex 请求转换的内存分配
…across large histories
…wArray` with `SetRawArrayItems` methods
…I requests - Added `promoteXAIAdditionalTools` to normalize and migrate `additional_tools` to the top-level `tools` array in XAI request bodies. - Updated test cases to validate the promotion logic and ensure unsupported `additional_tools` items are excluded from input payloads. Closes: #4434
…ation - Refactored state management to introduce deterministic output indexing for reasoning, messages, and function calls. - Added new structures `MessageItems` and `ReasoningItems` to aggregate responses with consistent indices. - Updated OpenAI response generation to include `output_index` for all outputs, ensuring correct order and no gaps. - Enhanced tests to validate contiguous output indices and response event lifecycle. Fixed: #4429
… JSON structure - Added conditional logic to append `content_block_start` for empty responses, ensuring correct event flow. - Updated default `responseJSON` structure to use an empty array (`[]`) for the `content` field instead of `null`. Fixed: #4431
…ponse handling - Updated `ConvertOpenAIResponsesRequestToOpenAIChatCompletions` to include namespaces when generating function names for tool calls. - Added test case to validate namespace qualification logic for function call histories. Fixed: #4423
… type - Added `NormalizeOpenAIFileData` utility to parse and validate file content, ensuring proper MIME type handling and base64 extraction. - Refactored translation logic to use normalized file data for Gemini, Antigravity, and Interactions processors. - Introduced comprehensive unit tests for both valid and invalid file data scenarios across all translators. Fixed: #4416
… Codex input processing - Updated `SanitizeCodexInputItemIDs` to remove encrypted reasoning items with IDs exceeding the Codex length limit. - Refactored logic to deterministically shorten other overlong input item IDs, ensuring compliance with the Codex format. - Added new tests to verify dropping behavior for encrypted reasoning and shortening of lengthy IDs without encrypted content.
… payloads - Introduced field normalization functions (`setCodexRequiredBool`, `setCodexRequiredInclude`) to ensure correct Codex input structure. - Added tests for normalized payload reuse and field validation in `ConvertOpenAIResponsesRequestToCodex`. - Implemented `deleteCodexRequestFields` utility to remove unsupported fields dynamically. - Added benchmarks for normalized payload processing to measure performance across different payload sizes. Closes: #4362
…across translators - Added tests to ensure no-copy payload reuse for various translators (Codex, Gemini, OpenAI, Claude, etc.). - Covered scenarios for field normalization, tool parameter cleaning, and thought signature sanitization. - Included a benchmark for SanitizeGeminiRequestThoughtSignatures with large normalized payloads.
…onditional payload updates - Introduced `SetStringIfDifferent`, `SetBoolIfDifferent`, and similar helpers in `payload_helpers` to avoid unnecessary writes during JSON modifications. - Simplified message patching in `kimi_executor` for reasoning and tool call adjustments. - Updated all executors (Gemini, Codex, XAI, Antigravity, etc.) to use the new helpers, enhancing readability and potentially reducing overhead. - Removed obsolete `filterKimiEmptyAssistantMessages` function in `kimi_executor`.
…g without data duplication - Added `GetGJSONBytesNoCopy` in `internal/util` for safe, no-copy JSON parse operations leveraging `unsafe`. - Replaced `gjson.GetBytes` with the new helper in key payload processing paths (`kimi_executor`, `vertex_payload_helpers`, etc.) to improve performance. - Added unit tests for behavior validation, including edge cases with empty input.
…ent models - Deleted unused `instructions_variables` and `approvals` fields from `codex_client_models.json`.
…#4444) Preserve Codex and XAI upstream message-too-big closes across the Responses WebSocket boundary while treating them as request-scoped errors. Prevent CPA reconnect and credential cooldown/fallback, scope close state to the active connection, retain terminal errors under backpressure, and ensure downstream disconnect cleanup cannot wait behind a blocked writer.
…onciliation - Implemented tests for scenarios involving incomplete, conflicting, and reconciled tool calls in response payloads. - Enhanced coverage for `restoreResponsesWebsocketCompletionOutput` and `responseCompletedOutputFromPayload` logic. - Refactored `isCompleteResponsesWebsocketToolCall` to validate string fields in tool calls. - Improved caching behavior to skip incomplete tool calls and ensure reconciliation logic aligns with expected outputs. Closes: #4447
- Replaced references to K2.6 with K3 across README files (EN, CN, JA). - Highlighted Kimi K3's capabilities as the world's first open 3T-class model, including 2.8T parameters, native vision, and enhanced context window (1M tokens). - Updated quickstart links and clarified CLIProxyAPI support information.
…#4599)
Since #4525 a Claude Code session against Antigravity Gemini could die
permanently with HTTP 400 "missing Claude tool provenance". The reserved
cpa_gemini_<digest> IDs live in the client transcript forever, so once the
replay ledger cannot resolve them every later request fails the same way and
the request never reaches upstream.
Live testing against gemini-3.6-flash-high confirmed four independent ways the
ledger lookup breaks, all producing the same 400:
A contents mutated earlier in the history -> contextHash rejects an exact
opaque-ID match, so proven identity is discarded along with the signature
B one extra system block -> the session key embeds the
system lane, so the whole ledger bucket switches and comes back empty
C process restart or TTL expiry -> empty bucket
D one mid-stream client abort -> that turn never commits
D needs nothing but a single interrupted stream and kills the session from its
very first tool turn, which matches the reported symptom most closely. Parallel
tool calls are not the trigger; they only lengthen the history.
Split tool identity recovery from context-bound signature replay:
- antigravityFunctionCallProvenanceLocation resolves a call when the payload ID
equals the opaque digest derived from a ledger item. That digest is
sha256(call_id, name, args), so an exact match already proves the identity and
the context hash adds nothing to it. Such a call is restored to its native
id/name/args with its paired functionResponse, but deliberately stays
unsigned - the cached signature belongs to a different history.
- Unresolved reserved IDs are now rewritten to deterministic neutral IDs rather
than aborting the request. Pairing is preserved, untrusted signatures are
dropped, and only genuinely malformed histories still error.
- antigravityRepairUnsignedFirstFunctionCalls re-asserts the leading-call
signature invariant after replay, because the request-level sanitizer runs
before it. Native signatures are never touched.
Also fixes a corruption the fail-closed check was masking: when a client changed
a call's arguments, replay inserted a duplicate native functionCall next to the
mutated one, leaving more calls than responses.
Adds forensic debug logging (hashed session keys and counts only) that
distinguishes a ledger miss from a context-hash rejection.
Verified live: happy path unchanged over 20 upstream requests and 100 parallel
call groups (0 residual reserved IDs, every group 1 native-signed + 4 unsigned);
all four failure modes now return 200; and a session survives a mid-stream abort
plus 5 further requests that previously died.
Reasoning replay treated a changed history as proof that a cached thought signature had become invalid, so a drifted context or a ledger miss dropped the signature and left the call on the bypass sentinel. Once that happened the damage cascaded: every later ledger item verifies its contextHash against the restored bytes of all preceding contents, so one broken link cost the whole tail of the conversation its reasoning. Testing the assumption directly against daily-cloudcode-pa.googleapis.com shows it does not hold. Gemini validates a thought signature's own integrity and nothing else -- corrupting one byte returns "Corrupted thought signature", while changing the system instruction, adding a tool, rewriting an earlier call's args, rewriting a tool result, or swapping two turns' signatures are all accepted. Only the newest functionCall group has to carry a signature at all, and the bypass sentinel satisfies that. Keeping the signature is worth doing rather than merely harmless: on an otherwise identical request, replacing every signature with the sentinel raises thoughtsTokenCount from 11-15 to 41-53, so a broken chain makes the model re-reason from scratch. Restore the signature on the identity-only path, and stop deleting the client's in-band signature while degrading unresolved provenance IDs. Argument integrity is unaffected: that is the opaque digest ID's job, not the signature's.
A cached text signature is pinned to its part by that part's own content fingerprint. Gemini validates a signature's own integrity and never its binding to the surrounding history, so drift elsewhere in the conversation cannot invalidate it. Gating the fingerprinted lookup on the context hash only discarded reasoning the model then had to redo. The legacy positional fallback has no such proof and stays gated.
feat(home): enhance membership protocol handling
…dation fix(antigravity): stop killing sessions on unresolved tool provenance (#4599)
…eight validation - Added support for weighted round-robin authentication scheduling strategy. - Implemented credential weight validation for attributes and metadata, with strict error handling for invalid weights. - Enhanced scheduler with smooth weighted state handling and proportional selection logic. - Introduced tests for credential weight parsing, validation, and weighted round-robin behavior. - Updated configuration to include `weight` field for credentials with range validation. Closes: #4470
- Added `ClientRequestMetadata` struct to capture client IP, `X-Forwarded-For` headers, and user agent. - Implemented metadata extraction in HTTP handlers and propagation through context. - Updated Redis queue plugin to include client request metadata in payloads. - Added tests to validate metadata extraction and inclusion in request contexts.
…r-v2 fix(claude): align headers with upstream streaming / 修复 Claude 请求头与上游流式模式不一致
…and-swap
Client.KVCompareAndSwap sent Redis EVAL with a Lua script, but the Home RESP
subset does not implement EVAL, so Home replied "ERR unknown command 'eval'".
That broke the Antigravity and Codex reasoning replay caches in Home mode.
Switch the transport to Home's dedicated CAS command:
CAS <key> <expected-exists 0|1> <expected-value> <new-value> [PX <ttl-ms>]
The semantics match the old script argument for argument, so KVCompareAndSwap's
signature and all its callers are unchanged. Omitting PX when ttl <= 0 mirrors
the script's SET-without-PX branch, which clears the TTL.
Deployments that predate CAS reject the command. Detect that by matching the
unsupported-command error, latch ErrCompareAndSwapUnsupported for the client
lifetime so later calls skip the round trip, and warn exactly once. The latch is
deliberately not carried across NewLifetime, so a Home upgrade takes effect on
the next reconnect rather than requiring a CPA restart.
Also stop replay-state failures from failing the request. A bare replay error has
no HTTP status, so resultErrorFromError does not classify it as request-scoped and
MarkResult marks the credential unavailable for that model, walking every
candidate credential until alias resolution has nothing left and returns 503. A
ledger miss is already a tolerated outcome, so degrade to "no replay this turn"
instead. The pairing failure still returns its 400.
Verified end to end against a real Home over RESP/mTLS on PostgreSQL with
Antigravity OAuth credentials: patched Home recreates the replay row through CAS
with its TTL, while a pre-CAS Home latches once, keeps returning 200 instead of
503, and records no credential error attributable to the replay path.
Refs router-for-me/CLIProxyAPIHome#79
fix(home): use Home's CAS command instead of EVAL for replay compare-and-swap
…ApplyRequestThinking` - Replaced instances of `thinking.ApplyThinking` with `helps.ApplyRequestThinking` across all executors for consistency. - Updated `applyGeminiInteractionsThinking` to accept `cliproxyexecutor.Request` and `Options`. - Centralized logic for request thinking application to `helps` package for improved maintainability. Closes: #4618
- Deleted the `gemini-3.5-flash-lite` model specification from `models.json`. Closes: #4636
… and response formatting - Introduced `CleanJSONSchemaForAntigravityResponse` to process schemas without adding tool-specific placeholders. - Updated `cleanJSONSchema` with `removeGeminiMetadata` parameter for improved schema control. - Refactored Antigravity schema sanitization to handle declaration and generation paths independently. - Mapped OpenAI `response_format` to Antigravity settings, ensuring proper response schema cleaning. - Expanded tests to verify proper placeholder-free response schema handling and metadata preservation. Closes: #4652
…etails - Updated `OpenAIUsage` to include `cachedCreationTokens` for improved token tracking. - Adjusted token calculations and usage mapping to incorporate `cachedCreationTokens`. - Expanded tests to verify inclusion of `cachedCreationTokens` in usage details.
…se conversion - Replaced `pendingCodexFunctionCall` with `codexFunctionCallStream` for enhanced function call tracking. - Introduced `DeferredStreamEvents` to handle deferred event processing. - Simplified and standardized codex function call state management with consolidated methods. - Enhanced reasoning and thinking block handling to ensure proper closure and new block initiation. - Removed redundant methods, improving maintainability. Closes: #4655
…nversion - Added logic to merge consecutive tool responses into a single user message for better grouping. - Updated `ConvertOpenAIRequestToClaude` to track previous roles and adjust message blocks accordingly. - Introduced a comprehensive test to validate tool result grouping behavior and content preservation. Closes: #4656
This was referenced Jul 29, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
4a2eb54dc6bf943196be4fb515e6a9407a4db143cache_controlfor Kimi execute, stream, and token-count requestsValidation
go test -count=1 ./...: passedSupersedes blocked upstream-sync issues #137, #138, #140, #142, #148, #150, #151, #153, #154, and #155. These will be closed after release verification.