Commit Graph

535 Commits

  • **fix(handlers): refactor API response capture to append data safely**
    - Introduced `appendAPIResponse` helper to preserve and append data to existing API responses.
    - Ensured newline inclusion when appending, if necessary.
    - Improved `nil` and data type checks for response handling.
    - Updated middleware to skip request logging for `GET` requests.
  • **fix(executor): update antigravity executor to enhance model metadata handling**
    - Added additional metadata fields (`Name`, `Description`, `DisplayName`, `Version`) to `ModelInfo` struct initialization for better model representation.
    - Removed unnecessary whitespace in the code.
  • fix(registry): correct Claude Opus 4.5 created timestamp
    Update epoch from 1730419200 (2024-11-01) to 1761955200 (2025-11-01).
  • feat(registry): add Claude Opus 4.5 model definition
    Add support for claude-opus-4-5-20251101 with 200K context window
    and 64K max output tokens.
  • **fix(translator): add conditional check for key renaming in Gemini tools**
    - Ensured `functionDeclarations` key renaming only occurs if the key exists in Gemini tools processing.
    - Prevented unnecessary JSON reassignment when the target key is absent.
  • **fix(translator): adjust key renaming logic in Gemini request processing**
    - Fixed parameter key renaming to correctly handle `functionDeclarations` and `parametersJsonSchema` in Gemini tools.
    - Resolved potential overwriting issue by reassigning JSON strings after each key rename.
  • **feat(config): add TLS support for HTTPS server configuration**
    - Introduced `TLSConfig` to support HTTPS configurations, including enabling TLS, specifying certificate and key files.
    - Updated HTTP server logic to handle HTTPS mode when TLS is enabled.
    - Enhanced `config.example.yaml` with TLS settings example.
    - Adjusted internal URL generation to respect protocol based on TLS state.
  • #293
    **feat(retry): add configurable retry logic with cooldown support**
    
    - Introduced `max-retry-interval` configuration for cooldown durations between retries.
    - Added `SetRetryConfig` in `Manager` to handle retry attempts and cooldown intervals.
    - Enhanced provider execution logic to include retry attempts, cooldown management, and dynamic wait periods.
    - Updated API endpoints and YAML configuration to support `max-retry-interval`.
  • **feat(logging, middleware): add error-based logging support and error log management**
    - Introduced `logOnErrorOnly` mode to enable logging only for error responses when request logging is disabled.
    - Added endpoints to list and download error logs (`/request-error-logs`).
    - Implemented error log file cleanup to retain only the newest 10 logs.
    - Refactored `ResponseWriterWrapper` to support forced logging for error responses.
    - Enhanced middleware to capture data for upstream error persistence.
    - Improved log file naming and error log filename generation.
  • **fix(translator): reintroduce thoughtSignature bypass logic for model parts**
    - Restored `thoughtSignature` validator bypass for model-specific parts in Gemini content processing.
    - Removed redundant logic from the `executor` for cleaner handling.
  • fix(aistudio): strip Gemini generation config overrides
    Remove generationConfig.maxOutputTokens, generationConfig.responseMimeType and generationConfig.responseJsonSchema from the Gemini payload in translateRequest so we no longer send unsupported or conflicting response configuration fields. This lets the backend or caller control response formatting and output limits and helps prevent potential API errors caused by these keys.
  • **chore(executor): update default agent version and simplify const formatting**
    - Updated `defaultAntigravityAgent` to version `1.11.5`.
    - Adjusted const value formatting for improved readability.
    
    **feat(executor): introduce fallback mechanism for Antigravity base URLs**
    
    - Added retry logic with fallback order for Antigravity base URLs to handle request errors and rate limits.
    - Refactored base URL handling with `antigravityBaseURLFallbackOrder` and related utilities.
    - Enhanced error handling in non-streaming and streaming requests with retry support and improved metadata reporting.
    - Updated `buildRequest` to support dynamic base URL assignment.
  • **feat(executor, translator): enhance token handling and payload processing**
    - Improved Antigravity executor to handle `thinkingConfig` adjustments and default `thinkingBudget` when `thinkingLevel` is removed.
    - Updated translator response handling to set default values for output token counts when specific token data is missing.
  • **feat(executor): add model alias mapping and improve Antigravity payload handling**
    - Introduced `modelName2Alias` and `alias2ModelName` functions for mapping between model names and aliases.
    - Improved Antigravity payload transformation to include alias-to-model name conversion.
    - Enhanced processing for Claude Sonnet models to adjust template parameters based on schema presence.
  • **feat(watcher): optimize auth file handling with hash-based change detection**
    - Added `authFileUnchanged` to skip reloads for unchanged files based on SHA256 hash comparisons.
    - Introduced `isKnownAuthFile` to verify known files before handling removal events.
    - Improved event processing in `handleEvent` to reduce unnecessary reloads and enhance performance.
  • **feat(translator): improve content processing and Antigravity request conversion**
    - Refactored response translation logic to support mixed content types (`input_text`, `output_text`, `input_image`) with better role assignments and part handling.
    - Added image processing logic for embedding inline data with MIME type and base64 encoded content.
    - Updated Antigravity request conversion to replace Gemini CLI references for consistency.
  • Merge pull request #303 from router-for-me/image
    feat(translator): support image size and googleSearch tools
  • Fixed: #302
    **feat(executor): enhance WebSocket error handling and metadata logging**
    
    - Added handling for stream closure before start with appropriate error recording.
    - Improved metadata logging for non-OK HTTP status codes in WebSocket responses.
    - Consolidated event processing logic with `processEvent` for better error handling and payload management.
    - Refactored stream initialization to include the first event handling for smoother execution flow.
  • **feat(auth): implement Antigravity OAuth authentication flow**
    - Added new endpoint `/antigravity-auth-url` to initiate Antigravity authentication.
    - Implemented `RequestAntigravityToken` to manage the OAuth flow, including token exchange and user info retrieval.
    - Introduced `.oauth-antigravity` temporary file handling for state and code management.
    - Added `sanitizeAntigravityFileName` utility for safe token file names based on user email.
    - Registered `/antigravity/callback` endpoint for OAuth redirects.
  • **feat(translator): add Antigravity translation logic**
    - Introduced request and response translation functions to enable compatibility between OpenAI Chat Completions API and Antigravity.
    - Registered translation utilities for both streaming and non-streaming scenarios.
    - Added support for reasoning content, tool calls, and metadata handling.
    - Established request normalization and embedding for Antigravity-compatible payloads.
    - Added new fields to `Params` struct for better tracking of finish reasons, usage metadata, and tool usage.
    - Refactored handling of response transitions, final events, and state-driven logic in `ConvertAntigravityResponseToClaude`.
    - Introduced `appendFinalEvents` and `resolveStopReason` helper functions for cleaner separation of concerns.
    - Added `TotalTokenCount` field to `Params` struct for enhanced token tracking.
    - Updated token count calculations to fallback on `TotalTokenCount` when specific counts are missing.
    - Introduced `hasNonZeroUsageMetadata` function to validate presence of token data in `usage_metadata`.
  • **feat(auth, executor, cmd): add Antigravity provider integration**
    - Implemented OAuth login flow for the Antigravity provider in `auth/antigravity.go`.
    - Added `AntigravityExecutor` for handling requests and streaming via Antigravity APIs.
    - Created `antigravity_login.go` command for triggering Antigravity authentication.
    - Introduced OpenAI-to-Antigravity translation logic in `translator/antigravity/openai/chat-completions`.
    
    **refactor(translator, executor): update Gemini CLI response translation and add Antigravity payload customization**
    
    - Renamed Gemini CLI translation methods to align with response handling (`ConvertGeminiCliResponseToGemini` and `ConvertGeminiCliResponseToGeminiNonStream`).
    - Updated `init.go` to reflect these method changes.
    - Introduced `geminiToAntigravity` function to embed metadata (`model`, `userAgent`, `project`, etc.) into Antigravity payloads.
    - Added random project, request, and session ID generators for enhanced tracking.
    - Streamlined `buildRequest` to use `geminiToAntigravity` transformation before request execution.
  • Fixed: #291
    **feat(executor): add thinking level to budget conversion utility**
    
    - Introduced `ConvertThinkingLevelToBudget` to map thinking level ("high"/"low") to corresponding budget values.
    - Applied the utility in `aistudio_executor.go` before stripping unsupported configs.
    - Updated dependencies to include `tidwall/gjson` for JSON parsing.
  • **refactor(middleware): extract request logging logic and optimize condition checks**
    - Added `shouldLogRequest` helper to simplify path-based request logging logic.
    - Updated middleware to skip management endpoints for improved security.
    - Introduced an explicit `nil` logger check for minimal overhead.
    - Updated dependencies in `go.mod`.
    
    **feat(auth): add handling for 404 response with retry logic**
    
    - Introduced support for 404 `not_found` status with a 12-hour backoff period.
    - Updated `manager.go` to align state and status messages for 404 scenarios.
    
    **refactor(translator): comment out debug logging in Gemini responses request**
  • **refactor(executor): simplify Gemini CLI execution and remove internal retry logic**
    - Removed nested retry handling for 429 rate limit errors.
    - Simplified request/response handling by cleaning redundant retry-related code.
    - Eliminated `parseRetryDelay` function and max retry configuration logic.
  • security: fix localhost middleware header spoofing vulnerability
    Fix critical security vulnerability in amp-restrict-management-to-localhost
    feature where attackers could bypass localhost restriction by spoofing
    X-Forwarded-For headers.
    
    Changes:
    - Use RemoteAddr (actual TCP connection) instead of ClientIP() in
      localhostOnlyMiddleware to prevent header spoofing attacks
    - Add comprehensive test coverage for spoofing prevention (6 test cases)
    - Update documentation with reverse proxy deployment guidance and
      limitations of the RemoteAddr approach
    
    The fix prevents attacks like:
      curl -H "X-Forwarded-For: 127.0.0.1" https://server/api/user
    
    Trade-off: Users behind reverse proxies will need to disable the feature
    and use alternative security measures (firewall rules, proxy ACLs).
    
    Addresses security review feedback from PR #287.
  • fix(amp): enable OAuth fallback for Gemini v1beta1 routes
    AMP CLI sends Gemini requests to non-standard paths that were being
    directly proxied to ampcode.com without checking for local OAuth.
    
    This fix adds:
    - GeminiBridge handler to transform AMP CLI paths to standard format
    - Enhanced model extraction from AMP's /publishers/google/models/* paths
    - FallbackHandler wrapper to check for local OAuth before proxying
    
    Flow:
    - If user has local Google OAuth → use it (free tier)
    - If no local OAuth → fallback to ampcode.com (charges credits)
    
    Fixes issue where gemini-3-pro-preview requests always charged AMP
    credits even when user had valid Google Cloud OAuth configured.
  • fix(amp): filter context-1m beta header for local OAuth providers
    Amp CLI sends 'context-1m-2025-08-07' in Anthropic-Beta header which
    requires a special 1M context window subscription. After upstream rebase
    to v6.3.7 (commit 38cfbac), CLIProxyAPI now respects client-provided
    Anthropic-Beta headers instead of always using defaults.
    
    When users configure local OAuth providers (Claude, etc), requests bypass
    the ampcode.com proxy and use their own API subscriptions. These personal
    subscriptions typically don't include the 1M context beta feature, causing
    'long context beta not available' errors.
    
    Changes:
    - Add filterBetaFeatures() helper to strip specific beta features
    - Filter context-1m-2025-08-07 in fallback handler when using local providers
    - Preserve full headers when proxying to ampcode.com (paid users get all features)
    - Add 7 test cases covering all edge cases
    
    This fix is isolated to the Amp module and only affects the local provider
    path. Users proxying through ampcode.com are unaffected and receive full
    1M context support as part of their paid service.
  • Add AMP fallback proxy and shared Gemini normalization
    - add fallback handler that forwards Amp provider requests to ampcode.com when the provider isn’t configured locally
    - wrap AMP provider routes with the fallback so requests always have a handler
    - share Gemini thinking model normalization helper between core handlers and AMP fallback
  • feat: Add Amp CLI integration with comprehensive documentation
    Add full Amp CLI support to enable routing AI model requests through the proxy
    while maintaining Amp-specific features like thread management, user info, and
    telemetry. Includes complete documentation and pull bot configuration.
    
    Features:
    - Modular architecture with RouteModule interface for clean integration
    - Reverse proxy for Amp management routes (thread/user/meta/ads/telemetry)
    - Provider-specific route aliases (/api/provider/{provider}/*)
    - Secret management with precedence: config > env > file
    - 5-minute secret caching to reduce file I/O
    - Automatic gzip decompression for responses
    - Proper connection cleanup to prevent leaks
    - Localhost-only restriction for management routes (configurable)
    - CORS protection for management endpoints
    
    Documentation:
    - Complete setup guide (USING_WITH_FACTORY_AND_AMP.md)
    - OAuth setup for OpenAI (ChatGPT Plus/Pro) and Anthropic (Claude Pro/Max)
    - Factory CLI config examples with all model variants
    - Amp CLI/IDE configuration examples
    - tmux setup for remote server deployment
    - Screenshots and diagrams
    
    Configuration:
    - Pull bot disabled for this repo (manual rebase workflow)
    - Config fields: AmpUpstreamURL, AmpUpstreamAPIKey, AmpRestrictManagementToLocalhost
    - Compatible with upstream DisableCooling and other features
    
    Technical details:
    - internal/api/modules/amp/: Complete Amp routing module
    - sdk/api/httpx/: HTTP utilities for gzip/transport
    - 94.6% test coverage with 34 comprehensive test cases
    - Clean integration minimizes merge conflict risk
    
    Security:
    - Management routes restricted to localhost by default
    - Configurable via amp-restrict-management-to-localhost
    - Prevents drive-by browser attacks on user data
    
    This provides a production-ready foundation for Amp CLI integration while
    maintaining clean separation from upstream code for easy rebasing.
    
    Amp-Thread-ID: https://ampcode.com/threads/T-9e2befc5-f969-41c6-890c-5b779d58cf18
  • fix(executor): prevent streaming on failed response when no fallback
    Fix critical bug where ExecuteStream would create a streaming channel
    from a failed (non-2xx) response after exhausting all retries with no
    fallback models available.
    
    When retries were exhausted on the last model, the code would break from
    the inner loop but fall through to streaming channel creation (line 401),
    immediately returning at line 461. This made the error handling code at
    lines 464-471 unreachable, causing clients to receive an empty/closed
    stream instead of a proper error response.
    
    Solution: Check if httpResp is non-2xx before creating the streaming
    channel. If failed, continue the outer loop to reach error handling.
    
    Identified by: codex-bot review
    Ref: https://github.com/router-for-me/CLIProxyAPI/pull/280#pullrequestreview-3484560423