Skip to content

Sync official CLIProxyAPI v8.1.9 and repair runtime validation - #16

Open
PinableAgents wants to merge 31 commits into
mainfrom
sync/upstream-20261201-bdf40d5214b3
Open

PinableAgents wants to merge 31 commits into
mainfrom
sync/upstream-20261201-bdf40d5214b3

Conversation

@PinableAgents

Copy link
Copy Markdown
Owner

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.

sususu98 and others added 30 commits November 28, 2026 11:04
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants