Commit Graph

123 Commits

Author SHA1 Message Date
Luis Pater
e0b4956242 fix(openai): ensure Responses usage includes token detail fields
- add shared `EnsureResponsesUsageDetails` helper to patch `usage` objects with:
  - `output_tokens_details.reasoning_tokens = 0`
  - `input_tokens_details.cached_tokens = 0`
  - for both plain JSON and SSE `data:` frames, including multi-line frames
- apply the helper to OpenAI Response format outputs in non-stream and stream paths across executors/plugins so translated payloads consistently include required usage details
- update websocket/completion payload builders to emit default `usage` detail fields for prewarm/finish responses

Closes: #4985
2026-08-15 15:00:19 +08:00
Luis Pater
ac82bedfaf fix(claude): add Anthropic unified rate-limit parsing helpers
- Add new Claude rate-limit helper utilities to detect unified header-based quota rejections (5h/7d), handling case-insensitive headers and missing canonical forms.
- Compute deterministic retry duration from `Retry-After` and header reset timestamps, preferring the longest applicable unified window so cooldowns can be applied consistently.
- Introduce reusable rate-limit classification logic to distinguish header-authoritative rejections from request-scoped errors (e.g. fast-mode entitlement failures) for correct credential/model cooldown behavior.

Closes: #4874
2026-08-15 14:08:16 +08:00
sususu
bdde638c27 fix(claude): pass through caller MCP tools on alias server collision
The word-based virtual server spans only ~2048^2 names, and plausible
real MCP server names such as file_system or web_search are valid BIP-39
word pairs. When a caller's own server matched the derived one, its tools
stopped passing through and entered alias recovery instead: they were
silently restored to an unrelated proxied tool, or failed the request
with a 500 when no semantic suffix matched.

Record untouched caller MCP tool names as identity entries in the reverse
map, skip those entries when collecting virtual servers and recovery
candidates, and forward them unchanged on an exact hit. Recording is
skipped when nothing was aliased, so an untouched request still keeps an
empty reverse map and a no-op restore path.

Also warn instead of silently forwarding an original name when the alias
space is exhausted, report an empty embedded wordlist, trace the
semantic-suffix fallback because it guesses rather than fails, and build
both alias entry points through one shared constructor so the exhaustion
tests cannot drift away from the production path.

Refs #4916
2026-08-14 22:45:09 +08:00
sususu
f6f03e4de9 fix(claude): use BIP-39 words for OAuth MCP tool aliases
Replace high-entropy Base32 alias IDs with request-local BIP-39 English
words so weaker models are less likely to drift tool names. Keep a
two-word virtual server plus one-word tool ID, linearly probe wordlist
space on collision without self-overlap, and fall through to unambiguous
longest semantic-suffix recovery after a successful but wrong parse.

Fixes #4916
2026-08-14 22:45:09 +08:00
Luis Pater
7cf92793c1 fix(gemini): skip zero-token usage placeholders and always finalize stream reporters
- Add `defer reporter.EnsurePublished(ctx)` to Gemini, Gemini Vertex, and AI Studio streaming goroutines so stream reporting is always finalized on exit.
- Update Gemini usage parsing to reject all-zero `usageMetadata` frames, preventing placeholder usage events from being accepted.

Closes: #4964
2026-08-14 22:38:56 +08:00
Luis Pater
b08fe3b492 fix(codex): preserve multi-agent-v2 namespace handling across incremental websocket turns
Closes: #4909
2026-08-12 15:04:17 +08:00
Luis Pater
db143aebac fix(codex): make input ID sanitization collision-resistant and deterministic
- Track normalized ID state (`occupied`/`preserved`) during preprocessing to avoid remapping valid existing IDs.
- Resolve collisions by appending deterministic hash-based suffixes until a free ID is found.
- Share occupancy tracking across shortening and remapping so sanitized IDs remain stable and idempotent.

Closes: #4891
2026-08-12 01:04:22 +08:00
sususu
a8bbbea2b9 fix(claude): recognize and pass through native Haiku helpers
Claude Code issues measured Haiku helper requests that intentionally omit the
claude-code beta and, for the minimal shape, the system field. Treat those
profiles as confirmed native clients so CPA does not cloak or rewrite them.

Accept the native metadata builder optional parent_session_id, require
platform headers only for presence and software baseline rather than exact
equality, derive timeout and version from the same header defaults the emitter
uses, and keep discriminating signals strict: exact beta allowlist, body
shape, lowercase hex CCH, and session binding. Preserve helper transport
headers, omit synthetic stream false on markerless helpers, and gate the
billing and CCH fallback on system presence so a later pipeline-attached system
prompt cannot go upstream unsigned while the measured no-system wire stays
intact.
2026-08-11 19:33:40 +08:00
sususu
516ec3a000 fix(antigravity): harden per-credential transport pooling
Review and live-test follow-ups to the shared upstream transport.

