Repository navigation
Sync official CLIProxyAPI v8.1.9 and repair runtime validation - #16
Merged
Merged
Conversation
…tex (router-for-me#8576) Populate functionCall.id and functionResponse.id when translating OpenAI Chat Completions requests to Gemini so parallel calls to the same function retain 1-to-1 correlation, matching the Claude and OpenAI Responses translators. Extend StripVertexOpenAIResponsesToolCallIDsDoc to also strip tool call IDs for the openai source format on Vertex AI where REST schemas do not define an id field.
…okens (router-for-me#8577) Pass an explicit countTokens flag through Gemini/Antigravity reasoning replay preparation so models.countTokens requests with partial or isolated Content fragments (such as a single functionResponse turn for token estimation) pass original contents through instead of failing locally with HTTP 400. Skip wrapping and pairing validation when countTokens did not mutate contents, while still validating and restoring original contents if replay or normalization changed them. Regular generateContent requests keep strict ValidateGeminiFunctionCallPairing enforcement.
…ter-for-me#8578) Add translatorcommon.AlignGeminiFunctionResponses and apply it after merging adjacent user turns in the Gemini and Antigravity Claude request translators so split or out-of-order parallel tool_result blocks align to the preceding functionCall order without disturbing non-response parts. Update ValidateGeminiFunctionCallPairing to match parallel functionResponse parts 1-to-1 by id (and name) regardless of order when all pending functionCall parts carry non-empty IDs, with a zero-allocation positional fast path and strict positional validation for ID-less calls.
- Bump antigravityFallbackVersion to 2.36.0 so pre-refresh and fallback requests report the latest Hub release. - Add the verified changelist mapping for Hub 2.36.0 (cl=1031268331) so manifest lookups no longer pin back to 2.35.2. - Update version resolution and User-Agent test expectations to cover 2.36.0 and unmapped version pinning. Closes: router-for-me#8573
- Record the freshly allocated [][]byte copy in internal/translator/common/gemini.go inside reviewedInPlaceByteWrites with count 1 and its no-copy safety rationale. - Restore TestInPlaceByteWritesAreReviewed after the parallel tool-result alignment change while preserving strict count-based detection for future writes. Closes: router-for-me#8579
…keep recovery scheduled - Isolate Codex refresh HTTP transports from stale pooled connections, pin wire-tracked requests to HTTP/1.1, and classify proven zero-byte post-connect failures as retryable pre-send errors while failing closed on in-flight writes or custom TLS dialers. - Keep recoverable refresh_outcome_unknown credentials scheduled at refreshCheckInterval across both expired pre-flight and post-refresh failure paths without unscheduling superseded registrations. - Add race-verified regression tests covering stale idle connections, zero-byte and partial wire writes, custom ALPN HTTP/2 TLS dialers, in-flight write accounting, and on-demand recovery scheduling. Closes: router-for-me#8582
….36.0" This reverts commit 69db2b0. Restore the Hub 2.35.2 fallback version and changelist mapping baseline for the Hub 2.35.2 alignment changes on this branch.
…l plane, and cross-tenant isolation - Cross-tenant session/LCP affinity across model switches, cascade/parent subagent alias extraction and RESP forwarding, automatic subagent custom_agent requestType promotion, credential-scoped reasoning replay isolation, foreign thoughtSignature scrubbing on *ojson.Doc, 14-key payload order, and 270s prompt-cache keepalive guards. - Shared Google RPC array and HTTP 200 in-band error unwrapping/classification, pre-first-byte same-auth micro-retries for 14 TPU transient errors, expanded quota/billing/policy classification with strict HTTP 403/gRPC 7 TOS validation, and read-only SafetySignals logging. - 32-leg continuationToken stream resumption, dynamic deprecatedModelIds rerouting, Orchestrator model synthesis, ModelDetails capability persistence, authenticated rewriteUri grounding redirects, FULL_ELIGIBILITY_CHECK, ClaimAICodeBankedQuotaReset, and validated no-redirect dynamic endpointUrl onboarding. - PKCE S256 OAuth login, downscoped auth/aicode token minting with bounded cache, mutually verified Home RESP aicode-token handoff, grant/digest refresh continuity verification, flat v1alpha *ojson.Doc codec with GOOGLE_ONE_AI fallback experience, businessaicode parent support, and unbroken FinalizePayloadDoc semantic barrier across v1alpha, v1internal, 403 fallback, continuation, and countTokens. - Full v1alpha control-plane integration (fetchConfig with 8-group proto agySurfaceConfig, typed Mendel flags with conflict rejection, fetchLicenses, prod/preprod consistency, and 2 MiB-guarded KV snapshot publication), auto-mode Mendel routing, real-time v1alpha:fetchQuotaStatus credits refresh with read-only dark-launch shadow comparison and exact int64 comparison, and unified pure-Go Hub 2.35.2 UA + HTTP/1.1-only no-ALPN transport.
Avoid full-payload copies when evaluating payload rules and reading HTTP request bodies, cutting heap allocation amplification on multi-megabyte base64 requests by >80% with zero behavioral changes: - Evaluate single-item payload query predicates directly on ojson.Result without copying item.Raw into a temporary "[...]" buffer (with exact fallback for edge/malformed syntax). - Resolve clean array "@reverse.<N>" paths via zero-copy ForEach traversal instead of ojson.modReverse full-array cloning. - Fast-path scalar, empty-container ([] / {}), and type-mismatch checks in payloadResultEquals to skip moego/json.Unmarshal on large arrays, and use bytes.TrimSpace in normalizedPayloadJSON. - Cache compiled moego/regexp patterns in payload.replace with a bounded map. - Release originalRequest in ClaudeInputTokenState once disabled or handled, and only retain replayRequestPayload in Antigravity stream when replayScope is valid. - Preallocate raw request body buffers from Content-Length (capped at 4 MiB) in ReadRawRequestBody to avoid io.ReadAll slice-doubling copies.
…ct usage Previously, observeAndTranslateExecutorStream published final usage from the upstream observer goroutine and treated any ctx.Err() as a stream failure. When a client disconnected immediately after receiving the terminal SSE event (e.g. response.completed, message_stop, or finishReason), completed plugin streams were falsely reported as 499 failures, while non-canceled downstream flush errors were not reconciled with usage.WaitStreamDelivery. - Synchronize streamUsage/streamErr/lineBuffer with a mutex and wait for upstream observation completion (observeDone) after closing the output channel so downstream delivery acknowledgment never deadlocks. - Track terminal SSE chunk delivery across split chunk boundaries (covering Gemini, OpenAI, Responses, Claude, and Interactions events). - Reconcile usage.WaitStreamDelivery(ctx): treat post-terminal context.Canceled as success while preserving failure reporting for pre-terminal disconnects and non-canceled delivery errors. - Add unit tests covering post-terminal cancel, pre-terminal disconnect, and post-terminal delivery errors.
…s and Claude translators Preserve non-empty upstream functionCall.id values across regular and custom tool calls in ConvertGeminiResponseToOpenAIResponses (streaming and non-streaming) and across Vertex streaming, standard streaming, and non-streaming paths in ConvertGeminiResponseToClaude, synthesizing fallback IDs only when upstream omits them or disambiguation is required. Closes router-for-me#8594
…nd Claude paths Deduplicate repeated or whitespace-colliding upstream functionCall IDs within OpenAI Responses streams and non-stream responses, harden Gemini-to-Claude fallback IDs with nanosecond prefixes and unnamed-continuation ID checks, and preserve collision-free raw-to-Claude tool ID pairing when replaying OpenAI Responses history to Claude.
…skip thought parts in ID pre-scan Avoid splitting nameless non-Vertex functionCall continuation chunks into empty-name Claude tool_use blocks when an ID is present, and ignore thought parts during non-stream tool call ID reservation.
…gy CLI 1.5.18 - Unify labels.cascade_id session ID space, separate affinity-only aliases from identity-equivalent groups, align agent envelope parity before FinalizePayloadDoc, and add pre-first-byte 401 same-credential force-refresh retry-once (with Home force_refresh + rejected_aicode_token_sha256 contract) - Align Hub 2.36.0 TPU/502/400 retry rules, 240s multi-signal delay cap, 7 hard-billing reasons + HTTP 402 + daily word-boundary markers, AI_POLICY_REQUIRED diagnostics, and bounded-candidate SSEJSONAssembler - Bump Hub version floor to 2.36.0 (CL 1031268331), 256 MiB stream scanner, continuation leg 2+ parity, budget-exhausted synthetic MAX_TOKENS, usage modality merge, ModelDetails field 48 & THINKING_LEVEL_MAX, single-POST OnboardUser + LRO GET polling, and 2-pass LoadCodeAssist paidTier resolution - Harden AICode strict single-scope gate, shared grant-scoped 1h cooldown with pinned in-flight guard, 403 LOCATION_NOT_ELIGIBLE & §19.3 zero-ErrorInfo 403 fallback, 43-entry strict denial precedence, paidTier gate, FinishReason +1 shift, safetySettings proto normalization, X-Goog-User-Project omission, Home KV capability consumption, and owner/epoch-scoped KV suppression
Add the virtual copilot/auto model for accounts whose /meta default tier is enabled, resolved from account plan and published only while the entitlement remains valid. Select concrete models via /auto with scoring and RL multi-turn policies, bounded prompt history, token refresh, duplicate handling, and expiry checks before inference. Rebuild portable history across Chat, Responses, Messages, and Gemini route switches, including stored response and item continuations and Gemini tool-call ID normalization. Keep Auto state scoped by account, caller, and explicit session, and redact session and RL state tokens from logs.
Publish fusion-standard, fusion-high, and fusion-max based on the Fusion tiers enabled by /meta, instead of the single Auto model. Route balance through /auto and higher tiers through /model/fusion with validated solo, cascade, and critique plans, catalog-bounded fallbacks, and per-phase reasoning efforts. Execute draft, review, repair, and revision phases without leaking speculative output, reviewer content, or session tokens to clients. Pin tool and response continuations to the originating credential, prevent reissuing answered tool calls, apply payload rules as the final barrier on routing and inference payloads, and update the CLI identity and headers to 1.0.117. BREAKING CHANGE: copilot/auto is no longer published; use copilot/fusion-standard, copilot/fusion-high, or copilot/fusion-max instead
Cache the translated reply for each tool-result submission so retries replay identical non-streaming and streaming responses without re-running upstream inference, while failed attempts release the key and evicted replies return a conflict. Track delivered tool call IDs across all phases of a turn and reject upstream repeats of answered calls. Capture draft-only reasoning, prose, signatures, and encrypted Responses state before exposing its tool batch, then restore that private history for Chat, Responses, and Messages continuations without leaking it to clients or reviewers. Drop hardcoded temperature/top_p from fusion review requests that reasoning models may reject, and normalize line endings in embedded CLI prompts.
Fusion can select upstream models that reject explicit temperature, top_p, and top_k parameters. Strip client-provided sampling controls before payload configuration so fusion phases do not fail with invalid request errors.
Use providerKey instead of provider protocol format in thinking config logs so entries identify the actual executor, such as copilot or a configured compatibility upstream.
Snapshot and restore account catalogs and Fusion entitlements for Home dispatch, bound to the credential, trusted origin, model, and expiry. Concrete models carry only endpoint and reasoning defaults, while entitled Fusion tiers carry the ordered directory and aliases. Resolve Home routes from the restored catalog, expose the required SDK API, and pin Fusion continuations via published aliases and the Home caller scope. Replay completed draft tool exchanges to later phases, suppress repeated draft actions, and report usage for every Fusion phase, including failures, with additional-phase attribution.
Capture the frontend-authenticated caller scope at WebSocket upgrade and after each turn's authentication, restoring the upgrade scope before re-authenticating so Home's usage identity written to userApiKey cannot leak into later turns. Pass the captured scope through executor options and prefer it when deriving the Home Copilot caller scope, clearing stale metadata when the captured scope is empty. This keeps Copilot fusion tool results and previous_response_id continuations bound to the correct caller. Add regression tests for per-turn key rotation and Home WebSocket fusion continuation across WebSocket and HTTP.
Track output item IDs and resolve item_reference inputs to their owning credential, including for local OAuth model aliases, so stored Responses continuations stay pinned to the issuing account. Treat credential-status failures from Copilot route planning as credential-scoped upstream attempts and route them through the normal failure pipeline in sync, count, streaming, and Home execution, enabling cooldown and failover instead of aborting.
Use IsCredentialStatus in SelectAuto so 402 and 429 responses, alongside 401 and 403, abort selection and allow the manager to try the next credential instead of failing the request. Add regression tests for standard routing failover and for fusion re-planning on a rate-limited account, verifying that session tokens remain bound to their owning account.
feat(copilot)!: add Fusion tiers replacing the Auto model
… fixes - Batch A: fix ObserveAntigravitySafetySignals for results[]/embeddingVerdicts/numeric 2/snake_case with structured logrus fields, align used_claude_conservative OR-latch and subagent_type underscore sanitization, unify Anthropic model detection (claude/fable-/opus-/sonnet-/haiku-) across all 11 core sites with C4 linear adjacent-user merge and unified signature provider/cache group resolution, add legObservedPayload continuation retry guard, strip request.stream/snake_case/duplicate toolConfig, and cap non-2xx/unary response reads - Batch B: enforce 1 MiB OAuth refresh body cap and pre-RTT expiry, add compare-and-delete invalidateAICodeAccessToken on AICode 401 and broad refresh, harden sdk/cliproxy AICode token minter (Antigravity User-Agent, pre-RTT, non-cancelable singleflight, 400 invalid_grant AuthError, 401 retry-once, stale metadata suppression isolated from broad-bearer suppression), tighten status-code-aware NEW-06 scope gating, and pool/cache /v1internal:rewriteUri grounding URL resolution - Batch C: complete 4 hard-quota 429 substrings, 240s retry ceiling, numeric gRPC 8/14 and missing error.status handling, retry-after-ms header precedence, PayGo X-Goog-User-Project omission helper, 5 snake_case GenerationConfig aliases, BlockReason 5->6 normalization, read-only post-FinalizePayloadDoc GOOGLE_ONE_HELIUM rejection, remaining Mendel cutover flags and rate-limited sign-out-missing-aicode-scope warnings, tieredModelIds + M-04 disabled model filtering, telemetry JSON label scrubbing across all request types, shared bare-token/plt redaction, and allowlisted OAuth error parsing preserving typed 403 TOS/validation metadata - Batch D: reject empty access_token and non-positive expires_in with proxy/epoch-scoped OAuth singleflight, wire AdaptiveThinking/ThoughtCirculation/DeferredToolLoading/TieredModelIDs through sdk/cliproxy, harden credits quota admission guards, map FormatAntigravity to "antigravity" with mixed-pool LCP mirroring and dual rollback generations, upgrade signature ownership to Get() LRU recency + Home KV SSOT with millisecond PX backfill and NX lease protection, and add bounded 32-leg unary Execute continuation loop
…ents - Treat requests with non-empty X-Codex-Window-Id or X-Codex-Turn-Metadata headers as Codex clients in isCodexResponsesClientRequest so custom originators receive response.failed instead of bare error frames. - Add regression tests covering custom-originator requests with Codex headers across upstream SSE error frames and stream error channels. Closes: router-for-me#8596
…eld patch - Export file alias metadata projection and rebuild runtime model_aliases attributes in PatchAuthFileFields before committing and invoking postAuthPersistHook. - Delete stale model_aliases attributes when SetOAuthModelAliasesAttribute receives an empty alias list while preserving and restoring plugin-provided default aliases on clear. - Add unit and end-to-end regression tests covering alias addition, replacement, clearing, plugin default restoration, /v1/models, and ResolveExecutionModel. Closes: router-for-me#8601
- Add per-session and per-credential session-affinity invalidation with bounded release watermarks and cross-account history preservation across SessionCache, MerklePrefixMatcher, SessionAffinitySelector, and auth Manager. - Expose DELETE /v8/management/routing/session-affinity in a dedicated v8-only internal/api/handlers/managementv8 package supporting session_id, auth_index, and name selectors without touching /v0/management. - Document the new v8 routing endpoint in docs/management-api-v8.md and add regression tests for session migration, colon-delimited IDs, release eviction, and cross-account history. Closes: router-for-me#8593
- Filter captureClaudeUsagePlugin and captureAnyProviderUsagePlugin records by a required non-empty authID in addition to provider. - Assign t.Name() as the mock auth ID across Claude terminal, truncation, error, and cancellation stream test fixtures. - Add unit tests verifying foreign, empty-authID, and wrong-provider usage records are ignored. Closes: router-for-me#8602
…lays - Add opt-in allow-vertex-signatures (default false) to GeminiKey with v8 group inheritance, per-key override, config diff reporting, and synthesizer attribute propagation. - Select Vertex-preserving thought signature sanitization in GeminiExecutor across Execute, ExecuteStream, CountTokens, and native Interactions paths when enabled. - Add regression tests covering executor paths, legacy and v8 config decoding, synthesizer attributes, and config diffs. Closes: router-for-me#8603
…failures - Pass RefreshPreSendError errors from RefreshClaim through journalRefresh unwrapped while keeping ambiguous claim errors fail-closed as RefreshOutcomeUnknownError. - Classify definite FileRefreshJournal pre-creation and durably rolled-back sync failures as RefreshPreSendError, while failing closed on ambiguous mkdir errors or unsynced rollback deletions. - Add regression tests covering pre-send file claim recovery, fail-closed rollback and ambiguous mkdir handling, and auth manager renewal state preservation. Closes: router-for-me#8610
…xt history - Defer assistant message doc serialization in the Claude-to-Codex request translator so closing assistant text replays with phase "final_answer" while preamble text followed by additional assistant output replays with phase "commentary". - Gate inferred assistant phases to GPT/Codex targets (and unmapped aliases on the Codex path only) so generic Responses targets with unknown models and known non-GPT families remain unchanged. - Update commentary replay assertions and add regression tests for phase inference, split assistant turns, no-output tool reference blocks, and target-model gating. Closes: router-for-me#8613
Track routing attempts, retry reasons, HTTP and scores status in a new PlanLookup passed through Auto and Fusion selection, parse hydra_scores for Fusion plans, and expose drift distance instead of a boolean escalation check. Emit one redacted, ordered debug log per lookup when debug logging and a request ID are present, covering candidate/effective models, scores, drift, skip state, fallback and timing, and add tests for anchor, drift, fallback, failure, redaction and disabled cases.
…on and session ownership
…and stabilize compaction IDs
…completions
- Emit the opening tool_calls delta chunk with empty arguments on content_block_start and forward each non-empty input_json_delta fragment immediately on content_block_delta.
- Emit a fallback "{}" arguments delta on content_block_stop only when no argument fragments were streamed, and update streaming tool call unit tests accordingly.
Closes: router-for-me#8629
- Propagate callback context cancellation and callback scope closure to in-flight model stream startup before handoff while preserving post-handoff detachment semantics. - Synchronously verify callback context validity before completing stream registration so startup races cannot deliver a canceled stream. - Add deterministic regression tests for bootstrap parent cancellation, delayed cancel handoff rejection, scope closure, expired deadlines, and stream isolation. Closes: router-for-me#8624
feat(logging): add debug logs for Copilot plans and static plugins
… on compaction turns - Enable read-only Gemini reasoning replay lookups on Antigravity public compaction turns using the original session key and a compaction-scoped context hash that keeps strict toolConfig checks intact for normal Responses turns. - Align top-level additional_tools collection and allowed_tools declaration subsetting between normal and compaction turns while forcing toolConfig mode to NONE before payload finalization. - Add end-to-end and unit regression tests covering tool declaration parity, allowed_tools subsetting, read-only replay isolation, and normal-turn tool-policy rejection. Closes: router-for-me#8619
…rable thought-signature-ttl - Scrub unverified or expired thought signatures across contents, system instructions, and post-replay payloads before finalization while preserving post-finalize ownership verification. - Add global server.kv-store.thought-signature-ttl configuration (default 168h, whole-second precision) wired into startup, hot-reload, signature cache, and ownership leases. - Add regression tests covering /v1/responses resumption, replay-hit expiration, systemInstruction scrubbing, and TTL validation and enforcement. Closes: router-for-me#8646
… prefix
- Add opt-in cloak entrypoint ("cli" or "sdk-cli") across upstream.claude.cloak, per-key cloak config, and auth metadata, keeping identity text, cc_entrypoint billing tag, User-Agent suffix, and entrypoint-specific Anthropic-Beta headers aligned while preserving existing defaults.
- Add optional cloak system-prompt-prefix (inline or trusted local config file with regular-file and 1 MiB bounded-read checks) inserted after the billing and identity system blocks on cloaked Claude requests.
- Add unit and regression tests covering config normalization, diff reporting, bounded prefix loading, header/body coherence, payload barrier ordering, and security boundaries.
Closes: router-for-me#8647
- Add routing.session-affinity-rebind-on-models configuration and canonical model normalization so selected models enforce rebind-never pinning while unlisted models follow global session-affinity-rebind-on. - Update session affinity selector, execution/home failover paths, Antigravity explicit/LCP namespace isolation, and keepalive lookups to evaluate rebind-never per model without cross-model binding overwrite. - Apply session-affinity-rebind-on-models hot-reloads in place to preserve active session bindings and add unit, reload, and end-to-end regression tests. Closes: router-for-me#8606
Update question and response shapes to match the real decisions API and verify payload override and replace rules on nested question fields instead of synthetic top-level fields
Remove the CopilotEndpoint confirmation field from ModelInfo and Home dispatch, deriving Decisions access from the static compatibility profile and account-advertised endpoints instead. Strip Decisions explicitly in Auto and Fusion routes so fixed models can use it while chat routes cannot. Add non-streaming keepalive and JSON content type to the Decisions handler to keep long-running requests alive.
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.
Merge official v8.1.9 (bdf40d5) with Pinable runtime changes preserved. Extract existing Antigravity wire helpers into a protocol-neutral package without changing the Interactions architecture-boundary test. Use native Visual Studio 2026 hosted images; Windows smoke locates actual target cl.exe and still builds, verifies and loads the trusted fixture DLL. Run the six-platform verify-only workflow on the PR and only publish after the verified main push.
Validation: local server build and 62 Python runtime/sync tests passed. Full native CI required: the managed Linux sandbox denies netlink route enumeration in Pion WebRTC tests. Merge with a merge commit only, preserving upstream history; do not merge before full validation.