- Preserve API key entries with empty `api_key` when `base_url` is configured, and extend config dedupe/ID logic to include base URL, proxy, prefix, and headers so identities are stable.
- Update config/auth handling so `auth_kind=apikey` is treated as config API-key auth even without an `api_key` field, enabling base_url-only credential records.
- Ensure Gemini/Codex/XAI request path clears `Authorization`/provider auth headers when token is empty to avoid leaking unrelated auth state.
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
- 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.
- Introduced `disable-codex-cloaking` to allow disabling enforced `User-Agent` and `Originator` headers for Codex requests.
- Updated header application logic to conditionally include `codexUserAgent` and `codexOriginator` based on configuration.
- Enhanced config diff tracking to detect changes in `disable-codex-cloaking`.
- Expanded tests to cover new config behavior and header application scenarios.
Preserve Codex and XAI upstream message-too-big closes across the Responses WebSocket boundary while treating them as request-scoped errors. Prevent CPA reconnect and credential cooldown/fallback, scope close state to the active connection, retain terminal errors under backpressure, and ensure downstream disconnect cleanup cannot wait behind a blocked writer.
- Updated `SanitizeCodexInputItemIDs` to remove encrypted reasoning items with IDs exceeding the Codex length limit.
- Refactored logic to deterministically shorten other overlong input item IDs, ensuring compliance with the Codex format.
- Added new tests to verify dropping behavior for encrypted reasoning and shortening of lengthy IDs without encrypted content.
- Introduced `normalizeCodexWebsocketParallelToolCalls` and `normalizeCodexParallelToolCalls` to enforce consistent `parallel_tool_calls` handling.
- Updated WebSocket and HTTP executor logic to support headers during parallel tool normalization.
- Refactored redundant logic by consolidating normalization routines for improved clarity and maintainability.
- Introduced agent-specific cache key isolation to ensure distinct prompt caching across agents.
- Improved reasoning replay handling for Claude models, including cumulative tool turn restoration and validation.
- Enhanced HTTP and WebSocket session consistency during execution scope and cache replay synchronization.
- Added new unit tests and extended coverage for prompt caching, agent isolation, and replay cache functionality.
Closes: #4352
- Implemented deterministic shortening of overlong Codex input item IDs to meet 64-character limit.
- Added `SanitizeCodexInputItemIDs` helper for efficient ID shortening in request bodies.
- Updated Codex executor and websocket implementations to utilize the new helper.
- Introduced unit tests to validate ID length restrictions, avoidance of collisions, and deterministic behavior.
Closes: #4401
- Introduced `override_header` in model configurations to support runtime customization of upstream request headers.
- Added `applyModelHeaderOverrides` utility to enforce header overrides for relevant executor and websocket paths.
- Updated model registry and `models.json` with enhanced configurations for header customizations.
- Implemented and extended test cases to validate header override behavior for various models and scenarios.
- Added `mapCodexWebsocketReadError` to handle `CloseMessageTooBig` errors with proper status and error code mapping.
- Updated error propagation and logging in Codex WebSocket executor.
- Introduced corresponding unit test to verify `message_too_big` error mapping in streamed responses.
Closes: #4017
- Enhanced Codex Websockets Executor to capture `response.done` as a terminal event, alongside `response.completed` and `error`.
- Improved error propagation for upstream websocket errors with comprehensive message handling.
- Introduced utility functions for recognizing terminal events and extracting error messages.
- Expanded tests to validate new websocket event logic, including terminal event handling and upstream error propagation.
- Updated session handling to replace `Session_id` and `Conversation_id` headers with new logic ensuring consistent use of `Cache.ID` and prompt keys.
- Restored `Session_id` as a priority extraction source for `ExtractSessionID`.
- Added tests to validate case-sensitive and case-insensitive headers, canonical account header usage, and session key preservation.
- Removed legacy support for deprecated `Conversation_id` header to clean up API.
- Modified `applyCodexIdentityConfuse*` functions to include `turn_id` and `window_id` in metadata transformations.
- Updated test cases to validate the inclusion and restoration of these fields.
- Removed deprecated `Conversation_id` header support and related logic for cleaner implementation.
- Added `applyCodexIdentityConfuse*` functions for remapping request and response payloads and headers to enhance security.
- Updated WebSocket and HTTP logic to handle identity state transformations seamlessly.
- Introduced unit tests to verify remapping and restoration of identity-related fields.
- Updated all references from v6 to v7 for `github.com/router-for-me/CLIProxyAPI`.
- Ensured consistency in imports within core libraries, tests, and integration tests.
- Added missing tests for new features in Redis Protocol integration.
- Introduced `UpstreamDisconnectChan` for Codex WebSocket sessions to notify downstream connections of upstream disconnections.
- Implemented `notifyUpstreamDisconnect` to signal errors and close channels on disconnect events.
- Added integration tests to validate WebSocket session behavior on upstream disconnect.
- Updated OpenAI WebSocket response handlers to properly close connections upon upstream disconnect notifications.
Restore Claude continuity after the continuity refactor, keep auth-affinity keys out of upstream Codex session identifiers, and only persist affinity after successful execution so retries can still rotate to healthy credentials when the first auth fails.
Align websocket continuity resolution with the HTTP Codex path, make auth-affinity principal keys use a stable string representation, and extract small helpers that remove duplicated continuity and affinity logic without changing the validated cache-hit behavior.
Prompt caching on Codex was not reliably reusable through the proxy because repeated chat-completions requests could reach the upstream without the same continuity envelope. In practice this showed up most clearly with OpenCode, where cache reads worked in the reference client but not through CLIProxyAPI, although the root cause is broader than OpenCode itself.
The proxy was breaking continuity in several ways: executor-layer Codex request preparation stripped prompt_cache_retention, chat-completions translation did not preserve that field, continuity headers used a different shape than the working client behavior, and OpenAI-style Codex requests could be sent without a stable prompt_cache_key. When that happened, session_id fell back to a fresh random value per request, so upstream Codex treated repeated requests as unrelated turns instead of as part of the same cacheable context.
This change fixes that by preserving caller-provided prompt_cache_retention on Codex execution paths, preserving prompt_cache_retention when translating OpenAI chat-completions requests to Codex, aligning Codex continuity headers to session_id, and introducing an explicit Codex continuity policy that derives a stable continuity key from the best available signal. The resolution order prefers an explicit prompt_cache_key, then execution session metadata, then an explicit idempotency key, then stable request-affinity metadata, then a stable client-principal hash, and finally a stable auth-ID hash when no better continuity signal exists.
The same continuity key is applied to both prompt_cache_key in the request body and session_id in the request headers so repeated requests reuse the same upstream cache/session identity. The auth manager also keeps auth selection sticky for repeated request sequences, preventing otherwise-equivalent Codex requests from drifting across different upstream auth contexts and accidentally breaking cache reuse.
To keep the implementation maintainable, the continuity resolution and diagnostics are centralized in a dedicated Codex continuity helper instead of being scattered across executor flow code. Regression coverage now verifies retention preservation, continuity-key precedence, stable auth-ID fallback, websocket parity, translator preservation, and auth-affinity behavior. Manual validation confirmed prompt cache reads now occur through CLIProxyAPI when using Codex via OpenCode, and the fix should also benefit other clients that rely on stable repeated Codex request continuity.
feat(proxy): centralize proxy handling with `proxyutil` package and enhance test coverage
- Added `proxyutil` package to simplify proxy handling across the codebase.
- Refactored various components (`executor`, `cliproxy`, `auth`, etc.) to use `proxyutil` for consistent and reusable proxy logic.
- Introduced support for "direct" proxy mode to explicitly bypass all proxies.
- Updated tests to validate proxy behavior (e.g., `direct`, HTTP/HTTPS, and SOCKS5).
- Enhanced YAML configuration documentation for proxy options.
- Simplified connection logic by removing `connCreateSent` and related state handling.
- Updated `buildCodexWebsocketRequestBody` to always use `response.create`.
- Added unit tests to validate `response.create` behavior and beta header preservation.
- Dropped unsupported `response.append` and outdated `response.done` event types.