Bound the cache with an LRU that closes idle connections on eviction, so
rotating a credential's proxy or supplying a per-request base transport can
no longer leak pools.

Stop deriving a pool scope from Auth.Label: it is documented as an optional
human readable label for logging and carries no uniqueness guarantee, so two
OAuth identities sharing a label would share one TCP/TLS pool. Prefer a
refresh-token digest, which stays stable across access-token rotation and is
available to refresh requests that run before any access token exists.

Replace a typed-nil *http.Transport taken from the request context. It passes
the interface nil check, so leaving it in place made http.Client fall back to
http.DefaultTransport, which advertises h2 over ALPN and breaks the
HTTP/1.1-only fingerprint.

Only widen pool limits: treat MaxIdleConns == 0 and IdleConnTimeout == 0 as
unlimited, and leave a negative MaxIdleConnsPerHost alone because that is how
an operator disables pooling.

Size the cache for large deployments. An unused entry costs under 1 KB and no
goroutines, whereas evicting a live pool forces a fresh TCP + TLS handshake,
so capacity is not the lever for bounding memory.
2026-08-11 18:33:50 +08:00
sususu
c33a33e14a perf(antigravity): reuse native upstream connections 2026-08-11 18:33:50 +08:00
sususu
5fa66293db fix(antigravity): preserve request plugin hook semantics 2026-08-11 16:07:42 +08:00
sususu
cf8c27fe90 perf(antigravity): translate each upstream request once
Execute, executeClaudeNonStream and ExecuteStream all assign the validated
original payload to the request and then translate both values. Since both
translations saw the same bytes, every Antigravity request paid for a second
full scan of the client payload. On a captured 24MB tool-history request that
second pass cost roughly 0.9s of CPU and 651MB of allocations.

Translate once when both inputs share a backing array and hand the caller an
independent duplicate, because later stages edit the working copy in place.
Payloads that genuinely differ still get two translations.
2026-08-11 16:07:42 +08:00
Luis Pater
5d9b629962 fix(runtime): close per-request uTLS HTTP/2 connections with request context
- Create a fresh uTLS/HTTP-2 connection per request instead of reusing cached connections.
- Pass request context through dialing and TLS handshake to make `RoundTrip` cancelable.
- Wrap response bodies so the underlying HTTP/2 connection is closed when the body is closed, and clean up promptly on request/response failures.

Closes: #4878
2026-08-11 00:58:13 +08:00
Luis Pater
673bac5fc6 fix(codex): normalize custom_tool_call_output IDs with ctco_ prefix during Codex input sanitization 2026-08-09 21:34:01 +08:00
Luis Pater
197f520426 fix(codex): normalize custom_tool_call IDs with ctc_ prefix during Codex input sanitization 2026-08-08 23:25:11 +08:00
Luis Pater
4b3cc55cdc fix(cliproxy): centralize client error status mapping and apply context cancellation/deadline HTTP codes
Closes: #4601
2026-08-08 04:53:34 +08:00
jizhenggang
c30e60a11b Reduce Codex request amplification for large payloads
Reuse immutable request bytes during input inspection and avoid a redundant websocket clone while preserving the required outbound envelope.

Constraint: Preserve request immutability and one final WebSocket request-body allocation
Rejected: In-place JSON mutation | request buffers are shared across translation and execution stages
Confidence: high
Scope-risk: narrow
Directive: Do not retain no-copy gjson results or mutate their backing payload while results are in use
Tested: GOTOOLCHAIN=local go test ./...; targeted 8 MiB allocation benchmarks
Not-tested: Live Codex upstream network traffic
2026-08-07 19:16:06 +08:00
Luis Pater
0a95fa62a1 feat(compat): preserve Claude thinking/tool-call content for is-compat OpenAI compatibility models
- Add `is-compat` support to OpenAI compatibility model config, capabilities, hashing, and example config.
- Propagate `IsCompat` through API-key model resolution and switch OpenAI-compat executor translation to compatibility-aware routing.
- Keep Claude assistant thinking content in compatibility mode while keeping default behavior unchanged when `is-compat` is disabled.

