Commit Graph

1304 Commits

Author SHA1 Message Date
sususu
58a4d04f32 fix(signature): recognize Vertex bare-Tink Gemini thought signatures
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
2026-10-26 23:33:12 +08:00
Luis Pater
aa4130e64c fix(gemini): keep truncated HTTP 200 streams out of credential cooldown and failover
- 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
2026-10-26 21:07:08 +08:00
Luis Pater
1d45a5f332 fix(claude): handle forced tool restrictions in claude 5.5
- 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
2026-10-26 20:36:51 +08:00
Luis Pater
ede07cafa6 fix(interactions): emit [DONE] sentinel after terminal usage frame in Antigravity and Gemini streams
- 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
2026-10-26 18:40:53 +08:00
Luis Pater
531721bfce fix(codex): restore Codex commentary history via internal thinking signature marker
- 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
2026-10-26 15:58:41 +08:00
Luis Pater
064e008b07 feat(codex): add full-chain compression for Codex upstream and downstream traffic
- 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
2026-10-26 10:09:56 +08:00
Luis Pater
e5321f535c fix(auth,pluginapi,usage): share per-selection ID between Scheduler.Pick and UsageRecord
- 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
2026-10-26 03:25:42 +08:00
Luis Pater
307803510b fix(aistudio): translate every SSE frame of a relay stream chunk
- 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
2026-10-25 22:45:00 +08:00
Luis Pater
84e8344147 test(executor): fix race conditions in flaky websocket executor tests
- 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
2026-10-25 22:34:48 +08:00
Luis Pater
3dae075de2 feat(devin): aggregate swe-2 lightning UIDs into swe-2-lightning model
- 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
2026-10-25 22:17:43 +08:00
Supra4E8C
ba06ec58a1 fix(vertex): default credential location to global 2026-10-25 21:36:40 +08:00
Luis Pater
0c61b12cf2 fix(xai): deduplicate tools when promoting historical additional_tools
- 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
2026-10-25 11:39:33 +08:00
Luis Pater
e48d780f9b fix(plugin): preserve caller scope for replayed Claude OAuth MCP tool aliases
- 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
2026-10-25 11:35:02 +08:00
Luis Pater
6340fe4312 fix(codex): bind duplex websocket turns to requested client model after interceptor rewrites
- 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
2026-10-25 02:11:02 +08:00
Luis Pater
2bb6ac6faa fix(lint): resolve go vet lostcancel and static analysis warnings from v8.0.42
- 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
2026-10-25 02:10:05 +08:00
Luis Pater
c9af5290a6 fix(pluginhost): run canonical thinking pipeline before plugin execution
- 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
2026-10-24 21:38:42 +08:00
Luis Pater
da21f1e58e fix(antigravity): restore non-stream tool signatures and preserve stream call indices
- 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
2026-10-24 20:42:16 +08:00
sususu
ab139b4505 fix(kimi): share thinking replay across K3.1 Pro variants 2026-10-24 14:43:50 +08:00
Luis Pater
8289ec4c71 fix(usage): preserve interactions token semantics when merging stream usage
- Preserve separate-reasoning and subset token breakdown semantics in MergeStreamUsageDetail instead of unconditionally rebuilding merged stream usage with independent cache and inclusive reasoning rules.
- Add regression tests covering cumulative, identical, and partial Interactions stream usage merges as well as end-to-end plugin executor stream usage reporting.

Closes: #6925
2026-10-24 02:18:56 +08:00
Luis Pater
3f5d3a161b fix(gemini/vertex): preserve non-content finish reasons and surface prompt blocks
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
2026-10-23 18:03:10 +08:00
Luis Pater
e5434f65c8 fix(signature): sign the first Gemini function call after a text part
- 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
2026-10-23 17:04:24 +08:00
Luis Pater
d946c4fba6 feat(codex): ignore use_siwc and enforce non-SIWC credentials for Codex client requests
- Add request-aware helper functions (`IsCodexClientRequest`, `IsCodexUseSIWCForRequest`, `codexCredsForRequest`, etc.) to detect Codex client user agents and bypass `use_siwc` settings accordingly.
- Update Codex HTTP, streaming, WebSocket, and conductor execution flows to evaluate credentials and routing rules against the incoming request context and headers.
- Add comprehensive regression tests (`TestCodexExecutorCodexClientIgnoresUseSIWC`) covering client identification, credential isolation, default URL resolution, and WebSocket session reuse.

