63 Commits

  • refactor: standardize dataTag processing across response translators
    - Unified `dataTag` initialization by removing spaces after `data:`.
    - Replaced manual slicing with `bytes.TrimSpace` for consistent and robust handling of JSON payloads.
  • feat: add support for Gemini 2.5 Flash image preview alias
    - Introduced `gemini-2.5-flash-image-preview` alias in `GeminiWebAliasMap` for enhanced model handling.
    - Added `gemini-2.5-flash-image-preview` as a new model variant with custom ID, name, display name, and description.
  • refactor(auth): Centralize logging for saving credentials
    The logic for logging the path where credentials are saved was duplicated across several client implementations.
    
    This commit refactors this behavior by creating a new centralized function, `misc.LogSavingCredentials`, to handle this logging. The `SaveTokenToFile` method in each authentication token storage struct now calls this new function, ensuring consistent logging and reducing code duplication.
    
    The redundant logging statements in the client-level `SaveTokenToFile` methods have been removed.
  • refactor(auth): Introduce generic cookie snapshot manager
    This commit introduces a generic `cookies.Manager` to centralize the logic for handling cookie snapshots, which was previously duplicated across the Gemini and PaLM clients. This refactoring eliminates code duplication and improves maintainability.
    
    The new `cookies.Manager[T]` in `internal/auth/cookies` orchestrates the lifecycle of cookie data between a temporary snapshot file and the main token file. It provides `Apply`, `Persist`, and `Flush` methods to manage this process.
    
    Key changes:
    - A generic `Manager` is created in `internal/auth/cookies`, usable for any token storage type.
    - A `Hooks` struct allows for customizable behavior, such as custom merging strategies for different token types.
    - Duplicated snapshot handling code has been removed from the `gemini-web` and `palm` persistence packages.
    - The `GeminiWebClient` and `PaLMClient` have been updated to use the new `cookies.Manager`.
    - The `auth_gemini` and `auth_palm` CLI commands now leverage the client's `Flush` method, simplifying the command logic.
    - Cookie snapshot utility functions have been moved from `internal/util/files.go` to a new `internal/util/cookies.go` for better organization.
  • refactor(cookie): Extract cookie snapshot logic to util package
    The logic for managing cookie persistence files was previously implemented directly within the `gemini-web` client's persistence layer. This approach was not reusable and led to duplicated helper functions.
    
    This commit refactors the cookie persistence mechanism by:
    - Renaming the concept from "sidecar" to "snapshot" for clarity.
    - Extracting file I/O and path manipulation logic into a new, generic `internal/util/cookie_snapshot.go` file.
    - Creating reusable utility functions: `WriteCookieSnapshot`, `TryReadCookieSnapshotInto`, and `RemoveCookieSnapshot`.
    - Updating the `gemini-web` persistence code to use these new centralized utility functions.
    
    This change improves code organization, reduces duplication, and makes the cookie snapshot functionality easier to maintain and potentially reuse across other clients.
  • feat: add client availability tracking and error handling improvements
    - Introduced `IsAvailable` and `SetUnavailable` methods to clients for availability tracking.
    - Integrated availability checks in client selection logic to skip unavailable clients.
    - Enhanced error handling by marking clients unavailable on specific error codes (e.g., 401, 402).
    - Removed redundant quota verification logs in client reordering logic.
  • feat(gemini): Implement pseudo-streaming and improve context reuse
    This commit introduces two major enhancements to the Gemini Web client to improve user experience and conversation continuity.
    
    First, it implements a pseudo-streaming mechanism for non-code mode. The Gemini Web API returns the full response at once in this mode, leading to a poor user experience with a long wait for output. This change splits the full response into smaller chunks and sends them with an 80ms delay, simulating a real-time streaming effect.
    
    Second, the conversation context reuse logic is now more robust. A fallback mechanism has been added to reuse conversation metadata when a clear continuation context is detected (e.g., a user replies to an assistant's turn). This improves conversational flow. Metadata lookups have also been improved to check both the canonical model key and its alias for better compatibility.
  • Add support for forcing GPT-5 Codex model configuration
    - Introduced a new `ForceGPT5Codex` configuration option in settings.
    - Added relevant API endpoints for managing `ForceGPT5Codex`.
    - Enhanced Codex client to handle GPT-5 Codex-specific logic and mapping.
    - Updated example configuration file to include the new option.
    
    Add GPT-5 Codex model support and configuration options in documentation
  • Update internal module imports to use v5 package path
    - Updated all `github.com/luispater/CLIProxyAPI/internal/...` imports to point to `github.com/luispater/CLIProxyAPI/v5/internal/...`.
    - Adjusted `go.mod` to specify `module github.com/luispater/CLIProxyAPI/v5`.
  • Fixed bug #38
    Add support for API key indexing in OpenAI compatibility clients
    
    - Updated `NewOpenAICompatibilityClient` to accept `apiKeyIndex` for managing multiple API keys.
    - Modified client instantiation loops to initialize one client per API key.
    - Adjusted client ID format to include `apiKeyIndex` for unique identification.
    - Removed API key rotation logic within `GetCurrentAPIKey`.
    - Updated `.gitignore` to include `AGENTS.md`.
  • Add support for Codex API key authentication
    - Introduced functionality to handle Codex API keys, including initialization and management via new endpoints in the management API.
    - Updated Codex client to support both OAuth and API key authentication.
    - Documented Codex API key configuration in both English and Chinese README files.
    - Enhanced logging to distinguish between API key and OAuth usage scenarios.
  • Remove redundant dataUglyTag parsing logic in streaming responses
    Eliminated duplicate blocks handling `dataUglyTag` in `openai-compatibility_client.go`, simplifying the streaming response logic.
  • **Fix model switch logic when quota is exceeded**
    Ensure `modelName` is updated after switching to a new model, avoiding inconsistencies in subsequent iterations.
  • **Handle data: without trailing space in streaming responses**
    Add support for API providers that emit `data:` (no space) in Server‑Sent Events. Introduces a new `dataUglyTag` and corresponding parsing logic to correctly process and forward these lines, ensuring compatibility with non‑standard streaming formats.
    
    Fuck for them all
  • Refactor translator packages for OpenAI Chat Completions
    - Renamed `openai` packages to `chat_completions` across translator modules.
    - Introduced `openai_responses_handlers` with handlers for `/v1/models` and OpenAI-compatible chat completions endpoints.
    - Updated constants and registry identifiers for OpenAI response type.
    - Simplified request/response conversions and added detailed retry/error handling.
    - Added `golang.org/x/crypto` for additional cryptographic functions.
  • Enhance client reload process with new OpenAI compatibility support
    - Added handling for OpenAI-compatible providers during client reload.
    - Implemented client unregistration for old clients during reload.
    - Improved logging for detailed client reload insights.
    
    Expand `AuthDir` handling to support tilde (`~`) for home directory resolution
    
    - Added logic to replace `~` with the user's home directory in `AuthDir`.
    - Prevents errors when using `~` in configuration paths.
  • Add support for new GPT-5 model variants
    - Renamed existing GPT-5 variants for consistency (`nano` → `minimal`, `mini` → `low`, etc.).
    - Added metadata definitions for new variants: `gpt-5-minimal`, `gpt-5-low`, `gpt-5-medium`, and updated logic to reflect variant-specific reasoning efforts.
  • Add token refresh handling for 401 responses across clients
    - Implemented `RefreshTokens` method in client interfaces and Gemini clients.
    - Updated handlers to call `RefreshTokens` on 401 responses and retry requests if token refresh succeeds.
    - Enhanced error handling and retry logic to accommodate token refresh flow.
  • Update README documentation to clarify auth-dir configuration for Windows users
    - Added a note for setting `auth-dir` on Windows systems in both English and Chinese README files.
    - Improved descriptions for existing configuration options.
    
    Address Qwen3 tool injection issue to prevent random token insertions
    
    - Modify Qwen client to insert a placeholder tool when none is defined, avoiding erratic behavior in streaming responses.
  • Add nil-check for GetRequestMutex across handlers to prevent potential panics
    - Updated all handlers to safely unlock the request mutex only if it's non-nil.
    - Enhanced mutex locking and unlocking logic to avoid runtime errors.
    - Improved robustness of resource cleanup across clients.
    
    Add `GetRequestMutex` method for synchronization across clients
    
    - Introduced a new `GetRequestMutex` method in OpenAICompatibilityClient, CodexClient, GeminiCLIClient, GeminiClient, and QwenClient for request synchronization.
    - Ensures only one request is processed at a time to manage quotas effectively.
  • Suppress debug logs for model routing and ignore empty tools arrays
    - Comment out verbose routing logs in the API server to reduce noise.
    - Remove the `tools` field from Qwen client requests when it is an empty array.
    - Add guards in Claude, Codex, Gemini‑CLI, and Gemini translators to skip tool conversion when the `tools` array is empty, preventing unnecessary payload modifications.
  • Add support for localhost unauthenticated requests
    - Introduced `AllowLocalhostUnauthenticated` flag allowing unauthenticated requests from localhost.
    - Updated authentication middleware to bypass checks for localhost when enabled.
    
    Add new Gemini CLI models and update model registry function
    
    - Introduced `GetGeminiCLIModels` for updated Gemini CLI model definitions.
    - Added new models: "Gemini 2.5 Flash Lite" and "Gemini 2.5 Pro".
    - Updated `RegisterModels` to use `GetGeminiCLIModels` in Gemini client initialization.
  • Add OpenAI compatibility support and improve resource cleanup
    - Introduced OpenAI compatibility configurations for external providers, enabling model alias routing via the OpenAI API format.
    - Enhanced provider logic in `GetProviderName` to handle OpenAI aliases and added new helper functions for compatibility checks.
    - Updated API handlers and client initialization to support OpenAI compatibility models.
    - Improved resource cleanup across clients by closing response bodies and streams using deferred functions.
  • Add request logging capabilities to API handlers and update .gitignore
    Enhance API response handling by storing responses in context and updating request logger to include API responses
  • Fix activation URL extraction logic and improve warning message formatting
    - Corrected JSON path for error code and activation URL extraction in client error handling.
    - Improved readability of the activation warning message with better spacing.
  • Refactor API handlers organization and simplify error response handling
    - Modularized handlers into dedicated packages (`gemini`, `claude`, `cli`) for better structure.
    - Centralized `ErrorResponse` and `ErrorDetail` types under `handlers` package for reuse.
    - Updated all handlers to utilize the shared `ErrorResponse` model.
    - Introduced specialization of handler structs (`GeminiAPIHandlers`, `ClaudeCodeAPIHandlers`, `GeminiCLIAPIHandlers`) for improved clarity and separation of concerns.
    - Refactored `getClient` logic with additional properties and better state management.
    
    Refactor `translator` package by modularizing code for `claude` and `gemini`
    
    - Moved Claude-specific logic (`PrepareClaudeRequest`, `ConvertCliToClaude`) to `translator/claude/code`.
    - Moved Gemini-specific logic (`FixCLIToolResponse`) to `translator/gemini/cli` for better package structure.
    - Updated affected handler imports and method references.
    
    Add comprehensive package-level documentation across key modules
    
    - Introduced detailed package-level documentation for core modules: `auth`, `client`, `cmd`, `handlers`, `util`, `watcher`, `config`, `translator`, and `api`.
    - Enhanced code readability and maintainability by clarifying the purpose and functionality of each package.
    - Aligned documentation style and tone with existing codebase conventions.
    
    Refactor API handlers and translator modules for improved clarity and consistency
    
    - Standardized handler struct names (`GeminiAPIHandlers`, `ClaudeCodeAPIHandlers`, `GeminiCLIAPIHandlers`, `OpenAIAPIHandlers`) and updated related comments.
    - Fixed unnecessary `else` blocks in streaming logic for cleaner error handling.
    - Renamed variables for better readability (`responseIdResult` to `responseIDResult`, `activationUrl` to `activationURL`, etc.).
    - Addressed minor inconsistencies in API handler comments and SSE header initialization.
    - Improved modularization of `claude` and `gemini` translator components.
    
    Standardize configuration field naming for consistency across modules
    
    - Renamed `ProxyUrl` to `ProxyURL`, `ApiKeys` to `APIKeys`, and `ConfigQuotaExceeded` to `QuotaExceeded`.
    - Updated all relevant references and comments in `config`, `auth`, `api`, `util`, and `watcher`.
    - Ensured consistent casing for `GlAPIKey` debug logs.
  • Fix alt parameter handling in URL construction
    - Ensured `alt` parameter is only appended when non-empty.
    - Added debug logging for constructed URLs.
  • Add GeminiGetHandler, enhance Gemini functionality, and enable token counting
    - Added `GeminiGetHandler` for handling GET requests with extended Gemini model support.
    - Introduced `geminiCountTokens` function to calculate token usage.
    - Refactored `APIRequest` and related methods to support `alt` parameter for enhanced flexibility.
    - Updated routes and request processing to integrate new handler and functions.
  • Improve error logging and add user guidance for issue reporting
    - Added fatal log in `login.go` for Cloud AI API enablement check failures, prompting users to report issues.
    - Enhanced error logging in `client.go` with warning messages directing users to copy and provide error details when creating issues.