Closes: #4776
2026-08-07 06:26:33 +08:00
Luis Pater
5e25566c24 fix(codex): normalize reasoning and function_call item IDs during input sanitization 2026-08-07 05:52:20 +08:00
Luis Pater
dcee14dd3c feat(compat): preserve compat-mode thinking/signature blocks for API-key models
- Added `is-compat` model metadata plumbing from config through executor and helpers, including hash computation.
- Introduced a compatibility-aware translation path (`TranslateRequestWithAPIKeyModelCompatibility`) and wired it into Claude/Gemini/Codex/Interactions request flows.
- Updated Claude message sanitization/translation behavior to keep empty-thinking compatibility blocks (including signatures) when `is-compat` is enabled, while keeping default behavior unchanged.
2026-08-06 17:19:24 +08:00
Luis Pater
e5ea945ed9 feat(codex): add model-level is-compat flag to rewrite MultiAgentV2 agent_message for Responses-compatible endpoints
Closes: #4801
2026-08-06 04:49:28 +08:00
DefinitelyNotSpammy
533b69e3e0 fix(claude): skip context management when thinking is disabled 2026-08-05 18:25:40 +08:00
Luis Pater
42eef103d6 feat(antigravity): obfuscate sensitive words in system instructions
Closes: #4696 #4723 #4732
2026-08-05 00:27:32 +08:00
sususu
8cf1d46f06 fix(usage): account for Claude thinking tokens 2026-08-03 22:30:00 +08:00
Supra4E8C
0fc028613b chore: exclude test changes from Home fixes 2026-08-03 21:40:06 +08:00
Supra4E8C
a81b9e9ced fix(home): report every unauthorized attempt 2026-08-03 21:40:06 +08:00
Supra4E8C
1df21b14bf fix(usage): update token fingerprint after refresh 2026-08-03 21:39:48 +08:00
Supra4E8C
d952cb4297 fix(home): reject disabled refreshed credentials 2026-08-03 21:39:48 +08:00
Supra4E8C
1e38a3a544 fix: retry Home OAuth requests after unauthorized 2026-08-03 21:39:48 +08:00
sususu
903e41b6dc docs(claude): clarify exact fingerprint baseline 2026-08-03 15:25:17 +08:00
sususu
a5f63909a5 fix(claude): harden request lifecycle
Classify malformed caller metadata and Fast failures as request-scoped, reuse the strict Anthropic origin gate, bound diagnostics and proxy caches, and remove the unrelated translator test change.
2026-08-03 14:47:26 +08:00
sususu
707934917a feat(claude): enable TLS session resumption 2026-08-03 14:47:26 +08:00
sususu
b3ed702e3a fix(claude): harden OAuth identity and native routing 2026-08-03 14:47:26 +08:00
sususu
f63a925d15 fix(claude): replay measured OAuth wire, Fast and diagnostic profiles
Align the remaining measured OAuth wire profiles, including the ordered
connection writer in internal/httpwire that reproduces the observed header
sequence, and the refresh/profile response shapes in internal/auth/claude.

Replay the measured Fast path and keep diagnostic continuity across cloaked and
native requests.

Preserve the native direct token-counting shape so a caller that reaches
count_tokens itself is not reshaped into the cloaked form.

Scope cloak dates to the credential's timezone rather than the host's, so
currentDate matches what the real client would have sent for that account.
2026-08-03 14:47:26 +08:00
sususu
4fdf59c436 fix(claude): synchronize credential metadata and device pools
A single *Auth is shared by every concurrent request that selects the same
credential, so any path reaching into Auth.Metadata directly races the others.
The credential identity helpers initialized and wrote the map outside
claudeDevicePoolMu; only EnsureDeviceIDPool took the lock, so a lazy
`auth.Metadata = make(...)` racing a pool write could abort the whole process
with "concurrent map writes" instead of failing a request.

Locking only the device-pool helpers was not enough: the account-profile and
refresh paths kept mutating the same map unguarded, which a concurrency probe
surfaced as data races. Widen the lock to the whole metadata map and route the
remaining call sites through new accessors in internal/auth/claude, including
the lazy map initialization, which needs a pointer to the field to stay inside
the critical section. claudeAccountProfileLookupDue now takes the already-read
timestamp so it cannot be handed an unsynchronized map.
2026-08-03 14:47:26 +08:00
sususu
afdd251cca fix(claude): preserve semantics in MCP tool aliases
Keep the opaque MCP alias reversible and meaning-preserving so a cloaked
caller's tool declarations, choices and history survive the round trip without
changing tool ownership.
2026-08-03 14:47:26 +08:00
sususu
f3e25ab2ba feat(claude): align OAuth wire identity and TLS with Claude Code 2.1.220
Detect confirmed CLI, sdk-cli and VSCode callers before mutation so native
software, system, tool, cache and beta shapes pass through, while unconfirmed
OAuth clients receive a coherent minimum CLI identity.