Closes: #6833
2026-10-23 08:09:28 +08:00
Luis Pater
b90190dbaa fix(usage): propagate claude usage.speed into response service tier
- 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
2026-10-23 01:07:20 +08:00
Luis Pater
07b5a7a1ca feat(usage): report effective outbound service tier after payload rules
- 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
2026-10-22 21:05:27 +08:00
Luis Pater
88732ad574 fix(vertex): use regional endpoint hosts for multi-region us and eu locations
- 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
2026-10-22 19:26:31 +08:00
Luis Pater
d2e61d19b5 fix(claude): validate cloak_mode never headers against configured defaults
- 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
2026-10-22 18:33:39 +08:00
Luis Pater
c2dfec28d5 fix(claude): map model_context_window_exceeded to length in chat completions
- 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
2026-10-22 17:21:21 +08:00
Luis Pater
9e79552fb7 fix(codex): hold response.metadata during stream bootstrap buffering
- 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
2026-10-22 11:55:16 +08:00
Luis Pater
b9bb031dcb fix(openai): reauthorize responses websocket turns and support denied status
- 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
2026-10-22 03:41:06 +08:00
Luis Pater
0db1902557 fix(codex): use original oauth credentials for alpha search
- 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
2026-10-21 23:04:23 +08:00
Luis Pater
009f8d7ae3 fix(thinking): preserve standalone Claude effort on Codex requests
- 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
2026-10-21 20:19:05 +08:00
Luis Pater
80aa2b1d17 fix(antigravity): preserve tool call replay continuity and caller isolation
- 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
2026-10-21 18:16:58 +08:00
Luis Pater
b12db8c3d8 fix(gemini): preserve usage after terminal stream cancellation
- 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
2026-10-21 10:33:05 +08:00
Luis Pater
df07b1e598 fix(claude): drop empty text blocks and skip them during cache_control injection
- 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
2026-10-21 08:44:10 +08:00
Luis Pater
06fd5b8bc2 feat(management): add read-only SIWC credential status endpoint
- 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
2026-10-21 08:07:38 +08:00
Luis Pater
d44f8682bc feat(vertex): support per-model and per-credential openapi routing settings
- 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
2026-10-21 02:19:42 +08:00
Luis Pater
20c9095cac fix(claude): treat sdk-ts as native Claude Code and preserve caller headers under cloak_mode never
- Allowlist the sdk-ts Agent SDK entrypoint and recognize its measured Haiku 5.5 helper requests so genuine Claude Code traffic passes through uncloaked.
- Preserve plausible newer Stainless SDK and runtime versions for confirmed clients and retain confirmed-shape caller headers when cloak_mode is never.
- Recognize the Agent SDK CLI identity prompt block alongside existing Claude Code identity strings.

Closes: #6812
2026-10-21 01:11:27 +08:00
Luis Pater
3870639096 fix(translator): preserve gemini thought signatures across openai chat translations
- Map Gemini functionCall thoughtSignature fields to OpenAI tool_calls extra_content.google.thought_signature when translating Gemini requests to OpenAI chat completions.
- Restore OpenAI tool_calls thought signatures onto Gemini functionCall parts across both non-streaming and streaming response translations while preserving deterministic tool call ordering.

Closes: #6807
2026-10-21 00:29:47 +08:00
Luis Pater
cddc9bb814 fix(claude): scope web search result cache by upstream credential
- Include a hash of the selected upstream credential identity in claudeWebSearchResultCacheScope so cached encrypted_content is only restored for the credential that produced it.
- Pass auth into web search result cache scope resolution across Execute, ExecuteStream, and CountTokens paths and add regression coverage for credential switching.

Closes: #6810
2026-10-21 00:23:55 +08:00
Luis Pater
aadb34f916 fix(claude): map refusal, context window and pause_turn stop reasons; honor parallel_tool_calls
- Map Claude refusal, model_context_window_exceeded, and pause_turn stop reasons across OpenAI Responses and Chat Completions translators, executors, and streaming handlers.
- Preserve paused server-side web search turns on continuation and map OpenAI Responses parallel_tool_calls=false to Claude tool_choice.disable_parallel_tool_use=true.

