- Require exactly one non-reminder text block matching quota/test/probe/./Hi for probe request matching.
- Identify title helper requests via expanded session title patterns.
- Implement post-payload bidirectional probe reclassification: strip CPA diagnostics and billing tags on probes, while restoring continuity if declassified.
- Preserve caller-owned and payload-supplied diagnostics on probe requests.
- Gate late sensitive-word obfuscation strictly on cloaked requests in Execute and ExecuteStream.
- Add comprehensive end-to-end tests for probe classification, diagnostics isolation, and late cloaking.
- Inject '# Reporting outcomes' system block for Fable 5.1 / Mythos 5.1 models matching Claude Code 2.1.258 tengu_dapper_lagoon behavior.
- Support both string-format and block-array system prompts for Fable reporting injection.
- Add reconcileClaudeCodeFableModelAfterPayload to reconcile model additions when payload rules override model or thinking.
- Reliably re-add reporting block if omitted after payload rules modify system blocks.
- Drop injected thinking.display on Fable models when payload changes thinking type from adaptive to disabled.
- Enhance payload rule path tracking with ancestor target matching in ApplyPayloadConfigWithTrackedPaths.
- Introduce 2.1.258 dynamic betas: thinking-display-updates-2026-08-18, server-side-fallback-2026-06-01, and fallback-credit-2026-03-24.
- Prune effort-2025-11-24 on Haiku models, probes, and when thinking is disabled.
- Prune thinking-display-updates on disabled thinking and probe/helper turns.
- Identify Fable 5.1 / Mythos 5.1 models with boundary checks and inject default fallbacks and adaptive thinking display.
- Strictly pair 1h cache control with extended-cache-ttl-2025-04-11, stripping TTL on probes and subagents.
- Assemble x-anthropic-billing-header strictly following official 2.1.258 binary sequence: cc_version -> cc_entrypoint -> cch -> cc_workload -> cc_is_subagent -> cc_prev_req -> cc_prompt_id.
- Track upstream request-id in thread-safe bounded session continuity state and inject into subsequent turns as cc_prev_req.
- Generate and enforce RFC 4122 UUIDv4 cc_prompt_id per user prompt turn, preserving it across tool continuations while suppressing it on probes and title helpers.
- Detect subagents via agent headers and session metadata to emit cc_is_subagent=true.
- Harmonize diagnostics and continuity lifecycles to prevent uncommitted or truncated streams from corrupting state.
- Exclude x-anthropic-billing-header system blocks from sensitive-word zero-width space injection.
- Extract the credential-identity block shared by the streaming and
non-streaming Claude paths into applyClaudeCLIIdentity, so the identity
seed choice (API key versus stable Kimi auth identity) cannot drift
between the two paths
- Move stripDefaultKimiClaudeCodeAttribution next to the other attribution
and CCH helpers in claude_signing.go; it is only called from the Claude
executor paths and never from the Kimi executor itself
- Reattach the addConfigHeadersToAttrs doc comment to its function in the
watcher synthesizer helpers
Claude Code 2.1.220 through 2.1.234 emit the cch attribution only for
firstParty on api.anthropic.com and for vertex; every other backend sends
the billing header unsigned. CPA had dropped its endpoint check, so an
opted-in API key signed a per-request hash on any gateway and could bust
that gateway's prompt cache.
- Restore the endpoint gate in claudeCCHSigningEnabled: a real Claude OAuth
credential still signs on every upstream, because a downstream Claude Code
pointed at CPA cannot produce that value itself, while a claude-code-cli
API key signs only on api.anthropic.com or Vertex
- Drop the unused origin parameter from Claude fingerprint policy resolution
and restore the original resolveClaudeWirePolicy signature; the wire profile
follows the credential and only CCH follows the origin
- Add config.NormalizeClaudeFingerprintProfile / ValidateClaudeFingerprintProfile
as the single source of truth for fingerprint-profile values
- Reject unknown fingerprint-profile values in the Management API, and warn
once per distinct value at request time instead of on every resolution,
which previously logged about four warnings per request for one typo
- Preserve unrecognized values through config sanitization so rewriting a
config file never discards operator input
- Update config.example.yaml and tests for the origin-scoped CCH behavior
* feat(config): add fingerprint-profile to Claude keys and auth JSON
- Add FingerprintProfile to ClaudeKey configuration struct and normalizer
- Track fingerprint-profile in config diff
- Map fingerprint-profile / fingerprint_profile to auth attributes in file and config synthesizers
- Support fingerprint-profile in Management API PatchClaudeKey and normalization
- Add Claude billing attribution string manipulation utilities in internal/util
- Document fingerprint-profile options in config.example.yaml
* feat(claude): add fingerprint policy and request-local CLI identity
- Centralize Claude fingerprint policy resolution in claude_fingerprint_policy.go
- Support stable Claude CLI identity synthesis (UUIDv5 account_uuid and SHA-256 device_id)
seeded from API keys or stable OAuth IDs, keeping access tokens isolated
- Warn on unrecognized fingerprint-profile values
* feat(claude): apply CLI fingerprint to Messages and keep API keys caller-owned
- Wire centralized fingerprint policy into Claude and Kimi executors
- Keep first-party Anthropic API keys and delegated providers caller-owned by default
- Apply Claude Code CLI wire profile (betas, metadata, diagnostics, MCP aliases)
when fingerprint-profile=claude-code-cli is configured
- Strictly align CCH signing with native Claude Code 2.1.220: only first-party
api.anthropic.com and Vertex sign dynamic CCH; third-party gateways and Kimi
receive billing header without cch= to avoid prompt cache busting
- Respect caller-owned count_tokens bodies by default while aligning CLI shape on opt-in
- Fall back to CLIProxyAPI/<version> User-Agent when caller sends no UA in caller-owned mode
- Scope custom operator header overrides accurately in caller-owned mode
- Add comprehensive test coverage for policy resolution, gateway opt-in, Kimi, and token counting
- 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
A caller can put a {"role":"system"} turn inside messages. Models older than
the role=system turn reject it outright, verified against api.anthropic.com on
both /v1/messages and /v1/messages/count_tokens:
400 role 'system' is not supported on this model
claude-haiku-4-5, claude-sonnet-4-5, claude-sonnet-4-6 and claude-opus-4-6
answer that way, while claude-sonnet-5 and claude-opus-5 accept the turn.
claudeLegacySystemReminderModels already enumerates that boundary, which is why
claudeCodeCLIBetas withholds mid-conversation-system-2026-04-07 for those
models, but caller-provided turns were forwarded unchanged and always spent an
upstream call on a guaranteed rejection.
The native client does not produce the pairing either: it gates the turn on the
model. In 314 captured native requests the turn appears only on
claude-opus-5 and claude-sonnet-5, and on none of the 43 requests addressed to
a model in that set. That is an observation about the captures rather than a
proof about the upstream, so it only corroborates the measured rejection.
Validate the finished body, and only inside the evidence that produced the
rule:
- The check runs after the body is finalized and before
http.NewRequestWithContext. Payload rules can rewrite model and messages long
after translation, so an earlier check would not describe what is sent.
- Only Anthropic's first-party origin is covered, matching the reasoning
shouldUseClaudeUpstreamTokenCount already applies to count_tokens. A
third-party gateway may map these model IDs onto something that accepts the
turn and therefore decides for itself.
- A confirmed native caller keeps the passthrough. It gates the turn itself, so
its body is forwarded untouched and the upstream error reaches it unchanged.
- Unknown and future model IDs stay optimistic and are forwarded, matching how
checkSystemInstructions treats them.
- rebuild_mid_system_message still folds caller turns into the system slot; the
final check therefore preserves the explicit escape hatch.
Cloaking adds one extra ordering case: it can place a caller's top-level system
prompt into a role=system turn for a modern model before a payload rule changes
the model to legacy. Track only the exact contiguous turns that CPA inserted,
using both their position and the corresponding message-count increase as
provenance. After payload rules settle the model, replay those turns through the
existing legacy <system-reminder> path. Pre-existing caller turns, even if they
have identical content, remain caller-owned and are still rejected. If payload
rules also rewrite the tracked messages, reconciliation fails closed and final
validation returns 400 rather than guessing provenance.
The 400 is request-scoped like claudeCallerSystemBlockError: the invalid
body/model pairing is independent of first-party credential health, so no
credential is cooled or retried.
Translated requests never carry the pairing, because every non-Claude source
format hoists system content into the top-level system field. Tests pin that for
OpenAI, Gemini, Responses and Interactions, and separately drive Execute,
ExecuteStream and CountTokens through an injected first-party transport.
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.
Cloaked Responses/Chat/Gemini→Claude traffic was skipping ensureCacheControl
once the first-user cloak marker existed, freezing multi-turn cache hits.
Always ensure section-independent system and rolling-message breakpoints for
non-native callers, keep confirmed Claude Code placement intact, and leave
tools unstamped when a usable system prompt already covers the prefix.
Align the wire shape with the Claude Code 2.1.220/2.1.221/2.1.227 cache-control
constructor: the default is {"type":"ephemeral"} with no ttl. A 1h body ttl is
applied only after placement, only for OAuth credentials, and only onto blocks
that already carry cache_control, so it stays strictly paired with
extended-cache-ttl-2025-04-11. Explicit caller-owned 5m choices survive.
Match the native rolling selector (skip thinking-like assistant tails; final
system string special case), fall back to a tools breakpoint when system is
absent or blank, and leave empty/whitespace string systems unconverted so they
cannot double-stamp tools plus a useless system host.
- Add Claude replay enablement and scope derivation for API-key compatible Claude requests with isolated model/session keys.
- Restore cached signed reasoning blocks into outbound requests and persist completed assistant turns after execution, including stream handling.
- Introduce a dedicated Claude thinking-replay cache with local + home-KV paths, CAS-based snapshot replace/clear, TTL/size limits, and bounded eviction/expiration management.
Closes: #4856
- 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.
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.
CPA negotiates ALPN http/1.1 with Anthropic, so header names are not lowercased
by HPACK and reach the server verbatim. The casing is therefore part of the
fingerprint, and six of the eighteen names CPA emits were wrong because Go
canonicalises everything passed through Header.Set: anthropic-beta,
anthropic-dangerous-direct-browser-access, anthropic-version, x-app,
x-client-request-id and X-Stainless-OS. Writing the map keys directly is the
only way to keep the original casing.
This also fixes ordering at no extra cost. Go sorts header names bytewise when
it serialises a request, and the captured order of the real client is exactly
that same bytewise sort. Host, User-Agent and Content-Length stay misplaced
because Go writes them ahead of the sorted block; a test records that gap and
will fail if it ever closes.
The pass runs at the send boundary rather than inside applyClaudeHeaders: the
rewritten keys are unreachable through Header.Get, and doing it earlier hid
these headers from the rest of the pipeline. The boundary is a single
doClaudeUpstreamRequest helper pinned by a structural test, after a mutation
check showed that dropping the call from the streaming path alone was otherwise
undetectable. Expected order is pinned by serialising the request and reading
the header lines back, not by inspecting the header map.
An account without the fast-mode entitlement answers speed:"fast" with HTTP 429
and "Usage credits are required for fast mode." The generic pipeline treats any
429 as quota exhaustion: it marks the credential Quota.Exceeded, assigns an
exponential cooldown up to 30 minutes and rotates to the next credential, so a
single request could walk and cool down the entire Claude pool over a
capability the account will never have.
Classify it through the existing RequestScopedError contract instead, which
already suppresses cooldown, rotation and retry. The status and body are then
returned verbatim: the classifier exists to stop the generic pipeline from
handling the error, not to handle it.
Detection deliberately requires both "fast mode" and a credits phrase, so a
genuine rate limit, which never mentions fast mode, keeps its cooldown. Tests
cover both observed wordings, byte-exact pass-through, and the negative cases.
Claude Code builds Anthropic-Beta per request instead of sending a fixed list.
Captured from an isolated 2.1.220 profile pointed at api.anthropic.com through
a local proxy, over two rounds covering 11 model IDs and the [1m] variants:
constant claude-code, interleaved-thinking, redact-thinking,
thinking-token-count, context-management, prompt-caching-scope
tools advanced-tool-use-2025-11-20 only when tools are declared
model mid-conversation-system-2026-04-07 only on models that accept a
role=system turn
[1m] context-1m-2025-08-07, directly after claude-code-20250219 rather
than at the end
trailing effort-2025-11-24, then server-side-fallback-2026-06-01
claude-sonnet-5 emits mid-conversation-system-2026-04-07, so it accepts a
role=system turn and must not sit in the legacy reminder whitelist.
count_tokens does not reuse the inference fingerprint. Running /context in an
interactive session issues 37 identical calls, which made the endpoint
observable for the first time: four betas only, and 21 headers rather than 22
because X-Stainless-Timeout is absent. The profile is selected from the request
path so no call site has to thread another flag.
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.
- 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
- Removed deprecated interceptor and executor-related methods, including `callRequestInterceptor`, `callResponseInterceptor`, and `callStreamChunkInterceptor`.
- Consolidated unused logic and pruned redundant imports to streamline `adapters.go`.
- No functional changes.