Persist each Claude OAuth credential's upstream account metadata and one stable
device ID, derive one stable session per agent conversation, and keep body and
header identity synchronized across Messages, streaming and count_tokens.

Alias every cloaked third-party custom tool through caller-stable opaque MCP
names and restore declarations, choices, history, references, non-stream
responses and SSE events without changing tool ownership.

Implement the Claude Code 2.1.220 CCH algorithm over the final serialized
request bytes, align currentDate and first-user cache layout, update the
official beta/header baseline, and use upstream count_tokens for OAuth and
first-party Anthropic credentials.

Match the 2.1.220 TLS ClientHello so the transport fingerprint agrees with the
identity the request now claims, and document the CLI defaults and automatic
OAuth signing / tool alias behaviour in config.example.yaml.
2026-08-03 14:47:26 +08:00
Luis Pater
13435c93d2 feat(executor): normalize OpenAI tool results for text-only compatibility models
- Add OpenAI-compat executor-time normalization for `tool` message content, converting non-string tool results to plain text and replacing image parts with a clear unsupported marker for models configured with text-only `input-modalities`.
- Apply normalization in both regular and streaming OpenAI-compat execution paths before prompt-cache processing.
- Update config example to document `[text]` `input-modalities` for upstreams that reject multimodal tool-result content.

Closes: #4737
2026-08-03 03:37:24 +08:00
Luis Pater
8d675e690d feature(codex): Normalize invalid sub2api message item IDs during Codex input sanitization
- Prefix non-compliant message input IDs with `msg_` while leaving valid/prefixed IDs unchanged.
- Apply normalization before length checks and shortening to keep ID handling deterministic and consistent across Codex request paths.
2026-08-03 02:45:49 +08:00
hkfires
a63da8ae76 Revert "Merge pull request #4687 from router-for-me/fix/home-401-refresh-recovery"
This reverts commit 4a31513673, reversing
changes made to 7d00936acc.
2026-07-31 16:35:33 +08:00
sususu98
9d46c8d145 Merge pull request #4684 from sususu98/fix/thinking-summary-visibility
feat(thinking): preserve cross-protocol summary visibility
2026-07-31 14:12:00 +08:00
sususu
c4dcd8703a fix(thinking): respect final summary authority 2026-07-31 13:28:14 +08:00
sususu
0c2ec7da23 fix(thinking): honor normalized summary payloads 2026-07-31 12:45:13 +08:00
Supra4E8C
4db8e12029 fix: recover Home OAuth credentials after 401 2026-07-31 01:34:11 +08:00
sususu
b3046d29b9 feat(thinking): preserve cross-protocol summary visibility 2026-07-30 21:53:30 +08:00
Luis Pater
f32291436a refactor(executor): consolidate thinking.ApplyThinking into helps.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
2026-07-29 14:14:18 +08:00
Luis Pater
57ef784224 feat(executor): implement local token counting for Claude requests
- Added `CountClaudeInputTokens` for estimating token usage with O200kBase tokenizer.
- Enhanced `ClaudeExecutor` to handle token counting locally, reducing dependency on upstream services.
- Introduced validation for token count requests for improved error handling.
- Updated tests to cover local token counting behavior and invalid request handling.

Closes: #4103
2026-07-27 00:50:11 +08:00
Luis Pater
f6c32ec3ff feat(runtime): implement derived session identity features and tests
- Added utilities for generating stable session identities, including `DerivedSessionID`, `DerivedSessionUUID`, and `ProviderSessionUUID`.
- Introduced support for Antigravity's negative decimal `DerivedAntigravitySessionID` mapping.
- Enhanced metadata handling for provider-scoped UUID stabilization and consistent session identity inference.
- Added comprehensive tests for stability, namespace isolation, and preferred execution session prioritization.
2026-07-26 03:07:21 +08:00
Luis Pater
84bf9376e5 feat(executor): replace sdktranslator.TranslateRequest with helps.TranslateRequestWithCodexMultiAgentV2
- Updated Kimi and Gemini executors to use `TranslateRequestWithCodexMultiAgentV2` for improved multi-agent v2 optimization.
- Enhanced configuration and API server to support `CodexOptimizeMultiAgentV2`.
- Added codex multi-agent V2 optimizations in `config`, `executor`, and `watcher` modules.
2026-07-25 00:32:37 +08:00
Luis Pater
42f36b94e0 fix(usage): harden canonical token normalization 2026-07-24 01:18:18 +08:00