Closes: #6800
2026-10-20 23:42:36 +08:00
Dylan
02e9e85204 fix(antigravity): align Hub requests and invalidate versioned model caches
Include the captured client User-Agent in model capability cache and backoff
keys, discard obsolete publications, and cancel stale probes on refresh.

Use release-specific Hub changelists and the daily loadCodeAssist endpoint
for project discovery and credits queries.

Refs #6619
2026-10-20 18:46:02 +08:00
Dylan
c6447551e7 Merge pull request #6794 from router-for-me/fix/meta-stream-ttft
fix(meta): measure streaming TTFT on effective token frames
2026-10-20 17:35:33 +08:00
Dylan
f434192a68 fix(executor): count completed reasoning items toward TTFT
Responses reasoning emitted only in response.output_item.done was ignored
until a later token or terminal event. Count non-empty summary and content
text in the shared classifier while excluding empty and encrypted-only
items.

Add deterministic coverage for Meta Responses and Claude downstreams,
classification boundaries, and preservation of an earlier token time.
Refresh the bootstrap-buffering comment to match the shared helper.

Refs #6664
2026-10-20 17:17:41 +08:00
Luis Pater
5026f36531 feat(executor): pass through downstream User-Agent and set default xAI User-Agent
- Forward downstream User-Agent headers in xAI non-CLI-proxy and WebSocket requests with fallback to the Grok workspace User-Agent instead of Go's default HTTP client User-Agent.
- Forward downstream User-Agent headers in OpenAI-compatible requests while retaining cli-proxy-openai-compat as the fallback and preserving custom header overrides.

Closes: #6791
2026-10-20 17:05:03 +08:00
Dylan
9d463e39f0 fix(meta): measure streaming TTFT on effective token frames
Meta streaming armed protocol-aware TTFT tracking but never observed token
events, so usage records kept the first-body-byte fallback even when
substantive output arrived later. Observe Responses events before failure
publication and translation using the existing shared helper.

Add deterministic virtual-clock coverage for content, terminal events,
error fallbacks, downstream translation, and non-streaming timing.

Fixes #6664
2026-10-20 16:57:14 +08:00
sususu
e198f3cd4c fix(usage): parse flat reasoning_tokens dialect in OpenAI-compat usage (SGLang)
SGLang's OpenAI-compatible server emits reasoning tokens flat on the
usage object instead of nesting them in completion_tokens_details /
output_tokens_details, so the keeper recorded reasoning_tokens=0 for
affected upstreams. Add a third fallback plus bucket detection for the
flat key; regression included.

Fixes #6792
2026-10-20 12:25:57 +08:00
Luis Pater
344e0ef929 feat(executor): support Codex remote-compaction v2 on Kimi and Meta Responses routes
- Intercept compaction_trigger items on Kimi and Meta OpenAI Responses execution paths to synthesize sealed CPA compaction capsules and reject incomplete upstream summaries.
- Expand replayed CPA compaction capsules into developer context messages and drop foreign compaction items across Kimi and Meta execution and token-counting paths.

Closes: #6781
2026-10-19 22:07:14 +08:00
Luis Pater
ab9c06b42e feat(cache): add Home KV support to Claude web search result cache
- Store and retrieve cached Claude web search results via Home KV with sliding TTL expiration when Home mode is enabled.
- Propagate request context through Claude web search result recording and restoration helpers in execution and token-counting paths.

Closes: #6780
2026-10-19 21:57:53 +08:00
Luis Pater
e7d4c7316f fix(codex): reconcile replayed web_search_call history with tool declarations
- Inject a web_search tool declaration for standard Codex requests when input replays web_search_call items without a web_search tool so upstream response protection remains available during compaction.
- Strip replayed web_search_call items from Responses Lite requests where top-level hosted tool declarations are omitted.

Closes: #6770
2026-10-19 19:00:41 +08:00
Luis Pater
084b9ca717 feat(claude): strip Claude Code identity on API keys with cloak mode never or uncloak
- Strip incoming Claude Code billing attribution, CLI identity system blocks, metadata user IDs, and diagnostics when a non-CLI API key explicitly configures cloak mode as never or uncloak.
- Remove Claude Code CLI headers, beta flags, and user-agent strings on uncloaked API key requests while preserving capability betas and credential header overrides.
- Keep global disable-claude-cloak-mode passthrough behavior unchanged for credentials without explicit per-key cloak configuration.

Closes: #6762
2026-10-19 12:59:13 +08:00